body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'd like this to be reviewed:</p> <pre><code>public class MaxHeap&lt;E extends Comparable&lt;E&gt;&gt; { private E[] heap; private int capacity; // maximum size of heap private int numberOfNodes; // number of nodes in current heap /** * Create a new MaxHeap object. * * @param heap * @param capacity * @param numberOfNodes */ public MaxHeap(E[] heap, int capacity, int numberOfNodes) { this.heap = heap; this.capacity = capacity; this.numberOfNodes = numberOfNodes; this.buildHeap(); } /** * Put all nodes within the max heap in the correct position. */ void buildHeap() { for (int i = (this.numberOfNodes / 2 - 1); i &gt;= 0; i--) { this.correctNodeIndexByShifting(i); } } /** * Insert a new node at the current position within the max-heap. * * @param nodeValue * The node to be inserted. */ public void insert(E nodeValue) { if (this.capacity &lt;= this.numberOfNodes) { throw new IllegalArgumentException("In method insert of class " + "MaxHeap the element: " + nodeValue + " could not be inserted because the max-heap is full"); } int currentNodePosition = this.numberOfNodes++; this.heap[currentNodePosition] = nodeValue; // start at the end of most bottom right leaf node and shift up // until the nodeValue has a parent with a greater or equal value while ((currentNodePosition != 0) &amp;&amp; (this.heap[currentNodePosition].compareTo(this.heap[this .getParentIndex(currentNodePosition)]) &gt; 0)) { this.swap(currentNodePosition, this.getParentIndex(currentNodePosition)); currentNodePosition = this.getParentIndex(currentNodePosition); } } /** * Remove the node at arrayIndex within the MaxHeap and return the node * value that the removed node is replaced with. * * @param arrayIndex * Index of the node within the array based max-heap to be * removed. * @return The element that was removed. */ public E remove(int arrayIndex) { int changingArrayIndex = arrayIndex; if ((changingArrayIndex &lt; 0) || (changingArrayIndex &gt;= this.numberOfNodes)) { throw new IllegalArgumentException("In method remove of class " + "MaxHeap the input node postion to be removed is invalid"); } // if the most bottom right node is being removed there is no work to be // done if (changingArrayIndex == (this.numberOfNodes - 1)) { this.numberOfNodes--; } else { // swap node to be removed with most bottom right node this.swap(changingArrayIndex, --this.numberOfNodes); // if swapped node is large, shift it up the tree while ((changingArrayIndex &gt; 0) &amp;&amp; (this.heap[changingArrayIndex].compareTo(this.heap[this .getParentIndex(changingArrayIndex)]) &gt; 0)) { this.swap(changingArrayIndex, this.getParentIndex(changingArrayIndex)); changingArrayIndex = this.getParentIndex(changingArrayIndex); } if (this.numberOfNodes != 0) { // if swapped node is small, shift it down the tree this.correctNodeIndexByShifting(changingArrayIndex); } } return this.heap[changingArrayIndex]; } /** * @return maximum node value in max-heap. */ public E removeMaximumValue() { if (this.numberOfNodes &lt;= 0) { throw new IllegalStateException( "In method removeMaximumValue of class " + "MaxHeap the value you cannot remove a value from an " + "empty max-heap"); } // swap maximum with last value this.swap(0, --this.numberOfNodes); if (this.numberOfNodes != 0) { // if not the last element this.correctNodeIndexByShifting(0); } return this.heap[this.numberOfNodes]; } /** * Place given node position in the correct position within the complete * binary tree. * * @param arrayIndex * Index of node to be correctly shifted to the correct position. */ void correctNodeIndexByShifting(int arrayIndex) { int changingArrayIndex = arrayIndex; if ((changingArrayIndex &lt; 0) || (changingArrayIndex &gt;= this.numberOfNodes)) { throw new IllegalArgumentException( "In method shiftDown of class " + "MaxHeap the value: " + changingArrayIndex + " represents a node that does not exist in the current heap"); } while (!this.isLeafNode(changingArrayIndex)) { int childIndex = this.getLeftChildIndex(changingArrayIndex); if ((childIndex &lt; (this.numberOfNodes - 1)) &amp;&amp; (this.heap[childIndex] .compareTo(this.heap[childIndex + 1]) &lt; 0)) { childIndex++; // childIndex is not at index of child with // greater node value } if (this.heap[changingArrayIndex].compareTo(this.heap[childIndex]) &gt;= 0) { return; } this.swap(changingArrayIndex, childIndex); changingArrayIndex = childIndex; // node shifted down } } /** * Switch the node at arrayIndex1 into node at arrayIndex2 and vice versa. * * @param arrayIndex1 * @param arrayIndex2 */ void swap(int arrayIndex1, int arrayIndex2) { if (arrayIndex1 &lt; 0 || arrayIndex1 &gt; this.numberOfNodes) { throw new IllegalArgumentException( "In method swap of class " + "MaxHeap the input arrayIndex1 is not a valid node position"); } else if (arrayIndex2 &lt; 0 || arrayIndex2 &gt; this.numberOfNodes) { throw new IllegalArgumentException( "In method swap of class " + "MaxHeap the input arrayIndex2 is not a valid node position"); } E tempNodeValue = this.heap[arrayIndex1]; this.heap[arrayIndex1] = this.heap[arrayIndex2]; this.heap[arrayIndex2] = tempNodeValue; } /** * @param arrayIndex * Index of child node. * @return Index of parent to given index of child. * */ public int getParentIndex(int arrayIndex) { if (arrayIndex &lt;= 0) { throw new IllegalArgumentException( "In method getParentPosition of class " + "MaxHeap your input node position at " + arrayIndex + " must be &gt; 0"); } else { return (arrayIndex - 1) / 2; } } /** * @param arrayIndex * Index of parent node. * @return Index of right child within array based max-heap to given parent * node. */ public int getRightChildIndex(int arrayIndex) { if (arrayIndex &gt;= (this.numberOfNodes / 2)) { throw new IllegalArgumentException("In method rightChild of class " + "MaxHeap your input node position at " + arrayIndex + " does not have a right child."); } else { return 2 * arrayIndex + 2; } } /** * @param arrayIndex * Index of parent node. * @return Index of left child within array based max-heap to given parent * node. */ public int getLeftChildIndex(int arrayIndex) { if (arrayIndex &gt;= (this.numberOfNodes / 2)) { throw new IllegalArgumentException("In method leftChild of class " + "MaxHeap your input node position at " + arrayIndex + " does not have a left child."); } else { return 2 * arrayIndex + 1; } } /** * @param arrayIndex * Index of node to be checked. * @return True if node at given arrayIndex is a leaf node; otherwise return * false. */ public boolean isLeafNode(int arrayIndex) { if ((arrayIndex &gt;= (this.numberOfNodes / 2)) &amp;&amp; (arrayIndex &lt; this.numberOfNodes)) { return true; } else { return false; } } /** * @return The number of nodes in this max-heap. */ public int getNumberOfNodes() { return this.numberOfNodes; } /** * @return The height of the heap. */ public int getHeapHeight() { double approximateHeight = Math.log(this.numberOfNodes) / Math.log(2); int actualHeight = (int) (Math.floor(approximateHeight) + 1); return actualHeight; } /** * @return String representation of elements in the array used to implement * the max-heap. */ public String printMaxHeapArray() { StringBuilder maxHeapArray = new StringBuilder(); for (int i = 0; i &lt; this.heap.length; i++) { maxHeapArray.append(this.heap[i] + " "); } return maxHeapArray.toString(); } } </code></pre>
[]
[ { "body": "<p>I haven't checked the details of the algorithm, just some general feedback on the code, API, etc:</p>\n\n<ol>\n<li><p>It's usually a good practice to make a copy of mutable input parameters. (<code>E[] heap</code> in this case.) It prohibits malicious clients to modify the heap's internal structure or it could save you from a few hours of debugging. (<em>Effective Java, 2nd Edition, Item 39: Make defensive copies when needed</em>) </p>\n\n<p>Copying the input array would make the <code>capacity</code> field redundant. You could use <code>heap.length</code> instead of it.</p></li>\n<li><p>The constructor should validate its input parameters. Currently it's too easy to call it with a wrong size array:</p>\n\n<pre><code>String[] heap = {\"aa\", \"ac\", \"bb\"};\nint capacity = 4;\nint numberOfNodes = 4;\nMaxHeap&lt;String&gt; maxHeap =\n new MaxHeap&lt;String&gt;(heap, capacity, numberOfNodes);\n</code></pre>\n\n<p>If you call a <code>maxHeap.insert(\"ab\")</code> after that you get a mysterious <code>ArrayIndexOutOfBoundsException</code>. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>) (Copying the input array to a properly sized array could solve this issue too.)</p></li>\n<li><p>It's easy to misunderstood the parameter of <code>remove()</code>. Currently it's an index. A client easily think that the following code removes <code>20</code> from the heap:</p>\n\n<pre><code>final Integer[] initialData = {10, 30, 20, 40};\nint capacity = 4;\nint numberOfNodes = 3;\nMaxHeap&lt;Integer&gt; heap =\n new MaxHeap&lt;Integer&gt;(initialData, capacity, numberOfNodes);\nheap.remove(20);\n</code></pre>\n\n<p>Actually it throws an exception, since there aren't 20 items in the heap.</p>\n\n<p>Note that there isn't any other method which returns an index so how could a client figure out a valid parameter of the <code>remove</code> method? A <code>remove(E item)</code> method would be better.</p></li>\n<li><p>Implementation of <code>printMaxHeapArray</code> could be replaced with <code>return Arrays.toString(heap);</code> if output format is not bound. (Output of <code>Arrays.toString()</code> is a slightly different: <code>[cc, bb, aa, ab]</code>). Otherwise, I'd use a more compact foreach loop:</p>\n\n<pre><code>for (final E item: heap) {\n maxHeapArray.append(item + \" \");\n}\n</code></pre>\n\n<p>Checking it again I guess <code>i &lt; this.heap.length</code> should be <code>i &lt; this.numberOfNodes</code>. I think you don't want to print the removed items.</p></li>\n<li><p>Java already has a <code>toString()</code> method. If you use <code>printMaxHeapArray</code> only for debugging or logging purposes and clients don't rely on its exact output you should implement (override) <code>toString()</code> instead. <code>toString()</code> is more convenient for most developers. (<em>Effective Java, 2nd Edition, Item 10: Always override toString</em>)</p></li>\n<li><p>Comments like this are unnecessary:</p>\n\n<pre><code>/**\n * Create a new MaxHeap object.\n * \n * @param heap\n * @param capacity\n * @param numberOfNodes\n */\n</code></pre>\n\n<p>They say nothing more than the code already does, it's rather noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>Instead of comments like this:</p>\n\n<pre><code> * @param arrayIndex\n * Index of parent node.\n</code></pre>\n\n<p>rename the parameter to <code>parentIndex</code> or <code>parentNodeIndex</code>. It would help readers, make the code readable and you could get rid of the comment. The same is true for <code>getParentIndex(final int arrayIndex)</code> (<code>childIndex</code>).</p></li>\n<li><p><code>boolean isLeafNode(final int arrayIndex)</code> returns <code>false</code> when the given index is higher than the size of the array. I guess calling the method with a definitely invalid index is a bug in the client code. Crash early, throw an <code>IllegalArgumentException</code> (as the <code>getLeftChildIndex()</code> method does). See: <em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.</p></li>\n<li><p>The <code>else</code> keyword is unnecessary here:</p>\n\n<pre><code>if (arrayIndex1 &lt; 0 || arrayIndex1 &gt; this.numberOfNodes) {\n throw new IllegalArgumentException(\"In method swap of class \"\n + \"MaxHeap the input arrayIndex1 is not a valid node position\");\n} else if (arrayIndex2 &lt; 0 || arrayIndex2 &gt; this.numberOfNodes) {\n throw new IllegalArgumentException(\"In method swap of class \"\n + \"MaxHeap the input arrayIndex2 is not a valid node position\");\n}\n</code></pre>\n\n<p>It could be simply</p>\n\n<pre><code>if (arrayIndex1 &lt; 0 || arrayIndex1 &gt; this.numberOfNodes) {\n throw new ...\n}\nif (arrayIndex2 &lt; 0 || arrayIndex2 &gt; this.numberOfNodes) {\n throw new ...\n}\n</code></pre></li>\n<li><p>Furthermore, you could extract out the checking logic (since it's duplicated, used twice for the two parameters and the same logic is in other methods too) to a validator method:</p>\n\n<pre><code>void swap(final int arrayIndex1, final int arrayIndex2) {\n checkValidIndex(arrayIndex1,\n \"In method swap of class MaxHeap the input arrayIndex1 is not a valid node position: \" + arrayIndex1);\n checkValidIndex(arrayIndex2,\n \"In method swap of class MaxHeap the input arrayIndex2 is not a valid node position: \" + arrayIndex2);\n ...\n}\n\nprivate void checkValidIndex(final int arrayIndex, final String message) {\n if (arrayIndex &lt; 0 || arrayIndex &gt; this.numberOfNodes) {\n throw new IllegalArgumentException(message);\n }\n}\n</code></pre>\n\n<p><a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Google Guava</a> has similar <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkArgument%28boolean,%20java.lang.String,%20java.lang.Object...%29\" rel=\"nofollow\">checkArgument</a> method which supports handy template strings (<code>%s</code>) too. (See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>I'd use a little bit shorter exception messages, like <code>\"invalid arrayIndex: \" + arrayIndex1</code>. The stacktrace will show the place of the error. It helps debugging if you put the invalid value to the message.</p></li>\n<li><p>I think that the <code>tempNodeValue</code> could have a better name. Currently it does not express the developer's intent and the purpose of the variable. (Every local variable is temporary.) I'd call it <code>oldValue</code> instead since it stores the old value of index1.</p></li>\n<li><p>The <code>this.heap[changingArrayIndex].compareTo(this.heap[this.getParentIndex(changingArrayIndex)]) &gt; 0</code> condition is duplicated. It could be extracted out to a helper method:</p>\n\n<pre><code>private boolean compareWithParent(final int arrayIndex) {\n final int parentIndex = this.getParentIndex(arrayIndex);\n return heap[arrayIndex].compareTo(heap[parentIndex]) &gt; 0;\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T22:51:25.330", "Id": "42020", "ParentId": "32269", "Score": "7" } } ]
{ "AcceptedAnswerId": "42020", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T01:41:51.157", "Id": "32269", "Score": "6", "Tags": [ "java", "heap" ], "Title": "MaxHeap implementation" }
32269
<p>I use this interface for my BST node class:</p> <pre><code>public interface BinNode&lt;E&gt; { public E getValue(); public void setValue(E value); public BinNode&lt;E&gt; getLeftChild(); public BinNode&lt;E&gt; getRightChild(); public boolean isLeaf(); } </code></pre> <p>My BSTNode is implemented as follows:</p> <pre><code>public class BinarySearchTreeNode&lt;Key, E&gt; implements BinNode&lt;E&gt; { private Key key; private E value; private BinarySearchTreeNode&lt;Key, E&gt; leftChild; private BinarySearchTreeNode&lt;Key, E&gt; rightChild; public BinarySearchTreeNode(Key key, E value, BinarySearchTreeNode&lt;Key, E&gt; leftChild, BinarySearchTreeNode&lt;Key, E&gt; rightChild) { this.key = key; this.value = value; this.leftChild = leftChild; this.rightChild = rightChild; } public Key getKey() { return this.key; } public void setKey(Key key) { this.key = key; } @Override public E getValue() { return this.value; } @Override public void setValue(E value) { this.value = value; } @Override public BinarySearchTreeNode&lt;Key, E&gt; getLeftChild() { return this.leftChild; } public void setLeftChild(BinarySearchTreeNode&lt;Key, E&gt; leftChild) { this.leftChild = leftChild; } @Override public BinarySearchTreeNode&lt;Key, E&gt; getRightChild() { return this.rightChild; } public void setRightChild(BinarySearchTreeNode&lt;Key, E&gt; rightChild) { this.rightChild = rightChild; } @Override public boolean isLeaf() { if (this.leftChild == null &amp;&amp; this.rightChild == null) { return true; } else { return false; } } } </code></pre> <p>And finally my binary search tree is implemented as:</p> <pre><code>public class BinarySearchTree&lt;Key extends Comparable&lt;? super Key&gt;, E&gt; implements Dictionary&lt;Key, E&gt; { private BinarySearchTreeNode&lt;Key, E&gt; rootNode; private int numberOfNodes; public BinarySearchTree() { this.rootNode = null; this.numberOfNodes = 0; } @Override public void clear() { this.rootNode = null; this.numberOfNodes = 0; } @Override public void insert(Key key, E element) { this.rootNode = this.insertHelp(this.rootNode, key, element); this.numberOfNodes++; } @Override public E remove(Key key) { // first find the node to remove E nodeToRemove = this.findHelp(this.rootNode, key); if (nodeToRemove != null) { // now remove the found node this.rootNode = this.removeHelp(this.rootNode, key); this.numberOfNodes--; } return nodeToRemove; } @Override public E removeRandomElement() { if (this.rootNode == null) { return null; } E randomeNodeToRemove = this.rootNode.getValue(); this.rootNode = this.removeHelp(this.rootNode, this.rootNode.getKey()); this.numberOfNodes--; return randomeNodeToRemove; } @Override public E find(Key key) { return this.findHelp(this.rootNode, key); } @Override public int size() { return this.numberOfNodes; } private E findHelp(BinarySearchTreeNode&lt;Key, E&gt; rootNode, Key key) { if (rootNode == null) { return null; } if (rootNode.getKey().compareTo(key) &gt; 0) { return this.findHelp(rootNode.getLeftChild(), key); } else if (rootNode.getKey().compareTo(key) == 0) { return rootNode.getValue(); } else { return this.findHelp(rootNode.getRightChild(), key); } } private BinarySearchTreeNode&lt;Key, E&gt; insertHelp( BinarySearchTreeNode&lt;Key, E&gt; rootNode, Key key, E element) { if (rootNode == null) { return new BinarySearchTreeNode&lt;Key, E&gt;(key, element, null, null); } if (rootNode.getKey().compareTo(key) &gt; 0) { rootNode.setLeftChild(this.insertHelp(rootNode.getLeftChild(), key, element)); } else { rootNode.setRightChild(this.insertHelp(rootNode.getRightChild(), key, element)); } return rootNode; } private BinarySearchTreeNode&lt;Key, E&gt; removeHelp( BinarySearchTreeNode&lt;Key, E&gt; rootNode, Key key) { if (rootNode == null) { return null; } if (rootNode.getKey().compareTo(key) &gt; 0) { rootNode.setLeftChild(this.removeHelp(rootNode.getLeftChild(), key)); } else if (rootNode.getKey().compareTo(key) &lt; 0) { rootNode.setRightChild(this.removeHelp(rootNode.getRightChild(), key)); } else { // found node to remove if (rootNode.getLeftChild() == null) { return rootNode.getRightChild(); } else if (rootNode.getRightChild() == null) { return rootNode.getLeftChild(); } else { // there are 2 children BinarySearchTreeNode&lt;Key, E&gt; nodeToRemove = this .getNodeWithMinimumValue(rootNode.getRightChild()); rootNode.setValue(nodeToRemove.getValue()); rootNode.setKey(nodeToRemove.getKey()); rootNode.setRightChild(this.deleteNodeWithMinimumValue(rootNode.getRightChild())); } } return rootNode; } private BinarySearchTreeNode&lt;Key, E&gt; getNodeWithMinimumValue( BinarySearchTreeNode&lt;Key, E&gt; rootNode) { if (rootNode.getLeftChild() == null) { return rootNode; } return this.getNodeWithMinimumValue(rootNode.getLeftChild()); } private BinarySearchTreeNode&lt;Key, E&gt; deleteNodeWithMinimumValue( BinarySearchTreeNode&lt;Key, E&gt; rootNode) { if (rootNode.getLeftChild() == null) { return rootNode.getRightChild(); } rootNode.setLeftChild(this.deleteNodeWithMinimumValue(rootNode.getLeftChild())); return rootNode; } // TODO: add traversal functions } </code></pre>
[]
[ { "body": "<p>When you have a custom implementation of something, and it has internal structures, like, in your case, the <code>BinarySearchTreeNode</code>, there is no real reason to have the interface for it. There is no public use of the interface, and not even your actual tree uses it. It is redundant. You can delete it, and remove the reference from the <code>BinarySearchTreeNode</code></p>\n\n<p>Additionally, there is no need for the <code>BinarySearchTreeNode</code> to be public. You never return the instance from the Tree, so there is no reason to expose it. Leaving it package-private (no <code>public</code> or <code>private</code> declaration) would be a decent choice, but commonly, the class is actually nested as a private-static inner class in the actual tree.</p>\n\n<p>I am not sure what the <code>Dictionary&lt;&gt;</code> interface is ... Oh... really? <code>java.util.Dictionary</code> ... this should be <code>java.util.Map&lt;...&gt;</code> since the documentation for Dictionary (which, in 10 years, I have never seen before now) says:</p>\n\n<blockquote>\n <p>NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class.</p>\n</blockquote>\n\n<p>Apart from that, the class looks pretty good.</p>\n\n<pre><code>public class BinarySearchTree&lt;Key extends Comparable&lt;? super Key&gt;, E&gt;\nimplements Map&lt;Key, E&gt; {\n\n private static class BinarySearchTreeNode&lt;Key, E&gt; {\n\n ....\n\n }\n\n .....\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:18:41.457", "Id": "40667", "ParentId": "32270", "Score": "3" } }, { "body": "<p>Just a small improvement: although this might be seen as a matter of taste, I personally find this kind of construction too verbose:</p>\n\n<pre><code> if (this.leftChild == null &amp;&amp; this.rightChild == null) {\n return true;\n } else {\n return false;\n }\n</code></pre>\n\n<p>You could easily convert it into a one-liner:</p>\n\n<pre><code>return (this.leftChild == null &amp;&amp; this.rightChild == null);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:44:15.060", "Id": "40754", "ParentId": "32270", "Score": "3" } } ]
{ "AcceptedAnswerId": "40667", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T01:45:46.860", "Id": "32270", "Score": "3", "Tags": [ "java", "tree", "binary-search" ], "Title": "Generic binary search tree implementation" }
32270
<p>I am writing code for breadth-first search of a tree with C++'s STL. Please help as I am new to the STL.</p> <pre><code>#include&lt;iostream&gt; #include&lt;malloc.h&gt; //on llvm we don't need this #include&lt;list&gt; using namespace std; typedef struct Node{ int val; struct Node* left; struct Node* right; }node; void push(node** root,int val) { if(!(*root)) { node* temp=(node*)malloc(sizeof(node)); temp-&gt;val=val; temp-&gt;right=temp-&gt;left=NULL; *root=temp; } else if(val&lt;(*root)-&gt;val) push(&amp;((*root)-&gt;left),val); else push(&amp;((*root)-&gt;right),val); } void printout(node* head) { node* temp; temp=head; list&lt;node*&gt;qu; //using bfs here while(temp!=NULL) { cout&lt;&lt;temp-&gt;val&lt;&lt;endl; if(temp-&gt;left!=NULL) qu.push_back(temp-&gt;left); if(temp-&gt;right!=NULL) qu.push_back(temp-&gt;right); free(temp); if (qu.empty()) { break; } temp=qu.front(); qu.pop_front(); } } int main() { node* root=NULL; push(&amp;root,3); push(&amp;root,4); push(&amp;root,1); push(&amp;root,10); push(&amp;root,2); printout(root); } </code></pre> <p>The output is:</p> <pre><code>3 1 4 2 10 </code></pre>
[]
[ { "body": "<p>Don't use <code>malloc()</code>. If you do then you will need to track memory that is allocated with new and that allocated with malloc and use the appropriate de-allocation functions. Also using new calls the constructor and makes sure the object is correctly initialized.</p>\n\n<pre><code>#include&lt;malloc.h&gt; //on llvm we don't need this\n</code></pre>\n\n<p>Don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n\n<p>In C++ you don't need to typedef structs. struct names are in the same namespace as everything else. Also Add a constructor to make sure things are correctly initialized.</p>\n\n<pre><code>typedef struct Node{\n int val;\n struct Node* left;\n struct Node* right;\n}node;\n\n// Prefer\nstruct Node\n{\n int val;\n Node* left;\n Node* right;\n Node(int v):val(v), left(NULL), right(NULL) {}\n};\n</code></pre>\n\n<p>When pushing a value onto a tree or list. Return the new value rather than pass out values.</p>\n\n<pre><code>void push(node** root,int val)\n\n// Your current usage is:\npush(&amp;head, 5);\n\n// Easier usage\nhead = push(head, 5);\n</code></pre>\n\n<p>Don't use C casts</p>\n\n<pre><code> node* temp=(node*)malloc(sizeof(node));\n</code></pre>\n\n<p>If you must cast then use one of the C++ cast's. But any casts are a sign of bad design. Also using new means this is not required.</p>\n\n<pre><code>// Easier implementation of push:\nNode* push(Node* current, value)\n{\n if (current == NULL)\n { return new Node(value);\n }\n\n if (value &lt;= current-&gt;value)\n current-&gt;left = push(current-&gt;left, value);\n else\n current-&gt;right = push(current-&gt;right, value); \n\n return current;\n}\n</code></pre>\n\n<p>In your breadth first printing of the tree don't treat the head as special. You should just push the head node onto the list. The loop while the list is not empty. Thus you remove the item at the top of the loop not the bottom.</p>\n\n<pre><code>// Code deliberately left out to make you work.\n</code></pre>\n\n<p>Don't free the nodes as past of the print function. Add a destructor to your node. So that it calls delete on left and right.</p>\n\n<pre><code>~Node()\n{ delete left;\n delete right;\n}\n</code></pre>\n\n<p>Then all you need to do is delete the head and all the nodes will be destroyed correctly.</p>\n\n<p>Your design should hide the memory management. You should put the head node inside its own structure. So that it hides all the memory management and you the user of your class does not need to worry about any of that</p>\n\n<pre><code>class Tree\n{ \n Node* head;\n Tree(Tree const&amp; copy);\n Tree&amp; operator=(Tree const&amp; rhs);\n public:\n Tree(): head(NULL) {} // Set up empty tree.\n ~Tree() {delete head;} // Memory management done.\n\n void push(int val)\n {\n head = ::push(head, val);\n }\n void printBF()\n {\n ::printout(head);\n }\n};\n</code></pre>\n\n<p>Note the functions you wrote should also made as members of Node.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T05:04:57.747", "Id": "32359", "ParentId": "32276", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T08:09:45.407", "Id": "32276", "Score": "0", "Tags": [ "c++", "memory-management", "tree", "stl", "breadth-first-search" ], "Title": "Breadth-first tree traversal using STL list" }
32276
<p>This implements binary search on an array of cstrings. One thing I'm wondering about is it faster or slower to pass a variable as <code>const</code> i.e. len. Also <code>strcmp()</code> gets called a lot and since I can't find any specific details on how it works, is it worthwhile to make my own function? For example does it immediately return a value if the first character of each arguments are different?</p> <pre><code>/* *IN: scope: array of cstrings to be searched *IN: len: length of array *IN: find: cstring to be found *OUT: true if find is in scope, otherwise false */ bool binSrch(char** scope, const int len, char* find) { int c, first, last, middle; first = 0; last = len - 1; middle = (first+last)/2; while( first &lt;= last ) { if (strcmp(scope[middle], find) &lt; 0 ) first = middle + 1; else if (strcmp(scope[middle], find) == 0) { return true; } else last = middle - 1; middle = (first + last)/2; } if ( first &gt; last ) return false; } </code></pre> <p>EDIT: is there a way to intelligently choose the pivot point? For example if your looking in a phone book for a name starting with Z you wouldn't start at the middle you'd start closer to the back.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T08:31:12.100", "Id": "51564", "Score": "0", "body": "This question appears to be off-topic because it is about trying to understand the code snippet and not about seeking a review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T08:52:40.930", "Id": "51567", "Score": "1", "body": "@Jamal this is my second post on this site so I'm still learning :) what makes you say I don't understand the code, the fact I point out some areas I see pitfalls? Would you rather I have posted just the code and not said anything?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T09:15:21.687", "Id": "51571", "Score": "1", "body": "It's working code, posted with some notes about concerns. I see nothing wrong with the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T17:59:55.163", "Id": "51589", "Score": "0", "body": "Okay, the latest edit did help. Close vote retracted." } ]
[ { "body": "<p>You can assume that the implementation of <code>strcmp()</code> is not stupid. A <em>lot</em> of code out there relies on <code>strcmp()</code>, so rest assured that a lot of work has gone into optimizing it. Nevertheless, you don't want to call it twice per iteration through your loop.</p>\n\n<p>Interestingly, <code>len</code> is the only parameter that doesn't need to be declared <code>const</code>, since it is passed by value. In contrast, <code>scope</code> and <code>find</code> are passed by reference, so a promise that <code>binSrch()</code> won't alter them would be helpful.</p>\n\n<p>At the end, you don't need to test for <code>first &gt; last</code> before returning <code>false</code>. The only way you can get past the <code>while</code> loop is with <code>first &gt; last</code>.</p>\n\n<p>You have an unused variable <code>c</code>. Avoid such mistakes by getting into the habit of assigning right away:</p>\n\n<pre><code>int first = 0,\n last = len - 1,\n middle = (first + last) / 2;\n</code></pre>\n\n<p>I think the braces on your <code>else if</code> look weird. Either remove them, or put them everywhere consistently. (I prefer the latter.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T08:56:57.280", "Id": "51569", "Score": "0", "body": "\"promise that binSrch() won't alter them would be helpful\" I could use a refresher on this, so if a pointer is passed as const that means the value it points to doesn't change right? Or does it mean the address the pointer points to doesn't change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T09:12:04.220", "Id": "51570", "Score": "0", "body": "It [depends on where you put the `const`](http://stackoverflow.com/q/6407041/1157100). In your case, feel free to sprinkle `const` liberally, since you never mutate anything. `bool binSrch(char const *const *scope, int len, char const* find)` would work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T09:30:30.863", "Id": "51572", "Score": "0", "body": "Right so since I'm not changing the value or address pointed two should I use two `const` on each variable e.g. `char const * const find`? Perhaps that's a question by itself..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T09:40:07.493", "Id": "51573", "Score": "0", "body": "`char const * const find` would be a bit like `const int len` — correct, but superfluous and unimportant from the caller's point of view." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T08:50:34.790", "Id": "32278", "ParentId": "32277", "Score": "2" } }, { "body": "<p>A few comments:</p>\n\n<ul>\n<li><p>I don't much like double pointers so I would probably define a type to be passed:</p>\n\n<pre><code>typedef const char* String;\n</code></pre>\n\n<p>Then let's define the function </p>\n\n<pre><code>int binSrch(const String *list, size_t len, const char *find)\n</code></pre>\n\n<p>You can still pass an array of char* to this. I have added some <code>const</code>, used <code>size_t</code> for the array length (which is common with standard library functions) and replaced the <code>bool</code> with an <code>int</code> - which I prefer.</p></li>\n<li><p>Your code duplicates this line:</p>\n\n<pre><code>middle = (first+last)/2;\n</code></pre>\n\n<p>and uses different spacing for each. Just do it once.</p></li>\n<li><p>Your brackets are inconsistent. I prefer to see brackets even when not strictly needed.</p></li>\n<li><p>Your duplicate <code>strcmp</code> calls should be removed.</p></li>\n</ul>\n\n<p>Here is how it ends up:</p>\n\n<pre><code>int binSrch(const String *list, size_t len, const char *find)\n{\n int start = 0;\n int end = len;\n while (start &lt; end) {\n int middle = (start + end) / 2;\n int comp = strcmp(list[middle], find);\n if (comp &lt; 0 ) {\n start = middle + 1;\n }\n else if (comp &gt; 0) {\n end = middle;\n }\n else return 1;\n }\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:33:21.813", "Id": "32541", "ParentId": "32277", "Score": "0" } } ]
{ "AcceptedAnswerId": "32278", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T08:16:19.720", "Id": "32277", "Score": "1", "Tags": [ "c", "binary-search" ], "Title": "Binary search on cstrings" }
32277
<p>Here, this vector was used at many APIs in the code with sync block on it. And all the places they want to search another collection based on each <code>itr.next()</code>.</p> <pre><code>synchronised(vector) { Iterator itr = vector.iterator(); while (itr.hasNext) { //Perform some search on another collection using the value from itr.next() :: THIS IS COSTLY JOB WITH SYNCH BLOCK //If that collection doesn't have any entry for itr.next() then perform itr.remove(); } } </code></pre> <p>This is like a vector of conference IDs. Using each conference ID, it gets a conference from list of conferences, then searches again for a user within that conference having user ID from list of users available in that conference.</p> <p>As stated above: now the sync block is doing a time-consuming search job on another objects. And other threads keep waiting for this vector lock. And the total number of threads in the blocked state increases much while load testing.</p> <p>I changed the code from <code>Vector</code> to <code>Collections.newSetFromMap(new ConcurrentHashMap&lt;psConference,Boolean&gt;())</code>. I assume that, since this is concurrent collection, no <code>ConcurrentModificationException</code> while performing iteration. Add/remove operations while iteration is allowed here, so I have removed all sync block in my code.</p> <p>But I come to know from <code>ConcurrentHashMap</code> Java doc:</p> <blockquote> <p>iterators are designed to be used by only one thread at a time.</p> </blockquote> <p>From the above, I think I have moved the sync block problem from my code to the Java API. There is no advantage over this change.</p> <p>I finally found the best return copy of original vector collection each time any APIs requires that vector of conference IDs. Let the iteration happen on this new vector with that costly searching and other jobs and then finally perform the remove separately.</p> <pre><code>Vector newVectorObject = mgr.getCopyOfVector(); List toBedeleted = new ArryList(); Iterator itr = newVectorObject .iterator(); while (itr.hasNext) { //Perform some search on another collection using itr.next() //If that collection doesn't have any entry for itr.next() then perform toBedeleted.add(itr.next()) } mgr.removeVector(toBedeleted); public Vector getCopyOfVector(){ return new Vector(vector); } public Vector removeVector(List toBedeleted){ return vector.removeAll(toBedeleted); } </code></pre> <p>I think in this case, no lock is required on the vector. No threads will be blocked.</p>
[]
[ { "body": "<p>It looks like you are trying to re-invent the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html\" rel=\"nofollow\">CopyOnWriteArrayList</a>.</p>\n\n<p>By the way, <code>Vector</code> is very old fashioned, but I guess you are working with legacy code. The code also does not use generics. CopyOnWriteArrayList started with Java 5, so might not be able to use it if you are stuck with an older Java version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T14:55:54.080", "Id": "32285", "ParentId": "32280", "Score": "1" } }, { "body": "<p>Just some thoughts:</p>\n\n<ul>\n<li>For your list use a <code>Collections.newSynchronizedList(new\nArrayList&lt;ConferenceID&gt;())</code>, only perform <code>add()</code>, <code>remove()</code> or <code>addAll()</code>, don't use <code>Iterator</code>s. That way the <code>synchronized</code> blocks will be short.</li>\n<li>When you start processing, insert(copy) all the <code>ConferenceID</code> objects into a <code>BlockingQueue</code>. This <code>BlockingQueue</code> is consumed by some thread(s) that run the (time consuming) Job. </li>\n<li>Use some <code>ExecutorService</code> with <code>Futures</code> (eg. <code>Futures&lt;Tuple&lt;ConferenceId, Boolean&gt;&gt;</code>) for the jobs to indicate if the processed <code>ConferenceID</code> has to be removed.</li>\n<li>Remove the <code>ConferenceID</code> from your original list if necessary once the job has finished.</li>\n</ul>\n\n<p>Keep your <code>synchronized</code> blocks as short as possible. Have you many objects in the list? (Because you copy them every time you start your processing).</p>\n\n<p>I also like idea with the <code>CopyOnWriteArrayList</code>, as @toto2 mentioned. But you have to be careful, since writes are expensive and the <code>Iterator</code> does not support modifying operations.</p>\n\n<p>That being said, Java is fast with object creation/deletion. So you have to try out. It is more likely that you end up starving because some resource is blocked(<code>synchronized</code>), so creating copies should be a good idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T16:35:10.177", "Id": "32291", "ParentId": "32280", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T12:55:48.223", "Id": "32280", "Score": "1", "Tags": [ "java", "thread-safety" ], "Title": "Synchronized block over concurrent collections" }
32280
<p>This Review Request evolves into <a href="https://codereview.stackexchange.com/questions/32348/kings-drinking-game-review-request-2-0-jform-gui">this Review Request</a> now with a custom UI and other changes.</p> <p>I wrote a program to simulate the drinking card game Kings. This is my third Java Project. I didn't quite understand how to create the classes <code>Card</code> and <code>Deck</code>. I was struggling to create them so I went ahead and used someones code who had made them in a tutorial. But I think I get it now.</p> <p>I plan on adding a main menu in the <code>PSVM</code> under a <code>while-true</code> <code>loop</code> with a similar structure to the one in <code>playGame()</code>.</p> <p>I would like a review of my code and some pointers on making it more efficient, cleaner, easier to read, or any other general pointers you have.</p> <p>The explanation of the game is in the code comment box here:</p> <pre><code> /** * @author :KyleMHB * Project Number :0003 * Project Name :Kings * IDE :NETBEANS * Goal of Project - * Kings is a rule based drinking game using cards for 4+ players. * The Rules are read in from a rules.txt so that one can easily change the rules. * How the game works: * Players shuffle a deck of cards, place a glass between them and circle the * cards around the base of the glass. * The players then take turns picking cards, each card has its own rule associated to it. * Most importantly, there are 4 Kings, each time a King is picked, * the player who picked it can pour as much of his/her drink into the glass between * them as they wish. * The game ends when the fourth and final King is picked. * The player to pick the final King must down the glass in the center of table. */ </code></pre> <hr> <p><strong>Card Class:</strong></p> <pre><code>public static class Card { private int rank, suit; private String[] suits = { "Hearts", "Spades", "Diamonds", "Clubs" }; private String[] ranks = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" }; Card(int suit, int rank){ this.rank=rank; this.suit=suit; } public @Override String toString(){ return ranks[rank] + " of " + suits[suit]; } public int getRank() { return rank; } public int getSuit() { return suit; } } </code></pre> <p><strong>Deck Class</strong></p> <pre><code>public static class Deck { private static ArrayList&lt;Card&gt; cards; Deck() { cards=new ArrayList&lt;Card&gt;(); for (int a=0; a&lt;=3; a++){ for (int b=0; b&lt;=12; b++){ cards.add( new Card(a,b) ); } } Collections.shuffle(cards, new Random()); Collections.shuffle(cards, new Random(System.nanoTime())); //double shuffle for randomness } public Card drawFromDeck(){ return cards.remove( 0 ); } public int getTotalCards(){ return cards.size(); } } </code></pre> <p><strong><code>PSVM()</code> and <code>rules</code> declaration:</strong></p> <pre><code>private static List&lt;String&gt; rules; public static void main(String[] args) throws FileNotFoundException, IOException { setGameRules(new File("rules.txt")); playGame(getNum("How many people are going to play","Number of Players")); } </code></pre> <p><strong><code>setRules()</code> Method:</strong></p> <pre><code>/** * Rules are not hard-coded because people often have different ones, * Therefore I made an easily editable rules.txt file. * Also my rule file has formatting in using the \n, * However when the file is read it is read as \ and n * Hence why I used the replaceAll( "\\\\n","\n"); */ private static void setRules(File f) throws FileNotFoundException, IOException { rules = Files.readAllLines(f.toPath(), Charset.defaultCharset()); for(int i=0; i!=rules.size(); i++){ rules.set(i, rules.get(i).replaceAll( "\\\\n","\n")); } } </code></pre> <p><strong><code>getNum()</code> Method:</strong></p> <pre><code>//This method was left as getNum because I will use it later for a Main Menu private static int getNum(String prompt,String title) { return Integer.parseInt(JOptionPane.showInputDialog(null,prompt,title,3)); } </code></pre> <p><strong><code>playGame()</code> Method:</strong></p> <pre><code>private static void playGame(int players) { int playerTurn; int choice; int kings=0; Card cardDrawn; Deck deck=new Deck(); while(true){//loop to run the game till the 4th king is drawn playerTurn=0; while (playerTurn!=players){//used to give each player a turn choice=getChoice("Player "+(playerTurn+1), "Would you like to skip or draw?","Draw","Skip","Exit"); if (choice==0){ cardDrawn=deck.drawFromDeck(); System.out.println(cardDrawn); kings+=showCard(cardDrawn,kings,playerTurn+1); playerTurn++; } else if(choice==1) playerTurn++; else System.exit(0); }//Turn reset loop }//continuous loop } </code></pre> <p><strong><code>getChoice()</code> Method:</strong></p> <pre><code>//this method is used so that I can reuse it later in the main menu. private static int getChoice(String title, String prompt, String a, String b, String c) { Object[] options = { a, b, c}; return JOptionPane.showOptionDialog(null, prompt, title,0,2, null,options,options[0]); } </code></pre> <p><strong><code>showCard()</code> Method:</strong></p> <pre><code>//The method name was originally checkIfKing(), I think this is better? private static int showCard(Card a, int kings, int player) { if(a.rank==12)//checks if the card is a King if(kings==3){//checks if the card is the final King JOptionPane.showMessageDialog(null, "Player "+player+" has Drawn the Final King\n\n" + "Restart the Program to Play again",a.toString(),1); System.exit(0); return 0; } else{ JOptionPane.showMessageDialog(null,"Player "+player+ " has drawn the "+a.toString()+"\n" + "Which is King "+(kings+1)+"/4\n\n" +rules.get(a.rank),a.toString(),1); return 1; } else{ JOptionPane.showMessageDialog(null,"Player "+player+ " has drawn the "+a.toString()+"\n\n" + rules.get(a.rank),a.toString(),1); return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T00:54:39.903", "Id": "51602", "Score": "0", "body": "If the game loop runs until the 4th king is drawn (per comments), then why is the loop condition `while(true)`? If the loop condition was based on the 4th king being drawn you wouldn't need a comment there." } ]
[ { "body": "<p>Your code has exceptionally tight coupling between the business code (the actual implementation of the game) and the user interface code. This means I can't easily reuse your code e.g. to play it on the command line instead of the GUI you have implemented.</p>\n\n<p>You can achieve this seperation by defining an interface for all UI operations. In your <code>main</code>, you can then decide which UI implementation you want to use.</p>\n\n<pre><code>interface UserInterface {\n public int numberOfPlayers();\n public boolean playerWantsToDrawCard(int player); // if false: skip\n public void showCard(Card card, int player, boolean last);\n}\n</code></pre>\n\n<p>Your existing methods would then be refactored into a <code>GraphicalUserInterface implements UserInterface</code>. Note that this is a <em>different</em> abstraction than yours – the implementation you have shown abstracts over <em>what</em> is shown, but hardcodes <em>how</em> this is done. I'd rather do this the other way round.</p>\n\n<p>With that new interface, your <code>playGame</code> would be changed to:</p>\n\n<pre><code>private static void playGame(UserInterface ui) {\n int players = ui.numberOfPlayers();\n int kings = 0\n Deck deck = new Deck();\n\n while (!deck.isEmpty()) {\n for (int player = 0; player &lt; players; player++) {\n // players do not have to draw a card\n if (!ui.playerWantsToDrawCard(player)) {\n continue;\n }\n\n Card drawnCard = deck.draw();\n\n if (drawnCard.getRank() == Rank.KING) {\n kings++;\n }\n ui.showCard(drawnCard, player, kings == 4 || deck.isEmpty());\n\n // exit if we've seen all kings\n if (kings == 4) {\n return;\n }\n }\n }\n}\n</code></pre>\n\n<p>While this assumes some further changes (e.g. to the <code>Deck</code> API), the main point is that the business logic doesn't have to deal with UI directly. Other important changes are:</p>\n\n<ul>\n<li>I use a <code>for</code> loop to iterate through all players instead of obfuscating this through another <code>while</code> loop.</li>\n<li>I declare my variables in the tightest scope possible. The <code>drawnCard</code> is not needed outside the inner loop, so I declare it there. As a rule of thumb, you shouldn't declare variables without initializing them directly.</li>\n</ul>\n\n<p>One thing that isn't immediately obvious, but I let the <code>ui.showCard</code> method figure out wether this card was a king, and wether this was the last king. The only hint I have to provide is whether this was the last card in the game.</p>\n\n<hr>\n\n<p>One thing I haven't explained yet is <code>Rank.KING</code>. In your original code, you have hardcoded <code>12</code>, which doesn't explain anything to a reader of the code. Currently, you specify the suit and rank of each card using integers. This is arguably wrong, and you should be using an enum:</p>\n\n<pre><code>enum Rank {\n ACE (\"Ace\"),\n TWO (\"2\"),\n THREE (\"3\"),\n FOUR (\"4\"),\n FIVE (\"5\"),\n SIX (\"6\"),\n SEVEN (\"7\"),\n EIGHT (\"8\"),\n NINE (\"9\"),\n TEN (\"10\"),\n JACK (\"Jack\"),\n QUEEN (\"Queen\"),\n KING (\"King\");\n\n String name;\n\n Rank(String name) {\n this.name = name;\n }\n}\n</code></pre>\n\n<p>Ditto for <code>Suit</code>. Now our <code>Card</code> looks like</p>\n\n<pre><code>class Card {\n private Rank rank;\n private Suit suit;\n\n public String toString() {\n return rank.toString() + \" of \" + suit.toString();\n }\n\n ...\n}\n</code></pre>\n\n<p>with the remaining methods having updated their types. Using enums allows for more type safety, and automatic additions like comparability and a iterable view of all possible values. This allows us to construct the deck like</p>\n\n<pre><code>cards = new ArrayList&lt;Card&gt;();\nfor (Suit suit : Suit.values()) {\n for (Rank rank : Rank.values()) {\n cards.add(new Card(suit, rank));\n }\n}\nCollections.shuffle(cards, new Random());\n</code></pre>\n\n<p>Btw, shuffling once is “random” enough, and additional shuffling does not increase randomness. If you need a true cryptography-grade entropy source, the builtin pseudo-random number generator which <code>new Random()</code> gives you is <em>not sufficient</em>. But for the purpose of this game, its usage is quite allright.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T16:41:17.057", "Id": "51580", "Score": "0", "body": "Thanks for the reply I have implemented a few code changes. \n\nHowever, if I use an enum for the rank how will I call the rule for that card?\n\nLook at how this outputs:\n`display(\"Player \"+player+\" has drawn the \"+card+\"\\n\\n\"+rules.get(a.rank),card);`\n\nI built a display method to make it easier to use a custom UI." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T16:53:20.827", "Id": "51585", "Score": "0", "body": "I added a `getRule()` method that uses the `for(Rank rank: Rank.value())` to iterate through the ranks with an `if(card.rank==rank)` then call the rule with the counter at that point. Works like a charm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T17:02:26.677", "Id": "51586", "Score": "0", "body": "@KyleMHB Sorry, I didn't see that problem when I wrote my code. I think there is an `ordinal()` method on enum constants that returns the position – use it as an index." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T17:33:33.403", "Id": "51588", "Score": "0", "body": "Ah man... Thats so simple! `ordinal();` works much better. I made like this snazzy little iterative check I even felt clever :(" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T14:50:40.330", "Id": "32284", "ParentId": "32281", "Score": "5" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/32284/30349\">Following from this answer</a>\nThese changes were made:</p>\n\n<p><strong><code>Enum</code>s Added for both Rank and Suit:</strong></p>\n\n<pre><code>enum Rank {\n ACE (\"Ace\"),\n TWO (\"2\"),\n THREE (\"3\"),\n FOUR (\"4\"),\n FIVE (\"5\"),\n SIX (\"6\"),\n SEVEN (\"7\"),\n EIGHT (\"8\"),\n NINE (\"9\"),\n TEN (\"10\"),\n JACK (\"Jack\"),\n QUEEN (\"Queen\"),\n KING (\"King\");\n String name;\n Rank(String name) {\n this.name = name;\n }\n} \n\nenum Suit {\n HEARTS (\"Hearts\"),\n DIAMONDS (\"Diamonds\"),\n SPADES (\"Spades\"),\n CLUBS (\"Clubs\");\n String name;\n Suit(String name) {\n this.name = name;\n }\n}\n</code></pre>\n\n<p><strong><code>Card Class</code> changed:</strong></p>\n\n<pre><code>public static class Card {\n private Rank rank;\n private Suit suit;\n\n Card(Suit suit, Rank rank){\n this.rank=rank;\n this.suit=suit;\n }\n public @Override String toString(){\n return rank.toString() + \" of \" + suit.toString();\n }\n}\n</code></pre>\n\n<p><strong><code>Deck Class</code> was changed:</strong></p>\n\n<pre><code>public static class Deck {\n private static ArrayList&lt;Card&gt; cards;\n Deck() {\n cards=new ArrayList&lt;Card&gt;();\n for (Suit suit : Suit.values()){\n for (Rank rank : Rank.values()){\n cards.add( new Card(suit,rank));\n }\n }\n Collections.shuffle(cards, new Random());\n Collections.shuffle(cards, new Random(System.nanoTime()));\n //this double shuffle STILL provided me with better results.\n }\n public Card drawFromDeck(){ \n return cards.remove(0);\n }\n}\n</code></pre>\n\n<p><strong><code>playGame()</code> Method Changed:</strong></p>\n\n<pre><code>private static void playGame(int players) {\n int kings=0;\n Deck deck=new Deck();\n while(true){//Its impossible to reach the end of the deck so I stuck with this\n for (int playerTurn=0;playerTurn!=players;playerTurn++){//changed from a while\n int choice=getChoice(\"Player \"+(playerTurn+1),\n \"Would you like to skip or draw?\",\n \"Draw\",\"Skip\",\"Exit\");\n\n if (choice==0){\n Card cardDrawn=deck.drawFromDeck();\n kings+=checkIfKing(cardDrawn,kings,playerTurn+1); \n } \n else if(choice==2)\n System.exit(0); \n }//forloop\n }//continuous loop\n}\n</code></pre>\n\n<p><strong><code>showCard()</code> Method renamed to <code>checkIfKing()</code>:</strong></p>\n\n<p>The problem here was that previously to display the rule for the card picked I used <code>rules.get(a.rank)</code> as <code>a.rank</code> was an <code>int</code> that matched the position of that card in the <code>rules</code> list. so I created a <code>getRule()</code></p>\n\n<pre><code>private static int checkIfKing(Card a, int kings, int player) {\n String card=a.toString();\n if(a.rank==Rank.KING)//easier to read using enums\n if(kings==3){\n display(\"Player \"+player+\" has Drawn the Final King\\n\\n\"+\n getRule(a)+\"\\n\\n\"+\n \"Restart the Program to Play again\",card);\n System.exit(0);\n return 0;\n }\n else{\n display(\"Player \"+player+\" has drawn the \"+card+\"\\n\"\n + \"Which is King \"+(kings+1)+\"/4\\n\\n\"\n +getRule(a),card);\n return 1;\n }\n else{\n display(\"Player \"+player+\" has drawn the \"+card+\"\\n\\n\"\n +getRule(a),card);\n return 0;\n }\n}\n</code></pre>\n\n<p><strong><code>getRule()</code> Method created:</strong></p>\n\n<p><strike>Made a clever little adaption using a for loop and a counter</strike>\n<code>ordinal();</code> was used.</p>\n\n<pre><code>private static String getRule(Card card){\n return rules.get(card.rank.ordinal()); \n}\n</code></pre>\n\n<p><strong><code>display()</code> Method was created:</strong></p>\n\n<p>This was made to make it a bit easier to use your own UI like amon wanted. Its not overly helpful bu this program is built for JOptionPane anyway. And it neatens up my code in the other methods.</p>\n\n<pre><code>private static void display(String prompt, String title) {\n JOptionPane.showMessageDialog(null,prompt,title,1);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T22:15:39.060", "Id": "51597", "Score": "0", "body": "Loose coupling isn't \"helpful\" in terms of \"getting the thing to work\" - Mark Seeman accurately depicts tight coupling as a hairdryer that's hardwired into a cheap hotel room's wall; with loose coupling you have a socket instead, and changing the hairdryer for another one or plugging a laptop instead isn't complicated anymore. And it makes cleaner code, but that's almost a side-effect! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T17:24:40.197", "Id": "32296", "ParentId": "32281", "Score": "1" } } ]
{ "AcceptedAnswerId": "32284", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T13:19:38.437", "Id": "32281", "Score": "3", "Tags": [ "java", "optimization", "game", "collections", "playing-cards" ], "Title": "Kings Drinking Game" }
32281
<p>I have written this program to compute the leading set of the following productions</p> <pre><code>E-&gt;E+T E-&gt;T T-&gt;T*F T-&gt;F F-&gt;(E) F-&gt;# </code></pre> <p>Here identifier is taken as '#'</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;conio.h&gt; #include&lt;ctype.h&gt; struct leadT { int n; char lead[5]; }; struct leadT leading[7]; char ip[7][7]; int col,cnt=0; char Sym[5]={ '+','(',')','*','#','i' }; int isSym(char); void findLeading(char,int); void leadTabOp(char,int); void main() { int i,j,c; char b[4]; for(i=0;i&lt;=5;i++) { scanf("%s",&amp;ip[i]); } printf("\n"); for(i=0;i&lt;6;i++) { c=0; for(j=0;j&lt;i+1;j++) { if(ip[i][0] == b[j]) { c=1; break; } } if(c !=1) { b[cnt] = ip[i][0]; cnt++; } } for(i=cnt-1;i&gt;=0;i--) { leading[i].n=0; col=1; leading[i].lead[0]=b[i]; findLeading(b[i],i); } printf("\n"); for(i=0;i&lt;cnt;i++) { for(j=0;j&lt;=leading[i].n;j++) { if(j==0) { printf("leading(%c) = { ",leading[i].lead[j]); } else if(j == leading[i].n) { printf("%c ",leading[i].lead[j]); } else { printf("%c,",leading[i].lead[j]); } } printf("}"); printf("\n"); } } int isSym(char ip) { int i; for(i=0;i&lt;5;i++) { if(ip==Sym[i]) { return 1; } } return 0; } void findLeading(char p,int row) { int i; for(i=5;i&gt;=0;i--) { if(p == ip[i][0]) { if((ip[i][2] == '&gt;') &amp;&amp; (ip[i][4]=='\0')) { if(isupper(ip[i][3])) { leadTabOp(ip[i][3],row); } else { leading[row].lead[col]=ip[i][3]; leading[row].n++; col++; } } if( (ip[i][2] == '&gt;') &amp;&amp; ( isupper(ip[i][3]) ) &amp;&amp; ( isSym( ip[i][4] ) ) ) { leading[row].lead[col]=ip[i][4]; col++; leading[row].n++; } if( ( ip[i][2] == '&gt;') &amp;&amp; ( isSym( ip[i][3] ) ) &amp;&amp; ( isupper( ip[i][4] ) ) ) { leading[row].lead[col]=ip[i][3]; col++; leading[row].n++; } } } } void leadTabOp(char p,int row) { int i,j; for(i=0;i&lt;cnt;i++) { if(p == leading[i].lead[0]) { for(j=1;j&lt;=leading[i].n;j++) { leading[row].lead[col]=leading[i].lead[j]; col++; leading[row].n++; } } } } </code></pre> <p>Please review this.</p>
[]
[ { "body": "<p>You should structure your code a bit better and improve your naming conventions.</p>\n\n<p>The first loop in <code>main()</code> apparently scans 6 strings into <code>ip</code>. From that I might deduce that <code>ip</code> is supposed to hold your input. So name it <code>input</code> or even <code>inputProductions</code>. Current IDEs support code completion so not using longer names for the sake of less typing is not a valid argument. </p>\n\n<p>You could also put that code into a separate function <code>readInput(char **result)</code>. Later you can adjust how you read your input without changing <code>main</code>.</p>\n\n<p>Then you have a couple of nested loops which compute some values to be stored in <code>b</code> and a value <code>c</code>. Using <code>i</code> and <code>j</code> as loop counter is accepted practice so that's ok but what are <code>b</code> and <code>c</code> supposed to represent? Give them names which express their meaning.</p>\n\n<p>Also your outer loop counter <code>i</code> can go up to 5 and <code>j &lt; i + 1</code> means <code>j</code> can go up to 5 as well. <code>b</code> is only an array with 4 elements, so the last index you are allowed to access is 3 and <code>b[j]</code> would be out of bounds for any <code>j &gt; 3</code>.</p>\n\n<p>If that nested for loop is supposed to do some pre-processing then put it into a function and give it a sensible name which expresses what it is doing.</p>\n\n<p>You have a variable called <code>cnt</code> - what exactly is it that you are counting? Name the variable accordingly.</p>\n\n<p>Your functions access global variables like <code>cnt</code> or <code>ip</code>. You should pass all data those functions require as parameters. There is not need to create implicit dependencies.</p>\n\n<p>Organize your code so its concerns are separated: input parsing, data processing, output. Your <code>main</code> function should read something like this:</p>\n\n<pre><code>int main()\n{\n char input[7][7];\n char b[4];\n int count;\n\n if (!readInput(input))\n {\n puts(\"Failed to read input.\");\n return -1;\n }\n\n count = preProcessInput(input, b);\n if (count &lt; 0)\n {\n puts(\"Failed to pre-process input\");\n return -2;\n }\n\n if (!findLeadingSet(input, b, leadingSet, count))\n {\n puts(\"Failed to process input\");\n return -3;\n }\n\n printLeadingSet(leadingSet);\n\n return 0;\n}\n</code></pre>\n\n<p>This makes the structure immediately clear and explains what the steps are without having to read all the code and trying to understand it (apparently <code>preProcessInput</code> should be named as to what it is actually pre-processing).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T00:52:10.900", "Id": "32311", "ParentId": "32282", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T13:29:04.300", "Id": "32282", "Score": "0", "Tags": [ "c", "parsing" ], "Title": "Computing leading set (compiler design)" }
32282
<p>I'm using Bootstrap 3 as the front-end framework for this. It is quite simple but I feel I'm doing it wrong. I'm sure this code can be optimized not to duplicate the $('a[href=""]') functions but I just can't wrap my head around it.</p> <p>For now, this code is only for mobile. I'll have to figure out how to control the menu behavior for larger screens (not requested at this time).</p> <p><a href="http://jsfiddle.net/ttc1/zXe7C/3/" rel="nofollow noreferrer">jsFiddle</a> (you need to resize your browser to see the effect)</p> <pre><code>$(document).ready(function () { /* * Modification du boutton MENU pour CLOSE */ $('button').on('click', function(e){ var str = $(this).text(); if(str =="CLOSE"){ $(this).html("MENU"); } else{ $(this).html("CLOSE"); } if(str == "MAIN MENU"){ e.stopPropagation(); $('#menuContacts').css('display', 'none'); $('#menuWines').css('display', 'none'); $('#menuMain').css('display', 'block'); $('button').html('CLOSE'); } }); /* * Modification du menuMain pour le menuContacts */ $('a[href="#contacts"]').on('click', function(e){ e.preventDefault(); $('#menuMain').css('display', 'none'); $('#menuContacts').css('display', 'block'); $('button').html('MAIN MENU'); }); /* * Modification du menuMain pour le menuWine */ $('a[href="#wines"]').on('click', function(e){ e.preventDefault(); $('#menuMain').css('display', 'none'); $('#menuWines').css('display', 'block'); $('button').html('MAIN MENU'); }); }); </code></pre>
[]
[ { "body": "<p>you can add some data attribute to the HTML like this </p>\n\n<pre><code>&lt;ul id=\"menuMain\" class=\"nav navbar-nav\"&gt;\n &lt;li&gt;&lt;a href=\"#preface\"&gt;Préface&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#maison\"&gt;Maison Ilan&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#history\"&gt;History&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#vineyard\"&gt;Vineyard&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#cuverie\"&gt;Cuverie&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#chai\"&gt;Chai&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#wines\" data-menu=\"#menuWines\"&gt;Wines&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#contacts\" data-menu=\"#menuContacts\"&gt;Contacts&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt; \n</code></pre>\n\n<p>so instead of .on('click') for each link you can do something like this </p>\n\n<pre><code>//all the links in #menuMain\n$('#menuMain a').on('click', function(e){\n e.preventDefault();\n $('#menuMain').css('display', 'none');\n//$(this).data(\"menu\") have the id of the element to display\n $($(this).data(\"menu\")).css('display', 'block');\n $('button').html('MAIN MENU');\n}); \n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/zXe7C/4/\" rel=\"nofollow\">http://jsfiddle.net/zXe7C/4/</a><br>\nfor the example i only add the data attribute to the last two links but if you dont have something on the attribute or some element with that id then it will only hide \"menuMain\" but you can check first if the element $($(this).data(\"menu\")) exists</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:38:19.210", "Id": "51862", "Score": "0", "body": "Thanks a lot for your help @Abraham Uribe. It works just great as it is. Using data-menu is pretty clever, from a junior perspective as I am, anyways. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:55:11.040", "Id": "51864", "Score": "0", "body": "One little quirks though, if you click on a menu that doesn't have the data-menu attribute, the button reverts back to MAIN MENU instead of MENU." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:19:18.953", "Id": "51869", "Score": "0", "body": "if it need to revert to MENU then you can check if the element exists then change the html to menu" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:24:25.703", "Id": "51871", "Score": "1", "body": "Yes. Just solved it using your check idea in your initial response \"$(this).data(\"menu\")\"[jsFiddle](http://jsfiddle.net/ttc1/zXe7C/14/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:31:43.923", "Id": "51872", "Score": "0", "body": "also it will be good to change `$('button')` for some id like `$('#menubutton')` and add the id to your html so you could add more `<button>` without problems" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T17:02:43.213", "Id": "51883", "Score": "0", "body": "Thanks for your advice. Though, on this particular project, no other button will be used. Thanks again for your help @Abraham Uribe. It is much appreciated." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T18:24:41.917", "Id": "32429", "ParentId": "32288", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T15:28:23.190", "Id": "32288", "Score": "1", "Tags": [ "javascript", "performance", "jquery" ], "Title": "Optimizing jQuery functions for mobile menu" }
32288
<p>I am doing old versions of the Canadian Computing Competition, on a website where I can run my solution against some test cases they have. I am failing one of their test cases, and cannot figure out why. I have no access to the test case.</p> <p>I have posted below the full problem description as well as my attempted solution in C++.</p> <p><strong>The Problem</strong></p> <p>You are a salesperson selling trucks which can carry trucks which can carry trucks. Needless to say, your trucks are heavy. Also needless to say, you have to drive one of these trucks across a wide wet domain, and since it is wet, you need to drive over some bridges. In fact, on every road between two cities, there is a bridge but there is not a direct road between every pair of cities.</p> <p>Each bridge can support a certain maximum weight. This maximum weight is an integer from 0 to 100,000.</p> <p>You have been given a list of cities where there are customers who are eager to view one of your trucks. These cities are called destination cities. Since you must decide which truck you will drive through these cities, you will have to answer the following problem: what is the maximum weight that can be driven through these destination cities? You are to write a program to solve this problem.</p> <p><strong>Input</strong></p> <p>The first line of input will contain three positive integers: c, r and d specifying the number of cities (in total), number of roads between cities and number of destination cities, respectively. The cities are numbered from 1 to c. There are at most 10,000 cities and at most 100,000 roads.</p> <p>The next r lines contain triples x y w indicating that this road runs between city x and city y and it has a maximum weight capacity of w. The next d lines give the destination cities you must visit with your truck. There will be at least one destination city.</p> <p>You can assume that you are starting in city 1 and that city 1 is not a destination city. You can visit the d destination cities in any order, but you must visit all d destination cities.</p> <p><strong>Output</strong></p> <p>The output from your program is a single integer, the largest weight that can be driven through all d destination cities.</p> <p><strong>Sample Input</strong></p> <pre><code>5 7 3 1 2 20 1 3 50 1 4 70 1 5 90 2 3 30 3 4 40 4 5 60 2 4 5 </code></pre> <p><strong>Sample Output</strong></p> <pre><code>30 </code></pre> <p><strong>My Solution</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; using namespace std; const int MAX_WEIGHT = 100000; /** * Extremely basic implementation of a min function. */ int min (int a, int b) { return a &lt; b ? a : b; } void getRoads (int** M, int numRoads) { int weight, r; // weights and road indices are int unsigned short from, to; // city indices are u_short for (r = 0; r &lt; numRoads; r++) { scanf ("%hu %hu %d", &amp;from, &amp;to, &amp;weight); // deals with case of parallel edges if (M [from - 1][to - 1] &lt; 0 || weight &lt; M [from - 1][to - 1]) { // since all this shit is indexed from 1 M [from - 1][to - 1] = weight; M [to - 1][from - 1] = weight; } } } void getDest (bool* dest, unsigned short numDest) { unsigned short c, d; for (c = 0; c &lt; numDest; c++) { scanf ("%hu", &amp;d); // still indexed from 1 dest[d - 1] = true; } } int tally (int* A, bool* dest, unsigned short numCities) { int m = MAX_WEIGHT + 1; for (unsigned short c = 0; c &lt; numCities; c++) { if (dest[c] &amp;&amp; A[c] &lt; m) { m = A[c]; } } return m; } int main () { int numRoads, next; // using int for weights and road indices unsigned short numCities, numDest, c, c2; // using u_short for cities scanf("%hu %d %hu", &amp;numCities, &amp;numRoads, &amp;numDest); if (numDest &gt; numCities) { // invalid input return 1; } if (numDest == 0) { // trivial case printf("0\n"); return 0; } // create Matrix int** M = new int* [numCities]; for (c = 0; c &lt; numCities; c++) { M[c] = new int [numCities]; memset(M[c], -1, numCities * sizeof(int)); } getRoads (M, numRoads); // create destination array // for each city c, true iff c is a destination bool dest [numCities]; memset (dest, false, numCities); getDest (dest, numDest); // create dynamic programming array // keeps a record of smallest weight to each city int A [numCities]; memset (A, 0, numCities * sizeof (int)); // implementing a set in N + 1 bits. // updated vertices are flagged with a 1 // isEmpty set to true at beginning of pass, then if true at end of pass, is really empty bool isEmpty = false; bool Q [numCities]; memset(Q, false, numCities); Q[0] = true; while (! isEmpty) { isEmpty = true; for (c = 0; c &lt; numCities; c++) { if (! Q[c]) { continue; } else { Q[c] = false; } // don't look at edges which lead back to origin for (c2 = 1; c2 &lt; numCities; c2++) { if (c == c2 || M[c][c2] &lt; 0) continue; // only happens when c == 0 (hopefully) if (A[c] == 0) { next = M [c][c2]; } else { next = min(M [c][c2], A[c]); } if (next &gt; A[c2]) { A [c2] = next; Q[c2] = true; isEmpty = false; } } } } printf("%d\n", tally (A, dest, numCities)); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T18:47:11.033", "Id": "51591", "Score": "3", "body": "I've voted to keep this open despite @BlackSheep's admission that it gives incorrect results, because it does give the correct output for the sample input. According to the [Help Center](http://codereview.stackexchange.com/help/on-topic), \"correctness in unanticipated cases\" is on-topic." } ]
[ { "body": "<p>As far as I can tell, the only thing blocking your code from producing valid output is one line in <code>getRoads</code>. When loading the input, your code saves the <em>lowest</em> weight between two points rather than the <em>highest</em>.</p>\n<pre><code> if (M [from - 1][to - 1] &lt; 0 || weight &lt; M [from - 1][to - 1]) {\n</code></pre>\n<p>should instead be:</p>\n<pre><code> if (weight &gt; M [from - 1][to - 1]) {\n</code></pre>\n<p>The suggestion that this was the only problem is based on the test cases <a href=\"http://mmhs.ca/ccc/index.htm#2003%20Problems\" rel=\"nofollow noreferrer\">posted here</a> and the assumption that I followed the algorithm in your code correctly.</p>\n<hr />\n<h3>Off-Topic Bonus Note:</h3>\n<p><code>memset</code> works per byte, not - for example - per <strong>int</strong>. It works in your code for reasons <a href=\"https://stackoverflow.com/a/7202474\">explained here</a>, namely:</p>\n<blockquote>\n<ul>\n<li>0 is an exception since, if you set all the bytes to 0, the value will be zero</li>\n<li>-1 is another exception since, as Patrick highlighted -1 is 0xff (=255) in int8_t and 0xffffffff in int32_t</li>\n</ul>\n</blockquote>\n<p>It is safer to loop over the array and initialize each object for non byte-sized objects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T02:37:38.557", "Id": "32357", "ParentId": "32294", "Score": "2" } } ]
{ "AcceptedAnswerId": "32357", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T17:00:35.983", "Id": "32294", "Score": "0", "Tags": [ "c++", "optimization", "graph" ], "Title": "2003 Canadian Computing Competition, Stage 1 ; Why Is My Solution Invalid?" }
32294
<p>I am trying to find the uncommon elements from two sets in Java. Here is my way:</p> <pre><code>private void findUnCommon{ Set&lt;Integer&gt; a = new HashSet&lt;&gt;(Arrays.asList(1, 2, 3, 4)); Set&lt;Integer&gt; b = new HashSet&lt;&gt;(Arrays.asList(3, 4, 5, 6)); // get all elements from set a and set b System.out.println("Before.."); System.out.println("a is : " + a); System.out.println("b is : " + b); Set&lt;Integer&gt; result = new HashSet&lt;&gt;(a); result.removeAll(b); System.out.println("result is : " + result); Set&lt;Integer&gt; temp = new HashSet&lt;&gt;(b); temp.removeAll(a); System.out.println("temp is : " + temp); result.addAll(temp); System.out.println("Uncommon elements of set a and set b is : " + result); System.out.println("After.."); System.out.println("a is : " + a); System.out.println("b is : " + b); } </code></pre> <p>I have declared two extra sets. Can this be improved?</p>
[]
[ { "body": "<p>If data is ordered, as is the case in your example, you can use a merge-sort algorithm to do it while traversing each collection only once:</p>\n\n<pre><code> List&lt;Integer&gt; a = Arrays.asList(1, 2, 3, 4);\n List&lt;Integer&gt; b = Arrays.asList(3, 4, 5, 6);\n List&lt;Integer&gt; result = new ArrayList&lt;&gt;();\n\n int ia = 0, ib = 0;\n\n while(ia&lt;a.size() &amp;&amp; ib&lt;b.size()) {\n if (a.get(ia)&lt;b.get(ib)) {\n result.add(a.get(ia));\n ia++;\n } else if (a.get(ia)&gt;b.get(ib)) {\n result.add(b.get(ib));\n ib++;\n } else {\n ia++;\n ib++;\n }\n }\n result.addAll(a.subList(ia, a.size()));\n result.addAll(b.subList(ib, b.size()));\n\n System.out.println(\"Uncommon elements of set a and set b is : \" + result);\n</code></pre>\n\n<p>If an actual <code>java.util.Set</code> is required, instead of any collection that in this case behaves as a set, one may use a <code>java.util.SortedSet</code> implementation (e.g., <code>java.util.TreeSet</code>). The code above can be directly translated to iterators by using a <code>PeekableIterator</code> wrapper. Without <code>peek()</code>, it requires a little more effort to advance each iterator only when needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T18:34:17.043", "Id": "51590", "Score": "0", "body": "HashSets are never ordered, even if parameter lists in their constructors are." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T20:10:42.147", "Id": "51594", "Score": "0", "body": "The question seems to be about sets in general, not specifically about hashing (check the title). Sets can be represented with ordered data structures and I was precisely pointing out the usefulness of doing so here. I changed my reply to emphasize that the assumption is on the data, not on HashSets." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T17:55:47.437", "Id": "32298", "ParentId": "32297", "Score": "0" } }, { "body": "<p>This should work faster:</p>\n\n<pre><code>private void findUnCommon{\n\n Set&lt;Integer&gt; a = new HashSet&lt;&gt;(Arrays.asList(1, 2, 3, 4));\n Set&lt;Integer&gt; b = new HashSet&lt;&gt;(Arrays.asList(3, 4, 5, 6));\n\n Set&lt;Integer&gt; result = new HashSet&lt;&gt;();\n for (Integer el: a) {\n if (!b.contains(el)) {\n result.add(el);\n }\n }\n for (Integer el: b) {\n if (!a.contains(el)) {\n result.add(el);\n }\n }\n System.out.println(\"Uncommon elements of set a and set b is : \"\n + result);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T18:38:05.857", "Id": "32301", "ParentId": "32297", "Score": "3" } }, { "body": "<p>With <a href=\"http://commons.apache.org/proper/commons-collections/\" rel=\"noreferrer\">Apache Commons Collections</a> (<a href=\"http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#disjunction%28java.lang.Iterable,%20java.lang.Iterable%29\" rel=\"noreferrer\">javadoc</a>):</p>\n\n<pre><code>CollectionUtils.disjunction(a, b);\n</code></pre>\n\n<p>With <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"noreferrer\">Guava</a> (<a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#symmetricDifference%28java.util.Set,%20java.util.Set%29\" rel=\"noreferrer\">javadoc</a>):</p>\n\n<pre><code>Sets.symmetricDifference(a, b);\n</code></pre>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T20:56:36.360", "Id": "32304", "ParentId": "32297", "Score": "7" } }, { "body": "<p>Is this a method? You can't just plop code anywhere in Java.</p>\n\n<p>The name of the operation is <a href=\"http://en.wikipedia.org/wiki/Symmetric_difference\" rel=\"noreferrer\">symmetric difference</a>, so you should probably call it that.</p>\n\n<p>Here's a more compact implementation.</p>\n\n<pre><code>private Set&lt;T&gt; symmetricDifference(Set&lt;T&gt; a, Set&lt;T&gt; b) {\n Set&lt;T&gt; result = new HashSet&lt;T&gt;(a);\n for (T element : b) {\n // .add() returns false if element already exists\n if (!result.add(element)) {\n result.remove(element);\n }\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-02T03:26:06.017", "Id": "366632", "Score": "0", "body": "Now the above method will generate syntactical error for generic variable T. So change the method declaration to be like private <T> Set<T> symmetricDifference(Set<T> a, Set<T> b) {...}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-02T03:50:42.357", "Id": "366633", "Score": "0", "body": "@Vivek If the type variable `T` is introduced when the class is defined, it works as written." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T05:56:35.843", "Id": "32316", "ParentId": "32297", "Score": "10" } } ]
{ "AcceptedAnswerId": "32316", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-05T17:36:37.917", "Id": "32297", "Score": "3", "Tags": [ "java", "performance", "set" ], "Title": "Find the uncommon elements from two sets" }
32297
<p>I wrote a <code>FastReader</code> utility class that is supposed to read input fast. It's mostly aimed at parsing input files in competitive programming.</p> <p>How could I made this better? I am mainly looking for good code suggestions rather than the specific details of the logic. Though, any comments/recommendations are appreciated.</p> <pre><code>package com.muratdozen.playground.util.io; import com.muratdozen.playground.util.threading.NonThreadSafe; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.StringTokenizer; /** * FastReader class helps to read input in the form of words * from an {@link InputStream}. Good to use as a parser. * &lt;p&gt;&lt;/p&gt; * Usage: * &lt;pre&gt; * Assuming an input stream with the following lines: * asd xxx * 123 * {@code * final FastReader fastReader = FastReader.from(System.in); * final String s1 = fastReader.next(); * final String s2 = fastReader.next(); * final int n = fastReader.nextInt(); * ... * } * &lt;/pre&gt; * * @author Murat Derya Ozen * @since: 9/28/13 1:50 PM */ @NonThreadSafe public final class FastReader { private final BufferedReader bufferedReader; /* legacy class preferred over String#split and Scanner for performance */ private StringTokenizer tokenizer; private FastReader(final BufferedReader bufferedReader) { this.bufferedReader = bufferedReader; this.tokenizer = null; } /** * Returns a {@link FastReader} instance that reads input from {@code inputStream}. * * @param inputStream * @return Returns a {@link FastReader} instance that reads input from {@code inputStream}. */ public static final FastReader from(final InputStream inputStream) { return new FastReader(new BufferedReader(new InputStreamReader(inputStream))); } /** * Returns the next word acquired by {@link StringTokenizer}. * Moves on to the next line if the current line has been processed. * * @return Returns the next word acquired by {@link StringTokenizer}, * or null if end of stream has been reached. * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. */ public String next() { return tokenize() ? tokenizer.nextToken() : null; } /** * Checks to see if there are any more words left in the {@code inputStream}. * Can be used to check if end of stream has been reached, as well. * If required, reads another line from the {@code inputStream}; i.e this operation * might perform an I/O; possibly block if end of stream is not reached but stream * is not yet available to yield a new line. * * @return Returns true if there are more words to read in the {@code inputStream} * and end of stream has not been reached. False otherwise. * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. */ public boolean canReadMore() { return tokenize(); } private boolean tokenize() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { // read a line, see if end of stream has been reached String line = null; try { if ((line = bufferedReader.readLine()) == null) return false; } catch (IOException unexpected) { throw new RuntimeException(unexpected); } tokenizer = new StringTokenizer(line); } return true; } /** * Returns the next {@code int} acquired by {@link StringTokenizer} * using {@link Integer#parseInt(String)} on {@link #next()}. * Moves on to the next line if the current line has been processed. * * @return Returns the next {@code int} acquired by {@link StringTokenizer}. * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. * @throws NumberFormatException If an invalid input is encountered or end of stream has been reached. */ public int nextInt() { return Integer.parseInt(next()); } /** * Returns the next {@code long} acquired by {@link StringTokenizer} * using {@link Long#parseLong(String)} on {@link #next()}. * Moves on to the next line if the current line has been processed. * * @return Returns the next {@code long} acquired by {@link StringTokenizer}. * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. * @throws NumberFormatException If an invalid input is encountered or end of stream has been reached. */ public long nextLong() { return Long.parseLong(next()); } /** * Returns the next {@code double} acquired by {@link StringTokenizer} * using {@link Double#parseDouble(String)} on {@link #next()}. * Moves on to the next line if the current line has been processed. * * @return Returns the next {@code double} acquired by {@link StringTokenizer}. * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. * @throws NumberFormatException If an invalid input is encountered or end of stream has been reached. */ public double nextDouble() { return Double.parseDouble(next()); } /** * Returns the next {@link BigDecimal} acquired by {@link StringTokenizer} * using BigDecimal's String constructor on {@link #next()}. * Moves on to the next line if the current line has been processed. * * @return Returns the next {@code BigDecimal} acquired by {@link StringTokenizer}. * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. * @throws NumberFormatException If an invalid input is encountered or end of stream has been reached. */ public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } /** * Returns the next {@link BigInteger} acquired by {@link StringTokenizer} * using BigInteger's String constructor on {@link #next()}. * Moves on to the next line if the current line has been processed. * * @return Returns the next {@code BigInteger} acquired by {@link StringTokenizer}. * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. * @throws NumberFormatException If an invalid input is encountered or end of stream has been reached. */ public BigInteger nextBigInteger() { return new BigInteger(next()); } /** * Closes the input stream. * * @throws RuntimeException If {@link java.io.BufferedReader#readLine()} throws an {@link IOException}. * @see java.io.BufferedReader#close() */ public void close() { try { bufferedReader.close(); } catch (IOException unexpected) { throw new RuntimeException(unexpected); } } } </code></pre> <p>The code is hosted on <a href="https://github.com/muratdozen/playground/blob/master/util/src/main/java/com/muratdozen/playground/util/io/FastReader.java" rel="nofollow">GitHub</a> if anyone's interested. I will commit changes if necessary.</p>
[]
[ { "body": "<ol>\n<li><p>I'm always wary of naming my classes according to performance criteria. What if you (or someone else) finds a faster method of reading tokens from an input stream. Would you then write an <code>EvenFasterReader</code>? How about something like <code>TokenReader</code>?</p></li>\n<li><p>Consider letting the user pass the delimiters as well (optionally). This will make it more useful by allowing to parse input which is delimited by other things than white spaces.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T17:53:07.363", "Id": "32333", "ParentId": "32302", "Score": "3" } }, { "body": "<blockquote>\n <p>How could I made this better? </p>\n</blockquote>\n\n<p>Stop those annoying <code>Javadocs</code> commenting the obvious. This is only noise.</p>\n\n<pre><code> /**\n * Returns a {@link FastReader} instance that reads input from {@code inputStream}.\n *\n * @param inputStream\n * @return Returns a {@link FastReader} instance that reads input from {@code inputStream}.\n */\n public static final FastReader from(final InputStream inputStream) {\n return new FastReader(new BufferedReader(new InputStreamReader(inputStream)));\n }\n</code></pre>\n\n<p>In order to understand <code>1</code> single line of code, I have to go through <code>6</code> lines of commenting junk, 1 line boilerplate Java and at least a closing bracket.\nThis is useless. Anybody with little experience knows what this one line does, so why spend time on commenting it?</p>\n\n<p>Without the comments it is much better to read.</p>\n\n<pre><code>package com.muratdozen.playground.util.io;\n\nimport com.muratdozen.playground.util.threading.NonThreadSafe;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.StringTokenizer;\n\n@NonThreadSafe\npublic final class FastReader {\n\n private final BufferedReader bufferedReader;\n private StringTokenizer tokenizer;\n\n private FastReader(final BufferedReader bufferedReader) {\n this.bufferedReader = bufferedReader;\n this.tokenizer = null;\n }\n\n public static final FastReader from(final InputStream inputStream) {\n return new FastReader(new BufferedReader(new InputStreamReader(inputStream)));\n }\n\n public String next() {\n return tokenize() ? tokenizer.nextToken() : null;\n }\n\n public boolean canReadMore() {\n return tokenize();\n }\n\n private boolean tokenize() {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n String line = null;\n try {\n if ((line = bufferedReader.readLine()) == null) return false;\n } catch (IOException unexpected) {\n throw new RuntimeException(unexpected);\n }\n tokenizer = new StringTokenizer(line);\n }\n return true;\n }\n\n public int nextInt() {\n return Integer.parseInt(next());\n }\n\n public long nextLong() {\n return Long.parseLong(next());\n }\n\n public double nextDouble() {\n return Double.parseDouble(next());\n }\n\n public BigDecimal nextBigDecimal() {\n return new BigDecimal(next());\n }\n\n public BigInteger nextBigInteger() {\n return new BigInteger(next());\n }\n\n public void close() {\n try {\n bufferedReader.close();\n } catch (IOException unexpected) {\n throw new RuntimeException(unexpected);\n }\n }\n}\n</code></pre>\n\n<p>But while skimming through the code, two questions come to my mind:</p>\n\n<p>1) Why is this called a <code>FastReader</code> - besides the case, Chris mentioned, what makes it really <em>fast</em>? I am seeing the usage of a <code>BufferedReader</code>. Hopefully it is fast. I see nothing special in your code, that makes it <em>fast</em>.</p>\n\n<p>2) I do not see a single usecase for this. \nAt best, you have some kind of <code>DSL</code> which describes your Inputfile.</p>\n\n<p>Why waste time and put a wrapper around concrete data.</p>\n\n<pre><code> final String s1 = fastReader.next();\n final String s2 = fastReader.next();\n final int n = fastReader.nextInt();\n</code></pre>\n\n<p>So I could use directly a <code>BufferedReader</code>, read a line, and if necessary parse a line to an Integer. </p>\n\n<p>What is the advantage of a <code>FastReader</code>? I could not think of one. \nIn this case, I think, the whole idea is <em>overengineered</em>. It seems abstraction for the abstraction's sake. </p>\n\n<p>Besides: \nReading the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html\" rel=\"nofollow\">Documentation</a> at Oracle, it says »StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. <em>It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.</em>«</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-24T23:10:34.567", "Id": "57992", "ParentId": "32302", "Score": "1" } }, { "body": "<p>From the perspective of usage, the <code>tokenize()</code> method returns true if there is more to read, and false otherwise. As such, you could rename it to <code>canReadMore</code>, and drop the existing <code>canReadMore</code> method which was calling <code>tokenize</code> anyway.</p>\n\n<hr>\n\n<p>Since the characterizing feature of your reader is that it uses <code>StringTokenizer</code>, perhaps a more suitable name will be <code>TokenizerReader</code>.</p>\n\n<hr>\n\n<p>In this code, the initialization of <code>line</code> is pointless:</p>\n\n<blockquote>\n<pre><code>// read a line, see if end of stream has been reached\nString line = null;\ntry {\n if ((line = bufferedReader.readLine()) == null) return false;\n} catch (IOException unexpected) {\n throw new RuntimeException(unexpected);\n}\ntokenizer = new StringTokenizer(line);\n</code></pre>\n</blockquote>\n\n<p>It's enough to simply declare:</p>\n\n<pre><code>String line;\n</code></pre>\n\n<p>The comment about what the code does is obvious, you can just drop it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-02T17:55:09.747", "Id": "58845", "ParentId": "32302", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T19:54:26.713", "Id": "32302", "Score": "4", "Tags": [ "java", "io" ], "Title": "Simple I/O class for reading input data fast" }
32302
<p>I implemented an algorithm to solve a <a href="http://labs.spotify.com/puzzles/" rel="nofollow">constraint satisfaction problem</a>. It is a non-trivial one, so I do not intend to take your time with its details. I am mainly looking for good code suggestions rather than the specific details on the logic.</p> <p>How could I made the code better? Any comments/recommendations are appreciated.</p> <pre><code>package com.muratdozen.playground.spotify; import com.muratdozen.playground.util.io.FastReader; import java.io.PrintWriter; import java.util.*; /** * Spotify Challenge, Cat vs. Dog * * @author Murat Derya Ozen * @since: 10/2/13 10:47 AM * @see &lt;a href="https://www.spotify.com/us/jobs/tech/catvsdog/"&gt; * https://www.spotify.com/us/jobs/tech/catvsdog/&lt;/a&gt; */ public class CatVsDog { public static class Vote { public final boolean catLover; public final int keep; public final int throwout; public Vote(final boolean catLover, final int keep, final int throwout) { this.catLover = catLover; this.keep = keep; this.throwout = throwout; } public boolean isConflicting(Vote vote) { return this.catLover != vote.catLover &amp;&amp; (this.keep == vote.throwout || this.throwout == vote.keep); } } // some kind of a bipartite graph matching private static final int maxMatchings(final Map&lt;Vote,Set&lt;Vote&gt;&gt; conflictingVotes, final Map&lt;Vote,Set&lt;Vote&gt;&gt; reverseConflictingVotes) { // assign each cat lover vote to a conflicting dog lover vote // we need to find out the maximum number of such assignments (matchings) // we assign each cat lover vote to a conflicting vote by starting from // the cat lover vote that has the least number of options (conflicting votes) // list of cat lover votes sorted by the number of options each vote has final List&lt;Vote&gt; catLoversVotes = new ArrayList&lt;Vote&gt;(conflictingVotes.keySet()); Collections.sort(catLoversVotes, new Comparator&lt;Vote&gt;() { @Override public int compare(Vote vote, Vote vote2) { final Set&lt;Vote&gt; set1 = conflictingVotes.get(vote); final Set&lt;Vote&gt; set2 = conflictingVotes.get(vote2); return Integer.valueOf(set1.size()).compareTo(set2.size()); } }); int result = 0; final int len = catLoversVotes.size(); // assign each cat lover vote for (int i = 0; i &lt; len; ++i) { final Vote vote = catLoversVotes.get(i); // when choosing which conflicting dog lover vote to assign, // choose the one that affects the least amount of remaining cat lover voters final Set&lt;Vote&gt; choices = conflictingVotes.get(vote); if (choices == null || choices.isEmpty()) continue; Vote minAffectingVote = null; /* dog lover vote that is to be assigned */ int min = Integer.MAX_VALUE; for (Vote choice : choices) { final Set&lt;Vote&gt; set = reverseConflictingVotes.get(choice); if (set == null || set.isEmpty()) continue; final int numAffecting = set.size(); if (numAffecting &lt; min) { min = numAffecting; minAffectingVote = choice; } } if (minAffectingVote != null) { reverseConflictingVotes.remove(minAffectingVote); ++result; } } return result; } private static final &lt;T&gt; void addToMap(final Map&lt;T,Set&lt;Vote&gt;&gt; map, final T key, final Vote vote) { Set&lt;Vote&gt; votes = map.get(key); if (votes == null) { votes = new HashSet&lt;Vote&gt;(); votes.add(vote); map.put(key, votes); } else { votes.add(vote); } } private static final int solveTestCase(final FastReader fastReader) { // indexes of cat lover votes and dog lover votes final Set&lt;Vote&gt; catLovers = new HashSet&lt;Vote&gt;(); final Map&lt;Integer, Set&lt;Vote&gt;&gt; dogLoversIndexedByKeep = new HashMap&lt;Integer, Set&lt;Vote&gt;&gt;(); final Map&lt;Integer, Set&lt;Vote&gt;&gt; dogLoversIndexedByThrowout = new HashMap&lt;Integer, Set&lt;Vote&gt;&gt;(); // parse and collect data from input final int c = fastReader.nextInt(); final int d = fastReader.nextInt(); final int v = fastReader.nextInt(); if (v == 1) return 1; // fill in catLovers, dogLoversIndexedByKeep and dogLoversIndexedByThrowout for (int j = 0; j &lt; v; ++j) { final String keepStr = fastReader.next(); final String throwoutStr = fastReader.next(); final int keep = Character.getNumericValue(keepStr.charAt(1)); final int throwout = Character.getNumericValue(throwoutStr.charAt(1)); final boolean catLover = keepStr.charAt(0) == 'C'; final Vote vote = new Vote(catLover, keep, throwout); if (catLover) { catLovers.add(vote); } else { addToMap(dogLoversIndexedByKeep, keep, vote); addToMap(dogLoversIndexedByThrowout, throwout, vote); } } // build a map of conflicting votes // conflictingVotes has cat lovers' votes as keys. each key maps to a set of // dog lovers' votes that conflict with key. // similarly, reverseConflictingVotes contains dogLovers' votes mapped to a set // of conflicting votes. final Map&lt;Vote, Set&lt;Vote&gt;&gt; conflictingVotes = new HashMap&lt;Vote, Set&lt;Vote&gt;&gt;(catLovers.size()); final Map&lt;Vote, Set&lt;Vote&gt;&gt; reverseConflictingVotes = new HashMap&lt;Vote, Set&lt;Vote&gt;&gt;(); for (Vote catLover : catLovers) { final Set&lt;Vote&gt; conflicts = new HashSet&lt;Vote&gt;(); if (dogLoversIndexedByKeep.containsKey(catLover.throwout)) { conflicts.addAll(dogLoversIndexedByKeep.get(catLover.throwout)); } if (dogLoversIndexedByThrowout.containsKey(catLover.keep)) { conflicts.addAll(dogLoversIndexedByThrowout.get(catLover.keep)); } conflictingVotes.put(catLover, conflicts); for (Vote dogLoverVote : conflicts) { addToMap(reverseConflictingVotes, dogLoverVote, catLover); } } // match as many conflicting votes as possible // and return number of votes - number of matches return v - maxMatchings(conflictingVotes, reverseConflictingVotes); } public static final void main(String[] args) { final FastReader fastReader = FastReader.from(System.in); final int numTestCases = fastReader.nextInt(); final PrintWriter writer = new PrintWriter(System.out); final String LINE_SEPARATOR = System.getProperty("line.separator"); for (int i = 0; i &lt; numTestCases; ++i) { final int result = solveTestCase(fastReader); writer.write(Integer.toString(result)); writer.write(LINE_SEPARATOR); } writer.flush(); writer.close(); } } </code></pre> <p>The code is hosted on <a href="https://github.com/muratdozen/playground/blob/master/spotify-tech-puzzles/src/main/java/com/muratdozen/playground/spotify/CatVsDog.java" rel="nofollow">GitHub</a> if anyone's interested. I will commit changes if necessary.</p>
[]
[ { "body": "<p>I have not read your code in detail, but a lot of extra complexity comes from handling <code>Map&lt;Vote, Set&lt;Vote&gt;&gt;</code>. I'm a big fan of guava's <a href=\"http://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html\"><code>Multimap&lt;K, V&gt;</code></a>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T22:12:28.030", "Id": "51596", "Score": "0", "body": "+1 for that. I like Guava and I include it in most of my projects. For this piece of code, however, I wasn't able to use 3rd party libraries." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T22:01:50.500", "Id": "32306", "ParentId": "32303", "Score": "5" } }, { "body": "<p>Your original:</p>\n\n<pre><code>private static final &lt;T&gt; void addToMap(final Map&lt;T,Set&lt;Vote&gt;&gt; map, final T key, final Vote vote) {\n Set&lt;Vote&gt; votes = map.get(key);\n if (votes == null) {\n votes = new HashSet&lt;Vote&gt;();\n votes.add(vote);\n map.put(key, votes);\n } else {\n votes.add(vote);\n }\n}\n</code></pre>\n\n<p>Alternative:</p>\n\n<pre><code>private static final &lt;T&gt; void addToMap(final Map&lt;T,Set&lt;Vote&gt;&gt; map, final T key, final Vote vote) {\n\n if (null == map.get(key)) { \n map.put(key, new HashSet&lt;Vote&gt;());\n } \n\n map.get(key).add(vote); \n}\n</code></pre>\n\n<p>Edit to my preferred syntax:</p>\n\n<pre><code>private static final &lt;T&gt; void addToMap(final Map&lt;T,Set&lt;Vote&gt;&gt; map, final T key, final Vote vote) {\n if (!map.containsKey(key)) { \n map.put(key, new HashSet&lt;Vote&gt;());\n } \n map.get(key).add(vote); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:03:57.183", "Id": "51625", "Score": "0", "body": "Good point and thanks for the answer. However, I wanted to avoid 2 `map.get` operations for performance reasons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-15T20:37:49.617", "Id": "94756", "Score": "0", "body": "@Murat Then you can still move `votes.add(vote);` out of the branches (save 2 lines and make clear that `vote` gets always added)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-24T12:27:13.073", "Id": "278266", "Score": "0", "body": "@Murat I know this is a very old topic, but I think your performance concerns were unfounded. Map.get appears to be on average an O(1) operation. See: http://stackoverflow.com/q/1055243/3230218" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T05:11:38.937", "Id": "32315", "ParentId": "32303", "Score": "6" } }, { "body": "<p>Your methods are enormous. I would start by breaking them down into small segments that only do a single thing.</p>\n\n<p>You also have lots of comments around. This is needed because your methods are so big. In my opinion, ideally, you do not need inline comments because the methods should explain themselves, often by their name alone. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T20:53:03.650", "Id": "94484", "Score": "3", "body": "Welcome to Code Review! Your answer came up in the \"First Posts\" queue. You passed the test!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T20:16:50.940", "Id": "54195", "ParentId": "32303", "Score": "3" } }, { "body": "<p>Minor comments mostly:</p>\n\n<ul>\n<li>Javadoc is missing. For instance, what is the expected input format of the program?</li>\n<li>Missing <code>{}</code> after a <code>if</code> statement is not recommended</li>\n<li>I'd place <code>LINE_SEPARATOR</code> as static, but it's just a matter of taste</li>\n<li>The use of static methods make it impossible to mock up in tests</li>\n<li>You can shorten a bit <code>addToMap</code></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>private static final &lt;T&gt; void addToMap(final Map&lt;T,Set&lt;Vote&gt;&gt; map, final T key, final Vote vote) {\n Set&lt;Vote&gt; votes = map.get(key);\n if (votes == null) {\n votes = new HashSet&lt;Vote&gt;();\n map.put(key, votes);\n }\n votes.add(vote);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T21:50:04.277", "Id": "54203", "ParentId": "32303", "Score": "1" } }, { "body": "<ul>\n<li>You create an instance of comparator at each call of <code>maxMatchings</code>, ie one per line. You need only one instance for the full program, as a field.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T21:59:51.377", "Id": "54204", "ParentId": "32303", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T20:11:31.133", "Id": "32303", "Score": "7", "Tags": [ "java", "programming-challenge" ], "Title": "Spotify Cat vs. Dog Challenge" }
32303
<p>I implemented the <code>FixedSizePriorityQueue</code> class. The intended purpose is that, you can add as many elements as you want, but it will store only the greatest <code>maxSize</code> elements.</p> <p>I would like any suggestions on how to improve this data structure implementation. Any comments on how to make the surrounding code better is highly appreciated.</p> <pre><code>package com.muratdozen.playground.spotify; import com.muratdozen.playground.util.io.FastReader; import com.muratdozen.playground.util.threading.NonThreadSafe; import java.io.PrintWriter; import java.util.*; /** * Spotify Challenge, Zipfs Song * * @author Murat Derya Ozen * @since: 9/27/13 9:50 PM * @see &lt;a href="https://www.spotify.com/us/jobs/tech/zipfsong/"&gt; * https://www.spotify.com/us/jobs/tech/zipfsong/&lt;/a&gt; */ public class ZipfsSong { /** * FixedSizePriorityQueue is a priority queue implementation with a fixed size based on a {@link PriorityQueue}. * The number of elements in the queue will be at most {@code maxSize}. * Once the number of elements in the queue reaches {@code maxSize}, trying to add a new element * will remove the lowest element in the queue if the new element is greater than or equal to * the current lowest element. The queue will not be modified otherwise. */ @NonThreadSafe public static class FixedSizePriorityQueue&lt;E&gt; { private final PriorityQueue&lt;E&gt; priorityQueue; /* backing data structure */ private final Comparator&lt;? super E&gt; comparator; private final int maxSize; /** * Constructs a {@link FixedSizePriorityQueue} with the specified {@code maxSize} * and {@code comparator}. * * @param maxSize - The maximum size the queue can reach, must be a positive integer. * @param comparator - The comparator to be used to compare the elements in the queue, must be non-null. */ public FixedSizePriorityQueue(final int maxSize, final Comparator&lt;? super E&gt; comparator) { super(); if (maxSize &lt;= 0) { throw new IllegalArgumentException("maxSize = " + maxSize + "; expected a positive integer."); } if (comparator == null) { throw new NullPointerException("Comparator is null."); } this.priorityQueue = new PriorityQueue&lt;E&gt;(maxSize, comparator); this.comparator = priorityQueue.comparator(); this.maxSize = maxSize; } /** * Adds an element to the queue. If the queue contains {@code maxSize} elements, {@code e} will * be compared to the lowest element in the queue using {@code comparator}. * If {@code e} is greater than or equal to the lowest element, that element will be removed and * {@code e} will be added instead. Otherwise, the queue will not be modified * and {@code e} will not be added. * * @param e - Element to be added, must be non-null. */ public void add(final E e) { if (e == null) { throw new NullPointerException("e is null."); } if (maxSize &lt;= priorityQueue.size()) { final E firstElm = priorityQueue.peek(); if (comparator.compare(e, firstElm) &lt; 1) { return; } else { priorityQueue.poll(); } } priorityQueue.add(e); } /** * To be not used. Not an efficient operation. * @return Returns a sorted view of the queue as a {@link Collections#unmodifiableList(java.util.List)} * unmodifiableList. */ public List&lt;E&gt; asList() { return Collections.unmodifiableList(new ArrayList&lt;E&gt;(priorityQueue)); } } /** * Represents a Song where all fields are public and final. */ public static class Song { public static final Comparator&lt;? super Song&gt; COMPARATOR = new Comparator&lt;Song&gt;() { @Override public int compare(Song song1, Song song2) { if (song1.quality == song2.quality) { return -Integer.valueOf(song1.order).compareTo(song2.order); } return Long.valueOf(song1.quality).compareTo(song2.quality); } }; public final long quality; public final int order; public final String name; /** * @param quality - Quality of the song must be a non-negative integer. * @param order - Order of the song (as it appears in the album) must be a positive integer. * @param name - Name of the song must be non-null. */ public Song(final long quality, final int order, final String name) { super(); if (quality &lt; 0) { throw new IllegalArgumentException("quality = " + quality + "; expected a non-negative integer."); } if (order &lt;= 0) { throw new IllegalArgumentException("order = " + order + "; expected a positive integer."); } if (name == null) { throw new NullPointerException("Name is null."); } this.quality = quality; this.order = order; this.name = name; } } private static final void solveUsingFixedPriorityQueue() { final FastReader reader = FastReader.from(System.in); final int N = reader.nextInt(); final int M = reader.nextInt(); final FixedSizePriorityQueue&lt;Song&gt; songsQueue = new FixedSizePriorityQueue&lt;Song&gt;(M, Song.COMPARATOR); // process each song, add to queue for (int i = 1; i &lt;= N; ++i) { final long hits = reader.nextLong(); final long quality = hits * i; final String name = reader.next(); songsQueue.add(new Song(quality, i, name)); } reader.close(); // output the results in descending order final String[] descendingSongNames = new String[M]; int i = M - 1; Song song = null; while ((song = songsQueue.priorityQueue.poll()) != null) { descendingSongNames[i--] = song.name; } final PrintWriter writer = new PrintWriter(System.out); final String LINE_SEPARATOR = System.getProperty("line.separator"); for (String str : descendingSongNames) { writer.write(str); writer.write(LINE_SEPARATOR); } writer.flush(); writer.close(); } public static final void main(String[] args) { solveUsingFixedPriorityQueue(); } } </code></pre> <p>The code is hosted on <a href="https://github.com/muratdozen/playground/blob/master/spotify-tech-puzzles/src/main/java/com/muratdozen/playground/spotify/ZipfsSong.java" rel="nofollow">GitHub</a> if anyone's interested. I will commit changes if necessary.</p>
[]
[ { "body": "<p>Three things which seem questionable to me (I don't do much Java so I'm not entirely familiar with all the language features):</p>\n\n<ol>\n<li><p>You access the <code>private final priorityQueue</code> which is the backing data structure directly within <code>Song</code> (<code>songsQueue.priorityQueue.poll()</code>)</p></li>\n<li><p>The only public read access to your queue is a method labelled \"Do not use\"</p></li>\n<li><p>You have a method in your queue as part of your public interface which is commented as \"Do not use\". Either remove it, or simply state the draw backs so the user can make it's own decision.</p></li>\n</ol>\n\n<p><strong>Update</strong></p>\n\n<p>One more thing:</p>\n\n<p><code>solveUsingFixedPriorityQueue()</code> contains too much responsibility: it reads the data, solves the problem and outputs the data. Those concerns should be separated:</p>\n\n<ul>\n<li>Have one method reading the input and building the list of songs</li>\n<li>Pass the list of song to the <code>solve</code> method which should return the resulting list/array</li>\n<li>Have another write method generating the output by being passed in a list of songs.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T07:07:04.247", "Id": "32318", "ParentId": "32305", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-05T21:29:45.043", "Id": "32305", "Score": "1", "Tags": [ "java", "queue" ], "Title": "FixedSizePriorityQueue for storing a max number of elements" }
32305
<p>I have a <code>FaultType</code> <code>enum</code> with more than 100 members:</p> <pre><code>public enum FaultType { FaultType1, FaultType2, FaultType3, FaultType4, FaultType5, } </code></pre> <p>And I have a <code>FaultTypeConstants</code> <code>class</code> corresponding to <code>FaultType</code>:</p> <pre><code>public class FaultTypeConstants { public const int FaultType1 = 600; public const int FaultType2 = 100; public const int FaultType3 = 453; public const int FaultType4 = 200; public const int FaultType5 = 300; } </code></pre> <p>Now, I want to populate the <code>List&lt;FaultType&gt;</code> based on <code>FaultTypeConstants</code> values:</p> <pre><code>public static List&lt;FaultType&gt; GetFaults(List&lt;int&gt; FaultConstants) { var faults = new List&lt;FaultType&gt;(); FaultConstants.ForEach(fc =&gt; { switch (fc) { case FaultTypeConstants.FaultType1: faults.Add(FaultType.FaultType1); break; case FaultTypeConstants.FaultType2: faults.Add(FaultType.FaultType2); break; case FaultTypeConstants.FaultType3: faults.Add(FaultType.FaultType3); break; case FaultTypeConstants.FaultType4: faults.Add(FaultType.FaultType4); break; case FaultTypeConstants.FaultType5: faults.Add(FaultType.FaultType5); break; default: break; } }); return faults; } </code></pre> <p>Is there a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-10T15:59:42.517", "Id": "93787", "Score": "0", "body": "If you can't assign the `int`s directly in the `enum`, why not put it in a `Dictionary<FaultType,int>`? What possible reason could there be for splitting this into an `enum` and a `Class`?" } ]
[ { "body": "<p>Get rid of the constants entirely and assign those values to the enum members themselves.<br>\nYou can then use the enum everywhere.</p>\n\n<p>You can cast an enum member to <code>int</code> to get its numeric value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T00:49:11.773", "Id": "51601", "Score": "0", "body": "But that is not my requirement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T01:21:12.957", "Id": "51604", "Score": "8", "body": "@PrasadKanaparthi: Why not?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T14:19:59.860", "Id": "51710", "Score": "1", "body": "list the requirement in your question please." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T00:32:34.413", "Id": "32310", "ParentId": "32309", "Score": "10" } }, { "body": "<p>You can use reflection to query the members of both types and match them by name. Something along these lines:</p>\n\n<pre><code>typeof(FaultCodes)\n .GetFields(BindingFlags.Public | BindingFlags.Static)\n .Where(fi =&gt; FaultConstant.Contains(fi.GetValue(null)))\n .Select(fi =&gt; (FaultType)Enum.Parse(typeof(FaultType), fi.Name))\n .ToList();\n</code></pre>\n\n<p>A way to speed it up is to build a map from code to enum. You can do this once in a static contructor:</p>\n\n<pre><code>public static class FaultLookup\n{\n private static Dictionary&lt;int, FaultType&gt; _CodeEnumMap;\n public static FaultLoopkup()\n {\n _CodeEnumMap = typeof(FaultCodes)\n .GetFields(BindingFlags.Public | BindingFlags.Static)\n .ToDictionary(fi =&gt; fi.GetValue(null), \n fi =&gt; (FaultType)Enum.Parse(typeof(FaultType), fi.Name))\n }\n\n public static IList&lt;FaultType&gt; GetFaultTypes(IEnumerable&lt;int&gt; codes)\n {\n return codes.Where(c =&gt; _CodeEnumMap.ContainsKey(c))\n .Select(c =&gt; _CodeEnumMap[c])\n .ToList();\n }\n}\n</code></pre>\n\n<p>The best refactoring was mentioned by slaks though: Get rid of the implicit mapping and assign the codes directly to your enum values.</p>\n\n<p>In general: Try to accept the most generic collection type possible - this will give the users of the function more flexibility regarding passing in the arguments. I find nothing more annoying than having to make a temporary collection to satisfy some interface which expects a <code>List&lt;T&gt;</code> which might not even use the fact that it's a list.</p>\n\n<p>\"Be liberal in what you accept and conservative in what you produce\" - I find that approach quite useful not just in data processing but also for interfaces.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T00:54:37.883", "Id": "32312", "ParentId": "32309", "Score": "3" } } ]
{ "AcceptedAnswerId": "32312", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T00:30:14.397", "Id": "32309", "Score": "3", "Tags": [ "c#", "enum", "constants" ], "Title": "Managing fault types" }
32309
<p>I needed a utility function/method that would get the next available filename to save as.</p> <p>An example would be, if I need to save a file as <em>MyTestFile.html</em> but it already exists.</p> <p>This method would then check to see what the next availble filename would be, and it would return <code>MyTestFile2.html</code>. If <code>MyTestFile2.html</code> exists, then it would return <code>MyTestFile3.html</code>, and so on.</p> <p>I wrote the method, but it feels sloppy, and isn't really very elegant.</p> <p>Any ideas for improving the readability of this code, or a better way to do it?</p> <pre><code>public string GetNextAvailableName(List&lt;string&gt; files, string baseFile) { var baseFileWithoutExt = Path.GetFileNameWithoutExtension(baseFile); var baseExt = Path.GetExtension(baseFile); //clean files and get the ones containing oure baseFileName var cleanFiles = files .Select(i =&gt; Path.GetFileNameWithoutExtension(i.ToLower())) .Where(i =&gt; i.Contains(baseFileWithoutExt.ToLower())); var count = cleanFiles.Count(); if (count == 0) return baseFile; int indexCount = 1; do { indexCount++; } while (cleanFiles.Contains(baseFileWithoutExt.ToLower() + indexCount)); return baseFileWithoutExt + indexCount + baseExt; } </code></pre> <p>This would then be called like this:</p> <pre><code>GetNextAvailableName(Directory.GetFiles("C:\\MyFiles\\", "MyTestFile.html"); </code></pre> <p>Then if <code>MyTestFile.html</code> is already in use, it will return <code>MyTestFileX.html</code>, where <code>X</code> is the lowest positive integer where the filename doesn't exist yet.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T04:24:52.643", "Id": "51607", "Score": "0", "body": "What is a baseFile example when you call GetNextAvailableName()? I'm trying to understand better what it is you want to do - then I can comment on a better solution. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T04:29:23.197", "Id": "51608", "Score": "0", "body": "I tried your method with the following data, and I don't think it does what you want it to do. I passed in var files = new List<string>\n {\n \"MyTestFile.html\",\n \"MyTestFile2.html\",\n \"MyTestFile3.html\",\n \"MyTestFile4.html\",\n \"MyTestFile5.html\",\n \"MyTestFile6.html\",\n \"MyTestFile7.html\",\n \"MyTestFile8.html\",\n \"MyTestFile9.html\"\n };\n const string baseFile = \"MyTestFile4.html\"; and it returned \"MyTestFile42.html\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T09:57:25.860", "Id": "51609", "Score": "0", "body": "Why don't you check the extensions of `files`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T14:30:21.180", "Id": "51612", "Score": "0", "body": "@JoeBaltimore I updated the code with an example. It returned MyTestFile42.html, because you entered MyTestFile4.html as the base file. It saw that MyTestFile4.html was already taken, so it gave the next available filename, which was MyTestFile42.html. (Think of this as MyTestFile4 (version 2).html I think the basefile that should have passed in was \"MyTestFile.html\", and then it should have returned \"MyTestFile10.html\"" } ]
[ { "body": "<p>Your current code finds \"holes\" in the numbering. If that is not required (or desired) then you could parse the numbers of the end and find the max and return max + 1. Something along these lines:</p>\n\n<pre><code>public string GetNextAvailableName(List&lt;string&gt; files, string baseFile)\n{\n var baseFileWithoutExt = Path.GetFileNameWithoutExtension(baseFile);\n var baseExt = Path.GetExtension(baseFile);\n\n //clean files and get the ones containing oure baseFileName \n var maxUsedIndex = files\n .Select(f =&gt; Path.GetFileNameWithoutExtension(f.ToLower()))\n .Where(f =&gt; f.StartsWith(baseFileWithoutExt.ToLower()))\n .Select(f =&gt; f.Substring(baseFileWithoutExt.Length))\n .Select(f =&gt; Int32.Parse(f))\n .Max();\n\n return baseFileWithoutExt + (maxUsedIndex + 1) + baseExt;\n}\n</code></pre>\n\n<p>Note that the code above is not robust against malformed input (<code>Int32.Parse()</code> might throw). Also it requires that the passed in <code>files</code> are complete and no new file with a new index is created in the meantime.</p>\n\n<p>Note: When you use Linq then imagine your were to write a <code>foreach</code> loop instead and try name your loop variables accordingly. <code>i</code> had me slightly confused when looping over files - I think <code>foreach (var f in files)</code> is more intuitive than <code>foreach (var i in files)</code> as <code>i</code> is generally something related to a loop index rather than an actual object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T06:10:22.870", "Id": "32317", "ParentId": "32313", "Score": "3" } }, { "body": "<p>I don't understand why you want to pass a list of files. Simply check the existence of your filename candidates. Start with the base filename. If it does not exist, start counting. In my eyes this a straightforward approach and therefore easy to understand.</p>\n\n<pre><code>public string GetNextAvailableFilename(string filename)\n{\n if (!System.IO.File.Exists(filename)) return filename;\n\n string alternateFilename;\n int fileNameIndex = 1;\n do\n {\n fileNameIndex += 1;\n alternateFilename = CreateNumberedFilename(filename, fileNameIndex);\n } while (System.IO.File.Exists(alternateFilename));\n\n return alternateFilename;\n}\n\nprivate string CreateNumberedFilename(string filename, int number)\n{ \n string plainName = System.IO.Path.GetFileNameWithoutExtension(filename);\n string extension = System.IO.Path.GetExtension(filename);\n return string.Format(\"{0}{1}{2}\", plainName, number, extension);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T14:33:25.400", "Id": "51613", "Score": "0", "body": "Hmm.. I pass in the filenames I guess because I needed to do it for a certain directory, and the baseFile isn't a fully qualified path. But I think this way makes more sense, and will probably switch it" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T12:37:58.353", "Id": "32327", "ParentId": "32313", "Score": "7" } } ]
{ "AcceptedAnswerId": "32327", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T01:05:58.597", "Id": "32313", "Score": "8", "Tags": [ "c#" ], "Title": "Method to get next available filename" }
32313
<p>I wanted to try out F# so I decided to I converted a library file from c# to f#. I have done that successfully(thanks a you people in stackoverflow). At first I ported the code from c# to f#. Than I tried to covert the code into FP after a lot of pain I have managed to get this far.</p> <p>Here is the Source Code for the whole project if anyone what to use it.</p> <p><a href="http://dl.dropboxusercontent.com/u/87039989/TicTacToe.zip" rel="nofollow">dl.dropboxusercontent.com/u/87039989/TicTacToe.zip</a> The code has changed so the speed test may not be 100%. To the one here.</p> <p>[Speed: Average of 5 calls to Move() with same scenario]</p> <p>C# 466.4 (ticks/1000) </p> <pre><code>public class Agent { private readonly Reffery _reff = new Reffery(); public Agent(Board cBoard, int symbol) { this.Symbol = symbol; RootBoard = new Board(cBoard); } public Board RootBoard { get; set; } public int Symbol { get; set; } public int Move() { var max = -10; var bestMove = 0; if (RootBoard.MoveNumber == 0) return 4; for (var i = 0; i &lt;= 8; i++) { var board = new Board(RootBoard); if (!board.SetBoardBool(i)) continue; var val = MinMaxAlphaBeta(board, true, -10, 10); if (val &gt;= max) { max = val; bestMove = i; } } return bestMove; } private int MinMaxAlphaBeta(Board board, bool min, int alpha, int beta) { var point = BoardPoint(board); if (point != -2) { return point; } for (var i = 0; i &lt;= 8; i++) { var newBoard = new Board(board); newBoard.Copy(board); if (!newBoard.SetBoardBool(i)) continue; var val = MinMaxAlphaBeta(newBoard, !min, alpha, beta); if (min &amp;&amp; val &lt; beta) beta = val; else if (!min &amp;&amp; val &gt; alpha) alpha = val; } return min ? beta : alpha; } private int BoardPoint(Board board) { int hum = Symbol == 1 ? 2 : 1; var condition = _reff.checkBoardCondition(board); if (condition == (Reffery.Condition)Symbol) return 1; if (condition == (Reffery.Condition)hum) return -1; if (condition == (Reffery.Condition.Draw)) return 0; return -2; } } </code></pre> <p>F# imperative 327(Ticks/1000)</p> <pre><code>type Agent(board:Board,symbol:int)= let mutable _nodeCount=0; let mutable _rootBoard= new Board(board) let mutable _symbol = symbol let mutable _reff = new Boards.Reffery() new (board:Board) = Agent(board,0) member this.Move() :int = let mutable max= -10 let mutable bestMove=0 if _rootBoard.MoveNumber = 0 then 4 else for i= 0 to 8 do let mutable b = new Board(_rootBoard) if b.SetBoardBool(i) then let mutable value = this.MinMaxAlphaBeta(b, true, -10, 10) //Debug.Print (i.ToString() + " , " + value.ToString()) if value &gt;= max then max &lt;- value bestMove &lt;- i bestMove member private this.MinMaxAlphaBeta(board:Board, min:bool, alpha:int, beta:int):int= let mutable a=alpha //Extra Line let mutable b=beta //Extra Line let point = this.BoardPoint(board); if point &lt;&gt; -2 then point else for i = 0 to 8 do let mutable newBoard = new Board(board) if newBoard.SetBoardBool(i) then let mutable value = this.MinMaxAlphaBeta(newBoard,not min, a, b) if min &amp;&amp; value &lt; b then b &lt;- value elif (not min) &amp;&amp; value &gt; a then a &lt;- value; if min then b else a member private this.BoardPoint(board:Board):int= let hum = if _symbol= 1 then 2 else 1 let mutable pos = _reff.checkBoardCondition(board) if pos = enum&lt;Reffery.Condition&gt; _symbol then 1 elif pos = enum&lt;Reffery.Condition&gt; hum then -1 elif pos = Reffery.Condition.Draw then 0 else -2 </code></pre> <p>F# functional 453.6(Ticks/1000)</p> <pre><code>type Agent(board:Board,symbol:int)= let aisymbol= symbol let rootBoard= new Board(board) let _reff = new Boards.Reffery() member this.Move() :int = if rootBoard.MoveNumber=0 then 4 else let GetVal (i)= let b = new Board(rootBoard) if b.SetBoardBool(i) then this.MinMaxAlphaBeta(b, true, -10, 10) else -3 [| for i = 0 to 8 do yield (GetVal i , i) |] |&gt; Array.max |&gt; snd member private this.MinMaxAlphaBeta(board:Board, isMin:bool, alpha:int, beta:int):int= let betaF= ref beta let alphaF= ref alpha let point= this.BoardPoint(board) if point &lt;&gt; -2 then point else let UpdateAlplaBeta(x)= if x &lt;&gt; 10 then if isMin &amp;&amp; x &lt; !betaF then betaF := x elif (not isMin) &amp;&amp; x &gt; !alphaF then alphaF:=x x else if isMin then !betaF else !alphaF let GetVal (i,isMin,al, be)= let b = new Board(board) if b.SetBoardBool(i) then this.MinMaxAlphaBeta(b, isMin, al, be) else 10 let list = [| for i =0 to 8 do yield UpdateAlplaBeta(GetVal (i, (not isMin), !alphaF , !betaF)) |] if isMin then list|&gt;Array.min else list|&gt;Array.max member private this.BoardPoint(board:Board):int= let human = if aisymbol= 1 then 2 else 1 let condition = _reff.checkBoardCondition(board) if condition = enum&lt;Reffery.Condition&gt; aisymbol then 1 elif condition = enum&lt;Reffery.Condition&gt; human then -1 elif condition = Reffery.Condition.Draw then 0 else -2 </code></pre> <p>The problem I am facing now is these two lines</p> <pre><code> let betaF= ref beta let alphaF= ref alpha </code></pre> <p><strong>I can't remove these two variables.</strong> </p> <p>Also as you can see F# dll executes faster than its c# counter part but the one in functional style it take a bit more time to execute then the is imperative counter part, is this suppose to happen or is there something i am doing wrong? If so how can fix it?</p> <p><strong>Update</strong></p> <blockquote> <p>b.SetBoardBool(i)</p> </blockquote> <p>set a move on position i for the current player and returns true is successful other wise false.</p> <blockquote> <p>_reff.checkBoardCondition(board)</p> </blockquote> <p>take a board object check if it has X or O win condition, draw or no condition at all.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T17:43:07.370", "Id": "51622", "Score": "1", "body": "Any chance you could post the entire code? There are a number of simplifications you could make to your code to improve the performance, but it's difficult to know which optimizations you can really make without being able to look at the rest of the code (e.g., the definitions of `Board` and `Refferey.Condition`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:00:16.860", "Id": "51623", "Score": "0", "body": "will this help?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:17:23.360", "Id": "51628", "Score": "0", "body": "Not really. It's just more difficult to suggest changes if I can't put the code into VS and compile it." } ]
[ { "body": "<p>To start, I see a few issues with the functional version of your code which are contributing to the performance loss:</p>\n\n<ul>\n<li>Whenever you need maximum performance, use arrays instead of <code>list</code> or <code>seq</code> (if feasible for your specific application). Functions operating on arrays are <em>generally</em> faster than those operating on lists or sequences.</li>\n<li>Avoid creating intermediate variables. There are several places in the functional version of your code where you create a sequence, transform it into a <code>list</code>, then call a function (e.g., <code>List.max</code>) which uses the list once then discards it. That's fine to do when you're prototyping an application, but once things are working and you want to start improving the performance, look for places where you can consolidate two or more function calls to avoid creating intermediate variables. For example, you can use <code>Seq.max</code> instead of <code>Seq.toList</code> and <code>List.max</code>.</li>\n<li>Don't use <code>ref</code> cells unless you really need to. I know they seem like an obvious choice when you're coming from C#, since they allow you to update 'local' variables from within a locally-scoped function (e.g., your <code>UpdateAlphaBeta</code> function); however, they store your value in the heap instead of the stack so you end up paying an indirection penalty each time you access the value. You can often re-implement your functions to use recursion or mutual recursion and pass the values around to each other instead of using <code>ref</code> cells.</li>\n</ul>\n\n<hr>\n\n<p>Here's a functional style reworking of your code. There are still some performance optimizations that could be made, but this code should be reasonably fast anyway (I would be surprised if it wasn't noticeably faster than your original functional code). You'll want to compile this in <code>Release</code> mode for benchmarking, otherwise the recursive functions won't get optimized/inlined into simple loops. I'd be interested to hear how this code performs in your benchmark, just to have the numbers to compare against your original code.</p>\n\n<pre><code>type Agent (board : Board, symbol : int) =\n let aisymbol = symbol\n let rootBoard = Board (board)\n let _reff = Boards.Reffery ()\n\n member private this.BoardPoint (board : Board) : int =\n let condition = _reff.checkBoardCondition (board)\n\n let human = if aisymbol = 1 then 2 else 1\n\n if condition = enum&lt;Reffery.Condition&gt; aisymbol then 1\n elif condition = enum&lt;Reffery.Condition&gt; human then -1\n elif condition = Reffery.Condition.Draw then 0\n else -2\n\n member private this.MinMaxAlphaBeta (board : Board, isMin : bool, alpha : int, beta : int) : int =\n let point = this.BoardPoint (board)\n if point &lt;&gt; -2 then point\n else\n let UpdateAlphaBeta x alpha beta =\n match x with\n | 10 -&gt;\n if isMin then\n beta, alpha, beta\n else\n alpha, alpha, beta\n | _ -&gt;\n if isMin &amp;&amp; x &lt; beta then\n x, alpha, x\n elif not isMin &amp;&amp; x &gt; alpha then\n x, x, beta\n else\n x, alpha, beta\n\n let rec loop x alpha beta i =\n if i &gt; 8 then x\n else\n let x', alpha', beta' =\n let x =\n let b = Board (board)\n if b.SetBoardBool i then\n // NOTE : This is a _recursive_ call!\n this.MinMaxAlphaBeta (b, not isMin, alpha, beta)\n else 10\n\n UpdateAlphaBeta x alpha beta\n\n let x_new =\n if isMin then min x x' else max x x'\n\n loop x_new alpha' beta' (i + 1)\n\n let x_initial = 0\n loop x_initial alpha beta 0 // Start at the zero-th element.\n\n member this.Move () : int =\n if rootBoard.MoveNumber = 0 then 4\n else\n let GetVal i =\n let b = Board (rootBoard)\n if b.SetBoardBool i then\n this.MinMaxAlphaBeta (b, true, -10, 10)\n else -3\n\n // Gets the index (in the range [0..8]) which produces the maximum value.\n let rec getMaxVal maxValue maxIndex i =\n if i &gt; 8 then maxIndex\n else\n let value_i = GetVal i\n if value_i &gt; maxValue then\n getMaxVal value_i i (i + 1)\n else\n getMaxVal maxValue maxIndex (i + 1)\n\n getMaxVal (GetVal 0) 0 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T03:35:10.547", "Id": "51656", "Score": "0", "body": "its not working :( i am get the wrong answer seems like alpha beta not changing is value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T05:56:00.497", "Id": "51660", "Score": "0", "body": "All the value of GetVal is 10 or -10, value of alpha beta does not change" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:37:54.017", "Id": "51688", "Score": "1", "body": "I can't do any more unless you publish the rest of the code so I can compile/run it on my own machine. If you can't do that, then you'll have to debug the code and fix the problem yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T15:38:28.950", "Id": "51720", "Score": "0", "body": "https://dl.dropboxusercontent.com/u/87039989/TicTacToe.zip\nhere is the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T05:56:05.800", "Id": "51757", "Score": "0", "body": "The Code please see if you can help me, Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T12:38:56.790", "Id": "51773", "Score": "0", "body": "@Taufiq Yes, I can help you. I'm busy for the next couple of days though, so it'll have to wait until then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T18:27:12.797", "Id": "52028", "Score": "0", "body": "i will be waiting..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T14:24:53.357", "Id": "52203", "Score": "0", "body": "@Taufiq Ok, I updated the code, and it seems to work correctly now. Give it a try and please post benchmarking numbers for comparison (make sure to compile in Release mode)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T08:35:06.453", "Id": "52248", "Score": "0", "body": "Thanks but the result i am get is not correct, from the updated code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T12:29:48.000", "Id": "52257", "Score": "1", "body": "Sorry, you'll have to modify it to suit your needs then. It should be straightforward to step through the code in the debugger to see where it's going wrong, and fix it to get the result you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:50:57.080", "Id": "57918", "Score": "0", "body": "hey i just need to ask u. You are taking\n let x', alpha', beta' what is the difference between x and x'? Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:53:35.340", "Id": "57919", "Score": "0", "body": "also UpdateAlphaBeta x alpha beta how is this function working is it updating the parameter of the function ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T16:56:15.127", "Id": "58784", "Score": "0", "body": "@Taufiq In the `loop` function, `x` is \"score\" of the board (in other words, the value returned by `GetVal` in your original code). `x'` is the value which was returned by `MinMaxAlphaBeta` in your original code; my code uses recursion instead of the array comprehension you used (`let list = ...`), so assigning the result to `x'` before recursing makes the code a little easier to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T16:56:45.143", "Id": "58785", "Score": "0", "body": "`UpdateAlphaBeta` doesn't really \"update\" anything now, because there's no mutation; however, you could think of it that way, because it takes the current \"score\", alpha, and beta, and returns \"updated\" score, alpha, and beta values (which are assigned to `x'`, `alpha'`, and `beta'`)." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:14:05.627", "Id": "32334", "ParentId": "32319", "Score": "4" } } ]
{ "AcceptedAnswerId": "32334", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T07:20:51.423", "Id": "32319", "Score": "3", "Tags": [ "performance", "functional-programming", "f#" ], "Title": "Coding Functional style taking longer time than its Imperative style" }
32319
<p>I've been thinking about how to create a robust function that parses the command line arguments for valid filenames. I came up with a while-switch construct because that allows me to reduce redundancy (no break-statement at the end of case 2).</p> <p>As I am pretty new to programming, I can't really tell the quality of this code. Can you think of a way to improve this code in robustness as well as in elegance?</p> <pre><code>void spellchecker::openFiles(int argc, char* argv[]) { bool filesOpen = false; std::string dict_filename; std::string text_filename; while (filesOpen == false) { switch (argc) { case 2: printf("You already entered the name of the dictionary file as \"%s\". Is this correct? (y/n): ", argv[1]); if (std::cin.get() == 'y') { printf("Ok, please enter the name of the text file you want to check: "); std::cin &gt;&gt; text_filename; break; } /* no break so user can enter both filenames*/ default: case 1: printf("Please enter the name of the dictionary: "); std::cin &gt;&gt; dict_filename; printf("Please enter the name of the text file to check: "); std::cin &gt;&gt; text_filename; break; case 3: dict_filename = argv[1]; text_filename = argv[2]; break; } // switch if (!dict_file.is_open()) { dict_file.open(dict_filename.c_str(), std::ifstream::in); } if (!text_file.is_open()) { text_file.open(text_filename.c_str(), std::ifstream::in); } if (dict_file.good() &amp;&amp; text_file.good()) { filesOpen = true; } } // while } </code></pre>
[]
[ { "body": "<p>This solution does not sit well with me. It looks like you're doing too much: checking how to take the input, taking input, and then checking whether that input worked all at once.</p>\n\n<p>Before looking at the code, though, it's worth asking whether this is really the interface that you want to provide to the user. The way you've designed it, it looks like it is meant to be run by a human, as the requests for input will only muddle the output in a script. Furthermore, spell-checkers are usually non-destructive: running it with the wrong input file or the wrong dictionary file shouldn't lose you any data.</p>\n\n<p>All in all, this makes double-checking with the user whether the dictionary file is correct questionable. It is also inconsistent: you do validate the input in that case, but don't in the case that both files are provided, so the user has to remember that if he intends to rely on the input being checked.</p>\n\n<p>My first suggestion is thus to change your interface: only prompt for things that are not already provided, and if you detect an error, report it and exit.</p>\n\n<p>Now to the code: you have a few cases where the program can go in an infinite loop. This happens if the user closes <code>std::cin</code>, or if the user provided two filenames via <code>argv</code> and then at least one failed to open: you'll keep trying to open it and <code>filesOpen</code> will never be true.</p>\n\n<p>Secondly, you're using <code>operator&gt;&gt;</code> in most places, but use <code>std::cin.get()</code> to ask the user whether he's sure. This will likely break if the user provides one command-line argument and then some file fails to open.</p>\n\n<p>Thirdly, the condition of your loop seems strange to me. Why use an extra <code>bool</code> that you then set at the very end instead of using <code>break</code> or <code>return</code> to get out of the loop, or, better, checking the condition directly? You can use a do-while loop if you want to save yourself one check, though I wouldn't bother as the performance effect will be negligible, while the code will be clearer.</p>\n\n<p>As for the switch construct: I'd use a helper function or two instead. The code is sufficiently small for it to be clear, especially with the comment, but I don't think it wins you anything over two function calls. In general, the function looks too big to me, but I've already covered that above.</p>\n\n<p>Last and least, mixing <code>std::printf</code> and <code>std::cin</code> is strange. I can't come up with any technical problems, but mixing two styles without a good reason is generally more trouble than it's worth.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T10:00:17.880", "Id": "51843", "Score": "0", "body": "Thanks a lot for your thorough review! I'm very surprised that I could learn so much from this simple example.\nYou are right, this code wasn't intended to be used by a script.\nI've got 2 questions that I couldn't find answers on the net:\n1. How could a user close std::cin? By unplugging the keyboard? Or by aborting a script?\n1b. How could I improve my code in that case?\n2. I can't recreate the issue you mentioned with operator>> and std::cin.get(). Were you thinking about the issue that operator>> could leave a terminating char in the stream that std::cin.get() would then take as input?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T04:46:00.257", "Id": "51965", "Score": "0", "body": "@dev-random: (a) The key-combination on Linux is Ctrl-D, on Windows it's Ctrl-Z. (b) Yes; steps to reproduce: enter only a dictionary file, choose 'y', enter a file that will fail to open. Your `std::cin.get()` should now extract whitespace." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T09:49:28.010", "Id": "32323", "ParentId": "32321", "Score": "1" } }, { "body": "<p>You might want to change the interface of <code>openFiles</code> to this:</p>\n\n<pre><code>void spellchecker::openFiles(int argc, char** argv)\n</code></pre>\n\n<p>The following is a quote from James Kanze:</p>\n\n<blockquote>\n <p>I never declare a function with an array argument; I always use the\n pointer (the rare times I need it).</p>\n</blockquote>\n\n<p>On the other hand, many textbooks show <code>main()</code> as</p>\n\n<pre><code>int main( int argc, char* argv[] )\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>int main( int argc, char** argv )\n</code></pre>\n\n<p>(which is the way I write it).</p>\n\n<p>That's even how it is presented in the standard. And that\ninfluences people.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T02:22:52.817", "Id": "32737", "ParentId": "32321", "Score": "1" } } ]
{ "AcceptedAnswerId": "32323", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T08:46:30.733", "Id": "32321", "Score": "4", "Tags": [ "c++", "parsing", "beginner", "file" ], "Title": "Parsing argv with while-switch construct" }
32321
<p>I'm working on my students attendance system project. I have a list of students along with their ID (<code>jntuno</code>) and I need to create a database in MySQL for storing the daily attendance of each student for each subject.</p> <p><strong>Table:</strong> <code>students</code></p> <p><strong>Fields:</strong></p> <pre><code>slno int(5) auto increment, jntuno char(15), name char(50), primary key(slno,jntuno). </code></pre> <p><strong>Data:</strong></p> <p><img src="https://i.stack.imgur.com/zae9k.jpg" alt="Data in students table" /></p> <p>This <code>students</code> table holds the list of students and their IDs.</p> <p>Now I created another table:</p> <p><strong>Table:</strong> <code>dailyatt</code></p> <p><strong>Fields:</strong></p> <pre><code>date date, subject char(10), classesconducted int(2), `11341A0501` int(2), `11341A0502` int(2), `11341A0503` int(2), . . . `11341A0537` int(2), primary key(date,subject). </code></pre> <p>This table will look like:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>+------------+-----------+-----------------+------------+-----------+-----------+ |date |subject |classesconducted |11341A0501 |11341A0502 |11341A0503 |.... +------------+-----------+-----------------+------=-----+-----------+-----------+ | | | | | | | </code></pre> </blockquote> <p>Now every day upon entering the attendance on the PHP website, a new row will be created for each subject taught on that day.</p> <p>But many said that the database model is not a good one. Can someone suggest a better model for this kind of problem?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T17:23:44.847", "Id": "514557", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)." } ]
[ { "body": "<ol>\n<li>Remove all the <code>11341xxxx</code> fields.</li>\n<li>Add another table consisting of the student-ID and the course-number (I suppose, those <code>11341A0501</code>) are course numbers.</li>\n</ol>\n\n<p>To make it even better, introduce another table <code>Courses</code> with an ID (<code>autoinc</code>), the course-number (<code>11341A0501</code>) and -if you like- more information (name, description etc.)</p>\n\n<p>Then, your <code>student-visits-course</code> table consists of two columns(<code>student-ID</code>, <code>course-ID</code>)</p>\n\n<p><strong>Also</strong>: Why is <code>slno,jntuno</code> a combined primary key? use the <code>slno</code> alone and create a separate index on the <code>jntuno</code> column to speeding up searching for a specific student by number.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T12:22:06.850", "Id": "32326", "ParentId": "32322", "Score": "2" } }, { "body": "<ol>\n<li><p>Please use sensible names for your column names. Even though I read you explanation I can only vaguely guess what <code>slno</code> and <code>jntunno</code> might mean. I assume <code>jntunno</code> is some sort of student id (that's what I'm guessing from the <code>student</code> table - each student seems to have a unique one) - so what about <code>studentid</code>? I assume <code>slno</code> is simple primary id - so why no name it <code>id</code>?</p></li>\n<li><p>Your <code>dailyatt</code> table has a column for each student (based on my assumptions above). I assume it is supposed to show which student has attended a specific class at a specific date. Now what happens if you add a new student - you will have to add a new column to your db schema, and another one, and another one .... </p></li>\n</ol>\n\n<p>Furthermore the new students might not have been enrolled for older classes yet when you add a new column you have to choose a value for old attendances. So you start making special values for that case. </p>\n\n<p>Also try creating a query like <em>How many students have attended a specific class</em>. It will end up looking like this <code>select 11341A0501+11341A0502+... from dailyatt where ...</code> - not very nice.</p>\n\n<p><strong>In other words</strong>: Yes, it's a bad idea for more than one reason.</p>\n\n<p>When designing a schema and you try to think in terms of objects or concepts then a table should describe that object or concept - meaning the columns should be the properties of it and the rows should be the various instances of it. So I'd make three tables:</p>\n\n<p><code>courses</code> - describes courses (id, name, subject/description)</p>\n\n<p><code>classes</code> - describes classes (id, date and time, courseid) (so this table holds all the classes held for a specific course)</p>\n\n<p><code>classattendance</code> - student attendance for a specific class (id, classid, studentid)</p>\n\n<p>Then you could do a <code>select count(*) as numStudentsAttended from classattendance where classid = 1234</code> to find how many student attended a specific class for example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:47:16.803", "Id": "32338", "ParentId": "32322", "Score": "4" } }, { "body": "<p>In your <code>students</code> table, <code>slno</code> is already <code>AUTO_INCREMENT</code>, so the intention is that <code>slno</code> should uniquely identify a student. So why is <code>jntunno</code> also part of the primary key? I think it should be</p>\n\n<pre><code>CREATE TABLE students\n( slno int(5) NOT NULL AUTO_INCREMENT PRIMARY KEY\n, jntunno char(15) NOT NULL UNIQUE\n, name char(50)\n, UNIQUE KEY (jntunno)\n);\n</code></pre>\n\n<p>By the way, <code>slno</code> and <code>jntunno</code> are programmer-unfriendly names. Please pick something else.</p>\n\n<p><code>ALTER</code>ing the <code>dailyatt</code> table every time you add or remove a student is going to be a nightmare. Database schema changes should be extremely rare events, because they are risky, hard to manage, and hurt performance while they happen. Basically, it's wrong.</p>\n\n<pre><code>CREATE TABLE class_sessions\n( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY\n, date date\n, subject char(10)\n, classesconducted int(2)\n, UNIQUE KEY (date, subject) -- Maybe?\n);\n\nCREATE TABLE attendance\n( class_session_id INT NOT NULL\n, student_id int(5)\n, PRIMARY KEY (class_session_id, student_id)\n, FOREIGN KEY (class_session_id) REFERENCES class_sessions(id)\n, FOREIGN KEY (student_id) REFERENCES students(slno)\n);\n</code></pre>\n\n<p>If you want the data presented in one big table, with one column per student, you should leave it to your application-layer code or a <a href=\"https://stackoverflow.com/q/3516795/1157100\">stored procedure</a> to compose the query.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T23:28:30.783", "Id": "32439", "ParentId": "32322", "Score": "1" } } ]
{ "AcceptedAnswerId": "32338", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T09:44:54.487", "Id": "32322", "Score": "2", "Tags": [ "mysql", "sql" ], "Title": "Choice of tables for a project to handle attendance" }
32322
<p>I have a method to provide an <code>NSManagedObjectContext</code> using <code>UIManagedDocument</code>. I need to ensure that the <code>context</code> did initialize before I return, so I added an infinite while loop at the end of the method. But I think that was very stupid and is not acceptable. </p> <pre><code>- (NSManagedObjectContext *)context { NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; url = [url URLByAppendingPathComponent:@"Test"]; UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url]; if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) { [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) { if (success) { self.managedObjectContext = document.managedObjectContext; } else { NSLog(@"[%@ %@] FATAL Error CANNOT create DB", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); exit(1); } }]; } else if (document.documentState == UIDocumentStateClosed) { [document openWithCompletionHandler:^(BOOL success) { if (success) { self.managedObjectContext = document.managedObjectContext; } else { NSLog(@"[%@ %@] FATAL Error CANNOT open DB", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); exit(1); } }]; } else { self.managedObjectContext = document.managedObjectContext; } while (!self.managedObjectContext) { // Is there any way better? NSDate *futureTime = [NSDate dateWithTimeIntervalSinceNow:1]; [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:futureTime]; } return self.managedObjectContext; } </code></pre> <p>Any suggestion will be appreciated.</p>
[]
[ { "body": "<p>Create and run operation using </p>\n\n<pre><code>NSOperation *op = [NSBlockOperation ... your block...];\n[[NSOperationQueue new] addOperation: op];\n</code></pre>\n\n<p>and instead of using a runloop, wait for the result:</p>\n\n<pre><code>[op waitUntilFinished];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T22:45:56.143", "Id": "36381", "ParentId": "32324", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T10:55:27.333", "Id": "32324", "Score": "4", "Tags": [ "objective-c", "ios", "cocoa" ], "Title": "Is there a better way to make sure a variable is initialized when using blocks?" }
32324
<p>I have a website written in PHP but the whole script is old so today I started upgrading from Mysql to Mysqli.</p> <p>So here's my register page. I still have to add account confirmation and send mail part but that part can wait for now.</p> <pre><code>/* PUBLIC */ $IP = $_SERVER['REMOTE_ADDR']; /* PRIVATE */ if(isset($_POST['submit'])) { $email= $_POST['email']; $email_safe = $mysqli-&gt;real_escape_string($email); $password = $_POST['password']; $password_safe = $mysqli-&gt;real_escape_string($password); $password1 = $_POST['password1']; $password1_safe = $mysqli-&gt;real_escape_string($password1); @$referrer = $_POST['referrer']; $referrer_safe = $mysqli-&gt;real_escape_string($referrer); if ($password_safe == $password1_safe){ if(strlen($password) &lt; 8){ die('Password must be at least 8 characters'); } else { $result = $mysqli-&gt;query("SELECT email FROM user WHERE email='$email_safe'"); if ($result-&gt;num_rows &gt; 0) { die ("Duplicated email. Please use other email."); } else { $result = $mysqli-&gt;query("SELECT reg_ip FROM user WHERE reg_ip='$IP'"); if ($result-&gt;num_rows &gt; 0) { die ("Duplicated IP."); } else { $sql = "INSERT INTO user (email,passwd,ref) VALUES ('$email_safe','$password_safe','$referrer_safe')"; if(!$result = $mysqli-&gt;query($sql)){ die('There was an error running the query [' . $mysqli-&gt;error . ']'); } else { echo"Registering...."; } } } } } else { die ("Password didn't match. Please go back and fix this error."); } } else { HTML FORM } </code></pre> <p>Well ? How it's looking ? It is secure ? ( I mean any open gate :) )</p> <p>Thanks :) P.S : The code works 100%.</p> <p><img src="https://i.stack.imgur.com/FGP0U.jpg" alt="HTML form"></p>
[]
[ { "body": "<p>While it's great to see someone actually take the trouble to refactor code, to move away from the depreacted <code>mysql_*</code> extension, it's not so great to see that, like most, you're actually trying to use the replacement (<code>mysqli_*</code>) as a 1-on-1 copy of the old extension.<br/>\nOn a personal note, though I've restricted myself to only dealing with the <code>mysqli_*</code> extension, I couldn't help noticing you're using the OO API it offers. Personally, I find the <code>mysqli_*</code> API, both procedural <em>and</em> OO a tad, erm, ... messy. If you're collaborating with others, there's nothing to stop them from switching/inserting procedural-style code, and mixing it in with your OO code. That's just nasty. <code>PDO</code> is another, valid alternative. It's API is OO-only, a lot cleaner and waaaay more easy to use. It's said to be <em>slower</em>, but in reality, the differences are so minute, they don't outweight the upsides in terms of code maintainability. Look into <code>PDO</code>, too, is what I'm trying to say... :)</p>\n\n<p><em>Some history:</em><br/>\nThe old extension was created back in the days of MySQL version 3. Today, MySQL is already at version 5.6. Most hosts, if not all, offer mysql 5.x as standard DB. The list of features that weren't around back in the MySQL 3 era, but that are in common use now is rather impressive, and long:</p>\n\n<ul>\n<li>New and better storage engines</li>\n<li>Cursors</li>\n<li>Stored procedures, functions, views and triggers</li>\n<li>Foreign Key Contraints</li>\n<li>Cluster support (Though I'm no big fan of MySQL clusters)</li>\n<li>transactions (Commit, rollBack)</li>\n<li>Prepared statements!</li>\n<li><a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-nutshell.html\" rel=\"nofollow noreferrer\">Start here, browse back and forth between releases, and compare</a> for even more differences</li>\n</ul>\n\n<p>Of course, there were other reasons why the <code>mysql_*</code> extension was deprecated. Its source wasn't very maintainable, for example. It's been around longer than the ZendEngine2, too. In short: it'd become sort of historic ballast, that wouldn't have worked, considering the direction PHP is going in (compiled language, OOP supprt, namespaces...)</p>\n\n<p><em>Applied to your code:</em><br/>\nAll in all, there's a lot of changes, and some of them are quite useful when it comes to security. Take <em>prepared statements</em> for example (Note: <a href=\"http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html\" rel=\"nofollow noreferrer\">here's some info on what they are, what they do</a>). Rather than calling <code>$mysqli-&gt;escape_string()</code>, which as it happens <a href=\"http://php.net/manual/en/mysqli.real-escape-string.php\" rel=\"nofollow noreferrer\">requires you to set the charset!</a>, you can easily use a prepared statement, much to the same effect:</p>\n\n<pre><code>$emailStmt = $mysqli-&gt;prepare('SELECT email FROM user WHERE email= ?');\n$emailStmt-&gt;bindParam('s', $_POST['email');\n$emailStmt-&gt;bind_result($dbEmail);//fetches result into this variable\nif (!$emailStmt-&gt;execute() || $emailStmt-&gt;num_rows === 0)\n{\n header('Location: '.basename($_SERVER['PHP_SELF']));//302 redirect is fine here\n $emailStmt-&gt;close();\n $mysqli-&gt;close();//be tidy!\n exit();// I hate die statements\n}\n$emailStmt-&gt;close();\n</code></pre>\n\n<p>So, no tedious escaping of all params all the time anylonger, you don't even have to worry about the types anymore. Mysql is, after all, fairly picky when it comes to data-types. Sure it can handle <code>an_int_field &gt;= '123'</code>, but really, it's best to avoid forcing the DB server having to cast the data to the right type. That's not what it's for.<br/>\nAs I said in the comments, <code>mysqli-&gt;escape_string</code> is considered <em>as safe as prepared statements</em>, But:</p>\n\n<ul>\n<li>When working on your code, it's easy to <em>forget</em> that call to the <code>escape_string</code> method. Once you've forgotten that, your code is vulnerable to attacks.</li>\n<li>If you forget to set the correct char-set, your queries are no longer as safe as prepared statements would be</li>\n<li>getting into the habbit of using prepared statements is a good thing. You can prepare a single statement once, then use it to query your DB as much as you want. I've explained this <a href=\"https://codereview.stackexchange.com/questions/31853/is-there-a-more-efficient-way-of-executing-pdo-statements/31855#31855\">here</a>, with an example of how to do this.</li>\n<li>Preparing a statement for a simple query might seem like a bit <em>much</em>, and in some ways it is. That's why the <code>PDO</code> extension <em>emulates</em> the prepare calls. That's one of the benefits of <code>PDO</code>: the statements are prepared, without any intervention of the DB server, so there's very little overhead when using prepared stmts. Honestly, there's no reason <em>not</em> to use them.</li>\n</ul>\n\n<p>Anyway, I'm drifting off, slightly. What I'm actually trying to say is this:</p>\n\n<p>Since you're refactoring anyway, why not look into what sort of new goodies <code>mysqli_*</code> brings to the party? the <code>i</code> is for <em>improved</em> after all. Don't use it as a 1-on-1 copy of the old extension. Time has, as it tends to do, moved on. There are new features. Learn about them, and use them. You're code will be more reliable, more maintainable, more future proof and 9/10 more safe, too, because of it.<br/>\nBegin with using prepared statements, then move along to transactions. That's just a tip.</p>\n\n<p><em>Some other thoughts</em><br/>\nI see (or rather don't see) a worrying lack of data validation in your code. You just <em>assume</em> <code>$_POST['email']</code> is going to be set, and that its value is going to be an email address. At no point in time, do I see you use something like this:</p>\n\n<pre><code>if (isset($_POST['email'])) &amp;&amp; filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))\n{\n //query DB\n}\nelse\n{\n exit('no valid email address provided');\n}\n</code></pre>\n\n<p>The only time your code reflects any form of awareness that, perhaps, some POST data might not be set is here:</p>\n\n<pre><code> @$referrer = $_POST['referrer'];\n</code></pre>\n\n<p>But the way it's dealt with just gets to me. As I've said before, and as I will keep on saying until either the supressor of death (<code>@</code>, that is) or I am no more:</p>\n\n<blockquote>\n <p>Argh... the <code>@</code> suppressor of death! I hate that, don't use it... save for those few rare use-cases where you can't help a notice from being issued (seen this only 2 or 3 times in 10 years). If there's a notice, there's an issue, if there's an issue: don't ignore it <em>fix it</em>!</p>\n</blockquote>\n\n<p>In this case, there isn't even an issue that needs fixing, except for the <code>@</code> itself. Why not simply write:</p>\n\n<pre><code>$referrer = null;//declare var and assign null value\nif (isset($_POST['referrer']))\n{\n $referrer = $_POST['referrer'];\n}\n</code></pre>\n\n<p><code>isset</code> is a language construct, and therefore it's fast. supressing a notice isn't fast, it's slow, and completely pointless in most (if not all) cases. Don't.<br/>\nIf you don't want your code to be too long, because of all the <code>if(isset</code> branches, you can <em>easily</em> replace them with something like this:</p>\n\n<pre><code>if (isset($_POST))\n{\n $email = $password= $password1 = $referrer = false;//all default value\n foreach($_POST as $key =&gt; $value)\n {\n if (isset($$key) &amp;&amp; $$key === false)\n {//variable variable, check if it exists, and if its value is false\n $$key = trim($value);//if it is, assign POST val... perhaps trim while you're at it?\n }\n }\n}\n</code></pre>\n\n<p>With this code, though not very maintainable, you save a lot of space, and you <em>know</em> that if any of the variable's used holds <code>false</code> as a value, it wasn't posted. All other variables (the ones that <em>aren't</em> false) have been reassigned the posted data.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T15:56:18.430", "Id": "51616", "Score": "0", "body": "Huh, well, thanks for your reply. - Still trying to understand your reply fully, but thanks for referrer fix. About email verification, is being done by HTML code http://imageshack.com/scaled/800x600/15/4jk6.jpg" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T16:03:02.023", "Id": "51619", "Score": "0", "body": "About prepared statement, isn't that to much for a simple query ? In case I have an error , It's hard to find a fix for mysqli, therefore I try to keep it simple." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:07:53.643", "Id": "51626", "Score": "0", "body": "@rgerculy: HTML (client side) validation of the input is all well and good, but what if I were to disable JS? I would be able to post anything as email input. _Never_ trust client input, and _always_ validate/sanitize the input server-side, too. Escaping input is safer than blindly concatenating input into queries, true, it's even considered to be _as safe as prepared statements_, but your code remains [more error prone](http://stackoverflow.com/questions/13026469/mysql-escape-string-vulnerabilities), I'll add some more details to my answer on that subject" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:27:25.930", "Id": "51629", "Score": "0", "body": "True, without JS everything is down. Thanks for help and update." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T15:42:59.757", "Id": "32331", "ParentId": "32330", "Score": "1" } } ]
{ "AcceptedAnswerId": "32331", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T14:35:24.033", "Id": "32330", "Score": "3", "Tags": [ "php", "mysqli" ], "Title": "PHP Register Page ( MYSQLI )" }
32330
<p>Here is the implementation with the interface below:</p> <pre><code>public class DoublyLinkedList&lt;E&gt; implements ListInterface&lt;E&gt;, ListIteratorInterface&lt;E&gt; { private DoublyLinkedListNode&lt;E&gt; head; private DoublyLinkedListNode&lt;E&gt; tail; private DoublyLinkedListNode&lt;E&gt; currentNode; private int size; /** * Create a new empty DoublyLinkedList object. */ public DoublyLinkedList() { this.currentNode = this.head = new DoublyLinkedListNode&lt;E&gt;(null, null, null); this.tail = new DoublyLinkedListNode&lt;E&gt;(null, this.head, null); this.head.setNextNode(this.tail); this.size = 0; } @Override public void insert(E item) { this.currentNode.setNextNode(new DoublyLinkedListNode&lt;E&gt;(item, this.currentNode, this.currentNode.getNextNode())); this.currentNode.getNextNode().getNextNode() .setPreviousNode(this.currentNode.getNextNode()); this.size++; } @Override public void append(E item) { this.tail.setPreviousNode(new DoublyLinkedListNode&lt;E&gt;(item, this.tail .getPreviousNode(), this.tail)); this.tail.getPreviousNode().getPreviousNode() .setNextNode(this.tail.getPreviousNode()); this.size++; } @Override public E remove() { if (this.currentNode.getNextNode() == this.tail) { return null; // empty linked list } E item = this.currentNode.getNextNode().getValue(); // remember value to // be deleted this.currentNode.getNextNode().getNextNode() .setPreviousNode(this.currentNode); // remove current node this.currentNode.setNextNode(this.currentNode.getNextNode() .getNextNode()); this.size--; return item; } @Override public void clear() { // drop access to all other nodes this.head.setNextNode(null); this.currentNode = this.head = new DoublyLinkedListNode&lt;E&gt;(null, null, null); this.tail = new DoublyLinkedListNode&lt;E&gt;(null, this.head, null); this.head.setNextNode(this.tail); this.size = 0; } @Override public void moveToStart() { this.currentNode = this.head; } @Override public void moveToEnd() { this.currentNode = this.tail.getPreviousNode(); } @Override public boolean previous() { if (this.currentNode != this.head) { this.currentNode = this.currentNode.getPreviousNode(); return true; } else { return false; // no node before head node } } @Override public boolean next() { if (this.currentNode != this.tail.getPreviousNode()) { this.currentNode = this.currentNode.getNextNode(); return true; } else { return false; } } @Override public int length() { return this.size; } @Override public int currentPosition() { DoublyLinkedListNode&lt;E&gt; tempNode = this.head; int indexOfCurrentNode; for (indexOfCurrentNode = 0; this.currentNode != tempNode; indexOfCurrentNode++) { tempNode = tempNode.getNextNode(); } return indexOfCurrentNode; } @Override public void moveCurrentToPosition(int position) { if (position &lt; 0 || position &gt; this.size) { throw new IllegalArgumentException( "In method moveCurrentToPosition of class " + "DoublyLinkedList the input node postion to be " + "removed is out of bounds"); } this.currentNode = this.head; for (int i = 0; i &lt; position; i++) { this.currentNode = this.currentNode.getNextNode(); } } @Override public E getValue() { if (this.currentNode.getNextNode() == this.tail) { return null; } else { return this.currentNode.getNextNode().getValue(); } } /** * Creates a easy to read String representation of the doubly linked lists * contents. * * Example 1: &lt; 1 2 3 4 | 5 6 &gt; * * The vertical bar = the link immediately after the current node. * * @author Clifford A. Shaffer */ public String toString() { int oldPosition = this.currentPosition(); int length = this.length(); StringBuffer linkedListAsString = new StringBuffer((length() + 1) * 4); this.moveToStart(); linkedListAsString.append("&lt; "); for (int i = 0; i &lt; oldPosition; i++) { linkedListAsString.append(this.getValue()); linkedListAsString.append(" "); this.next(); } linkedListAsString.append("| "); for (int i = oldPosition; i &lt; length; i++) { linkedListAsString.append(this.getValue()); linkedListAsString.append(" "); this.next(); } linkedListAsString.append("&gt;"); this.moveCurrentToPosition(oldPosition); return linkedListAsString.toString(); } } </code></pre> <p>Here is the ListInterface and ListIteratorIterface</p> <pre><code>public interface ListInterface&lt;E&gt; { /** * Insert an element behind the current position. Must check that the linked * list's capacity is not exceeded. * * @param item * Item to be inserted. */ public void insert(E item); /** * Insert an element after the last element in the list. * * @param item * Item to be appended. */ public void append(E item); /** * Remove all contents from the list. */ public void clear(); /** * @return The number of items in the list. */ public int length(); /** * @param position * Position to move current to. */ public void moveCurrentToPosition(int position); } public interface ListIteratorInterface&lt;E&gt; { /** * Remove the element after the current element and return the value of the * removed element. * * @return The element that was removed. */ public E remove(); /** * Move current position to first element. */ public void moveToStart(); /** * Move current position to last element. */ public void moveToEnd(); /** * Move the current position one element before. No change if already at the * beginning. * * @return True if moved to previous position; otherwise return false. */ public boolean previous(); /** * Move the current position one element after. No change if already at the * end. * * @return True if moved to current position; otherwise return false. */ public boolean next(); /** * @return The current position. */ public int currentPosition(); /** * @return The current item in the current position. */ public E getValue(); } </code></pre>
[]
[ { "body": "<p>1) I would rename <code>getValue()</code> in your iterator to <code>currentValue()</code> to make it consistent with <code>currentPosition()</code> and also to express in name what the comment says (get current item).</p>\n\n<p>2) I don't like how the <code>ListInterface</code> and <code>ListIteratorInterface</code> implementations introduce a state in the list for the current position. It intermingles data representation with iteration. Also both <code>ListInterface</code> and <code>ListIteratorInterface</code> contain methods regarding a current position so they are no longer clearly separated.</p>\n\n<p>Have a look at C++ iterators. They remove the iteration concern completely from the list (by keeping the iteration state in the iterator and not in the list) yet allow you to do what you want: insert an element at a specific position (<code>Insert(iterator, value)</code>).</p>\n\n<ul>\n<li>You should remove the <code>currentNode</code> concept from your implementation and make an actual iterator object keeping the state.</li>\n<li>Remove the <code>moveCurrentPosition</code> from the <code>ListInterface</code> - that interface should have nothing to do with iteration except maybe accept an iterator for <code>insert</code> so you can insert an element at a specific position.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T19:30:01.027", "Id": "32343", "ParentId": "32335", "Score": "1" } } ]
{ "AcceptedAnswerId": "32343", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:33:44.567", "Id": "32335", "Score": "1", "Tags": [ "java", "linked-list", "interface" ], "Title": "Can someone review my doubly linked list?" }
32335
<p>The following is working but I just want to know if I can make it better in any way. The header file can be <a href="https://github.com/quinnliu/DataStructuresAlgorithmsDesignPatterns/blob/master/src/dataStructures/polynomialInC/Polynomial.h" rel="nofollow">viewed here</a>. </p> <pre><code>#include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include "Polynomial.h" static int64_t power(int64_t x, uint64_t y); /** * Initializes *P as described below. * * Pre: P points to an uninitialized Polynomial object, * C != NULL, * C[i] initialized for i = 0:D * Post: P-&gt;Degree == D, * P-&gt;Coeff != C (array is duplicated, not linked), * P-&gt;Coeff[i] == C[i] for i = 0:D * Returns: false if *P cannot be properly initialized, true otherwise */bool Polynomial_Set(Polynomial* const P, const uint8_t D, const int64_t* const C) { if (P == NULL || C == NULL ) { return false; } P-&gt;Degree = D; P-&gt;Coeff = malloc((D + 1) * sizeof(int64_t)); // malloc returns NULL if block of memory cannot be allocated if (P == NULL ) { return false; } else { for (int i = 0; i &lt;= P-&gt;Degree; i++) { P-&gt;Coeff[i] = C[i]; } return true; } } /** * Initializes *Target from *Source as described below. * * Pre: Target points to a Polynomial object, * Source points to a properly-initialized Polynomial object * Post: Target-&gt;Degree == Source-&gt;Degree, * Target-&gt;Coeff != Source-&gt;Coeff, * Target-&gt;Coeff[i] == Source-&gt;Coeff[i] for i = 0:Source-&gt;Degree * Returns: false if *Target cannot be properly initialized, true otherwise */bool Polynomial_Copy(Polynomial* const Target, const Polynomial* const Source) { return Polynomial_Set(Target, Source-&gt;Degree, Source-&gt;Coeff); } /** * Compares two polynomials. * * Pre: Left points to a properly-initialized Polynomial object, * Right points to a properly-initialized Polynomial object * Returns: true if Left and Right have the same coefficients, false otherwise */bool Polynomial_Equals(const Polynomial* const Left, const Polynomial* const Right) { if (Left-&gt;Degree != Right-&gt;Degree) { return false; } for (int i = 0; i &lt;= Left-&gt;Degree; i++) { if (Left-&gt;Coeff[i] != Right-&gt;Coeff[i]) { return false; } } return true; // since all coefficients are equal between // the two polynomials } /** * Computes value of polynomial at X. * * Pre: P points to a properly-initialized Polynomial object * Returns: value of P(X); 0 if cannot be evaluated */ int64_t Polynomial_EvaluateAt(const Polynomial* const P, const int64_t X) { if (P == NULL ) { return 0; } //TODO: check for overflow, only 2^63 bits can be used to represent the evaluated number int64_t result = 0; for (int i = 0; i &lt;= P-&gt;Degree; i++) { int64_t termCoefficient = P-&gt;Coeff[i]; // 3 int64_t termResult = termCoefficient * power(X, i); result = result + termResult; } return result; } /** * Initializes *Scaled to represent K times *Source * * Pre: Scaled points to a Polynomial object, * Source points to a properly-initialized Polynomial object, * Source != Target * Post: Scaled-&gt;Degree == Source-&gt;Degree, * Scaled-&gt;Coeff != Source-&gt;Coeff, * Scaled-&gt;Coeff[i] == K * Source-&gt;Coeff[i] for i = 0:Scaled-&gt;Degree * Returns: false if *Scaled cannot be properly initialized, true otherwise */bool Polynomial_Scale(Polynomial* const Scaled, const Polynomial* const Source, const int64_t K) { if (Polynomial_Copy(Scaled, Source) == false || Scaled == NULL || Source == NULL ) { return false; } else { for (int i = 0; i &lt;= Scaled-&gt;Degree; i++) { Scaled-&gt;Coeff[i] = K * Scaled-&gt;Coeff[i]; } return true; } } /** * Initializes *Sum to equal *Left + *Right. * * Pre: Sum points to a Polynomial object, * Left points to a properly-initialized Polynomial object, * Right points to a properly-initialized Polynomial object, * Sum != Left, * Sum != Right * Post: Sum-&gt;Degree == max(Left-&gt;Degree, Right-&gt;Degree), * Sum-&gt;Coeff[i] == Left-&gt;Coeff[i] + Right-&gt;Coeff[i] * with proper allowance for the case that * Left-&gt;Degree != Right-&gt;Degree * Returns: false if *Sum cannot be properly initialized, true otherwise */bool Polynomial_Add(Polynomial* const Sum, const Polynomial* const Left, const Polynomial* const Right) { if (Sum == NULL || Left == NULL || Right == NULL ) { return false; } if (Left-&gt;Degree &gt; Right-&gt;Degree) { if (Polynomial_Set(Sum, Left-&gt;Degree, Left-&gt;Coeff)) { for (int i = 0; i &lt;= Right-&gt;Degree; i++) { Sum-&gt;Coeff[i] = Sum-&gt;Coeff[i] + Right-&gt;Coeff[i]; } Sum-&gt;Degree = Left-&gt;Degree; } else { return false; } } else { // Right polynomial &gt; Left polynomial || Right polynomial == Left polynomial if (Polynomial_Set(Sum, Right-&gt;Degree, Right-&gt;Coeff)) { for (int i = 0; i &lt;= Left-&gt;Degree; i++) { Sum-&gt;Coeff[i] = Sum-&gt;Coeff[i] + Left-&gt;Coeff[i]; } Sum-&gt;Degree = Right-&gt;Degree; } else { return false; } } // Consider the case where largest degrees has the same coefficients // for Left and Right polynomial and cancel out each other lowering // the degree by one. ex. Largest term in each polynomial are // 2X^7 and -2X^7 means the Sum will have a degree less than 7. // The exact same problem can reoccur for the next polynomial term as // well. // 1 + 3X^1 + 3X^2 + 4X^3 // -1 - 2X^1 - 3X^2 - 4X^3 int sumDegree = Sum-&gt;Degree; while(Sum-&gt;Coeff[sumDegree] == 0 &amp;&amp; sumDegree &gt;= 0) { Sum-&gt;Degree -= 1; sumDegree--; } return true; } /** * Initializes *Diff to equal *Left - *Right. * * Pre: Diff points to a Polynomial object, * Left points to a properly-initialized Polynomial object, * Right points to a properly-initialized Polynomial object, * Diff != Left, * Diff != Right * Post: Diff-&gt;Degree is set correctly, * Diff-&gt;Coeff[i] == Left-&gt;Coeff[i] - Right-&gt;Coeff[i] * with proper allowance for the case that * Left-&gt;Degree != Right-&gt;Degree * Returns: false if *Diff cannot be properly initialized, true otherwise */bool Polynomial_Subtract(Polynomial* const Diff, const Polynomial* const Left, const Polynomial* const Right) { if (Diff == NULL || Left == NULL || Right == NULL ) { return false; } for (int i = 0; i &lt;= Right-&gt;Degree; i++) { Right-&gt;Coeff[i] = -Right-&gt;Coeff[i]; } return Polynomial_Add(Diff, Left, Right); } /** * Computes the first derivative of Source. * * Pre: Target points to a Polynomial object, * Source points to a properly-initialized Polynomial object, * Target != Source * Post: Target-&gt;Degree is set correctly * Target-&gt;Coeff[i] == iith coefficient of Source' * * Returns: false if Source' cannot be properly initialized, true otherwise */bool Polynomial_Differentiate(Polynomial* const Target, const Polynomial* const Source) { if (Target == NULL || Source == NULL ) { return false; } // EXAMPLE: //Source-&gt;Coeff 0 1 2 3 // 1X^0 + 2X^1 + 3X^2 + 4X^3 // 0 + 2*1X^0 + 2*3X^1 + 3*4X^2 //free(Target-&gt;Coeff); if (Source-&gt;Degree == 0) { Polynomial_Zero(Source); Polynomial_Copy(Target, Source); return true; } Target-&gt;Degree = Source-&gt;Degree - 1; // add 1 to Target-&gt;Degree because one additional space is need to // hold a int64_t at Target-&gt;Coeff[0] Target-&gt;Coeff = malloc((Target-&gt;Degree + 1) * sizeof(int64_t)); for (int degree = 1; degree &lt;= Source-&gt;Degree; degree++) { //Target-&gt;Coeff[0] = 1 * 2 = 2 //Target-&gt;Coeff[1] = 2 * 3 = 6 //Target-&gt;Coeff[2] = 3 * 4 = 12 Target-&gt;Coeff[degree-1] = degree * Source-&gt;Coeff[degree]; } return true; } /** * Reset P to represent zero polynomial. * * Pre: P points to a Polynomial object * Post: P-&gt;Degree == 0 * P-&gt;Coeff is set appropriately */bool Polynomial_Zero(Polynomial* const P) { if (P == NULL ) { return false; } else { free(P-&gt;Coeff); P-&gt;Degree = 0; P-&gt;Coeff = malloc((P-&gt;Degree + 1) * sizeof(int64_t)); P-&gt;Coeff[0] = 0; return true; } } /** * power function that calculated x raised to the * power y in O(log N). */ static int64_t power(int64_t x, uint64_t y) { int temp; if (y == 0) { return 1; } temp = power(x, y / 2); if (y % 2 == 0) { return temp * temp; } else { return x * temp * temp; } } </code></pre>
[]
[ { "body": "<p><code>Polynomial_EvaluateAt</code> returns 0 if <code>P</code> is <code>NULL</code>. But I guess the function could also return 0 as part of a \"normal\" result (X == 0 for example). Not sure if it's important to distinguish between those two. You could consider returning a <code>bool</code> and pass the result through a pass-by-ref argument. This would be slightly more consistent with your other functions which basically do the same.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T19:07:58.130", "Id": "32341", "ParentId": "32336", "Score": "1" } } ]
{ "AcceptedAnswerId": "32341", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:36:57.650", "Id": "32336", "Score": "1", "Tags": [ "c", "mathematics" ], "Title": "Polynomial data structure" }
32336
<p>Can someone review this?</p> <p>The header file can be <a href="https://github.com/quinnliu/DataStructuresAlgorithmsDesignPatterns/blob/master/src/dataStructures/rationalInC/Rational.h" rel="nofollow">viewed here</a>.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #include &lt;math.h&gt; // searches default library classpaths #include "Rational.h" // searchs my directory // let's the compiler know that this is a function static bool Rational_isPositive(Rational rational); static double absolute(double number); /** * Creates and initializes a new Rational object. * Pre: * Denominator != 0 * Returns: * A Rational object X such that X.Top == Numerator * and X.Bottom = Denominator. */ Rational Rational_Construct(int Numerator, int Denominator) { // make all rationals into the equivalent rational with // either a postive or negative numerator and never a // negative denominator Rational newRational; if (Numerator &lt; 0 &amp;&amp; Denominator &lt; 0) { Numerator = -Numerator; Denominator = -Denominator; } else if (Numerator &gt;= 0 &amp;&amp; Denominator &lt; 0) { Numerator = -Numerator; Denominator = -Denominator; } newRational.Top = Numerator; if (Denominator != 0) { newRational.Bottom = Denominator; } else { printf("You have set a denominator = 0"); newRational.Bottom = 0; } return newRational; } /** * Compute the arithmetic negation of R. * Pre: * R has been properly initialized. * Returns: * A Rational object X such that X + R = 0. */ Rational Rational_Negate(const Rational R) { Rational negatedR; negatedR.Top = -R.Top; negatedR.Bottom = R.Bottom; return negatedR; } /** * Compute the arithmetic floor of R. * Pre: * R has been properly initialized. * Returns: * The largest integer N such that N &lt;= R. */ int Rational_Floor(const Rational R) { if (Rational_isPositive(R)) { return R.Top / R.Bottom; } else { if (R.Top % R.Bottom == 0) { return R.Top / R.Bottom; } else { return R.Top / R.Bottom - 1; } } } /** * Compute the arithmetic ceiling of R. * Pre: * R has been properly initialized. * Returns: * The smallest integer N such that N &gt;= R. */ int Rational_Ceiling(const Rational R) { if (Rational_isPositive(R)) { if (R.Top % R.Bottom == 0) { return R.Top / R.Bottom; } else { return R.Top / R.Bottom + 1; } } else { return R.Top / R.Bottom; } } /** * Round R to the nearest integer. * Pre: * R has been properly initialized. * Returns: * The closest integer N to R. */ int Rational_Round(const Rational R) { double decimalFormat = (double) R.Top / (double) R.Bottom; double R_ceiling = (double) Rational_Ceiling(R); double R_floor = (double) Rational_Floor(R); double distanceToR_ceiling = absolute(R_ceiling - decimalFormat); double distanceToR_floor = absolute(R_floor - decimalFormat); // decimalFormat is closer to the ceiling if (distanceToR_ceiling &lt; distanceToR_floor) { return (int) R_ceiling; } else { return (int) R_floor; } } /** * Compute the sum of Left and Right. * Pre: * Left and Right have been properly initialized. * Returns: * A Rational object X equal to Left + Right. */ Rational Rational_Add(const Rational Left, const Rational Right) { Rational sum; sum.Top = (Left.Top * Right.Bottom) + (Right.Top * Left.Bottom); sum.Bottom = Left.Bottom * Right.Bottom; return sum; } /** * Compute the difference of Left and Right. * Pre: * Left and Right have been properly initialized. * Returns: * A Rational object X equal to Left - Right. */ Rational Rational_Subtract(const Rational Left, const Rational Right) { Rational sum; sum.Top = (Left.Top * Right.Bottom) - (Right.Top * Left.Bottom); sum.Bottom = Left.Bottom * Right.Bottom; return sum; } /** * Compute the product of Left and Right. * Pre: * Left and Right have been properly initialized. * Returns: * A Rational object X equal to Left * Right. */ Rational Rational_Multiply(const Rational Left, const Rational Right) { Rational product; product.Top = Left.Top * Right.Top; product.Bottom = Left.Bottom * Right.Bottom; return product; } /** * Compute the quotient of Left and Right. * Pre: * Left and Right have been properly initialized. * Right != 0. * Returns: * A Rational object X equal to Left / Right. */ Rational Rational_Divide(const Rational Left, const Rational Right) { Rational quotient; quotient.Top = Left.Top * Right.Bottom; quotient.Bottom = Left.Bottom * Right.Top; return quotient; } /** * Determine whether Left and Right are equal. * Pre: * Left and Right have been properly initialized. * Returns: * True if Left == Right, false otherwise. */ bool Rational_Equals(const Rational Left, const Rational Right) { if (Left.Top * Right.Bottom == Left.Bottom * Right.Top) { return true; } else { return false; } } /** * Determine whether Left and Right are not equal. * Pre: * Left and Right have been properly initialized. * Returns: * True if Left != Right, false otherwise. */ bool Rational_NotEquals(const Rational Left, const Rational Right) { if (Rational_Equals(Left, Right)) { return false; } else { return true; } } /** * Determine whether Left is less than Right. * Pre: * Left and Right have been properly initialized. * Returns: * True if Left &lt; Right, false otherwise. */ bool Rational_LessThan(const Rational Left, const Rational Right) { // double leftValue = (double) Left.Top / (double) Left.Bottom; // double rightValue = (double) Right.Top / (double) Right.Bottom; int leftValue = Left.Top * Right.Bottom; int rightValue = Left.Bottom * Right.Top; if (leftValue &lt; rightValue) { return true; } else { return false; } } /** * Determine whether Left is less than or equal to Right. * Pre: * Left and Right have been properly initialized. * Returns: * True if Left &lt;= Right, false otherwise. */ bool Rational_LessThanOrEqual(const Rational Left, const Rational Right) { if( Rational_Equals(Left, Right) | Rational_LessThan(Left, Right)) { return true; } else { return false; } } /** * Determine whether Left is greater than Right. * Pre: * Left and Right have been properly initialized. * Returns: * True if Left &gt; Right, false otherwise. */ bool Rational_GreaterThan(const Rational Left, const Rational Right) { if (Rational_LessThanOrEqual(Left, Right)) { return false; } else { return true; } } /** * Determine whether Left is greater than or equal to Right. * Pre: * Left and Right have been properly initialized. * Returns: * True if Left &gt;= Right, false otherwise. */ bool Rational_GreaterThanOrEqual(const Rational Left, const Rational Right) { if (Rational_GreaterThan(Left, Right) | Rational_Equals(Left, Right)) { return true; } else { return false; } } /** * Determines if rational is positive. * Pre: rational has been properly initialized. * Returns: True if rational &gt;=0, false otherwise. */ static bool Rational_isPositive(Rational rational) { // all rationals are equivalently represented without a negative // denominator if (rational.Top &gt;= 0) { return true; } else { return false; } } /** * Computes absolute value of a double number. */ static double absolute(double number) { if (number &lt; 0) { return -number; } else { return number; } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>I like that you are treating your rationals as immutable by returning new rationals from all your operations.</p></li>\n<li><p>Your naming conventions are a bit unusual. In most C like languages (C, C++, C#, Java) local variables and parameters are <code>camelCase</code>. Specifically in C method names tend to be <code>camelCase</code> or <code>snake_case</code>. </p></li>\n<li><p>You are using the mathematical terms <code>Numerator</code> and <code>Denominator</code> for the parameters of you construction function however you use <code>Top</code> and <code>Bottom</code> for the properties of you <code>Rational</code> type which seems a bit unusual - why not stick to the mathematical terms?</p></li>\n<li><p>When someone passes in a <code>Denominator</code> which is <code>0</code> you just have a <code>printf</code> in there. </p>\n\n<ul>\n<li>If anything it should print at least to <code>stderr</code>.</li>\n<li>It doesn't really alert the programer to the error and just fails in some later operations anyway (like <code>Round</code>, <code>Floor</code>, <code>Ceil</code>).</li>\n</ul>\n\n<p>Consider forcing the error by causing the div by zero right there or changing the interface of the method to:</p>\n\n<pre><code>bool Rational_Construct(int numerator, int denominator, Rational* result)\n</code></pre>\n\n<p>and return <code>false</code> if the input is invalid.</p></li>\n<li><p>Most of your comparisons like this</p>\n\n<pre><code>if (Left.Top * Right.Bottom == Left.Bottom * Right.Top) {\n return true;\n} else {\n return false;\n}\n</code></pre>\n\n<p>can be shortened to </p>\n\n<pre><code>return Left.Top * Right.Bottom == Left.Bottom * Right.Top;\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T18:58:59.007", "Id": "510369", "Score": "0", "body": "As an alternative to printing an error if the denominator is zero, consider printing `inf`, `-inf` and `nan`, to match the behavior of [`float` and `double`](https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T08:58:12.167", "Id": "36949", "ParentId": "32337", "Score": "7" } }, { "body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/36949/11728\">ChrisWue's comments</a>, I'd add:</p>\n\n<ol>\n<li><p>In this block of code:</p>\n\n<pre><code>if (Numerator &lt; 0 &amp;&amp; Denominator &lt; 0) {\n Numerator = -Numerator;\n Denominator = -Denominator;\n} else if (Numerator &gt;= 0 &amp;&amp; Denominator &lt; 0) {\n Numerator = -Numerator;\n Denominator = -Denominator;\n} \n</code></pre>\n\n<p>both branches do the same thing, so you could combine them into one condition:</p>\n\n<pre><code>if (Numerator &lt; 0 &amp;&amp; Denominator &lt; 0 || Numerator &gt;= 0 &amp;&amp; Denominator &lt; 0) {\n Numerator = -Numerator;\n Denominator = -Denominator;\n}\n</code></pre>\n\n<p>Now both parts of the condition have <code>Denominator &lt; 0</code>, so you could write:</p>\n\n<pre><code>if ((Numerator &lt; 0 || Numerator &gt;= 0) &amp;&amp; Denominator &lt; 0) {\n Numerator = -Numerator;\n Denominator = -Denominator;\n}\n</code></pre>\n\n<p>Now it's clear that the condition <code>Numerator &lt; 0 || Numerator &gt;= 0</code> is always true, so it can be dropped, leaving:</p>\n\n<pre><code>if (Denominator &lt; 0) {\n Numerator = -Numerator;\n Denominator = -Denominator;\n}\n</code></pre></li>\n<li><p>In the comment for <code>Rational_Construct</code> you specify a precondition <code>Denominator != 0</code>. But if the caller passes in zero, then you just print a message to standard output. It would be better to write:</p>\n\n<pre><code>assert(Denominator != 0)\n</code></pre>\n\n<p>so that the program aborts. Having rationals with denominator 0 leads to many sorts of trouble: for example the rational <sup>0</sup>/<sub>0</sub> compares equal to every other rational.</p></li>\n<li><p>The comment for <code>Rational_Construct</code> says that it returns:</p>\n\n<pre><code>A Rational object X such that X.Top == Numerator and X.Bottom = Denominator.\n</code></pre>\n\n<p>but in fact this is not true, since the denominator may be negated. Instead it should say something like:</p>\n\n<pre><code>A Rational object R such that R.Top/R.Bottom == Numerator/Denominator.\n</code></pre></li>\n<li><p>Your operator implementations don't call <code>Rational_Construct</code>: they just build a new <code>Rational</code> structure however they please. This means that the consistency checks in <code>Rational_Construct</code> (such as making sure that the denominator is positive) are skipped.</p>\n\n<p>It would result in shorter and more reliable code if you always called <code>Rational_Construct</code>. For example:</p>\n\n<pre><code>Rational Rational_Negate(const Rational R) {\n return Rational_Construct(-R.Top, R.Bottom);\n}\n\nRational Rational_Add(const Rational Left, const Rational Right) {\n return Rational_Construct(Left.Top * Right.Bottom + Right.Top * Left.Bottom,\n Left.Bottom * Right.Bottom);\n}\n</code></pre></li>\n<li><p>Even small computations with your rationals result in integer overflow. For example, consider the following program:</p>\n\n<pre><code>int main(int argc, char **argv) {\n Rational sixteenth = Rational_Construct(1, 16);\n Rational sum = Rational_Construct(0, 1);\n int i;\n for (i = 0; i &lt; 10; ++i) {\n sum = Rational_Add(sum, sixteenth);\n printf(\"%d/%d\\n\", sum.Top, sum.Bottom);\n }\n return 0;\n}\n</code></pre>\n\n<p>The program looks as if it is supposed to add <sup>1</sup>/<sub>16</sub> ten times, getting the result <sup>10</sup>/<sub>16</sub>. But it actually has undefined behaviour due to signed integer overflow. On my computer it prints:</p>\n\n<pre><code>1/16\n32/256\n768/4096\n16384/65536\n327680/1048576\n6291456/16777216\n117440512/268435456\n-2147483648/0\n0/0\n0/0\n</code></pre>\n\n<p>Now, because you're using C's fixed-size integers, there are bound to be computations whose results are too large to be represented. But it would be better to raise an error when the result is too large, rather than causing undefined behaviour. And you should at the very least make some effort to ensure that integer overflow doesn't happen in small examples like this: when we add <sup>1</sup>/<sub>16</sub> ten times we ought to be able to get <sup>10</sup>/<sub>16</sub>.</p>\n\n<p>An easy way to avoid integer overflow in small examples is to always reduce rationals to their lowest terms (thus turning <sup>2</sup>/<sub>4</sub> as <sup>1</sup>/<sub>2</sub>). For example, you could do this:</p>\n\n<pre><code>#include &lt;assert.h&gt; /* for the assert() prototype */\n#include &lt;limits.h&gt; /* for INT_MIN */\n#include &lt;stdlib.h&gt; /* for the abs() prototype */\n\nRational Rational_Construct(int Numerator, int Denominator) {\n /* Ensure that Denominator is positive */\n assert(Denominator != 0);\n if (Denominator &lt; 0) {\n assert(Numerator != INT_MIN);\n assert(Denominator != INT_MIN);\n Numerator = -Numerator;\n Denominator = -Denominator;\n }\n\n /* Find the greatest common divisor of Numerator and Denominator. */\n int a = abs(Numerator), b = Denominator;\n while (b) {\n int c = a % b;\n a = b;\n b = c;\n }\n\n /* Reduce the fraction to lowest terms. */\n Rational newRational;\n newRational.Top = Numerator / a;\n newRational.Bottom = Denominator / a;\n return newRational;\n}\n</code></pre>\n\n<p>Now the program I gave above prints:</p>\n\n<pre><code>1/16\n1/8\n3/16\n1/4\n5/16\n3/8\n7/16\n1/2\n9/16\n5/8\n</code></pre>\n\n<p>(Of course this doesn't solve the integer overflow problem in the general case, but at least it allows small programs like this to complete successfully.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T11:41:48.897", "Id": "36954", "ParentId": "32337", "Score": "7" } }, { "body": "<ol>\n<li><p>Usually only one of the two scalars of a rational has a sign and usually the so-called numerator is the scalar having the sign. This in turn would translate to:</p>\n<pre><code> typedef struct {\n int Numerator;\n unsigned Denominator;\n } Rational;\n</code></pre>\n</li>\n</ol>\n<p>This choice will gift you with less code for the sign management and 1 extra bit of data.</p>\n<ol start=\"2\">\n<li><p>Denominators cannot be zero, unless you want to have a wasteful number of representations of the infinity and really need to handle them in operations.\nSo denominators should be represented as <code>n-1</code>, that is you write <code>0</code> (<em>zero</em>) but actually mean <code>1</code> (<em>one</em>). Maybe a little bit more code but an extra value for denominators and extra precision.</p>\n</li>\n<li><p>There is another simple representation trick that will save you the wasteful number of representations of the zero. Again, you get a little bit of extra code but will gain you some more room to represent numbers. But this very one is left as an exercise to the keen coder.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T15:22:01.677", "Id": "258843", "ParentId": "32337", "Score": "1" } } ]
{ "AcceptedAnswerId": "36949", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:38:23.047", "Id": "32337", "Score": "4", "Tags": [ "c", "rational-numbers" ], "Title": "Rational implementation" }
32337
<pre><code>/** * credential * * Easy password hashing and verification in Node. * Protects against brute force, rainbow tables, and * timing attacks. * * Cryptographically secure per-password salts prevent * rainbow table attacks. * * Variable work unit key stretching prevents brute force. * * Constant time verification prevents hang man timing * attacks. * * Created by Eric Elliott for the book, * "Programming JavaScript Applications" (O'Reilly) * * MIT license http://opensource.org/licenses/MIT */ 'use strict'; var crypto = require('crypto'), mixIn = require('mout/object/mixIn'), /** * pdkdf(password, salt, workUnits, workKey, * keyLength, callback) callback(err, hash) * * A standard to employ hashing and key stretching to * prevent rainbow table and brute-force attacks, even * if an attacker steals your password database. * * This function is a thin wrapper around Node's built-in * crypto.pbkdf2(). * * See Internet Engineering Task Force RFC 2898 * * @param {String} password * @param {String} salt * @param {Number} workUnits * @param {Number} workKey * @param {Number} keyLength * @param {Function} callback * @return {undefined} */ pbkdf2 = function pbkdf2(password, salt, workUnits, workKey, keyLength, callback) { var baseline = 1000, iterations = (baseline + workKey) * workUnits; crypto.pbkdf2(password, salt, iterations, keyLength, function (err, hash) { if (err) { return callback(err); } callback(null, new Buffer(hash).toString('base64')); }); }, hashMethods = { pbkdf2: pbkdf2 }, /** * createSalt(keylength, callback) callback(err, salt) * * Generates a cryptographically secure random string for * use as a password salt using Node's built-in * crypto.randomBytes(). * * @param {Number} keyLength * @param {Function} callback * @return {undefined} */ createSalt = function createSalt(keyLength, callback) { crypto.randomBytes(keyLength, function (err, buff) { if (err) { return callback(err); } callback(null, buff.toString('base64')); }); }, /** * toHash(password, callback) callback(err, hash) * * Takes a new password and creates a unique hash. Passes * a JSON encoded object to the callback. * * @param {[type]} password * @param {Function} callback */ /** * callback * @param {Error} Error Error or null * @param {String} hashObject JSON string * @param {String} hashObject.hash * @param {String} hashObject.salt * @param {Number} hashObject.keyLength * @param {String} hashObject.hashMethod * @param {Number} hashObject.workUnits * @return {undefined} */ toHash = function toHash(password, callback) { var hashMethod = this.hashMethod, keyLength = this.keyLength, workUnits = this.workUnits, workKey = this.workKey; // Create the salt createSalt(keyLength, function (err, salt) { if (err) { return callback(err); } // Then create the hash hashMethods[hashMethod](password, salt, workUnits, workKey, keyLength, function (err, hash) { if (err) { return callback(err); } callback(null, JSON.stringify({ hash: hash, salt: salt, keyLength: keyLength, hashMethod: hashMethod, workUnits: workUnits })); }); }.bind(this)); }, /** * constantEquals(x, y) * * Compare two strings, x and y with a constant-time * algorithm to prevent attacks based on timing statistics. * * @param {String} x * @param {String} y * @return {Boolean} */ constantEquals = function constantEquals(x, y) { var result = true, length = (x.length &gt; y.length) ? x.length : y.length, i; for (i=0; i&lt;length; i++) { if (x.charCodeAt(i) !== y.charCodeAt(i)) { result = false; } } return result; }, parseHash = function parseHash(encodedHash) { try { return JSON.parse(encodedHash); } catch (err) { return err; } }, /** * verify(hash, input, callback) callback(err, isValid) * * Takes a stored hash, password input from the user, * and a callback, and determines whether or not the * user's input matches the stored password. * * @param {String} hash stored JSON object * @param {String} input user's password input * @param {Function} callback(err, isValid) */ verify = function verify(hash, input, callback) { var storedHash = parseHash(hash), workKey = this.workKey; if (!hashMethods[storedHash.hashMethod]) { return callback(new Error('Couldn\'t parse stored ' + 'hash.')); } hashMethods[storedHash.hashMethod](input, storedHash.salt, storedHash.workUnits, workKey, storedHash.keyLength, function (err, newHash) { if (err) { return callback(err); } callback(null, constantEquals(newHash, storedHash.hash)); }); }, /** * configure(options) * * Alter settings or set your secret `workKey`. `Workkey` * is a secret value between one and 999, required to verify * passwords. This secret makes it harder to brute force * passwords from a stolen database by obscuring the number * of iterations required to test passwords. * * Warning: Decreasing `keyLength` or `work units` * can make your password database less secure. * * @param {Object} options Options object. * @param {Number} options.keyLength * @param {Number} options.workUnits * @param {Number} options.workKey secret * @return {Object} credential object */ configure = function configure(options) { mixIn(this, this.defaults, options); return this; }, defaults = { keyLength: 66, workUnits: 60, workKey: parseInt(process.env.credential_key, 10) || 388, hashMethod: 'pbkdf2' }; module.exports = mixIn({}, defaults, { hash: toHash, verify: verify, configure: configure }); </code></pre>
[]
[ { "body": "<p>At first, disclaimer - I'm not a crypto expert so maybe another answer will be better than mine, but I hope that the my comments still will be useful.</p>\n\n<ol>\n<li>The code is not protected against incorrect values. So the property <code>keyLength</code> and <code>workUnits</code> may be unintentionally set to 0 and the algorithm will fail.</li>\n<li><code>verify</code> actually disclose the reason of the failure which is not correct - there should not be absolutely no difference in timing and returned value. I would rather remove returns because of the err's and always call <code>constantEquals</code>.</li>\n<li>It is really doubtful whether the suggested method <code>constantEquals</code> really helps but anyway, the time of <code>charCodeAt</code> may be different depending on where the character is in the character list. So <code>constantEquals</code> can disclose the average character index. However, I'm not sure that this will help an attacker.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T20:41:15.560", "Id": "53623", "Score": "0", "body": "Thanks Alex. For 1, both `keyLength` and `workUnits` have default values. You would have to intentionally set `keyLength` and `workUnits` to 0 to make the code fail. Does this open up any attack vectors that you can see? Good point for 2. For 3, the hash length is the only thing I can think of that would be revealed by the average character index. Does that open up any potential attack vectors?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:05:08.630", "Id": "53649", "Score": "0", "body": "1. Not direct, but it may be possible to target the configuration, not the algorythm itself. So for me it looks reasonable to somehow handle the situation when these values are low (throw exception or use hardcoded safe values). 3. While bruteforcing it may be enough to test the hashes with some specific average character. Consider simple 5 character hash - if atacker knows that the average is \"j\", then everything below jjjjj is not a hash. This greatly (n! vs x^n) narrows down the hash space. And 4. Node js caches modules,so it may be an issue if the paramereters are diferent in these places" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:18:21.720", "Id": "53652", "Score": "0", "body": "But 3 is only under assumption that duration of the charCodeAt depens on the character code in position. If it is not or negligible (I almost sure in it, but it should be checked very carefully) then the method is safe. BTW JS compiler or minimizer can optimize this code so it become just \"==\". Maybe it is better to use sum of x - y and if it is 0 then hashes are equal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:11:17.663", "Id": "54665", "Score": "0", "body": "!== is strict inequality, and can't be safely optimized to ==. If it ever did happen, that would be a bug... and minimizing is not likely, since this code runs on Node, and doesn't need to be transmitted to a browser. Thanks a lot for your insightful input. =)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T17:39:20.553", "Id": "33411", "ParentId": "32346", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T20:49:30.767", "Id": "32346", "Score": "6", "Tags": [ "javascript", "security", "node.js" ], "Title": "Can we improve this password hashing library for Node.js?" }
32346
<p>This request is a new version of this request: <a href="https://codereview.stackexchange.com/questions/32281/kings-drinking-game-review-request">Kings Drinking Game</a></p> <p><strong>This version has a custom JForm GUI and almost all new methods.</strong></p> <p><strong>GUI:</strong> <img src="https://i.stack.imgur.com/rxd8F.png" alt="Kings GUI"></p> <p>I wrote a program to simulate the drinking card game Kings, now with a JFrom GUI. The GUI is also now not hard-coded into the business code and any UI can be easily used with little adaptation.</p> <p>I would like a review of my code and some pointers on making it more efficient, cleaner, easier to read, or any other general pointers you have.</p> <p>The explanation of the game is in the code comment box here:</p> <pre><code>/** * @author :KyleMHB * Project Number :0003 V2.0 * Project Name :Kings * Project Path :Kings/SourcePackages/JFrameKings/Kings.java * IDE :NETBEANS * Goal of Project - * MainFile is a rule based drinking game using cards for 4+ players. * The Rules are read in from a rules.txt so that one can easily change the rules. * How the game works: * Players shuffle a deck of cards, place a glass between them and circle the * cards around the base of the glass. * The players then take turns picking cards, each card has its own rule associated to it. * Most importantly, there are 4 MainFile, each time a King is picked, * the player who picked it can pour as much of his/her drink into the glass between * them as they wish. * The game ends when the fourth and final King is picked. * The player to pick the final King must down the glass in the center of table. */ </code></pre> <hr> <p><strong>Imports:</strong></p> <pre><code>package JFrameKings; import GUI.KingsGameGUI; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import javax.swing.JOptionPane; </code></pre> <p><strong><code>enum</code> declaration for <code>Rank</code>:</strong></p> <pre><code>enum Rank { ACE ("Ace"), TWO ("2"), THREE ("3"), FOUR ("4"), FIVE ("5"), SIX ("6"), SEVEN ("7"), EIGHT ("8"), NINE ("9"), TEN ("10"), JACK ("Jack"), QUEEN ("Queen"), KING ("King"); String name; Rank(String name) { this.name = name; } } </code></pre> <p><strong><code>enum</code> declaration for <code>Suit</code>:</strong></p> <pre><code>enum Suit { HEARTS ("Hearts"), DIAMONDS ("Diamonds"), SPADES ("Spades"), CLUBS ("Clubs"); String name; Suit(String name) { this.name = name; } } </code></pre> <p><strong>Card Class:</strong></p> <pre><code>public static class Card { public Rank rank; public Suit suit; Card(Suit suit, Rank rank){ this.rank=rank; this.suit=suit; } public @Override String toString(){ return rank.name + " of " + suit.name; } } </code></pre> <p><strong>Deck Class</strong></p> <pre><code>public static class Deck { public static ArrayList&lt;Card&gt; cards; Deck() { cards=new ArrayList&lt;Card&gt;(); for (Suit suit : Suit.values()){ for (Rank rank : Rank.values()){ cards.add( new Card(suit,rank)); } } Collections.shuffle(cards, new Random()); Collections.shuffle(cards, new Random(System.nanoTime())); } public Card getCard(){ return cards.get(0); } public void removeFromDeck(){ cards.remove(0); } } </code></pre> <p><strong><code>PSVM()</code> and <code>static</code> declarations:</strong></p> <pre><code>public static List&lt;String&gt; rules; public static int playerTurn=1; public static final int players=getNum("How many people are going to play", "Number of Players"); private static int kings=0; private static Deck deck=new Deck(); public static void main(String[] args) throws IOException{ setRules("rules.txt"); KingsGameGUI.main(null); } </code></pre> <p><strong><code>getNum()</code> Method:</strong></p> <pre><code>private static int getNum(String prompt,String title) { return Integer.parseInt (JOptionPane.showInputDialog(null,prompt,title,3)); } </code></pre> <p><strong><code>setRules()</code> Method:</strong></p> <pre><code>/** * Rules are not hard-coded because people often have different ones, * Therefore I made an easily editable rules.txt file. * Also my rule file has formatting in using the \n, * However when the file is read it is read as \ and n * Hence why I used the replaceAll( "\\\\n","\n"); */ private static void setRules(File f) throws FileNotFoundException, IOException { rules = Files.readAllLines(f.toPath(), Charset.defaultCharset()); for(int i=0; i!=rules.size(); i++){ rules.set(i, rules.get(i).replaceAll( "\\\\n","\n")); } } </code></pre> <p><strong><code>playGame()</code> Method:</strong></p> <pre><code>//is now a return type to return to my GUI public static String playGame() { String out; if(kings==3 &amp;&amp; checkIfKing()==true){ display("Player "+playerTurn+" has Drawn the Final King\n\n"+ getRule()+"\n\n", "Restart the Program to Play again"); System.exit(0); return null; } else if(checkIfKing()==true){ kings++; playerTurn++; out="Player "+(playerTurn-1)+" has picked the "+deck.getCard().toString() +"\n"+(4-kings)+" Kings remain" +"\n\n"+getRule(); deck.removeFromDeck(); if (playerTurn==players+1){playerTurn=1;} return out; } playerTurn++; out="Player "+(playerTurn-1)+" has picked the "+deck.getCard().toString() +"\n\n"+getRule(); deck.removeFromDeck(); if (playerTurn==players+1){playerTurn=1;} return out; } </code></pre> <p><strong><code>checkIfKing()</code> Method:</strong></p> <pre><code>//Small but keeps my playGame() method cleaner. public static boolean checkIfKing() { if(deck.getCard().rank==Rank.KING) return true; return false; } </code></pre> <p><strong><code>getRule()</code> Method:</strong></p> <pre><code>//Again, small but keeps my playGame() method cleaner. private static String getRule(){ return rules.get(deck.getCard().rank.ordinal()); } </code></pre> <p><strong><code>skipTurn()</code> Method:</strong></p> <pre><code>//Just used to skip a turn and pass the message to the GUI public static String skipTurn(){ String out; if (playerTurn==players){ out="Player "+playerTurn+"'s turn was skipped\n"; playerTurn=1; }else{ out="Player "+playerTurn+"'s turn was skipped\n"; playerTurn++; } return out; } </code></pre> <p><strong><code>passCard()</code> Method:</strong></p> <pre><code>//A public method built specifically to pass card as a string to the GUI public static String passCard(){ return deck.getCard().toString(); } </code></pre> <p><strong><code>finalMessage()</code> Method:</strong></p> <pre><code> //Just a legacy hanging around from the previous version, but it keeps my code clean. private static void finalMessage() { JOptionPane.showMessageDialog(null,"Player "+playerTurn+" has Drawn the Final King\n\n"+ getRule()+"\n\n", "Restart the Program to Play again",1); } </code></pre> <hr> <hr> <h2>GUI</h2> <p>I made the GUI with the built in NETBEANS builder, which I've never used before. Deleted the snipped the starter comments</p> <pre><code>/** *-snip- * Project Path :Kings/SourcePackages/JFrameKings/GameGUI.java * IDE :NETBEANS * -snip- */ </code></pre> <p><strong>Draw a Card Button on mouse pressed:</strong></p> <pre><code>private void drawCardButton1MousePressed(java.awt.event.MouseEvent evt){ cardLogTA.append("Player "+JFrameKings.Kings.playerTurn+" drew the " + JFrameKings.Kings.passCard()+"\n"); cardPickedTA.setText(JFrameKings.Kings.playGame()); playerLabel.setText("Player "+(JFrameKings.Kings.playerTurn)+"'s turn"); } </code></pre> <p><strong>Skip Turn Button on mouse pressed:</strong></p> <pre><code>private void skipTurnButtonMousePressed(java.awt.event.MouseEvent evt) { String skip=JFrameKings.Kings.skipTurn(); cardLogTA.append(skip); cardPickedTA.setText(skip); playerLabel.setText("Player "+(JFrameKings.Kings.playerTurn)+"'s turn"); } </code></pre> <p><strong>Exit Button on mouse CLICKED:</strong></p> <pre><code>private void exitButtonMouseClicked(java.awt.event.MouseEvent evt) { int sure=JOptionPane.showConfirmDialog(null, "Are you sure?"); if (sure == 0){ JOptionPane.showMessageDialog(null,"Bye!"); System.exit(0); } } </code></pre>
[]
[ { "body": "<p>Why do you do? It seems redundant to me.</p>\n\n<pre><code>Collections.shuffle(cards, new Random());\nCollections.shuffle(cards, new Random(System.nanoTime()));\n</code></pre>\n\n<p>I would not put labels of card ranks and other labels to the enums. I would use <a href=\"http://docs.oracle.com/javase/tutorial/essential/environment/properties.html\" rel=\"nofollow\">Properties</a> stored in a file and used enum as a key in the file.</p>\n\n<p>This</p>\n\n<pre><code>public static final int players=getNum(\"How many people are going to play\",\n \"Number of Players\");\n</code></pre>\n\n<p>does not seem as a good idea. If i call <code>new</code> for a class i expect object to be created and initialized not some actions to be happening.</p>\n\n<p>Indent your code! </p>\n\n<pre><code>if (playerTurn==players){\n out=\"Player \"+playerTurn+\"'s turn was skipped\\n\";\n playerTurn=1;\n }else{\n out=\"Player \"+playerTurn+\"'s turn was skipped\\n\";\n playerTurn++;\n }\n</code></pre>\n\n<p>Out is same in both branches.</p>\n\n<p>I really dont like this String retur value sfor almost all methods. skipTurn should just skip turn. I dont see any reason why it should return anything. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:07:27.180", "Id": "51782", "Score": "0", "body": "Thanks for the answer.\nAs for the double shuffle, well I had a single shuffle but the cards seemed to always draw unrealistically, like a 15 turn games. The second shuffle fixed it, so I left it.\n\nYeah the `getNum()` for the initialization is weird, I had it as a method I was going to use for additional menu options in the old GUI, it was already written and there so I just kinda left it for that one specific function.\n\nWhats wrong with my code indents?\n\nAlso the if statement branches are necessary. The first branch resets the player turn if its the final player, the second iterates the turn." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:09:01.160", "Id": "51783", "Score": "0", "body": "Also it does need to return a string value for the log of players turn so you can see if a turn was skipped." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T05:30:07.510", "Id": "51830", "Score": "0", "body": "The playGame is not indented as it should be. Maybe it is only this forum formatting. \nYes the if-else is necessary (or you could use ternary operator) but it is not necesary to assign the same value to variable `out` in if as in else. \nYou could do ` out=\"Player \"+playerTurn+\"'s turn was skipped\\n\"; playerTurn = (playerTurn==players) ? 1 : playerTurn + 1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T05:31:47.423", "Id": "51831", "Score": "0", "body": "And game log is a [View](http://martinfowler.com/eaaCatalog/modelViewController.html) thing, it does not belong to the game itself. Ask for the game state in view, do not force your game logic to return game log." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T10:44:13.957", "Id": "32421", "ParentId": "32348", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T21:28:15.693", "Id": "32348", "Score": "3", "Tags": [ "java", "optimization", "game", "playing-cards" ], "Title": "Kings Drinking Game Review Request 2.0 JForm GUI" }
32348
<p>I wrote the following interface and class to bijectively map a string to a long. I would like feedback on how to make the code more readable and maintainable. </p> <p><strong>Interface:</strong></p> <pre><code>/** * Bijectively maps a string consisting of chars from a predefined 'charSet' to a long value * Bijective mapping ensures that the conversions are collision-less * * @invariant: All mappings are bijective. * @invariant: Defined for all string permutations &lt;= getMaxStringLength() * @invariant: Defined for all longs in range [getMinLongValue(), getMaxLongValue()] */ public interface StringAndLongConverter { public char[] getMappedChars(); /* O(n) */ public long getMinLongValue(); /* O(1) */ public long getMaxLongValue(); /* O(1) */ public int getMaxStringLength(); /* O(1) */ public boolean isValidLong(final long n); /* O(1) */ public boolean isValidString(final String str); /* O(n) */ public String convertLongToString(final long n); /* O(n) */ public long convertStringToLong(final String str); /* O(n) */ } </code></pre> <p><strong>Concrete Class:</strong></p> <pre><code>import java.util.Arrays; import java.util.HashMap; import java.util.regex.Pattern; /** * @author awashburn * 1. Use base conversion principals to bijectively map * a string to a long for a pre-defined character set. * * 2. Treat the characters as digits * and the cardinality of the character set as the base * * 3. Use an imaginary empty character to mark string termination. */ public class ConcreteStringAndLongConveter implements StringAndLongConverter { private final char[] CHAR_MAP; private final HashMap&lt;Character,Integer&gt; CHAR_HASHMAP; private final int NUM_MAPPED_CHARS; private final int MAX_STR_LEN; private final long MIN_VALUE; private final long MAX_VALUE; private final Pattern REGEX_CHAR_VALIDATOR; public ConcreteStringAndLongConveter(char[] charSet) { if(charSet == null ) throw new IllegalArgumentException("Cannot Pass in null reference"); if(charSet.length==0) throw new IllegalArgumentException("Cannot Pass in empty set" ); /* Don't re-arrange, order-dependent initializations */ CHAR_MAP = removeDuplicateCharacters(charSet); CHAR_HASHMAP = generateHashMap(); NUM_MAPPED_CHARS = CHAR_MAP.length+1; // accounts for imaginary empty character MAX_STR_LEN = calcMaxPossibleChars(); MIN_VALUE = calcLongMinVal(); MAX_VALUE = calcLongMaxVal(); REGEX_CHAR_VALIDATOR = createRegExValidator(); } /* --&lt;[ Dynamic Initialization Calculation Methods ]&gt;-- */ private final char[] removeDuplicateCharacters(char[] charArr) { char[] tmp = new char[charArr.length]; Arrays.sort(charArr); int index = 0; for(int i=0; i&lt;charArr.length-1; ++i) if(charArr[i]!=charArr[i+1]) tmp[index++] = charArr[i]; tmp[index++] = charArr[charArr.length-1]; return Arrays.copyOf(tmp,index); } private final HashMap&lt;Character,Integer&gt; generateHashMap() { HashMap&lt;Character,Integer&gt; mapping = new HashMap&lt;Character,Integer&gt;(); for(int i=0; i&lt;CHAR_MAP.length; ++i) mapping.put(CHAR_MAP[i], i+1); return mapping; } private final int calcMaxPossibleChars() { return (int)(Math.floor(Math.log(Long.MAX_VALUE) / Math.log(NUM_MAPPED_CHARS))); } private final long calcLongMinVal() { return 0L; } private final long calcLongMaxVal(){ StringBuilder sb = new StringBuilder(); for(int i=0; i&lt;MAX_STR_LEN; ++i) sb.append(CHAR_MAP[CHAR_MAP.length-1]); return encodeStrToLong(sb.toString()); } /* Dynamically create RegEx validation string for invalid characters */ private final Pattern createRegExValidator() { return Pattern.compile("^["+Pattern.quote(new String(CHAR_MAP))+"]+?$"); } /* --&lt;[ Interface Implmentation Methods ]&gt;-- */ @Override public final char[] getMappedChars() { return Arrays.copyOf(CHAR_MAP,CHAR_MAP.length); } @Override public final int getMaxStringLength() { return MAX_STR_LEN; } @Override public final long getMaxLongValue() { return MAX_VALUE; } @Override public final long getMinLongValue() { return MIN_VALUE; } @Override public final boolean isValidString(final String str) { return str != null &amp;&amp; !str.equals("") //not null or empty String &amp;&amp; str.length() &lt;= MAX_STR_LEN //not too long &amp;&amp; REGEX_CHAR_VALIDATOR.matcher(str).matches(); //and only valid chars in string } @Override public final boolean isValidLong(final long n) { return MIN_VALUE &lt;= n &amp;&amp; n &lt;= MAX_VALUE; } @Override public final String convertLongToString(final long n) { if(!isValidLong(n)) throw new IllegalArgumentException("Invalid Long: "+Long.toHexString(n)); return encodeLongToStr(n); } @Override public final long convertStringToLong(final String str) { if(!isValidString(str)) throw new IllegalArgumentException("Invalid String: "+str); return encodeStrToLong(str); } /* --&lt;[ Internal Helper Methods ]&gt;-- */ /* Assumes a validated Long was passed in */ private final String encodeLongToStr(long index) { StringBuilder sb = new StringBuilder(); for(; index!=0; index/=NUM_MAPPED_CHARS) sb.append(CHAR_MAP[(int)(index%NUM_MAPPED_CHARS)-1]); // -1 accounts for empty char return sb.toString(); } /* Assumes a validated String was passed in */ private final long encodeStrToLong(String str) { long output = 0L; for(int i=str.length()-1; i &gt;=0; --i) { output += CHAR_HASHMAP.get(str.charAt(i)); if(i!=0) output *= NUM_MAPPED_CHARS; } return output; } } </code></pre>
[]
[ { "body": "<p><strong>The interface</strong></p>\n\n<ul>\n<li>Always try to keep methods on an interface to a minimum.Try to focus on what a client really needs.</li>\n</ul>\n\n<p>In you case this should suffice :</p>\n\n<pre><code>public interface StringAndLongConverter {\n public boolean isValidLong(final long n);\n public boolean isValidString(final String str);\n public String convertLongToString(final long n);\n public long convertStringToLong(final String str);\n}\n</code></pre>\n\n<ul>\n<li>You list the order of complexity in the interface definition, but they are actually properties of the implementation. A different implementation may have different complexities.</li>\n</ul>\n\n<p><strong>The implementation class</strong></p>\n\n<ul>\n<li>my IDE immediately points out that your private methods are marked <code>final</code>. While not wrong, it is superfluous.</li>\n<li>fields that are non <code>static</code> or non <code>final</code> are usually named using <a href=\"http://en.wikipedia.org/wiki/CamelCase\" rel=\"nofollow\">camel case</a>.</li>\n<li>drop the methods that I've dropped on the interface.</li>\n<li>You use <code>for</code> and <code>if</code> without braces. Again, not wrong, but I find braces to be clearer. Especially when nesting.</li>\n<li>The name of the implementation class has a typo.</li>\n<li>Since you sort the characters (when eliminating duplicates), you could do the conversion of a character to a number without a HashMap, and just use binary search. This would still be very fast, but would use a lot less memory. (just an idea)</li>\n<li>replace <code>calcLongMinVal()</code> by a constant.</li>\n<li>encoding and decoding can also be done with bit manipulation With some clever naming it could even be more readable, it would not give the same mapping, but would avoid repeated divisions when converting long to String. (just an idea)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:11:03.460", "Id": "78319", "Score": "0", "body": "The repeated division was chosen rather then bit-twiddling to give a compact and continuous mapping of `long`s in the range. The bit-twiddling approach may produce a non-continuous range of of values, ie there may exist a `long n` such that `MIN_VALUE <= n && n<= MAX_VALUE && convertLongToString(n)` will throw an exception. [I tried the bit-twiddling before](http://stackoverflow.com/a/14541792/1465011)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T09:07:04.337", "Id": "78487", "Score": "0", "body": "This would only matter if you want to decode `long`s that aren'ty the result of being encoded by the converter. I can't see the use of that, but if you want that, you can stick to divisions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T13:15:52.300", "Id": "78517", "Score": "0", "body": "You are correct, but that is a feature that I want. Bit-twiddling is probably preferable if that feature isn't desired." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:15:25.503", "Id": "78522", "Score": "0", "body": "On closer inspection, this property also does not hold for repeated division; given alphabet `{'a', 'b'}` the converter will fail for `3L`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:43:44.747", "Id": "78529", "Score": "0", "body": "I should make a test suite to ensure this desired property exists. Thanks for pointing that out." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T22:52:45.373", "Id": "32399", "ParentId": "32349", "Score": "4" } } ]
{ "AcceptedAnswerId": "32399", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T21:33:03.193", "Id": "32349", "Score": "2", "Tags": [ "java" ], "Title": "Review of String to Long bijection class - focus on readability/maintainabiliy" }
32349
<p>I am currently working on a Python project. It is some sort of a hub, where you can do some cool but basic stuff, such as: setting timers, launching websites, doing basic math, ping and view source codes of URLs, and more.</p> <p>I want to make this code just a little more compact. I especially want my math menu more compact because I feel there is a way of doing it. I just can't seem to figure it out.</p> <pre><code>… elif userIn == ("math"): op = str(input(" * Enter operation (+, -, *, /, exp, sqrt, log): ")) blank() if op==("+") or op==("-") or op==("*") or op==("/") or op==("exp"): input_1 = int(input(" * Enter first number: ")) blank() input_2 = int(input(" * Enter second number: ")) blank() if op == ("+"): print (" &gt; "+str(input_1 + input_2)) blank() elif op == ("-"): print (" &gt; "+str(input_1-input_2)) blank() elif op == ("*"): print (" &gt; "+str(input_1*input_2)) blank() elif op == ("/"): print (" &gt; "+str(input_1/input_2)) blank() elif op == ("exp"): print (" &gt; "+str(input_1**input_2)) blank() elif op == ("sqrt"): oneInput=int(input(" * Enter number: ")) blank() print (" &gt; "+str(math.sqrt(oneInput))) blank() elif op == ("log"): input_1 = int(input(" * Enter number: ")) blank() input_2 = int(input(" * Enter base: ")) blank() print (" &gt; "+str(int((math.log(input_1, input_2))))) blank() </code></pre> <p><a href="http://pastebin.com/pEqvvaLZ" rel="nofollow">Link to the code (pastebin)</a>.</p> <p>Note: I have tried setting a basic for loop run through a list of operation symbols, and it would set the operation if the user op. was matched. But, as it turns out, I just couldn't use strings as math operators in the code itself. </p> <pre><code>opl=["+", "-", "*", "/"] for i in range(len(opl)): userInput1 (some way of setting op) userInput2 </code></pre>
[]
[ { "body": "<p>I would suggest using a <code>dict</code> as switch-statement like structure. </p>\n\n<p>First some global helper functions/data structures:</p>\n\n<pre><code>math_dict_binary = {'+': lambda a, b: a+b,\n '-': lambda a, b: a-b,\n # fill out the rest of you binary functions\n }\nmath_dict_uniary = {'sqrt': math.sqrt,\n # rest of you uniary\n }\n\n\ndef get_input(str_prompt):\n input = int(input(\" * {}: \".format(str_prompt)))\n blank()\n return input\n</code></pre>\n\n<p>in your main body:</p>\n\n<pre><code>elif userIn == (\"math\"):\n op = str(input(\" * Enter operation (+, -, *, /, exp, sqrt, log): \"))\n blank()\n if op in math_dict_binary:\n input_1 = get_input(\"Enter first number\")\n input_2 = get_input(\"Enter second number\")\n print( \" \" + str(math_dict_binary[op](input_1, input_2)))\n elif op in math_dict_uniary:\n input_1 = get_input(\"Enter number\")\n print( \" \" + str(math_dict_uniary[op](input_1)))\n else:\n print(\"Not a vlaid math option\")\n # deal with it\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T15:03:50.237", "Id": "51717", "Score": "0", "body": "Oh wow, never thought of using dictionaries. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T00:31:41.037", "Id": "32353", "ParentId": "32350", "Score": "2" } }, { "body": "<p>blank() was used at the end of every case so it can be used at the end of giant if block instead. Also, oneInput is unpythonic for a variable name use one_input. float has many magic methods. They have double underscores before and after the name. Here is a helpful list <a href=\"http://docs.python.org/3.2/library/operator.html\" rel=\"nofollow\">http://docs.python.org/3.2/library/operator.html</a>. These methods can also be seen by typing <code>dir(float)</code>. float was chosen due to division being used.</p>\n\n<pre><code> operators=['+', '-', '*', '/', 'exp'];\n\n user_operators=[\n getattr(float, '__{}__'.format(i))\n for i in ['add', 'sub', 'mul', 'truediv', 'pow']\n ];\n\n opl=dict(zip(operators, user_operators));\n output_prompt=' '*7+'&gt; ';\n\n if op in opl:\n print( output_prompt+str(opl[op](float(input_1), input2)) );\n #--snip-- other conditions for sqrt and log would go here\n else:\n raise ValueError('Unsupported operator {}'.format(op));\n blank();\n</code></pre>\n\n<p>However, if division is removed from the lists operators and operations then int could be used and <code>float(input_1)</code> could just be <code>input_1</code>.</p>\n\n<p>You may want to save opl[op] as a variable just to name it for easy reading. It is being used like a function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T15:04:55.210", "Id": "51718", "Score": "0", "body": "Oh so we add an exception handler as well? Seems fancy, i will try it out ASAP :) thanks for the answer :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T01:52:54.183", "Id": "32355", "ParentId": "32350", "Score": "1" } } ]
{ "AcceptedAnswerId": "32353", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T22:52:14.227", "Id": "32350", "Score": "2", "Tags": [ "python", "calculator" ], "Title": "Calculator that is part of a multipurpose program" }
32350
<p>I am trying to find unique hashtags from a tweet that a user inputs. I have the code to find the number of times a word is used in the input, but I just need to know the number of different hashtags used. For example, in the input</p> <pre><code>#one #two blue red #one #green four </code></pre> <p>there would be 3 unique hashtags as <code>#one</code>, <code>#two</code>, and <code>#green</code>. I cannot figure out how to code this.</p> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Tweet { public static void main(String[] args) { Scanner hashtag = new Scanner( System.in ); System.out.println( "Please enter a line of text" ); String userInput = hashtag.nextLine(); userInput = userInput.toLowerCase(); userInput = userInput.replaceAll( "\\W", " " ); // strip out any non words. userInput = userInput.replaceAll( " ", " " ); // strip out any double spaces // created from stripping out non words // in the first place! String[] tokens = userInput.split( " " ); System.out.println( userInput ); ArrayList&lt; String &gt; tweet = new ArrayList&lt; String &gt;(); tweet.addAll( Arrays.asList( tokens ) ); int count = 0; for( int i = 0; i &lt; tweet.size(); i++ ) { System.out.printf( "%s: ", tweet.get( i ) ); for( int j = 0; j &lt; tweet.size(); j++ ) { if( tweet.get( i ).equals( tweet.get( j ) ) ) count++; if( tweet.get( i ).equals( tweet.get( j ) ) &amp;&amp; count &gt; 1 ) tweet.remove( j ); // after having counted at least } // one, remove duplicates from List System.out.printf( "%d\n", count ); count = 0; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T00:31:29.623", "Id": "51646", "Score": "0", "body": "You might consider using a [`Set<String>`](http://docs.oracle.com/javase/6/docs/api/java/util/Set.html) to hold the hashtags." } ]
[ { "body": "<p>If it is not program for one purpose and then you will throw it away i will not put to much code in main method. I would just initialize the application, inputs and outputs in main and than call start, run or some other method.</p>\n\n<p>Also represent tweet as an object with methods <code>Tweet#parse</code> <code>Tweet#getHashTags</code> and so on. Or you can Create TweetParser and separate it even more, but i think in this case it is overkill.</p>\n\n<p>For tokenizing the string use built-in class <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html\" rel=\"nofollow\">StringTokenizer</a>\nAnd use Set as suggested in comment.</p>\n\n<p>My Tweet class:</p>\n\n<pre><code>package scjp.tweet;\n\nimport java.util.*;\n\npublic class Tweet {\n\n private final List&lt;String&gt; hashtags = new ArrayList&lt;String&gt;();\n\n private String text;\n\n private Tweet() {}\n\n public static Tweet getTweet(String tweetText) {\n Tweet tweet = new Tweet();\n tweet.text = tweetText;\n tweet.parse();\n return tweet;\n }\n\n private void parse() {\n StringTokenizer tokenizer = new StringTokenizer(this.text);\n while (tokenizer.hasMoreTokens()) {\n String token = tokenizer.nextToken();\n if (token.startsWith(\"#\")) {\n hashtags.add(token);\n }\n }\n }\n\n public Set&lt;String&gt; getUniqueHashtags() {\n Set&lt;String&gt; unique = new HashSet&lt;String&gt;();\n unique.addAll(hashtags);\n return unique;\n }\n\n}\n</code></pre>\n\n<p>And main class:</p>\n\n<pre><code>package scjp.tweet;\n\nimport java.util.Scanner;\n\npublic class TweetMain {\n\n public static void main(String... args) {\n Scanner hashtag = new Scanner( System.in );\n System.out.println( \"Please enter a line of text\" );\n String tweetText = hashtag.nextLine();\n\n Tweet tweet = Tweet.getTweet(tweetText.toLowerCase());\n\n System.out.println(tweet.getUniqueHashtags());\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T07:01:30.340", "Id": "32365", "ParentId": "32352", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T00:27:15.307", "Id": "32352", "Score": "-1", "Tags": [ "java", "array" ], "Title": "Unique hashtag extracting" }
32352
<p>Please pick my code apart and give me some feedback on how I could make it better or more simple.</p> <pre><code>final class Edge { private final Node node1, node2; private final int distance; public Edge (Node node1, Node node2, int distance) { this.node1 = node1; this.node2 = node2; this.distance = distance; } public Node getAdjacentNode (Node node) { return node.getValue() != node1.getValue() ? node1 : node2; } public int getDistance() { return distance; } } class Node { private final int v; private int distance = Integer.MAX_VALUE; public Node (int v) { this.v = v; } public int getValue() { return v; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } @Override public boolean equals(Object o) { Node node = (Node) o; return node.getValue() == v; } @Override public int hashCode() { return v; } } class Graphs { private final Map&lt;Node, ArrayList&lt;Edge&gt;&gt; map; private final int numberOfVertices; Graphs(int numberOfVertices) { if (numberOfVertices &lt; 0) { throw new IllegalArgumentException("A vertex cannot be less than zero"); } this.numberOfVertices = numberOfVertices; this.map = new HashMap&lt;Node, ArrayList&lt;Edge&gt;&gt;(); } public void addEdge (Node node1, Node node2, int distance) { // necessary to throw null ptr exceptions explicitly since, null can get propagated and saved in edge if (node1 == null || node2 == null) { throw new NullPointerException("Either of the 2 nodes is null."); } if (distance &lt; 0) { throw new IllegalArgumentException(" The distance cannot be negative. "); } Edge edge = new Edge(node1, node2, distance); addToMap(node1, edge); addToMap(node2, edge); } private void addToMap (Node node, Edge edge) { if (map.containsKey(node)) { List&lt;Edge&gt; l = map.get(node); l.add(edge); } else { List&lt;Edge&gt; l = new ArrayList&lt;Edge&gt;(); l.add(edge); map.put(node, (ArrayList&lt;Edge&gt;) l); } } public List&lt;Edge&gt; getAdj(Node node) { return map.get(node); } public Map&lt;Node, ArrayList&lt;Edge&gt;&gt; getGraph() { return map; } public int getNumVertices() { return numberOfVertices; } } public class Dijkstra { private final Graphs graph; public Dijkstra(Graphs graph) { if (graph == null) { throw new NullPointerException("The input graph cannot be null."); } this.graph = graph; } /** * http://stackoverflow.com/questions/2266827/when-to-use-comparable-and-comparator */ public class NodeCompator implements Comparator&lt;Node&gt; { @Override public int compare(Node n1, Node n2) { if (n1.getDistance() &gt; n2.getDistance()) { return 1; } else { return -1; } } }; public Set&lt;Node&gt; findShortest(int source) { final Queue&lt;Node&gt; queue = new PriorityQueue&lt;Node&gt;(10, new NodeCompator()); for (Entry&lt;Node, ArrayList&lt;Edge&gt;&gt; entry : graph.getGraph().entrySet()) { Node currNode = entry.getKey(); if (currNode.getValue() == source) { currNode.setDistance(0); queue.add(currNode); } } final Set&lt;Node&gt; doneSet = new HashSet&lt;Node&gt;(); while (!queue.isEmpty()) { Node src = queue.poll(); doneSet.add(src); for (Edge edge : graph.getAdj(src)) { Node currentNode = edge.getAdjacentNode(src); if (!doneSet.contains(currentNode)) { int newDistance = src.getDistance() + edge.getDistance(); if (newDistance &lt; currentNode.getDistance()) { currentNode.setDistance(newDistance); queue.add(currentNode); } } } } return graph.getGraph().keySet(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T06:54:33.293", "Id": "279875", "Score": "0", "body": "It looks ok to me (did not review functionality). The only thing I can suggest is to use [validation](http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/Validate.html#notNull%28T,%20java.lang.String,%20java.lang.Object...%29) from commons-lang so you can shorten your parameter validity checks." } ]
[ { "body": "<ol>\n<li><p>In your <code>Edge</code> class <code>getAdjacentNode()</code> returns <code>node1</code> or <code>node2</code> regardless whether the parameter is one of the two. You should consider throwing an exception (<code>IllegalStateEeption</code> maybe) if the parameter is neither of them.</p></li>\n<li><p>Your <code>Graphs</code> class should be <code>Graph</code> - an instance of that class represents a single graph and not multiple ones, doesn't it?</p></li>\n<li><p>What is the point of the <code>numberOfVertices</code> member? It's not used for anything. You should remove it.</p></li>\n<li><p>You use the <code>distance</code> member of the node to store transient values during the computation in <code>Dijkstra</code>. It's never good to intermingle data representation and iteration over the data. Keep the transient data you need for <code>Dijkstra</code> separate from the nodes and edges. It might incur some extra memory overhead but it's usually worth it. For example if your algorithm fails then it might leave the graph in an inconsistent state. Also you have to reset the graph when you want to re-compute.</p></li>\n<li><p>This code gets the node with the given value:</p>\n\n<blockquote>\n<pre><code>for (Entry&lt;Node, ArrayList&lt;Edge&gt;&gt; entry : graph.getGraph().entrySet()) {\n Node currNode = entry.getKey();\n if (currNode.getValue() == source) {\n currNode.setDistance(0);\n queue.add(currNode);\n } \n}\n</code></pre>\n</blockquote>\n\n<p>I would add this as a method to <code>Graph</code> like <code>getNode(int value)</code>. It makes sense to be able to ask a graph for a specific node.</p></li>\n<li><p>You should not have to care how the graph internally represents its nodes and edges. So instead of having a method <code>getGraph</code> which just dumps the internally used data structure onto the user have a define interface All you need is either a specific node (see point 5) or all nodes. So add another method <code>getAllNodes()</code> which returns all nodes.</p></li>\n</ol>\n\n<p>Alternatively consider adding <a href=\"https://stackoverflow.com/questions/5849154/can-we-write-our-own-iterator-in-java\">a custom iterator</a> which allows users to traverse all the nodes of the graph without having to care about the internal representation.</p>\n\n<p>The reasoning behind that is: If you ever want to change your internal representation then you either have to convert it to the exposed data structure (means you might have to copy around a lot of data) or you have to change all code using it. Neither of them is particularly nice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T07:14:21.133", "Id": "51760", "Score": "0", "body": "You can fix the codeblock by simply intending it by 8 spaces, no need for the quote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T07:16:36.047", "Id": "51761", "Score": "0", "body": "@Bobby: I didn't add the quote, someone else edited my answer. I assume he did it to highlight that that particular bit of code is a quote from the original question and I agree with that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T07:00:12.657", "Id": "32364", "ParentId": "32354", "Score": "8" } }, { "body": "<p>I would like to change a little your code:</p>\n\n<blockquote>\n<pre><code>for (Entry&lt;Node, ArrayList&lt;Edge&gt;&gt; entry : graph.getGraph().entrySet()) {\n Node currNode = entry.getKey();\n if (currNode.getValue() == source) {\n currNode.setDistance(0);\n queue.add(currNode);\n } \n}\n</code></pre>\n</blockquote>\n\n<p>And make it like this:</p>\n\n<pre><code>Node start = new Node(source);\nif (graph.getGraph().containsKey(start)) {\n start.setDistance(0);\n queue.offer(start);\n}\n</code></pre>\n\n<p>It allows us to decrease search time from O(n) loop search to constant O(1) map lookup.</p>\n\n<hr>\n\n<p>I can provide 1 example:</p>\n\n<pre><code>public static void main(String[] args) {\n Graphs G = new Graphs(7);\n G.addEdge(new Node(0), new Node(1), 4);\n G.addEdge(new Node(0), new Node(2), 3);\n G.addEdge(new Node(0), new Node(4), 7);\n G.addEdge(new Node(1), new Node(3), 5);\n G.addEdge(new Node(2), new Node(3), 11);\n G.addEdge(new Node(4), new Node(3), 2);\n G.addEdge(new Node(5), new Node(3), 2);\n G.addEdge(new Node(6), new Node(3), 10);\n G.addEdge(new Node(4), new Node(6), 5);\n G.addEdge(new Node(6), new Node(5), 3);\n\n\n Dijkstra dijkstra = new Dijkstra(G);\n Set&lt;Node&gt; path = dijkstra.findShortest(0);\n\n Iterator&lt;Node&gt; it = path.iterator();\n while (it.hasNext()) {\n System.out.println(it.next().getDistance());\n }\n\n}\n</code></pre>\n\n<p>And it returns the wrong value for the start node and for the last one which should be 12 and not 19.</p>\n\n<p><a href=\"https://www.youtube.com/watch?v=gdmfOwyQlcI\" rel=\"nofollow\">Proof</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-09T12:33:43.493", "Id": "104223", "ParentId": "32354", "Score": "3" } }, { "body": "<p>This code has a flaw.</p>\n\n<p>Try for this input:</p>\n\n<pre><code>Graph G = new Graph(4);\n G.addEdge(new Node(0), new Node(1), 30);\n G.addEdge(new Node(0), new Node(2), 100);\n G.addEdge(new Node(1), new Node(3), 2);\n G.addEdge(new Node(2), new Node(3), 10);\n</code></pre>\n\n<p>This code returns:</p>\n\n<pre><code>0\n30\n100\n32\n</code></pre>\n\n<p>But the correct answer is:</p>\n\n<pre><code>0\n30\n42\n32\n</code></pre>\n\n<p>The issue is that the code doesn't decrease the key when you find some node (which you have seen before but it has not been in the <code>doneSet</code> yet) which is now closer via a new path. But, you did a pretty great job in avoiding that complicated <code>decreaseKey()</code> implementation by allowing the addition of duplicate nodes in the queue. But, you didn't make use of it. By simple changes, your code can work perfectly.\nJust add this line:</p>\n\n<pre><code>if (!doneSet.contains(src))\n</code></pre>\n\n<p>to </p>\n\n<pre><code> while (!queue.isEmpty()) {\n Node src = queue.poll();\n if (!doneSet.contains(src)){\n doneSet.add(src);\n\n for (UndirectedEdge edge : graph.getAdj(src)) {\n Node currentNode = edge.getAdjacentNode(src);\n\n if (!doneSet.contains(currentNode)) {\n int newDistance = src.getDistance() + edge.getDistance();\n if (newDistance &lt; currentNode.getDistance()) {\n currentNode.setDistance(newDistance);\n queue.add(currentNode);\n } \n }\n }\n }\n }\n</code></pre>\n\n<p>Then, in the end, just return:</p>\n\n<pre><code>return doneSet;\n</code></pre>\n\n<p>rather than:</p>\n\n<pre><code>return graph.getGraph().keySet();\n</code></pre>\n\n<p>So, here is the complete implementation of the <code>findShortest(int source)</code> method, so as to remove any confusion:</p>\n\n<pre><code>public Set&lt;Node&gt; findShortest(int source) {\n final Queue&lt;Node&gt; queue = new PriorityQueue&lt;Node&gt;(10, new NodeCompator());\n\n for (Entry&lt;Node, ArrayList&lt;UndirectedEdge&gt;&gt; entry : graph.getGraph().entrySet()) {\n Node currNode = entry.getKey();\n if (currNode.getValue() == source) {\n currNode.setDistance(0);\n queue.add(currNode);\n } \n }\n\n final Set&lt;Node&gt; doneSet = new HashSet&lt;Node&gt;();\n\n while (!queue.isEmpty()) {\n Node src = queue.poll();\n if (!doneSet.contains(src)){\n doneSet.add(src);\n\n for (UndirectedEdge edge : graph.getAdj(src)) {\n Node currentNode = edge.getAdjacentNode(src);\n\n if (!doneSet.contains(currentNode)) {\n int newDistance = src.getDistance() + edge.getDistance();\n if (newDistance &lt; currentNode.getDistance()) {\n currentNode.setDistance(newDistance);\n queue.add(currentNode);\n } \n }\n }\n }\n }\n\n return doneSet;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-12T06:01:42.460", "Id": "110517", "ParentId": "32354", "Score": "2" } } ]
{ "AcceptedAnswerId": "32364", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T00:53:25.813", "Id": "32354", "Score": "7", "Tags": [ "java", "algorithm", "graph" ], "Title": "Implementation of Dijkstra's algorithm" }
32354
<p>I was wondering if anyone could give a critique of my code. We are supposed to be using inheritance and OOP principles. All the functions but the <code>PlayerSet</code> class were given, so really I just need someone to critique that class.</p> <p>The full code is <a href="http://ideone.com/42iFSt" rel="nofollow">here</a>.</p> <pre><code>class PlayerSet: '''A group of players to play the Pass The Pigs game.''' def __init__(self,playerCount): '''PlayerSet(int) -&gt; PlayerSet Contstructs a group of players, given how many there are and asks the name of each player.''' self.playerCount = playerCount # initialize count of players attribute self.playersList = [] # initialize list of players attrbute for i in range(1,self.playerCount+1): # for every i between 1 and plyerCount name = input('Player ' + str(i) + ', please enter your name:') # ask player i's name player = Player(name) # create a player with that name self.playersList.append(player) # add the player to the list of players self.currentPlayer = self.playersList[0] # initialize current player attribute def __str__(self): '''print(PlayerSet) -&gt; str Returns all of the player's name and score.''' string='' # will contain output for player in self.playersList: # for every player in the list of players string+= player.get_name() + ' has ' + str(player.get_score()) + ' points \n' # add a string saying the player's name and current score return string # return the string def get_curr_name(self): '''PlayerSet.get_curr_name() -&gt; str Returns the name of the current player.''' return self.currentPlayer.get_name() # return the name of the player def go_to_next_player(self): '''PlayerSet.go_to_next_player() Moves the current player to the next player.''' index = 0 # will contain index of the current player for i in range(len(self.playersList)): # for every index in list of players if self.playersList[i] == self.currentPlayer: # if that index is correct index = i # assign index to the desired index index += 1 # add 1 to the desired index, we want to move to next player index %= self.playerCount # if the number of the player goes over, take the residue mod playerCount self.currentPlayer=self.playersList[index] # make the current player equal to the new index of the list of players def is_curr_winner(self): '''PlayerSet.is_curr_winner() -&gt; bool Returns if the current player has won.''' if self.currentPlayer.get_score() &gt;= 100: # if the current player has won return True else: # otherwise return False def take_turn(self): '''PlayerSet.take_turn() Takes the player's turn.''' self.currentPlayer.play_turn() # use player's method - play_turn() which plays a turn def play_game(self): '''PlayerSet.play_game() Plays the real Pass The Pigs game! Woohoo!''' while self.is_curr_winner() == False: # until a player has won print(self) # print the status of the players print(self.get_curr_name() + ", it's your turn") # print whose turn it is self.take_turn() # take the player's turn if self.is_curr_winner() == True: # if the current player has won print(self) # print the status of the players return self.get_curr_name() + ' has won!' # return which player has won self.go_to_next_player() # go to the next player </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T04:29:08.333", "Id": "51657", "Score": "0", "body": "Use new style classes if you use Python 2.2+. I use to put the closing upper commas of a docstring in a new line, under the doc itself. This gives readability and kinda split's the docstring with the data." } ]
[ { "body": "<p>Do not create players in <code>__init__()</code>. Pass a list of players into constructor instead of count. This will make your class more flexible. Also you class should not be bound to the UI implementation, so do not read data from a user in <code>__init__()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:00:24.213", "Id": "32371", "ParentId": "32358", "Score": "2" } }, { "body": "<p><strong>General</strong></p>\n\n<p>Most of your comments are not really useful : <a href=\"http://www.codinghorror.com/blog/2006/12/code-tells-you-how-comments-tell-you-why.html\" rel=\"nofollow\">comments should tell you why, not how</a>.</p>\n\n<p><strong>Constructor</strong></p>\n\n<p>You don't need to keep the number of player if you keep the list of players anyway.</p>\n\n<pre><code>def __init__(self,playerCount):\n '''PlayerSet(int) -&gt; PlayerSet\n Contstructs a group of players,\n given how many there are and asks the\n name of each player.'''\n self.playerCount = playerCount # initialize count of players attribute\n self.playersList = [] # initialize list of players attrbute\n for i in range(1,self.playerCount+1): # for every i between 1 and plyerCount\n name = input('Player ' + str(i) + ', please enter your name:') # ask player i's name\n player = Player(name) # create a player with that name \n self.playersList.append(player) # add the player to the list of players\n self.currentPlayer = self.playersList[0] # initialize current player attribute\n</code></pre>\n\n<p>can become :</p>\n\n<pre><code>def __init__(self,playerCount):\n '''PlayerSet(int) -&gt; PlayerSet\n Constructs a group of players,\n given how many there are and asks the\n name of each player.'''\n self.playersList = []\n for i in range(self.playerCount):\n name = input('Player ' + str(i+1) + ', please enter your name:')\n player = Player(name)\n self.playersList.append(player)\n self.currentPlayer = self.playersList[0]\n</code></pre>\n\n<p>which can become </p>\n\n<pre><code>def __init__(self,playerCount):\n '''PlayerSet(int) -&gt; PlayerSet\n Constructs a group of players,\n given how many there are and asks the\n name of each player.'''\n self.playersList = []\n for i in range(self.playerCount):\n self.playersList.append(Player(input('Player ' + str(i+1) + ', please enter your name:')))\n self.currentPlayer = self.playersList[0]\n</code></pre>\n\n<p>which can become using list comprehension :</p>\n\n<pre><code>def __init__(self,playerCount):\n '''PlayerSet(int) -&gt; PlayerSet\n Constructs a group of players,\n given how many there are and asks the\n name of each player.'''\n self.playersList = [Player(input('Player ' + str(i+1) + ', please enter your name:')) for i in range(self.playerCount)]\n self.currentPlayer = self.playersList[0]\n</code></pre>\n\n<p><strong>Str</strong></p>\n\n<p>You probably should add a get_description method on players to handle the <code>player.get_name() + ' has ' + str(player.get_score()) + ' points'</code> part.\nThen, your <code>__str__</code> method could/should use join : <code>return \"\\n\".join(p.get_description() for p in self.playersList)</code>.</p>\n\n<p><strong>go_to_next_player</strong></p>\n\n<p>The pythonic way to loop is to avoid using the length of the list.</p>\n\n<pre><code>for i in range(len(self.playersList)):\n something(self.playersList[i])\n</code></pre>\n\n<p>could/should be written :</p>\n\n<pre><code>for p in self.playersList:\n something(p)\n</code></pre>\n\n<p>Also, everything could be much simpler if <code>self.currentPlayer</code> was the index of a Player and not a Player object.</p>\n\n<pre><code>def go_to_next_player(self):\n '''PlayerSet.go_to_next_player()\n Moves the current player to the next\n player.'''\n self.currentPlayer = (self.currentPlayer + 1) % len(self.playersList)\n</code></pre>\n\n<p>(The constructor needs to be updated accordingly to set <code>currentPlayer</code> to <code>0</code>).</p>\n\n<p><strong>is_curr_winner</strong></p>\n\n<p>This could simply be :\n<code>return self.playersList[self.currentPlayer].get_score() &gt;= 100</code>.</p>\n\n<p>Also, maybe you should add a <code>is_winner</code> method on the Player.</p>\n\n<p><strong>play_game</strong></p>\n\n<p>You shouldn't compare to <code>True</code> and <code>False</code>.</p>\n\n<p>I am not sure if there's a point in returning a string.</p>\n\n<p>I don't know enough about the logic of your game but is there a point in checking if the player has won before he plays if we do it after he plays anyway ?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:19:31.780", "Id": "51680", "Score": "0", "body": "+1 for \"comments should tell you why, not how\" and other good points. (But consider sticking to 79 columns in your code blocks so that we don't have to scroll to read them.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:01:09.127", "Id": "32372", "ParentId": "32358", "Score": "3" } }, { "body": "<ol>\n<li><p>The class could be better named. <code>PlayerSet</code> is not just a set of players: it also knows how to play the game. I would consider calling it <code>PassThePigs</code> since it implements the logic for the game.</p></li>\n<li><p>Most of your comments are unnecessary. Now, I understand that you're learning to program so you probably find it helpful at this stage to explain each line of code you write. But as you get more experienced, you'll realise that it's not necessary to write comments that merely say the same thing as the code. In cases like this:</p>\n\n<pre><code>return self.currentPlayer.get_name() # return the name of the player\n</code></pre>\n\n<p>you should find that you can easily read the code:</p>\n\n<pre><code>return self.currentPlayer.get_name()\n</code></pre>\n\n<p>as meaning \"return the name of the current player\".</p>\n\n<p>Comments like <code>return the name of the player</code> eventually become a burden rather than a help, because you have to remember to update the comment every time you update the code. For example, it would be all too easy to end up with code like this:</p>\n\n<pre><code>return self.currentPlayer.get_score() # return the name of the player\n</code></pre>\n\n<p>where the code has been changed and the comment is now wrong.</p>\n\n<p>The best comments explain things that can't easily be figured out by reading the code, for example <em>why</em> you wrote the code in a particular way. Here are a couple of my comments for comparison:</p>\n\n<p>From <a href=\"https://codereview.stackexchange.com/a/31767/11728\">here</a>:</p>\n\n<pre><code>assert(limit == 10 ** max_digits) # algorithm works for powers of 10 only\n</code></pre>\n\n<p>And from <a href=\"https://codereview.stackexchange.com/a/24282/11728\">here</a>:</p>\n\n<pre><code>dt = self.clock.tick(FPS) / 1000.0 # convert to seconds\n</code></pre></li>\n<li><p>The Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>) suggests that you</p>\n\n<blockquote>\n <p>Limit all lines to a maximum of 79 characters [... This] makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.</p>\n</blockquote>\n\n<p>Also, shorter lines wouldn't disappear off the right hand side of code blocks here on Code Review.</p>\n\n<p>You're not obliged to follow PEP 8, but it makes it easier for you to collaborate with other Python programmers.</p></li>\n<li><p>There's no need to store the number of players in <code>self.playersCount</code> because you can always get the number of players as <code>len(self.playersList)</code>. Storing a fact in two places leads to a risk of inconsistency.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>'Player ' + str(i) + ', please enter your name:'\n</code></pre>\n\n<p>consider:</p>\n\n<pre><code>'Player {}, please enter your name:'.format(i)\n</code></pre></li>\n<li><p>Building a string by repeatedly appending to it is an <a href=\"http://en.wikipedia.org/wiki/Anti-pattern\" rel=\"nofollow noreferrer\">anti-pattern</a> in Python: it takes time that's quadratic in the number of append operations, because each <code>+=</code> operation creates a new string. It's nearly always better to use the <a href=\"http://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join</code></a> method. So this code:</p>\n\n<pre><code>string=''\nfor player in self.playersList:\n string+= player.get_name() + ' has ' + str(player.get_score()) + ' points \\n'\nreturn string\n</code></pre>\n\n<p>is better written:</p>\n\n<pre><code>return ''.join('{} has {} points\\n'.format(player.get_name(), player.get_score())\n for player in self.playersList)\n</code></pre></li>\n<li><p>Python does not generally need <em>accessor methods</em> like the <code>get_name</code> and <code>get_score</code> in your <code>Player</code> class. Instead of <code>player.get_name()</code>, consider using just <code>player.name</code>. That allows you to write:</p>\n\n<pre><code>return ''.join('{0.name} has {0.score} points\\n'.format(player)\n for player in self.playersList)\n</code></pre></li>\n<li><p>If the player has exactly 1 point, then this is going to produce ungrammatical output:</p>\n\n<pre><code>Parminder has 1 points\n</code></pre>\n\n<p>You need something like:</p>\n\n<pre><code>'{0.name} has {0.score} point{1}\\n'.format(player, '' if player.score == 1 else 's')\n</code></pre></li>\n<li><p>The purpose of the <a href=\"http://docs.python.org/3/reference/datamodel.html#object.__str__\" rel=\"nofollow noreferrer\"><code>__str__</code> method</a> is \"to compute the “informal” or nicely printable string representation of an object\". But you are using it here to format the players' current scores. It would be better to use a method name like <code>format_scores</code>.</p></li>\n<li><p>The <code>go_to_next_player</code> method seems very complicated. First, you have a loop where you try to find the index of the current player in the list:</p>\n\n<pre><code>index = 0\nfor i in range(len(self.playersList)):\n if self.playersList[i] == self.currentPlayer:\n index = i\n</code></pre>\n\n<p>Whenever you find yourself iterating over the indexes of a list, consider using the <a href=\"http://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code> function</a>:</p>\n\n<pre><code>index = 0\nfor i, player in enumerate(self.playersList):\n if player == self.currentPlayer:\n index = i\n</code></pre>\n\n<p>Second, when you find the player in the list, you set <code>index</code> but you carry on looping. It would be better to break out of the loop as soon as you find what you are looking for:</p>\n\n<pre><code>index = 0\nfor i, player in enumerate(self.playersList):\n if player == self.currentPlayer:\n index = i\n break\n</code></pre>\n\n<p>I've shown you how to rewrite the loop, but in fact no loop is needed. Python comes with a built-in method <a href=\"http://docs.python.org/3/library/stdtypes.html#common-sequence-operations\" rel=\"nofollow noreferrer\"><code>list.index</code></a> for this operation:</p>\n\n<pre><code>index = self.playersList.index(self.currentPlayer)\n</code></pre>\n\n<p>Finally, why go to this effect of looking up the current player in the list of players, when you could just remember the index instead of the player? In <code>__init__</code> you could write:</p>\n\n<pre><code>self.current_player_index = 0\n</code></pre>\n\n<p>combined with a property:</p>\n\n<pre><code>@property\ndef currentPlayer(self):\n return self.playersList[self.current_player_index]\n</code></pre>\n\n<p>and then the <code>go_to_next_player</code> method would be very simple:</p>\n\n<pre><code>self.current_player_index = (self.current_player_index + 1) % len(self.playersList)\n</code></pre>\n\n<p>A more \"advanced\" approach would be to use <a href=\"http://docs.python.org/3/library/itertools.html#itertools.cycle\" rel=\"nofollow noreferrer\"><code>itertools.cycle</code></a>. In <code>__init__</code> you'd write:</p>\n\n<pre><code>self.player_cycle = itertools.cycle(self.playersList)\nself.currentPlayer = next(self.player_cycle)\n</code></pre>\n\n<p>and then the <code>go_to_next_player</code> method would become:</p>\n\n<pre><code>self.currentPlayer = next(self.player_cycle)\n</code></pre></li>\n<li><p>This code:</p>\n\n<pre><code>if self.currentPlayer.get_score() &gt;= 100:\n return True\nelse:\n return False\n</code></pre>\n\n<p>can be simplified to:</p>\n\n<pre><code>return self.currentPlayer.get_score() &gt;= 100\n</code></pre>\n\n<p>since Boolean expressions like <code>a &gt;= b</code> evaluate to <code>True</code> or <code>False</code>.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>while self.is_curr_winner() == False:\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>while not self.is_curr_winner():\n</code></pre>\n\n<p>but actually this should be</p>\n\n<pre><code>while True:\n</code></pre>\n\n<p>since the winner detection has already been done (after the player took their turn).</p></li>\n<li><p>The <code>play_game</code> method returns a string but this is not mentioned in the documentation for the method. (In fact, it's probably a mistake.)</p></li>\n<li><p>Consider giving a name to the value <code>100</code> so that it's clear what it means and so that it's easy to find and change if you need to.</p></li>\n<li><p>When you have a method that's called from only one place, and is only one line long, consider whether it's worth having a method at all. Adding methods is good because it improves the clarity of the code (you can give the method a name that explains its purpose, and provide documentation), but on the other hand each method increases the length of the code and makes it harder to read.</p></li>\n<li><p>Once you do this inlining process, it will become clear that there isn't really any persistent state in the game: everything important happens inside <code>PlayerSet.play_game</code>. So is it really worth having a class at all? Compare your implementation with this one:</p>\n\n<pre><code>from itertools import cycle\n\ndef pass_the_pigs(self, n, winning_score=100):\n \"\"\"Play a game of Pass the Pigs with n players.\"\"\"\n players = [Player(input('Player {}, please enter your name:'.format(i)))\n for i in range(1, n + 1)]\n for player in cycle(players):\n for p in players:\n print('{0.name} has {0.score} point{1}'\n .format(p, '' if p.score == 1 else 's'))\n for p in players:\n if p.score &gt;= winning_score:\n print('{0.name} has won!'.format(p))\n return\n print(\"{0.name}, it's your turn\".format(player))\n player.play_turn()\n</code></pre>\n\n<p>(Note that there's almost nothing here that's specific to <em>Pass the Pigs</em> — the same code would work as the main loop for any turn-based game where the players do not interact with each other, and where there's a winning score.)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T14:58:34.000", "Id": "51715", "Score": "0", "body": "My rule of thumb for code comments is \"Never write *what* the code does – always describe *why*.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T15:03:00.740", "Id": "51716", "Score": "0", "body": "@kojiro: *Never* is a bit strong: I think there's still a role for comments in explaining what the code does, when that is not obvious from reading the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T16:59:43.457", "Id": "51724", "Score": "0", "body": "@GarethRees it's a subtle difference, but I think if you have to explain what the code does, you should explain why you wrote it that way. Basically, when you feel it's necessary to write unidiomatic code, the *why* should leave enough context to understand the *what*. But the *what* should never stand alone." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:28:38.007", "Id": "32373", "ParentId": "32358", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T03:59:23.093", "Id": "32358", "Score": "3", "Tags": [ "python", "object-oriented", "game" ], "Title": "\"Pass the Pigs\" game" }
32358
<p>I posted a couple questions about a week ago, but have almost gotten it working. This program is supposed to simulate the following: </p> <ol> <li>Ask the user how many balls to drop</li> <li>Drop one ball at a time</li> <li>Allow it to bounce ten times moving either once to the right or once to the left each bounce</li> <li>Then print out the even numbers (since a ball could never land on an odd) -10 - 10 with a 'o' to represent each ball.</li> </ol> <p></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; /* Prototype for drop_Balls, int parameter is number of balls being dropped */ void drop_balls(int); /* Gets the number of balls that need to be dropped by the user */ int get_num_balls(); int main() { drop_balls(get_num_balls()); } int get_num_balls() { int num_balls; printf("How many balls should be dropped? "); scanf("%d", &amp;num_balls); /* Ensure that it is atleast one ball */ while(num_balls &lt;= 0) { printf("You have to drop at least one ball! \n "); printf("How many balls should be dropped? "); scanf("%d", &amp;num_balls); } /* Return the number of balls that will be dropped */ return num_balls; } void drop_balls(int num_balls) { /* Keeps track of how many balls landed where */ int ball_count[21]; /* What number ball are we on */ int ball_num = 0; /* Seed the generator */ srand(time(NULL)); /* Do the correct # of balls */ for(ball_num = 0; ball_num &lt; num_balls; ball_num++ ) { /* Start at 10 since its the middle of 21 */ int starting_point = 10; /* Bounce each ball 10 times */ for(starting_point = 10; starting_point &gt; 0; starting_point--) { int number; /* Create a random integer between 1-100 */ number = rand() % 100; /* If its less than 50 bounce to the right once */ if(number &gt;= 50) { starting_point++; } /* If its greater than 50, bounce to the left once */ else { starting_point--; } } /* Add one to simulate one ball landing there */ ball_count[starting_point]++; } /* Start at the -10 spot */ int ball_place = -10; int x; /* Go through the 21 spots, but skip the odd ones, since they never get balls */ for(x = 0; x &lt; 20; x+2) { printf("\n %d: ", ball_place); int l = 0; /* Print out an 'o' for each ball */ for(l = 0; l &lt; ball_count[x]; l++) { printf("o"); } /* Increase the spot, taking it from -10 - 10 */ ball_place = ball_place + 2; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T14:37:29.230", "Id": "51713", "Score": "1", "body": "So, what's the question? Is your code working the way you want it to? If not, then your question is off topic here." } ]
[ { "body": "<p><strong>Comments</strong></p>\n\n<p>You should use <code>//</code> comments for single-line comments.</p>\n\n<p>I am not sure you are using comments properly. Comments shouldn't explain how, it should explain why.</p>\n\n<pre><code>/* Prototype for drop_Balls, int parameter is number of balls being dropped */\nvoid drop_balls(int); \n</code></pre>\n\n<p>One can see that this is a prototype. <code>void drop_balls(int number_of_balls);</code> would probably provide as much information in a more compact way.</p>\n\n<pre><code>/* Return the number of balls that will be dropped */\nreturn num_balls; \n</code></pre>\n\n<p>This does not look like a useful comment to me.</p>\n\n<pre><code>/* Keeps track of how many balls landed where */\nint ball_count[21]; \n</code></pre>\n\n<p>A bit of explanation on the <code>21</code> here would be useful... but it is not provided.</p>\n\n<p>This leads me to the next section:</p>\n\n<p><strong>Magic numbers</strong></p>\n\n<p>You probably don't want to have hard-coded numbers all over the place. You could create a constant with value 21 and then:</p>\n\n<ul>\n<li><p><code>starting_point = 10</code> would become <code>starting_point = N /2</code>.</p></li>\n<li><p><code>for(x = 0; x &lt; 20; x+2)</code> would become <code>for(x = 0; x &lt; N; x+2)</code>.</p></li>\n<li><p><code>int ball_place = -10;</code> would become <code>int ball_place = - N/2;</code></p></li>\n</ul>\n\n<p><strong>Code organisation</strong></p>\n\n<p>It would probably be better now to call <code>srand</code> in <code>rand_balls</code> as it shouldn't be its responsibility. You can do it from <code>main()</code> if you want.</p>\n\n<p>Define variable in the smallest possible scope. For instance:</p>\n\n<pre><code>for(int ball_num = 0; ball_num &lt; num_balls; ball_num++ )\n</code></pre>\n\n<p>Also, how is this loop:</p>\n\n<pre><code>for(starting_point = 10; starting_point &gt; 0; starting_point--)\n</code></pre>\n\n<p>supposed to behave? Don't we always have the variable set to 0 or -1 at the end?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T06:25:20.150", "Id": "51661", "Score": "0", "body": "I agree with what you said about the commenting, I will also go through and change them to make more sense once I get it working. The constants I know make it look sloppy, I was going to go through and change that once I got everything working. That loop moves it once to the left or right every pass through, so I think its doing what its supposed to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:36:39.700", "Id": "51687", "Score": "1", "body": "Can you explain your advice, \"You should use `//` comments for single-line comments.\"? What if the OP needs the code to compile with the `-ansi` flag?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T23:52:34.497", "Id": "56896", "Score": "0", "body": "Shouldn't `srand()` always be called in `main()`? It doesn't look like it should be an option." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T06:19:54.013", "Id": "32362", "ParentId": "32361", "Score": "1" } }, { "body": "<p>In addition to @Josay's answer:</p>\n\n<p>This code contains some duplication which you can avoid:</p>\n\n<pre><code>printf(\"How many balls should be dropped? \");\nscanf(\"%d\", &amp;num_balls);\n/* Ensure that it is atleast one ball */\nwhile(num_balls &lt;= 0) \n{\n printf(\"You have to drop at least one ball! \\n \");\n printf(\"How many balls should be dropped? \");\n scanf(\"%d\", &amp;num_balls);\n}\n</code></pre>\n\n<p>Either refactor for the number of balls into it's own method:</p>\n\n<pre><code>int ask_for_number_of_balls()\n{\n printf(\"How many balls should be dropped? \");\n scanf(\"%d\", &amp;num_balls);\n}\n</code></pre>\n\n<p>And then your loop becomes:</p>\n\n<pre><code>int num_balls = ask_for_number_of_balls();\nwhile (num_balls &lt;= 0)\n{\n printf(\"You have to drop at least one ball! \\n \");\n num_balls = ask_for_number_of_balls();\n}\n</code></pre>\n\n<p>Or you get a bit clever:</p>\n\n<pre><code>int num_balls = -1;\nwhile (1)\n{\n printf(\"How many balls should be dropped? \");\n scanf(\"%d\", &amp;num_balls);\n if (num_balls &gt; 0) { break; }\n printf(\"You have to drop at least one ball! \\n \");\n}\n</code></pre>\n\n<p>I would probably prefer the refactored method over clever (clever is harder to read and maintain).</p>\n\n<p>I'm not sure about this loop:</p>\n\n<pre><code>for(starting_point = 10; starting_point &gt; 0; starting_point--)\n</code></pre>\n\n<p>You randomly add one or subtract one from <code>starting_point</code>, but the running condition for that loop is <code>starting_point &gt; 0</code>. So, as long as the starting point is greater than 0, this loop will run. This means that at the end, <code>starting_point</code> will always be 0 afterwards (not to mention that your loop could run for a long time if your random numbers happen to be greater than 50 most of the time).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T07:47:44.897", "Id": "32366", "ParentId": "32361", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T05:28:13.187", "Id": "32361", "Score": "3", "Tags": [ "c", "simulation" ], "Title": "Bouncing-ball simulation" }
32361
<p>I wonder whether or not I should improve my current practice on creating/calling dialogs with AngularJS.</p> <p>Think of a simple information, displayed on demand as a modal window. To create such a thing, I would write a directive, include it to my page and use <code>ng-hide</code> to hide it.</p> <p>If I want to call it, I would simply change the associated ng-hide value to false from within my main controller.</p> <pre><code>app.directive('modal',function(){ return{ restrict: 'E', template: '&lt;div ng-hide=state.modalVisibility&gt;&lt;/div&gt;', // etc } }); app.controller('Ctrl',function($scope){ $scope.state.modalVisibility = false; $scope.changeVisibility = function(){ $scope.state.modalVisibility = true; } }); </code></pre> <p>Are there any disadvantages or possible improvements on this practice? Is it a bad idea to have the modal-element "always there" but only displayed on demand? </p>
[]
[ { "body": "<p>The disadvantage is the modal directive hanging around for no good reason in the templates, and a tight coupling between the controller and the modal directive.</p>\n\n<p>Far better is using a service to inject this modal into the DOM as needed.\nThis is the approach that for example the <a href=\"http://angular-ui.github.io/bootstrap/#/modal\" rel=\"nofollow\">AngularUI team uses in their approach.</a></p>\n\n<p>This ensures lower coupling (more creative freedom and less technical debt), more easily testable code, and a more intuitive API. Simply inject and call a service, rather than having to make sure the directive is added, and the controller writes to the correct variable, and they share the same scope etc.</p>\n\n<p>The reason you are encouraged to use directives for DOM manipulation is first and foremost convention and testability issues. Using a service in this use-case is an acceptable exception.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-22T03:01:37.177", "Id": "135363", "Score": "0", "body": "[here](https://github.com/SET001/angularjs_test_3_modal_window/blob/master/coffee/services/test-modal.coffee) is a simple example of modal that uses approach described by Kenneth" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T01:08:29.077", "Id": "37007", "ParentId": "32367", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T08:03:11.570", "Id": "32367", "Score": "1", "Tags": [ "javascript", "angular.js" ], "Title": "Creating dialogs and modals with AngularJS" }
32367
<p>I have some C# unit tests which each basically perform the same steps but supply different arguments to the unit under test.</p> <p>I wanted to encapsulate the logic inside some "helper methods" but found that the method names, while descriptive, were cumbersome. For example, the code inside a test method would look like this contrived example:</p> <pre><code>var expected = 1; var set = new [] { 1, 2, 3, 4, 5 }; AssertThatCallToGetSmallestReturnsExpectedValueFromGivenSet(expected, set); </code></pre> <p>I simplified the method names and took up a convention of using C#'s named arguments feature:</p> <pre><code>AssertThatCallToGetSmallest( returnsValue: 1, fromSet: new [] { 1, 2, 3, 4, 5 } ); </code></pre> <p>The latter approach seems cleaner and more readable to me. I've been working with objective-c for a few months now so invoking methods in this manner has become less of an issue for me aesthetically. The other advantage is that this convention scales better with an increase in the number of parameters (if that should ever really be of value).</p> <p>One thing I'm particularly concerned with is the lack of enforced readability because named arguments are optional. There is the potential for programmers to later come along and "misuse" the helper methods I've created by failing to specify the parameter names:</p> <pre><code>AssertThatCallToGetSmallest(1, new [] { 1, 2, 3, 4, 5 }); // what does this even mean? </code></pre> <p>So, which way is "better"?</p> <p>I'm using the Visual Studio Unit Testing Framework with MSTest.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:01:43.920", "Id": "51728", "Score": "0", "body": "Which unit testing framework are you using? Many frameworks allow you to use multiple test cases on a single test method (e.g., NUnit's TestCaseAttribute), but the mechanism to do so will depend on which one you are using." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T00:30:54.713", "Id": "51751", "Score": "0", "body": "Hey @DanLyons Thanks for the reply. I've updated the post to answer your question." } ]
[ { "body": "<p>The most canonical way of accomplishing what you want is to use the testing framework's functionality for writing data-driven tests, rather than writing a common helper method and then a number of separate tests which pass arguments into it.</p>\n\n<p>Different frameworks do this differently, so I will focus on MSTest first, as that is the framework you use.</p>\n\n<p>In MSTest, there is a <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.datasourceattribute.aspx\" rel=\"nofollow\">DataSource</a> attribute you can supply, which defines how the framework can locate your test data. Additionally, you supply a TestContext property of type <a href=\"http://msdn.microsoft.com/en-US/library/microsoft.visualstudio.testtools.unittesting.testcontext.aspx\" rel=\"nofollow\">TestContext</a>.</p>\n\n<p>When the tests execute, TestContext will be populated with the data for a single test case, and you can access it by using named indexing into the <code>TestContext.DataRow</code> property.</p>\n\n<p>(Note: I haven't done MSTest in some time, so feel free chime in if there's a better way nowadays)</p>\n\n<p>Example:\n(Embedded resource: foo.xml)</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;Tests&gt;\n &lt;Test&gt;\n &lt;a&gt;1&lt;/a&gt;\n &lt;b&gt;2&lt;/b&gt;\n &lt;result&gt;3&lt;result&gt;\n &lt;/Test&gt;\n &lt;Test&gt;\n &lt;a&gt;2&lt;/a&gt;\n &lt;b&gt;2&lt;/b&gt;\n &lt;result&gt;4&lt;result&gt;\n &lt;/Test&gt;\n&lt;/Tests&gt;\n</code></pre>\n\n<p>(test file)</p>\n\n<pre><code> public TestContext TestContext { get; set; }\n\n [TestMethod]\n [DeploymentItem (\"foo.xml\")]\n [DataSource (\"Microsoft.VisualStudio.TestTools.DataSource.XML\",\n \"|DataDirectory|\\\\foo.xml\",\n \"Test\",\n DataAccessMethod.Sequential)]\n public void TestAdd ()\n {\n var first = (int) TestContext.DataRow [\"a\"];\n var second = (int) TestContext.DataRow [\"b\"];\n var expected = (int) TestContext.DataRow [\"result\"];\n var result = testObject.Add(first,second);\n Assert.AreEqual(expected, result);\n }\n</code></pre>\n\n<p>Adding more test cases is just a matter of adding elements with new data and re-building/re-running.</p>\n\n<p>The How-To MSDN page can be found <a href=\"http://msdn.microsoft.com/en-US/library/ms182527.aspx\" rel=\"nofollow\">here</a>, and some examples of DataSource configuration strings can be found <a href=\"http://msdn.microsoft.com/en-us/library/ee624082.aspx\" rel=\"nofollow\">here</a>.</p>\n\n<p>Just to give you a taste of this in other frameworks:</p>\n\n<p>NUnit TestCase</p>\n\n<pre><code> [TestCase(1,2,3)]\n [TestCase(2,2,4)]\n public void TestAdd(int first, int second, int expected)\n {\n var result = testObject.Add(first, second);\n Assert.That(result, Is.EqualTo(expected));\n }\n</code></pre>\n\n<p>NUnit TestCaseSource</p>\n\n<pre><code> public static IEnumerable&lt;TestCaseData&gt; TestData\n {\n yield return new TestCaseData(1, 2, 3);\n yield return new TestCaseData(2, 2, 4);\n }\n\n [TestCaseSource(\"TestData\")]\n public void TestAdd(int first, int second, int expected)\n {\n var result = testObject.Add(first, second);\n Assert.That(result, Is.EqualTo(expected));\n }\n</code></pre>\n\n<p>MbUnit Row</p>\n\n<pre><code> [RowTest]\n [Row(1,2,3)]\n [Row(2,2,4)]\n public void TestAdd(int first, int second, int expected)\n {\n var result = testObject.Add(first, second);\n Assert.AreEqual(result, expected);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T05:15:29.147", "Id": "52062", "Score": "0", "body": "I find MSTest's way of doing this comparatively hideous. I was aware of NUnit's TestCase attribute but have avoided using NUnit for reasons. In any case, thanks for the response. I appreciate your effort providing examples. =D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T18:46:46.607", "Id": "32431", "ParentId": "32374", "Score": "2" } } ]
{ "AcceptedAnswerId": "32431", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:39:13.287", "Id": "32374", "Score": "2", "Tags": [ "c#", ".net", "unit-testing" ], "Title": "Encapsulated unit testing logic" }
32374
<p>I am trying to make a <strong>very fast hash table</strong> based set of <strong>pointers</strong>. It is supposed to be as fast as possible, not conforming to standard C++ at times. This is always marked in the code. Collisions are resolved by linear probing. The maximum size is known at construction time and memory grows by multiples of 2. All memory is pre-allocated. The set should perform only insertions. No other functionality is needed.</p> <p>Here is my code:</p> <pre><code>#ifndef HASH_TABLE_H #define HASH_TABLE_H #include &lt;vector&gt; #include &lt;cstdint&gt; #include &lt;cstring&gt; #include &lt;algorithm&gt; #include "range_checking.h" // contains Positive&lt;int&gt; a simple range checking utility //&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; template &lt;typename TItem&gt; class HashTable { public: //--------------------------------------------------------------------- HashTable (Positive&lt;int&gt; maxSize, Positive&lt;int&gt; probableSize = 32); void reset(Positive&lt;int&gt; probableSize); bool insert(const TItem *address); int size() const; long nCollisions() const; private: //-------------------------------------------------------------------- typedef std::vector&lt;const TItem*&gt; TArray; std::vector&lt;TArray&gt; arrays_; int operatingArray_; uintptr_t computeIndex(const TItem* address) const; void expand(); bool performInsertion(const TItem *address); Real maxLoadFactor_; int currentArraySize_; int nItems_; int maxItems_; long nCollisions_ = 0; }; unsigned fastCeilLog2(unsigned argument); unsigned fastModuloPowerOfTwo(unsigned argument, unsigned powerOfTwo); //&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; //***************************************************************************** // Implementations: //***************************************************************************** //============================================================================= template &lt;typename TItem&gt; HashTable&lt;TItem&gt;::HashTable(Positive&lt;int&gt; maxSize, Positive&lt;int&gt; probableSize): operatingArray_(0), maxLoadFactor_(0.5), currentArraySize_(1), nItems_(0), maxItems_(0) { do { currentArraySize_ *= 2; arrays_.emplace_back(currentArraySize_, nullptr); } while (currentArraySize_ &lt; maxSize / maxLoadFactor_); reset(probableSize); } //============================================================================= //============================================================================= template &lt;typename TItem&gt; void HashTable&lt;TItem&gt;::reset(Positive&lt;int&gt; probableSize) { /// The following line is nonstandard and should be: /// std::fill(arrays_[operatingArray_].begin(), /// arrays_[operatingArray_].end(), nullptr); std::memset(&amp;(arrays_[operatingArray_][0]),0, arrays_[operatingArray_].size()*sizeof(int*)); maxItems_ = probableSize / maxLoadFactor_; operatingArray_ = fastCeilLog2(maxItems_) - 1; currentArraySize_ = arrays_[operatingArray_].size(); nItems_ = 0; } //============================================================================= //============================================================================= template &lt;typename TItem&gt; bool HashTable&lt;TItem&gt;::insert(const TItem* address) { if (nItems_ + 1 &gt; maxItems_) { expand(); return insert(address); } bool inserted = performInsertion(address); if (inserted) ++nItems_; return inserted; } //============================================================================= //============================================================================= template &lt;typename TItem&gt; int HashTable&lt;TItem&gt;::size() const { return nItems_; } //============================================================================= //============================================================================= template &lt;typename TItem&gt; long HashTable&lt;TItem&gt;::nCollisions() const { return nCollisions_; } //============================================================================= //============================================================================= template &lt;typename TItem&gt; uintptr_t HashTable&lt;TItem&gt;::computeIndex(const TItem* address) const { uintptr_t index = reinterpret_cast&lt;uintptr_t&gt;(address); /// Nonstandard index &gt;&gt;= 5; /// Ad hoc index = fastModuloPowerOfTwo(index, currentArraySize_); return index; } //============================================================================= //============================================================================= template &lt;typename TItem&gt; void HashTable&lt;TItem&gt;::expand() { TArray&amp; lastArray = arrays_[operatingArray_]; ++operatingArray_; currentArraySize_ = arrays_[operatingArray_].size(); maxItems_ = maxLoadFactor_ * currentArraySize_; for (auto i : lastArray) performInsertion(i); /// The following line is nonstandard and should be: /// std::fill(lastArray.begin(), lastArray.end(), nullptr); std::memset(&amp;lastArray[0], 0, lastArray.size()*sizeof(int*)); } //============================================================================= //============================================================================= template &lt;typename TItem&gt; bool HashTable&lt;TItem&gt;::performInsertion(const TItem *address) { uintptr_t index = computeIndex(address); const TItem* insertionSpot = arrays_[operatingArray_][index]; while (insertionSpot != nullptr) { ++nCollisions_; if (insertionSpot == address) return false; ++index; index = fastModuloPowerOfTwo(index, currentArraySize_); insertionSpot = arrays_[operatingArray_][index]; } arrays_[operatingArray_][index] = address; return true; } //============================================================================= //============================================================================= inline unsigned fastCeilLog2(unsigned argument) { unsigned logarithm = 1; while (argument &gt;&gt;= 1) ++logarithm; return logarithm; } //============================================================================= //============================================================================= inline unsigned fastModuloPowerOfTwo(unsigned argument, unsigned powerOfTwo) { argument &amp;= (powerOfTwo-1); return argument; } //============================================================================= #endif // HASH_TABLE_H </code></pre> <p>I am having problems with collisions. </p> <p>I made a benchmark that reserves 32 items and feeds data of various sizes and overlaps into the table, letting it grow naturally. Then it is cleared, reserved again and the same data is fed into it again. The times for 10 runs are summed and the same is done with <strong>std::unordered_set</strong> of <strong>gcc 4.8</strong>. The ratios and the average number of collisions for my hashtable are presented in this <a href="https://docs.google.com/spreadsheet/ccc?key=0AneL0ITWbQqTdHV5ZVlyZGdPRXp1ZXVCNG5idXRodnc&amp;usp=sharing" rel="nofollow">document</a>.</p> <p>I am concerned about:</p> <p><strong>The number of collisions:</strong> Should there be so many collisions? Is it normal that to feed 1600 items with 0.3 overlap (30% of the items are duplicates) results in 16 000 collisions?</p> <p><strong>The irregularity in the collision data, For example</strong>: </p> <p>1600 items, 0% overlap => cca 1700 collisions</p> <p>3200 items, 0% overlap => cca 1 700 000 collisions</p> <hr> <ol> <li>How can I improve my hash table?</li> <li>Could you give me general code assesment?</li> <li>Could you explain the strange collision data and the great number of collisions? Is this normal?</li> <li>How can I reduce the number of collisions?</li> </ol> <p>I made this hashtable just by some ad-hoc experimentation and reading the <a href="http://en.wikipedia.org/wiki/Hash_table" rel="nofollow">Wikipedia article</a> and it is the first time I made a hash table. So I am very inexperienced and humble, welcoming any advice at all.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:54:50.487", "Id": "51672", "Score": "4", "body": "Never design your own hashing algorithm (mathematically it is very complex to get correct to avoid collisions). But a hint. Use prime numbers in its generation will help with preventing collisions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:55:29.193", "Id": "51673", "Score": "1", "body": "You do realize that C++11 has std::unordered_set which is basically a hash table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:57:02.150", "Id": "51674", "Score": "1", "body": "Read this: [Good hash algorithm for list of (memory) addresses](http://stackoverflow.com/q/386771/14065)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:00:36.760", "Id": "51675", "Score": "0", "body": "Normally you don't expand a hash table. You make the underlying array large. Collisions should be `very` rare with a good hash. But when they do happen you build a list of objects at the same location." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:14:14.693", "Id": "51677", "Score": "0", "body": "@LokiAstari I wanted to use powers of 2 instead of primes so that I can compute the index very quickly using only masking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:17:56.647", "Id": "51678", "Score": "1", "body": "powers of 2 may be faster. But they are not a good technique for getting non clashing hashes. That is why you use primes to reduce the clashes (its a property of prime that helps in this. See your local maths text book for details)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:19:42.873", "Id": "51681", "Score": "0", "body": "Can not work out what `operatingArray_` is used for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:24:06.830", "Id": "51683", "Score": "0", "body": "@LokiAstari The hashtable tries to avoid memory allocations by holding arrays of 4, 8, 16, 32, ... items and always using just one array according to the number of items in the table. operatingArray_ is the index of the array being used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:35:36.003", "Id": "51734", "Score": "1", "body": "As a HashTable with max 4 billion elements grows approx 20 times until it is filled up completely (starting at approx 1000 elements), dynamically growing the array isn't much of a problem: It hardly ever happens. @MartinDrozdik: Your hash function is just way to bad, and that's why you end up in so many collisions. Remember: You have to fit 2^32 numbers in a much smaller range. Of course it's hard to find a good hash. Prime numbers are a good point to start. You might find <address> modulo <primenumber> good enough." } ]
[ { "body": "<p>Find it hard to believe that std::fill is slower than std::memeset</p>\n\n<pre><code>/// The following line is nonstandard and should be:\n/// std::fill(arrays_[operatingArray_].begin(),\n/// arrays_[operatingArray_].end(), nullptr);\nstd::memset(&amp;(arrays_[operatingArray_][0]),0,\n arrays_[operatingArray_].size()*sizeof(int*));\n</code></pre>\n\n<p>If you are in debug mode then you may see a difference but with optimizations ON seems unlikely. If there is a difference they you should add that as a comment to explain. Otherwise it is not non standard to use std::memset I would just add a comment on why.</p>\n\n<p>This seems perfectly valid to me:</p>\n\n<pre><code>uintptr_t index = reinterpret_cast&lt;uintptr_t&gt;(address);\n</code></pre>\n\n<p>The <code>uintptr_t</code> is specifically designed to hold a pointer without loss of data. Using <code>reinterpret_cast&lt;&gt;()</code> is valid to indicate the danger of the conversion. But it is a valid conversion.</p>\n\n<p>Again I see nothing unstandard about:</p>\n\n<pre><code>/// The following line is nonstandard and should be:\n/// std::fill(lastArray.begin(), lastArray.end(), nullptr);\nstd::memset(&amp;lastArray[0], 0, lastArray.size()*sizeof(int*));\n</code></pre>\n\n<p>But I would add a comment on why you chose <code>std::memset()</code>.</p>\n\n<p>No need for the recursive call here:</p>\n\n<pre><code>if (nItems_ + 1 &gt; maxItems_)\n{\n expand();\n return insert(address);\n}\n</code></pre>\n\n<p>I would just let it fall through. If there is a possibility that <code>expand()</code> does not grow it enough then use a loop rather than recursion. That will make it easier for the compiler to unroll and do other optimizations.</p>\n\n<p>Now what I would consider a good hashing function:</p>\n\n<pre><code>uintptr_t HashTable&lt;TItem&gt;::computeIndex(const TItem* address) const\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:29:10.900", "Id": "51684", "Score": "0", "body": "I just checked the implementation of std::hash and it seems to be the same as mine: return reinterpret_cast<size_t>(__p); The performance difference may be caused by not using primes as you suggested." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:10:10.947", "Id": "51695", "Score": "0", "body": "The reason why I marked the memsets as nonstandard is because I am comparing the result of a memset to nullptr, which does not have to be represented by all zeros according to the standard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:23:37.943", "Id": "51698", "Score": "0", "body": "I changed the bitshift to index >>= 4; and the maxLoadFactor_ to 0.4 and I started to get consistent results. There are still very many collisions, but it started outperforming std::unordered_set. But this would probably change on a 32 bit machine. Maybe I could try quadratic probing instead of linear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:32:22.827", "Id": "51701", "Score": "0", "body": "Anyhow thank you very much for looking into my source code. I feel much more confident now." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:14:07.847", "Id": "32378", "ParentId": "32375", "Score": "2" } } ]
{ "AcceptedAnswerId": "32378", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:44:59.257", "Id": "32375", "Score": "0", "Tags": [ "c++", "performance", "hash-map" ], "Title": "Fast hash table based set of pointers" }
32375
<p>I have written a simple copy file code, called 'Amature SVN', kindly review my code. </p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace AmatureSVN { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void btnSelectFolder_Click(object sender, EventArgs e) { DialogResult result = dirBrowserDlg.ShowDialog(); if (result == DialogResult.OK) { txtSelectedFolder.Text = dirBrowserDlg.SelectedPath; } } private void btnSelectFiles_Click(object sender, EventArgs e) { DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { string[] selectedFiles = openFileDialog1.FileNames; foreach (string str in selectedFiles) { //unique items if (listboxSelectedFiles.Items.Contains(str)) continue; listboxSelectedFiles.Items.Add(str); } } } private void btnCopy_Click(object sender, EventArgs e) { string backupDir = CreateBackupDir(); //if dir not created return if (string.IsNullOrEmpty(backupDir)) return; CopyFilesToDir(backupDir); //Create Readme if (!string.IsNullOrEmpty(txtReadMe.Text)) CreateReadMe(backupDir); } private void CreateReadMe(string backupDir) { using (StreamWriter writer = new StreamWriter(backupDir + @"\ReadMe.txt",false)) { try { writer.Write(txtReadMe.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } string CreateBackupDir() { //create backup folder at selected location if (!string.IsNullOrEmpty(txtSelectedFolder.Text)) { /*get todays date and time date will we folder for today time will be subfolder*/ string nowTime = DateTime.Now.ToString("dd MMM yyyy") + @"\" + DateTime.Now.ToString("hh mm"); string backupDir = txtSelectedFolder.Text + @"\" + nowTime; //create dir try { if (!Directory.Exists(backupDir)) { Directory.CreateDirectory(backupDir); } return backupDir; } catch (Exception ex) { MessageBox.Show(ex.Message); return ""; } } return ""; } void CopyFilesToDir(string backupDir) { foreach (string file in listboxSelectedFiles.Items) { //copy file with overwrite option try { File.Copy(file, backupDir + @"\" + file.Split('\\').Last(), checkBoxOverwrite.Checked); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } </code></pre>
[]
[ { "body": "<p>There isn't much too review. A few thing things that can be improved are:</p>\n\n<ol>\n<li>Use <code>Path.Combine()</code> instead of building file paths manually.</li>\n<li>Use <code>String.Empty</code> instead of <code>\"\"</code>.</li>\n<li><p>Reduce nesting by inverting <code>if</code> statements, e.g. by replacing </p>\n\n<pre><code>if (result == DialogResult.OK)\n{...}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>if (result != DialogResult.OK)\n return;\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:53:02.033", "Id": "51694", "Score": "0", "body": "@ss7don, not really, its pretty clear. It says `if <condition> then nothing happens`. While nested `if`s kind of force you to read through the whole execution path to figure out if something happens. It doesn't matter when you have 3-line-methods, but it helps, when methods are somewhat larger." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T12:21:28.367", "Id": "32379", "ParentId": "32376", "Score": "5" } }, { "body": "<p>You mix UI and logic together. You should extract all the copy code into a separate class and pass in the parameters from the form. This will make your code more reusable (right now you can't write an automated copy program which takes file names from a config file for example).</p>\n\n<p>When you refactor then let your exceptions bubble up and let the caller (the UI in this case) deal with them.</p>\n\n<p><code>CreateBackupDir</code> should probably be more something along the lines <code>EnsureBackupDirExists</code> (create if not exists).</p>\n\n<p>Something along these lines:</p>\n\n<pre><code>public class BackupUtility\n{\n private string _BackupDirectoryBase;\n private bool _OverWriteExistingFiles;\n\n public BackupUtility(string backupDirectoryBase, bool overwriteExistingFiles)\n {\n if (string.IsNullOrEmpty(backupDirectoryBase))\n throw new ArgumentException(\"Backup directory must not be null or empty\");\n _BackupDirectoryBase = backupDirectoryBase;\n _OverWriteExistingFiles = overwriteExistingFiles;\n }\n\n public void BackupFiles(IEnumerable files, string readmeContent)\n {\n var actualBackupDir = EnsureBackupDirExists();\n CopyFilesToBackupDir(actualBackupDir, files);\n CreateReadmeIfRequired(actualBackupDir, readmeContent);\n }\n\n private string EnsureBackupDirExists()\n {\n /* get todays date and time\n - date will we folder for today\n - time will be subfolder */\n string today = DateTime.Now.ToString(\"dd MMM yyyy\")\n string time = DateTime.Now.ToString(\"hh mm\");\n\n string backupDir = Path.Combine(_BackupDirectoryBase, today, time);\n\n if (!Directory.Exists(backupDir))\n {\n Directory.CreateDirectory(backupDir);\n }\n return backupDir;\n }\n\n private void CopyFilesToBackupDir(string actualBackupDir, IEnumerable files)\n {\n foreach (string file in file)\n {\n string fileName = Path.GetFileName(file);\n File.Copy(file, Path.Combine(actualBackupDir, fileName), _OverwriteExistingFiles);\n }\n }\n\n private void CreateReadMeIfRequired(string actualBackupDir, string readmeContent)\n {\n if (string.IsNullOrEmpty(readmeContent))\n return;\n\n var readmeFile = Path.Combine(actualBackupDir, \"ReadMe.txt\");\n File.WriteAllText(readmeFile, readmeContent); // will overwrite if exist\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T19:42:24.277", "Id": "32391", "ParentId": "32376", "Score": "3" } } ]
{ "AcceptedAnswerId": "32391", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T11:47:43.013", "Id": "32376", "Score": "3", "Tags": [ "c#", "optimization", ".net" ], "Title": "Amature SVN review" }
32376
<p>I am trying to make an universal implementation of <code>IDisposable</code> (as a base class):</p> <pre><code>public abstract class DisposableObject : IDisposable { private bool hasUnmanagedResources; private bool baseDisposeManagedResourcesCalled; private bool baseDisposeUnmanagedResourcesCalled; protected bool IsDisposed { get; private set; } protected bool IsDisposing { get; private set; } public DisposableObject() : this(false) { } public DisposableObject(bool hasUnmanagedResources) { this.hasUnmanagedResources = hasUnmanagedResources; if (!hasUnmanagedResources) { GC.SuppressFinalize(this); } } ~DisposableObject() { Dispose(false); } public void Dispose() { Dispose(true); if (hasUnmanagedResources) { GC.SuppressFinalize(this); } } protected virtual void DisposeManagedResources() { if (!IsDisposing) { throw new InvalidOperationException( "In order to dispose an object call the Dispose method. Do not call DisposeManagedResources method directly." + GetTypeString()); } baseDisposeManagedResourcesCalled = true; } protected virtual void DisposeUnmanagedResources() { if (!IsDisposing) { throw new InvalidOperationException( "In order to dispose an object call the Dispose method. Do not call DisposeUnmanagedResources method directly." + GetTypeString()); } baseDisposeUnmanagedResourcesCalled = true; } protected void HasUnmanagedResources() { if (!hasUnmanagedResources) { hasUnmanagedResources = true; GC.ReRegisterForFinalize(this); } } protected void ThrowIfDisposed() { if (IsDisposed) { throw new ObjectDisposedException("Object is already disposed." + GetTypeString()); } if (IsDisposing) { throw new ObjectDisposedException("Object is being disposed." + GetTypeString()); } } private void Dispose(bool disposeManagedResources) { if (IsDisposed) { throw new InvalidOperationException("Dispose called on an object that is already disposed." + GetTypeString()); } if (IsDisposing) { throw new InvalidOperationException("Dispose called on an object that is currently disposing." + GetTypeString()); } IsDisposing = true; if (disposeManagedResources) { DisposeManagedResources(); VerifyBaseDisposeManagedResourcesCalled(); } if (hasUnmanagedResources) { DisposeUnmanagedResources(); VerifyBaseDisposeUnmanagedResourcesCalled(); } IsDisposed = true; IsDisposing = false; } private void VerifyBaseDisposeManagedResourcesCalled() { if (!baseDisposeManagedResourcesCalled) { throw new InvalidOperationException("DisposeManagedResources of the base class was not called." + GetTypeString()); } } private void VerifyBaseDisposeUnmanagedResourcesCalled() { if (!baseDisposeUnmanagedResourcesCalled) { throw new InvalidOperationException("DisposeUnmanagedResources of the base class was not called." + GetTypeString()); } } private string GetTypeString() { string typeName = GetType().FullName; return " Type: " + typeName; } } </code></pre> <p>By default, the object is removed from the finalization queue (in the <code>DisposableObject</code> constructor). If some inheriting class has an unmanaged resource then it should invoke <code>HasUnmanagedResources</code> method to add the object back to the finalization queue.</p> <p>The most important question is: can I invoke <code>GC.SuppressFinalize(this)</code> in the constructor?.</p> <p>How do you find this implementation?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:16:38.273", "Id": "51696", "Score": "11", "body": "You only get to pick one base class - I'd have thought it unlikely that gaining a good Disposable implementation would be the most pressing requirement for most interesting classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:23:17.267", "Id": "51697", "Score": "0", "body": "But surely the interesting base class could itself inherit from Disposable. And if not, keep working your way back until it can... :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:24:47.457", "Id": "51699", "Score": "1", "body": "Why don't follow the standard `Dispose` pattern and move the `GC.SuppressFinalize(this);` to the finalizer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:34:33.887", "Id": "51702", "Score": "0", "body": "Because I do not want that objects without unmanaged resources enter the finalization queue! It would kill the garbage collector." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:51:08.233", "Id": "51706", "Score": "2", "body": "I have used a similar aproach in the past and really it gave me no problems, but I had always a mix feeling about it, one issue I faced was that this it's useless with classes that must override from base out of your control, and for unmanaged resources `SafeHandle` is always the best choice to handle them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T14:01:47.937", "Id": "51709", "Score": "4", "body": "It's a _pattern_ for a reason. If a base-class implementation was optimal we would have it. This looks overly complicated and should be mostly unnecessary because of `SafeHandle`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T19:46:17.447", "Id": "51739", "Score": "0", "body": "But how to safely disposabe for example a Stream or Bitmap object? How to handle it with a SafeHandle?" } ]
[ { "body": "<p>This abstraction is a <em>leaky abstraction</em> and should be avoided.</p>\n\n<p>As <a href=\"https://stackoverflow.com/a/2635733/1188513\">Mark Seeman puts it</a>:</p>\n\n<blockquote>\n <p>Consider why you want to add IDisposable to your interface. It's probably because you have a particular implementation in mind. Hence, the implementation leaks into the abstraction.</p>\n</blockquote>\n\n<p>Now in this specific context he's talking about <code>ISomeInterface : IDisposable</code>, but the same applies to an abstract class, because an abstract class <em>is</em> an abstraction just like an interface is.</p>\n\n<p>Implementing it in a base class prevents any derived class from deriving from anything else, because in C# a class can only derive from a single base class. This reason alone is a showstopper.</p>\n\n<p>Also, calling <code>Dispose()</code> twelve times in a row on a disposable object should not throw anything. Only <em>using</em> a disposed object should; your implementation breaks the pattern in ways that break POLS.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T17:08:32.360", "Id": "51725", "Score": "0", "body": "In my opnion your comment would be true for interfaces, domain models, decorators etc. However here we have an abstraction of implementation to minimize code redundation in simple scenarios when we do not need to derive anything. Honestly I would prefer doing such thing as an Aspect (AoP) but no idea how it could be done..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T17:17:55.257", "Id": "51726", "Score": "0", "body": "AOP buys you *vendor lock-in* (e.g. PostSharp) and boils down to a hack that injects code into the MSIL generated when you build your project. I think it's utterly bad and would highly recommend implementing aspects with IoC and *interception* instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T17:19:07.200", "Id": "51727", "Score": "1", "body": "If you have `an abstraction of implementation to minimize code redundation in simple scenarios` then you have the wrong reasons for inheritance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:10:01.643", "Id": "51729", "Score": "0", "body": "AOP using IoC interception is really slow if we are resolving many objects (tested by my friend).\n\nAs I think of the usage of the DisposableObject in the project... Honestly I start feeling that you are right that this implementation should not be ever used... Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:28:58.363", "Id": "51732", "Score": "0", "body": "Just out of curiosity, which IoC container are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T19:39:55.007", "Id": "51738", "Score": "0", "body": "It was tested on Unity. Currently I am using Autofac." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:19:36.320", "Id": "51870", "Score": "0", "body": "`If you have an abstraction of implementation to minimize code redundation in simple scenarios then you have the wrong reasons for inheritance.` What about base classes like ViewModelBase? Is it really wrong reason for inheritance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:47:44.503", "Id": "51874", "Score": "1", "body": "Inheritance is for \"is-a\" relationships. Functionality encapsulated in a `ViewModelBase` class is meant to be used by classes that *are* ViewModels. Now I foresee you'll argue that a class derived from `DisposableObject` *is-a* disposable object, but I still think it's a leaky abstraction (didn't say I *never* leak abstractions, just that it should be avoided)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-07T10:00:28.443", "Id": "92389", "Score": "0", "body": "Thanks for you comments! I have many thoughts which I would like to share. Generally the root problem is that a framework forces us to implement an interface to use some functionality. Best .NET examples .NET world are IDisposable and INotifyPropertyChanged. IMO it is nothing bad to have some common infrastructure implementation of these interfaces. However it can be bad if our code derives from them. We should inject a factory for these interface adapters and use them as aggregation (we can make make a T4 template). Then our code is not dependent on any implementation but on abstractions." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T16:28:35.100", "Id": "32383", "ParentId": "32380", "Score": "8" } }, { "body": "<p>Firstly, to address inheritance concerns, I use a t4 template to get around the single inheritance problem. ie. for every class where I need to introduce dispose support, I generate the an abstract base class that inherits from that class. Works a treat.</p>\n\n<p>Now, to your code. Here are the things that jump out at me:</p>\n\n<ol>\n<li>Constructors should be <code>protected</code> because the base class is <code>abstract</code>. This would make the code clearer to me, but YMMV.</li>\n<li>Lose the whole unmanaged resource tracking. It adds complexity without value. Just call <code>SuppressFinalize()</code> regardless - it's the <a href=\"http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx\">recommended pattern</a>, anyway.</li>\n<li>Your code is not thread-safe. Consider, for example, what happens if multiple threads call <code>Dispose()</code> simultaneously. You're got the potential for multiple calls to <code>DisposeManagedResources()</code> etcetera.</li>\n</ol>\n\n<p>FWIW, here is an example <code>Disposable</code> base class generated by my t4 template:</p>\n\n<pre><code>// Generated by t4 template in Utility project. DO NOT EDIT!\n#pragma warning disable 1591, 0612\n#region Designer generated code\n\nnamespace Foo\n{\n using System;\n using System.Diagnostics;\n using System.Diagnostics.CodeAnalysis;\n using System.Globalization;\n using System.Threading;\n using Kent.Boogaart.HelperTrinity.Extensions;\n\n /// &lt;summary&gt;\n /// A useful base class for disposable objects that inherit from &lt;see cref=\"object\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// &lt;para&gt;\n /// This base class simplifies the implementation of disposable objects by providing common functionality such as thread-safety on &lt;see cref=\"Dispose\"/&gt; calls,\n /// and a &lt;see cref=\"Disposing\"/&gt; event for pre-disposal notification.\n /// &lt;/para&gt;\n /// &lt;/remarks&gt;\n public abstract class DisposableBase : object, IDisposable\n {\n private const int DisposalNotStarted = 0;\n private const int DisposalStarted = 1;\n private const int DisposalComplete = 2;\n\n#if DEBUG\n // very useful diagnostics when a failure to dispose is detected\n private readonly StackTrace creationStackTrace;\n#endif\n\n // see the constants defined above for valid values\n private int disposeStage;\n\n#if DEBUG\n /// &lt;summary&gt;\n /// Initializes a new instance of the DisposableBase class.\n /// &lt;/summary&gt;\n protected DisposableBase()\n {\n this.creationStackTrace = new StackTrace(1, true);\n }\n\n /// &lt;summary&gt;\n /// Finalizes an instance of the DisposableBase class.\n /// &lt;/summary&gt;\n [SuppressMessage(\"Microsoft.Design\", \"CA1063\", Justification = \"The enforced behavior of CA1063 is not thread-safe or full-featured enough for our purposes here.\")]\n ~DisposableBase()\n {\n var message = string.Format(CultureInfo.InvariantCulture, \"Failed to proactively dispose of object, so it is being finalized: {0}.{1}Object creation stack trace:{1}{2}\", this.ObjectName, Environment.NewLine, this.creationStackTrace);\n Debug.Assert(false, message);\n this.Dispose(false);\n }\n#endif\n\n /// &lt;summary&gt;\n /// Occurs when this object is about to be disposed.\n /// &lt;/summary&gt;\n public event EventHandler Disposing;\n\n /// &lt;summary&gt;\n /// Gets a value indicating whether this object is in the process of disposing.\n /// &lt;/summary&gt;\n protected bool IsDisposing\n {\n get { return Interlocked.CompareExchange(ref this.disposeStage, DisposalStarted, DisposalStarted) == DisposalStarted; }\n }\n\n /// &lt;summary&gt;\n /// Gets a value indicating whether this object has been disposed.\n /// &lt;/summary&gt;\n protected bool IsDisposed\n {\n get { return Interlocked.CompareExchange(ref this.disposeStage, DisposalComplete, DisposalComplete) == DisposalComplete; }\n }\n\n /// &lt;summary&gt;\n /// Gets a value indicating whether this object has been disposed or is in the process of being disposed.\n /// &lt;/summary&gt;\n protected bool IsDisposedOrDisposing\n {\n get { return Interlocked.CompareExchange(ref this.disposeStage, DisposalNotStarted, DisposalNotStarted) != DisposalNotStarted; }\n }\n\n /// &lt;summary&gt;\n /// Gets the object name, for use in any &lt;see cref=\"ObjectDisposedException\"/&gt; thrown by this object.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// Subclasses can override this property if they would like more control over the object name appearing in any &lt;see cref=\"ObjectDisposedException\"/&gt;\n /// thrown by this &lt;c&gt;DisposableBase&lt;/c&gt;. This can be particularly useful in debugging and diagnostic scenarios.\n /// &lt;/remarks&gt;\n /// &lt;returns&gt;\n /// The object name, which defaults to the class name.\n /// &lt;/returns&gt;\n protected virtual string ObjectName\n {\n get { return this.GetType().FullName; }\n }\n\n /// &lt;summary&gt;\n /// Disposes of this object, if it hasn't already been disposed.\n /// &lt;/summary&gt;\n [SuppressMessage(\"Microsoft.Design\", \"CA1063\", Justification = \"The enforced behavior of CA1063 is not thread-safe or full-featured enough for our purposes here.\")]\n [SuppressMessage(\"Microsoft.Usage\", \"CA1816\", Justification = \"GC.SuppressFinalize is called indirectly.\")]\n public void Dispose()\n {\n if (Interlocked.CompareExchange(ref this.disposeStage, DisposalStarted, DisposalNotStarted) != DisposalNotStarted)\n {\n return;\n }\n\n this.OnDisposing();\n this.Disposing = null;\n\n this.Dispose(true);\n this.MarkAsDisposed();\n }\n\n /// &lt;summary&gt;\n /// Verifies that this object is not in the process of disposing, throwing an exception if it is.\n /// &lt;/summary&gt;\n protected void VerifyNotDisposing()\n {\n if (this.IsDisposing)\n {\n throw new ObjectDisposedException(this.ObjectName);\n }\n }\n\n /// &lt;summary&gt;\n /// Verifies that this object has not been disposed, throwing an exception if it is.\n /// &lt;/summary&gt;\n protected void VerifyNotDisposed()\n {\n if (this.IsDisposed)\n {\n throw new ObjectDisposedException(this.ObjectName);\n }\n }\n\n /// &lt;summary&gt;\n /// Verifies that this object is not being disposed or has been disposed, throwing an exception if either of these are true.\n /// &lt;/summary&gt;\n protected void VerifyNotDisposedOrDisposing()\n {\n if (this.IsDisposedOrDisposing)\n {\n throw new ObjectDisposedException(this.ObjectName);\n }\n }\n\n /// &lt;summary&gt;\n /// Allows subclasses to provide dispose logic.\n /// &lt;/summary&gt;\n /// &lt;param name=\"disposing\"&gt;\n /// Whether the method is being called in response to disposal, or finalization.\n /// &lt;/param&gt;\n protected virtual void Dispose(bool disposing)\n {\n }\n\n /// &lt;summary&gt;\n /// Raises the &lt;see cref=\"Disposing\"/&gt; event.\n /// &lt;/summary&gt;\n protected virtual void OnDisposing()\n {\n this.Disposing.Raise(this);\n }\n\n /// &lt;summary&gt;\n /// Marks this object as disposed without running any other dispose logic.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// Use this method with caution. It is helpful when you have an object that can be disposed in multiple fashions, such as through a &lt;c&gt;CloseAsync&lt;/c&gt; method.\n /// &lt;/remarks&gt;\n [SuppressMessage(\"Microsoft.Usage\", \"CA1816\", Justification = \"This is a helper method for IDisposable.Dispose.\")]\n protected void MarkAsDisposed()\n {\n GC.SuppressFinalize(this);\n Interlocked.Exchange(ref this.disposeStage, DisposalComplete);\n }\n }\n}\n\n#endregion Designer generated code\n#pragma warning restore 1591, 0612\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T03:22:09.540", "Id": "51754", "Score": "1", "body": "Well that's an interesting approach!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T07:56:11.603", "Id": "51765", "Score": "0", "body": "I love your solution! Thanks :) One question: **Why are you deriving from object?** `Lose the whole unmanaged resource tracking. It adds complexity without value.` There is a value - it is about the finalization queue. When an object is in the queue than it can enter easily into next generation (Gen1 or even in some cases Gen2). Quote from MSDN: X AVOID making types finalizable.\nCarefully consider any case in which you think a finalizer is needed. There is a real cost associated with instances with finalizers, from both a performance [...]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T07:58:53.240", "Id": "51766", "Score": "0", "body": "All your object that are generated using this pattern will enter the finiazlization queue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T09:43:01.430", "Id": "51768", "Score": "1", "body": "@Pellared: only in DEBUG builds will these objects *potentially* enter the finalization queue (and that's just to add a useful assertion - remove it if you prefer). If they're disposed proactively, they don't even get to the finalization queue because `SuppressFinalize` is called. As for deriving from `object`, the base class comes from a t4 template parameter. So it can derive whatever you tell it to derive from - I just chose the simplest case: deriving from `object`. I have several others, such as deriving from `ReactiveObject`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-17T12:41:11.983", "Id": "87977", "Score": "0", "body": "@KentBoogaart After some experience I must say that your implementation is really awesome. I also like the implementation of Disposable in AutoFac: https://github.com/autofac/Autofac/blob/master/Core/Source/Autofac/Util/Disposable.cs simple but robust!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T02:46:00.947", "Id": "32411", "ParentId": "32380", "Score": "9" } } ]
{ "AcceptedAnswerId": "32411", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:11:08.440", "Id": "32380", "Score": "7", "Tags": [ "c#", "design-patterns", "inheritance" ], "Title": "Dispose pattern - DisposableObject" }
32380
<p>I have a lot of classes which are principal equal, but they consist small differences so that I can´t abstract then very well.</p> <p>The classes represent different kinds of DataTables. Every Class has two important methods which every "table-class" has. Here a abstracted example:</p> <pre><code>internal class FooTable { internal static DataTable CreateTable() { using (DataTable fooTable = new DataTable("fooTable")) { // number and content of rows are different from table to table. fooTable.Columns.Add("ColFoo"); fooTable.Columns.Add("ColBar"); fooTable.Columns.Add("ColSomethingElse"); AddRow(fooTable, "ValueA", "ValueB", "ValueC"); AddRow(fooTable, "ValueD", "ValueE", "ValueF"); // ... more rows ... return fooTable; } } private static void AddRow( DataTable table, string ColFoo, string ColBar, string ColSomethingElse) { DataRow dataRow = table.NewRow(); dataRow["ColFoo"] = ColFoo; dataRow["ColBar"] = ColBar; dataRow["ColSomethingElse"] = ColSomethingElse; table.Rows.Add(dataRow); } } </code></pre> <p>The differences between the tables are the number of columns and the datatyp of column content. With this implementation I can´t use abstract classes, because of the different amount of columns. The names of the columns are also redundant in code.</p> <p>Finally I think about the use of <code>params</code> to solve the problem with different amount of columns, but I’m not sure how to make a good implementation other AddRow-methode.</p> <pre><code>private static void AddRow(DataTable table, params object[] values) { ... } </code></pre> <p>So did anyone know a better way to implement this? I'm sure there is a better way.</p>
[]
[ { "body": "<p>I can think of trying something like this.</p>\n\n<pre><code>interface ICount\n{\n int count();\n}\n\nclass CountOne : ICount { int count() { return 1; }}\nclass CountTwo : ICount { int count() { return 2; }}\n\nabstract class IFooTable&lt;T&gt; where T : ICount, new()\n{\n int count() { return (new T()).count(); }\n}\n\nclass FooTable&lt;T&gt; : IFooTable&lt;T&gt;\n{\n void AddRow(params object[] values) {\n assert(values.length = this.count());\n ...\n }\n}\n\nclass OneTable : FooTable&lt;CountOne&gt; { }\nclass TwoTable : FooTable&lt;CountTwo&gt; { }\n</code></pre>\n\n<p>But honestly I would just expect the add function to take a row. This is not something where I'd use generics, instead I'd just use mutable data structures that have constraint checks. I'm way more concerned with column names matching especially when a params statement doesn't make sure they're in the right order.</p>\n\n<pre><code>class FooTable\n{\n List&lt;string&gt; columns;\n List&lt;DataRow&gt; rows;\n\n void AddRow(DataRow row)\n {\n assert(column names for the row match the expected values);\n rows.add(row);\n }\n}\n</code></pre>\n\n<p>Alternatively, you could mix both approaches. Using the generics to ensure the number of columns and then adding a DataRow at a time to enforce column names match up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T05:35:35.897", "Id": "51755", "Score": "0", "body": "Hi Jean-Bernard Pellerin, thanks for your answer. At the moment I can't really see how first part of you answer helps me. From my point of view second part seems to be clear and I will consider this. Maybe you can explain part one a little bit more." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T00:07:49.967", "Id": "32402", "ParentId": "32382", "Score": "1" } } ]
{ "AcceptedAnswerId": "32402", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T13:39:48.540", "Id": "32382", "Score": "1", "Tags": [ "c#", ".net", ".net-datatable" ], "Title": "Find abstraction for classes which represent tables with differnt amount of colums (based on DataTables)" }
32382
<p>I am doing a bio-statistics calculation and the following code works. However, can someone help to improve the messy nested loop?</p> <pre><code>for(int i=0; i&lt;NN; i++) { for (int j=0; j&lt;NN; j++) { if (i != j){ thirdlayer = 0; for (int k=0; k&lt;NN; k++) { fourthlayer = 0; for (int l=0; l&lt;NN; l++) { fourthlayer = fourthlayer + V[j*NN+l]*V[NN+l]*J[k*NN+l]; } thirdlayer = thirdlayer + V[k]*V[i*NN+k]*fourthlayer; } if(pi_cod[j] != 0) Transitions[i*NN +j] = sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[i*NN +j]*thirdlayer/Padt; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:20:23.453", "Id": "51730", "Score": "3", "body": "This doesn't look like matrix multiplication. What are `V`, `J`, `pi_cod`, and `Transitions`? Why is `sqrt()` involved in matrix multiplication?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:31:09.530", "Id": "51733", "Score": "0", "body": "@200_success: I'd also like to know if this is C or C++. The `sqrt()` tells me it's the latter (assuming `std::` was left out), but looking at the rest of the code, I hope I'm wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:36:52.653", "Id": "51735", "Score": "0", "body": "@Jamal I think it's `C`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T22:49:16.700", "Id": "51749", "Score": "1", "body": "The `fourthlayer` values don't depend on `i`, so you could precompute them for every `j` and `k`. This should reduce time complexity from `O(NN^4)` to `O(NN^3)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:12:25.510", "Id": "51784", "Score": "0", "body": "@200_success Sorry I said wrong. It is no matrix multiplication, it's some biol statistic algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:14:01.847", "Id": "51785", "Score": "0", "body": "@Jamal It is written initially in C and then switched to c++. However, i don't think this matters much here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:15:54.373", "Id": "51786", "Score": "0", "body": "@nwellnhof the fourthlayer computed by `V[j*NN+1]` and `J[k*NN+l]` which depends on j and k. Could you show me sample code that to factor fourthlayr computation way out?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:27:41.087", "Id": "51796", "Score": "0", "body": "Are you sure `fourthlayer + V[j*NN+l]*V[NN+l]*J[k*NN+l]` is correct? The index of the second factor, `NN + l`, is suspicious, because it means that the second \"row\" of `V` is somehow special." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:32:05.777", "Id": "51797", "Score": "0", "body": "Similarly, the `[k]` in `V[k]` is suspicious." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T00:40:52.807", "Id": "52049", "Score": "0", "body": "@200_success Yes, in this case it is. However, the code below is not correct answer" } ]
[ { "body": "<p>Give this a shot. Though I suspect your compiler <em>might</em> have been doing this already.</p>\n\n<pre><code>for (int j=0; j&lt;NN; j++) {\n thirdlayer = 0;\n for (int k=0; k&lt;NN; k++) {\n fourthlayer = 0;\n for (int l=0; l&lt;NN; l++) {\n fourthlayer = fourthlayer + V[j*NN+l]*V[NN+l]*J[k*NN+l];\n }\n for(int i=0; i&lt;NN; i++) {\n thirdlayer = thirdlayer + V[k]*V[i*NN+k]*fourthlayer;\n }\n }\n for(int i=0; i&lt;NN; i++) { \n if(i != j &amp;&amp; pi_cod[j] != 0)\n Transitions[i*NN +j] = sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[i*NN +j]*thirdlayer/Padt;\n }\n}\n</code></pre>\n\n<p>This is what nwellnhof meant. Now there are only 3 levels of nesting loops.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T00:21:45.517", "Id": "52047", "Score": "0", "body": "OK. I carefully looked into that and realized it was not correct way to re-factory the code at all" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:07:30.223", "Id": "32426", "ParentId": "32384", "Score": "0" } }, { "body": "<p>removed the layer from 3rd and 4th because it made things annoyingly long, but moved some of the initializers into the for() and precomputed some x*NN, changed the a = a +... to a+=... and moved the 4 layer into its for loop (thus the trailing semicolon)</p>\n\n<pre><code>for(int i=0, iN=0; i&lt;NN; i++, iN=i*NN) {\n for(int j=0, third=0, jN=0; j&lt;NN; j++, jN=j*NN, third=0) {\n for(int k=0, fourth=0, kN=0; i!=j &amp;&amp; k&lt;NN; third += V[k]*V[iN+k]*fourth, k++, kN=k*NN)\n for(int l=0, jN=j*NN; l&lt;NN; fourth+=V[jN+l]*V[NN+l]*J[kN+l], l++);\n if (i!=j &amp;&amp; pi_cod[j] != 0)\n Transitions[iN+j]=sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[iN+j]*third/Padt;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T17:16:40.303", "Id": "52099", "Score": "0", "body": "the loop initialized fourth cannot be used outside `l` loop, so `third+=..*fourth` fails. Similarly, `iN` and `jN` in `Transitions[iN+j]` also fails as they are random number in this scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T20:25:20.863", "Id": "52110", "Score": "0", "body": "Thanks for editing. But the logical is still not right as it generates different result. Also, the running time seems even slower than original code" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T05:27:34.487", "Id": "32553", "ParentId": "32384", "Score": "0" } }, { "body": "<p>Using small <code>l</code> for the index is bad because it looks like the digit 1. It's better to use large <code>L</code>.</p>\n\n<p>Instead of <code>j*NN</code>, it's better to use a cached index that increments by <code>for</code>:</p>\n\n<pre><code>int NN2 = NN*NN\nfor(int iNN=k; iNN &lt; (NN2+k); iNN+=NN) {\n thirdlayer = thirdlayer + V[k]*V[iNN]*fourthlayer;\n}\n</code></pre>\n\n<p>This could be a bit faster.</p>\n\n<p>Another hook - more use pointer as array sintax:\nfor 3layer better get a row vector in wich 4layer for process:</p>\n\n<pre><code>int* VVj = &amp;(V[j*NN]);\nint* VNN = &amp;(V[NN]);\nfor (int k=0; k&lt;NN; k++) {\n int* JNNk = &amp;(J[k*NN]);\n fourthlayer = 0;\n for (int l=0; l&lt;NN; l++) {\n fourthlayer = fourthlayer + VVj[l]*VNN[l]*JNNk[l];\n }\n thirdlayer = thirdlayer + V[k]*V[i*NN+k]*fourthlayer;\n }\n</code></pre>\n\n<p>good compiler do it for you byself, but in such decomposition may better see data dependents, and it is a bit simpler and short</p>\n\n<p>also you can deploy from 4layer V[j*NN+l]*V[NN+l] into stanalone vector that can be prepared in outer j cycle.</p>\n\n<p>Instead of division <code>(xxx)/Padt</code> (better=faster), use multiplication <code>*(1/Padt)</code>, or move out from the last cycle:</p>\n\n<pre><code>double thp = thirdlayer/Padt;\nfor(int i=0; i&lt;NN; i++) { \n if(i != j &amp;&amp; pi_cod[j] != 0)\n Transitions[i*NN +j] = sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[i*NN +j]*thp;\n }\n</code></pre>\n\n<p>Instead of a conditional calculation, it's better to use a conditional assignment since it can better optimized for x86:</p>\n\n<pre><code>double thp = thirdlayer/Padt;\nfor(int i=0; i&lt;NN; i++) {\n int pcodj = (pi_cod[j] != 0)?pi_cod[j]: 1;\n double transition = sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[i*NN +j]*thp;\n if(i != j &amp;&amp; pi_cod[j] != 0)\n Transitions[i*NN +j] = transition;\n }\n</code></pre>\n\n<p>If it's rare misses for assignment, so penalty for calculation could be negligible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T20:13:33.693", "Id": "32577", "ParentId": "32384", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T17:32:50.887", "Id": "32384", "Score": "1", "Tags": [ "c++", "optimization", "c", "statistics" ], "Title": "Improve nested loop for bio-statistics calculation" }
32384
<p>I have the following code that I know can be written in a better way. Basically I query tables and display the results for each student for the homework that has been marked.</p> <pre><code>&lt;?php include 'inc/db_con.php'; mysql_select_db("homework", $con); $resultcourse = mysql_query("SELECT course_code FROM courses WHERE course_active='1' LIMIT 1"); $rowcode = mysql_fetch_assoc($resultcourse); $result = mysql_query("SELECT homework, total_mark, student, MAX(student_mark), COUNT(total_mark), student_name FROM homeworkone INNER JOIN students on homeworkone.student = students.student_uid WHERE homeworkone.homework='RegnTheory' &amp;&amp; students.student_course='$rowcode[course_code]' GROUP BY student_name ORDER BY student_name ASC"); function countScore($counting) { if($counting == '2'){ $counted = '&amp;bull;&amp;bull;'; } else if($counting == '3'){ $counted = '&amp;bull;&amp;bull;&amp;bull;'; } else $counted = '&amp;bull;'; return $counted; } ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en-GB"&gt; &lt;head&gt; &lt;meta charset=utf-8 /&gt; &lt;title&gt;ACS Homework Results&lt;/title&gt; &lt;link rel="stylesheet" href="css/reset_css3.css" /&gt; &lt;link rel="stylesheet" href="css/results.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;div class="contentwrap"&gt; &lt;div class="left"&gt; &lt;h1&gt;ACS Level 3&lt;/h1&gt; &lt;p&gt;Homework Results &lt;?php echo $rowcode['course_code']; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="right"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/header&gt; &lt;div id="wrapper"&gt; &lt;div id="clearheader"&gt;&lt;!-- used to make room for the #header --&gt;&lt;/div&gt; &lt;div class="contentwrap"&gt; &lt;section&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;1&lt;/th&gt; &lt;th&gt;2&lt;/th&gt; &lt;th&gt;3&lt;/th&gt; &lt;th&gt;4&lt;/th&gt; &lt;th&gt;5&lt;/th&gt; &lt;/tr&gt; &lt;?php while($row = mysql_fetch_array($result)){ $score = 0; $score2 = 0; $score3 = 0; $score4 = 0; $score5 = 0; $score6 = 0; $score7 = 0; $score8 = 0; $score8b = 0; $score9 = 0; $score10 = 0; $score11 = 0; $score12 = 0; $score13 = 0; $score14 = 0; $score15 = 0; $score16 = 0; $score17 = 0; $score18 = 0; $score19 = 0; if($row['total_mark']!=0){ $scorefirst = (100 / $row['total_mark']) * $row['MAX(student_mark)']; $score = number_format($scorefirst, 1, '.', ''); $counter = $row['COUNT(total_mark)']; $scoreCounter = countScore($counter); } $stu = $row['student']; $result2 = mysql_query("SELECT homework, student, total_mark, MAX(student_mark), COUNT(total_mark) FROM homeworkone WHERE homework='OPtoBCP' &amp;&amp; student='$stu'"); while($row2 = mysql_fetch_assoc($result2)) { if($row2['total_mark']!=0){ $scorefirst2 = (100 / $row2['total_mark']) * $row2['MAX(student_mark)']; $score2 = number_format($scorefirst2, 1, '.', ''); } $counter = $row2['COUNT(total_mark)']; $scoreCounter2 = countScore($counter); } $result3 = mysql_query("SELECT homework, student, total_mark, MAX(student_mark), COUNT(total_mark) FROM homeworkone WHERE homework='BCPtoGUN' &amp;&amp; student='$stu' GROUP BY student"); while($row3 = mysql_fetch_assoc($result3)) { if($row3['total_mark']!=0){ $scorefirst3 = (100 / $row3['total_mark']) * $row3['MAX(student_mark)']; $score3 = number_format($scorefirst3, 1, '.', ''); }} $result4 = mysql_query("SELECT homework, student, total_mark, MAX(student_mark), COUNT(total_mark) FROM homeworkone WHERE homework='FOOptions' &amp;&amp; student='$stu' GROUP BY student"); while($row4 = mysql_fetch_assoc($result4)) { if($row4['total_mark']!=0){ $scorefirst4 = (100 / $row4['total_mark']) * $row4['MAX(student_mark)']; $score4 = number_format($scorefirst4, 1, '.', ''); }} $result5 = mysql_query("SELECT homework, student, total_mark, MAX(student_mark), COUNT(total_mark) FROM homeworkone WHERE homework='CheckMap' &amp;&amp; student='$stu' GROUP BY student"); while($row5 = mysql_fetch_assoc($result5)) { if($row5['total_mark']!=0){ $scorefirst5 = (100 / $row5['total_mark']) * $row5['MAX(student_mark)']; $score5 = number_format($scorefirst5, 1, '.', ''); }} ?&gt; &lt;tr height="45px"&gt; &lt;td&gt;&lt;h3&gt;&lt;?php echo $row['student_name']; ?&gt;&lt;/h3&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $score; ?&gt;&amp;#37;&lt;br /&gt;&lt;?php echo $scoreCounter ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $score2; ?&gt;&amp;#37;&lt;br /&gt;&lt;?php echo $scoreCounter2 ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $score3; ?&gt;&amp;#37;&lt;/td&gt; &lt;td&gt;&lt;?php echo $score4; ?&gt;&amp;#37;&lt;/td&gt; &lt;td&gt;&lt;?php echo $score5; ?&gt;&amp;#37;&lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/table&gt; &lt;/section&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="results"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T19:33:32.183", "Id": "51737", "Score": "0", "body": "I am thinking that you might want to look at an array for the `$score##` variables, not sure what all you are doing with those, but it looks like a good spot for an array. it would clean up a little bit of code there, maybe" } ]
[ { "body": "<p>Your queries are only different in the type of homework they look for. Also the processing of the data seems common. The basic way to refactor code like this is to extract it into a method:</p>\n\n<pre><code>function getHomeworkScore($homework, $student)\n{\n $score = 0;\n $result = mysql_query(\"SELECT homework, student, total_mark, MAX(student_mark) as max_mark, COUNT(total_mark) as total_mark_count FROM homeworkone WHERE homework='$homework' &amp;&amp; student='$student' GROUP BY student\");\n\n while ($row = mysql_fetch_assoc($result))\n {\n if ($row['total_mark'] != 0)\n {\n $scorefirst = (100 / $row['total_mark']) * $row['max_mark'];\n $score = number_format($scorefirst, 1, '.', ''); \n }\n }\n\n return $score;\n}\n</code></pre>\n\n<p>Then you can call it:</p>\n\n<pre><code>$score = getHomeworkScore(\"OPtoBCP\", $stu);\n$score2 = getHomeworkScore(\"BCPtoGUN\", $stu);\n...\n</code></pre>\n\n<p>Some notes:</p>\n\n<ol>\n<li><p>You really want to look into <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow\">PDO</a> or <a href=\"http://php.net/manual/en/book.mysqli.php\" rel=\"nofollow\">mysqli</a> otherwise you leave yourself open for a world of pain (SQL injection attacks).</p></li>\n<li><p>Give your summary column names so you can easily reference them</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T19:25:51.330", "Id": "32390", "ParentId": "32385", "Score": "1" } } ]
{ "AcceptedAnswerId": "32390", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T17:54:43.550", "Id": "32385", "Score": "1", "Tags": [ "php", "mysql" ], "Title": "Code tidy-up for multiple queries" }
32385
<p>I have this class containing two constructors with different signatures but they do the same thing:</p> <pre><code>public Person(Dictionary dictionary, string someString) : base(dictionary, someString) { base.GetProperty("FirstName"); base.GetProperty("LastName"); } public Person(Dictionary dictionary, string[] someStringArray) : base(dictionary, someStringArray) { base.GetProperty("FirstName"); base.GetProperty("LastName"); } </code></pre> <p>The type of the second parameter in each of these constructors determines the behavior of the 'GetProperty' method.</p> <p>I've read about <code>casting</code> and the bad behaviors of it, but would it be appropriate to do something like this:</p> <pre><code>public Person(Dictionary dictionary, Object something) { } </code></pre> <p>and then cast <code>something</code> to either a <code>string</code> or <code>string[]</code> depending on whichever is appropriate?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T02:11:26.190", "Id": "52159", "Score": "0", "body": "Why must there be 2 constructors? Why can't there be only one: `public Person(Dictionary dct, string[] something)`. Simpler, better for the client." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T13:12:55.843", "Id": "52259", "Score": "0", "body": "In theory yes, I could just use one `string[]` and if its `string` just pick `string[0]` But the behavior between processing `string` and `string[]` are different, also the determination of `string` and `string[]` is based elsewhere. The object itself does not determine if the parameter is a `string` or `string[]`. I guess this is very vague. Im trying to add in a better example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T21:50:32.880", "Id": "52286", "Score": "0", "body": "_behavior between processing string and string[] are different_. So `string[0]` is not the same thing/object/property as `string` in the other contractor, yes? How about optional parameters: `public Person(Dictionary dict, string[] otherStuff, string Fname = null)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T12:58:13.413", "Id": "52303", "Score": "0", "body": "@radarbob I like the idea of optional parameter. I'll see if it makes sense to incorporate that in the scope of my project." } ]
[ { "body": "<p>Two things your could do:</p>\n\n<ol>\n<li><p>Refactor the common code into a method (like <code>Initialize</code>) and call that:</p>\n\n<pre><code>private void Initialize()\n{\n base.GetProperty(\"FirstName\");\n base.GetProperty(\"LastName\");\n}\n\npublic Person(Dictionary dictionary, string someString)\n : base(dictionary, someString)\n{\n Initialize();\n}\n\npublic Person(Dictionary dictionary, string[] someStringArray)\n : base(dictionary, someStringArray)\n{\n Initialize();\n}\n</code></pre></li>\n<li><p>Not sure whether that's an option as I don't know how the behaviour changes but you could reduce one case to the other:</p>\n\n<pre><code>public Person(Dictionary dictionary, string someString)\n : this(dictionary, new [] { someString })\n{\n}\n\npublic Person(Dictionary dictionary, string[] someStringArray)\n : base(dictionary, someStringArray)\n{\n base.GetProperty(\"FirstName\");\n base.GetProperty(\"LastName\");\n}\n</code></pre></li>\n</ol>\n\n<p>Apart from that:</p>\n\n<ul>\n<li><p>I'd avoid the casting. Apparently only strings or arrays of strings make sense to be passed in. If you change the parameter to <code>object</code> then it is no longer clear to the caller what he can and cannot pass in and would have to write a test to make sure that what he is passing in will be accepted. It reduces the clarity of the interface.</p></li>\n<li><p><code>GetProperty</code> seems to be a strange thing to call in a constructor. I'd expect it to return a property value yet you do nothing with the return value.</p></li>\n<li><p>Consider making \"FirstName\" and \"LastName\" (and any other property string you use) string constants rather than literals - especially if you use them in more than one place. <a href=\"https://stackoverflow.com/questions/2711435/typesafe-notifypropertychanged-using-linq-expressions\">Lambda expressions</a> might be an option if they are actual properties on the object.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:05:11.223", "Id": "51837", "Score": "0", "body": "In this case, both suggestions are OK, but generally I prefer the second one, because it allows me to use readonly modifier on fields. Further more, if the literals FirstName and LastName are used more then once in code, they should become as private static const string fields. Last but not least, if FirstName is the name of a property in base type, try to uses [lambda expressions](http://stackoverflow.com/questions/7728465/implementing-notifypropertychanged-without-magic-strings) (type safe) to select them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:20:01.483", "Id": "51839", "Score": "0", "body": "@hichaeretaqua: Good points, although I suspect the properties are supplied via the dictionary in which case lambda expressions won't be an option. Just a guess though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T13:14:11.193", "Id": "52260", "Score": "0", "body": "@ChrisWue Exactly!. The dictionary and the `string` or the `string[]` determines what `GetProperty` does." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:58:41.660", "Id": "32387", "ParentId": "32386", "Score": "7" } } ]
{ "AcceptedAnswerId": "32387", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T18:43:06.303", "Id": "32386", "Score": "5", "Tags": [ "c#", "casting" ], "Title": "Different Constructors, Same Implementation" }
32386
<p>I'm not familiar with threads but I am not against them either. A bit of background the original program would have taken about 2 years to run. I had modified it and knocked down that time to around 40 days.</p> <p>Can I make it even faster by using threads or updating my code?</p> <p>The reason it is 40 days is because it has to navigate through a directory of about 6 million files. That amount of files slows this program down.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.IO; using System.Data; using System.Threading; namespace LattitudeDocumentationOrganizer { class Program { static string connString = LattitudeDocumentationOrganizer.Properties.Settings.Default.ConnectionString; static void Main(string[] args) { string fileName; Guid documentID; string location; DateTime createdDate; bool runLoop = true; int x = 0; string msg; int fileCount = 0; int errorCount = 0; int number = 0; while (runLoop) { Console.Clear(); // reset variables fileName = ""; documentID = Guid.Empty; location = ""; using (SqlConnection connection = new SqlConnection(connString)) { connection.Open(); // Run through string sql = @"select top 1 d.UID, d.CreatedDate, d.Location, m.number from master m inner join documentation_attachments da on m.number = da.accountid inner join documentation d on da.documentid = d.uid where m.qlevel in (998,999) and d.location is not null and uid not in (select documentid from DocumentationIssues)"; using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { // If no data is returned assume no data is left and report statistic and exit loop if (!reader.HasRows) { runLoop = false; Console.WriteLine("Processed {0} files successfully.", fileCount); Console.WriteLine("Did not process {0} files successfully.", errorCount); Console.WriteLine("No more files were found with the current query"); Console.ReadLine(); Console.WriteLine("Exiting program."); break; } // Close the loop out as a specific day and time. DateTime currentDate = DateTime.Now; if (currentDate.DayOfWeek == DayOfWeek.Monday &amp;&amp; currentDate.Hour &gt;= 20) { runLoop = false; Console.WriteLine("Processed {0} files successfully.", fileCount); Console.WriteLine("Did not process {0} files successfully.", errorCount); Console.WriteLine("The time set for this process to end has been reached. Program exited at {0}", DateTime.Now); Console.ReadLine(); Console.WriteLine("Exiting program."); break; } Console.WriteLine("Processing data..."); while (reader.Read()) { // Row Values // 0 = UID // 1 = CreatedDate // 2 = Location documentID = reader.GetGuid(0); fileName = reader.GetSqlValue(0).ToString() + ".zip"; location = reader.GetString(2); createdDate = reader.GetDateTime(1); number = reader.GetInt32(3); Console.WriteLine("Current File #: {0}", fileCount); Console.WriteLine("Working on document {0}", documentID); FileInfo fileinfo = new FileInfo(Path.Combine(location, fileName)); if (!fileinfo.Exists) { // Log error to DocumentationIssues msg = "This file does not exist"; LogError(documentID, location, null, msg, number); Console.WriteLine("This file did not exist, logged it to the database and moving on to the next file."); errorCount++; } else { // file exists begin process to create new folders var fileYear = "DOCS" + createdDate.Year.ToString(); var fileMonth = createdDate.ToString("MMM"); var rootDir = @"\\server"; Console.WriteLine("File Exists, checking to make sure the directories needed exist."); if (!Directory.Exists(Path.Combine(rootDir, fileYear))) { // Error, cannot create root level network share folder. Log to Database. // Error Root Level Folder Missing // Directory.CreateDirectory(Path.Combine(rootDir,fileYear)); // Log error to DocumentationIssues msg = "Could not create root folder, log to skip this file"; LogError(documentID, location, Path.Combine(rootDir, fileYear), msg, number); errorCount++; } else { if (!Directory.Exists(Path.Combine(rootDir, fileYear, fileMonth))) { // Create the month folder Directory.CreateDirectory(Path.Combine(rootDir, fileYear, fileMonth)); Console.WriteLine("The month folder did not exist, created {0} folder", fileMonth); } // Call method to update location in database and move tile UpdateDocument(documentID, Path.Combine(rootDir, fileYear, fileMonth)); fileinfo.MoveTo(Path.Combine(rootDir, fileYear, fileMonth, fileName)); //File.Move(Path.Combine(location, fileName), Path.Combine(rootDir, fileYear, fileMonth, fileName)); msg = "SUCCESS"; LogError(documentID, location, Path.Combine(rootDir, fileYear, fileMonth), msg, number); //runLoop = false; Console.WriteLine("Successfully moved and logged the file, checking for more files."); fileCount++; } } } } } } } } static void UpdateDocument(Guid id, string newLocation) { using (SqlConnection connection = new SqlConnection(connString)) { connection.Open(); string sql = "update documentation set location = @newLocation where uid = @id"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.Add(new SqlParameter("id", id)); command.Parameters.Add(new SqlParameter("newLocation", newLocation)); command.ExecuteNonQuery(); } } } static void LogError(Guid id, string prevLocation, string newLocation, string msg, int number) { if (newLocation == null) { newLocation = "no new location"; } using (SqlConnection connection = new SqlConnection(connString)) { connection.Open(); string sql = @"insert into documentationissues (documentid, oldLocation, newLocation, errorMessage, dateAdded, number) values (@id, @prevLocation, @newLocation, @msg, GETDATE(), @number)"; using (SqlCommand command = new SqlCommand(sql, connection)) { command.Parameters.Add(new SqlParameter("id", id)); command.Parameters.Add(new SqlParameter("prevLocation", prevLocation)); command.Parameters.Add(new SqlParameter("newLocation", newLocation)); command.Parameters.Add(new SqlParameter("msg", msg)); command.Parameters.Add(new SqlParameter("number", number)); command.ExecuteNonQuery(); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T20:35:04.123", "Id": "51740", "Score": "0", "body": "What version of .Net are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T13:06:17.323", "Id": "51990", "Score": "1", "body": "Threading may help, and it's a great tool to have in your tool belt, but if you're navigating that many files, the bottleneck may be disk access. You could perform some profiling to figure out whether that's the case." } ]
[ { "body": "<p>Let's fire up some threads in the form of .NET 4.0 TPL <code>Task</code>s. I also create your commands once and <code>Prepare</code> the statements, only updating the parameters. That should relieve some GC and pooled database connection pressure. See how this works for you. Here's the updated code:</p>\n\n<pre><code>namespace LattitudeDocumentationOrganizer\n{\n using System;\n using System.Collections.Generic;\n using System.Data;\n using System.Data.SqlClient;\n using System.IO;\n using System.Threading.Tasks;\n\n internal class Program\n {\n private static readonly string connString = LattitudeDocumentationOrganizer.Properties.Settings.Default.ConnectionString;\n\n private static void Main()\n {\n int fileCount = 0;\n int errorCount = 0;\n List&lt;Task&gt; tasks = new List&lt;Task&gt;();\n\n while (true)\n {\n Console.Clear();\n // reset variables\n using (SqlConnection connection = new SqlConnection(connString))\n {\n connection.Open();\n // Run through\n const string Sql = @\"select top 1 d.UID, d.CreatedDate, d.Location, m.number from master m\n inner join documentation_attachments da\n on m.number = da.accountid\n inner join documentation d\n on da.documentid = d.uid\n where m.qlevel in (998,999)\n and d.location is not null\n and uid not in (select documentid from DocumentationIssues)\";\n using (SqlCommand command = new SqlCommand(Sql, connection))\n using (SqlCommand updateCommand = CreateUpdateCommand(connection))\n using (SqlCommand logErrorCommand = CreateLogErrorCommand(connection))\n {\n using (SqlDataReader reader = command.ExecuteReader())\n {\n // If no data is returned assume no data is left and report statistic and exit loop\n if (!reader.HasRows)\n {\n Console.WriteLine(\"Processed {0} files successfully.\", fileCount);\n Console.WriteLine(\"Did not process {0} files successfully.\", errorCount);\n Console.WriteLine(\"No more files were found with the current query\");\n Console.ReadLine();\n Console.WriteLine(\"Exiting program.\");\n break;\n }\n\n // Close the loop out as a specific day and time.\n DateTime currentDate = DateTime.Now;\n if (currentDate.DayOfWeek == DayOfWeek.Monday &amp;&amp; currentDate.Hour &gt;= 20)\n {\n Console.WriteLine(\"Processed {0} files successfully.\", fileCount);\n Console.WriteLine(\"Did not process {0} files successfully.\", errorCount);\n Console.WriteLine(\n \"The time set for this process to end has been reached. Program exited at {0}\",\n DateTime.Now);\n Console.ReadLine();\n Console.WriteLine(\"Exiting program.\");\n break;\n }\n\n Console.WriteLine(\"Processing data...\");\n while (reader.Read())\n {\n SqlCommand updateCommand1 = updateCommand;\n SqlCommand logErrorCommand1 = logErrorCommand;\n\n // Row Values\n // 0 = UID\n // 1 = CreatedDate\n // 2 = Location\n Guid documentID = reader.GetGuid(0);\n string fileName = reader.GetSqlValue(0) + \".zip\";\n string location = reader.GetString(2);\n DateTime createdDate = reader.GetDateTime(1);\n int number = reader.GetInt32(3);\n\n tasks.Add(Task.Factory.StartNew(() =&gt;\n {\n Console.WriteLine(\"Current File #: {0}\", fileCount);\n Console.WriteLine(\"Working on document {0}\", documentID);\n\n FileInfo fileinfo = new FileInfo(Path.Combine(location, fileName));\n\n string msg;\n if (!fileinfo.Exists)\n {\n // Log error to DocumentationIssues\n msg = \"This file does not exist\";\n LogError(logErrorCommand1, documentID, location, null, msg, number);\n Console.WriteLine(\n \"This file did not exist, logged it to the database and moving on to the next file.\");\n errorCount++;\n }\n else\n {\n // file exists begin process to create new folders\n var fileYear = \"DOCS\" + createdDate.Year;\n var fileMonth = createdDate.ToString(\"MMM\");\n const string RootDir = @\"\\\\server\";\n Console.WriteLine(\n \"File Exists, checking to make sure the directories needed exist.\");\n\n if (!Directory.Exists(Path.Combine(RootDir, fileYear)))\n {\n // Error, cannot create root level network share folder. Log to Database.\n // Error Root Level Folder Missing\n // Directory.CreateDirectory(Path.Combine(rootDir,fileYear));\n // Log error to DocumentationIssues\n msg = \"Could not create root folder, log to skip this file\";\n LogError(logErrorCommand1, documentID, location, Path.Combine(RootDir, fileYear), msg, number);\n errorCount++;\n }\n else\n {\n if (!Directory.Exists(Path.Combine(RootDir, fileYear, fileMonth)))\n {\n // Create the month folder\n Directory.CreateDirectory(Path.Combine(RootDir, fileYear, fileMonth));\n Console.WriteLine(\n \"The month folder did not exist, created {0} folder\", fileMonth);\n }\n\n // Call method to update location in database and move tile\n UpdateDocument(updateCommand1, documentID, Path.Combine(RootDir, fileYear, fileMonth));\n fileinfo.MoveTo(Path.Combine(RootDir, fileYear, fileMonth, fileName));\n ////File.Move(Path.Combine(location, fileName), Path.Combine(rootDir, fileYear, fileMonth, fileName));\n msg = \"SUCCESS\";\n\n LogError(\n logErrorCommand1,\n documentID,\n location,\n Path.Combine(RootDir, fileYear, fileMonth),\n msg,\n number);\n Console.WriteLine(\n \"Successfully moved and logged the file, checking for more files.\");\n fileCount++;\n ////break;\n }\n }\n }));\n }\n\n Task.WaitAll(tasks.ToArray());\n }\n }\n }\n }\n }\n\n private static SqlCommand CreateUpdateCommand(SqlConnection connection)\n {\n const string Sql = \"update documentation set location = @newLocation where uid = @id\";\n SqlCommand command = new SqlCommand(Sql, connection);\n\n command.Parameters.Add(new SqlParameter(\"id\", SqlDbType.UniqueIdentifier));\n command.Parameters.Add(new SqlParameter(\"newLocation\", SqlDbType.VarChar, 50)); // guessing varchar(50) here\n command.Prepare();\n\n return command;\n }\n\n private static void UpdateDocument(SqlCommand command, Guid id, string newLocation)\n {\n command.Parameters[\"id\"].Value = id;\n command.Parameters[\"newLocation\"].Value = newLocation;\n command.ExecuteNonQuery();\n }\n\n private static SqlCommand CreateLogErrorCommand(SqlConnection connection)\n {\n const string Sql =\n @\"insert into documentationissues (documentid, oldLocation, newLocation, errorMessage, dateAdded, number)\n values (@id, @prevLocation, @newLocation, @msg, GETDATE(), @number)\";\n SqlCommand command = new SqlCommand(Sql, connection);\n\n command.Parameters.Add(new SqlParameter(\"id\", SqlDbType.UniqueIdentifier));\n command.Parameters.Add(new SqlParameter(\"prevLocation\", SqlDbType.VarChar, 255)); // guessing varchar(255) here\n command.Parameters.Add(new SqlParameter(\"newLocation\", SqlDbType.VarChar, 255)); // guessing varchar(255) here\n command.Parameters.Add(new SqlParameter(\"msg\", SqlDbType.VarChar, 255)); // guessing varchar(255) here\n command.Parameters.Add(new SqlParameter(\"number\", SqlDbType.Int));\n\n command.Prepare();\n return command;\n }\n\n private static void LogError(SqlCommand command, Guid id, string prevLocation, string newLocation, string msg, int number)\n {\n if (newLocation == null)\n {\n newLocation = \"no new location\";\n }\n\n command.Parameters[\"id\"].Value = id;\n command.Parameters[\"prevLocation\"].Value = prevLocation;\n command.Parameters[\"newLocation\"].Value = newLocation;\n command.Parameters[\"msg\"].Value = msg;\n command.Parameters[\"number\"].Value = number;\n\n command.ExecuteNonQuery();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T21:02:41.047", "Id": "51743", "Score": "0", "body": "Hey Jesse I copied this over and it keeps erroring out stating that reader1 is closed. I'll have to step through it and play with it a bit, not sure what is causing the issue just yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T21:13:32.523", "Id": "51744", "Score": "0", "body": "I think I know why - gotta be honest I didn't test it due to the fact I don't have your database schema, etc. The tasks need to be waited on before the reader gets disposed. Let me see if I can come up with something interesting to mitigate that. (time passes) DONE. Give that a look-see." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T22:25:07.010", "Id": "51747", "Score": "0", "body": "A different error than before. It thinks there was no data found from the sql query. Running the query in sql server returns the correct result. I'm not sure how but it seems the reader is closing out before it is being used. With I knew more about threading. =(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T22:27:31.923", "Id": "51748", "Score": "0", "body": "Well, frak. I'll give it some more look-see a little later on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T14:40:34.047", "Id": "51779", "Score": "0", "body": "@JamesWilson updated once again. I moved the `reader.GetXX` operations outside of the task creation. I believe that should take care of things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:40:28.007", "Id": "51789", "Score": "0", "body": "That fixed it right up. The speed seems to be about the same, is there a way to increase the amount of threads running or would that not really increase the speed? Each thread should take 1-15 seconds to process with most of them taking around 1-2 seconds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T16:21:38.787", "Id": "51791", "Score": "1", "body": "@JamesWilson the TPL itself is managing a pool of threads that should be adequate for the computer it's being run on. However, check out this article at Microsoft: http://msdn.microsoft.com/en-us/library/ee789351" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T16:24:30.067", "Id": "51792", "Score": "0", "body": "I'll read over that article, I think threading is the next thing I am going to learn. Thank you very much for your help! :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T20:32:21.907", "Id": "32393", "ParentId": "32389", "Score": "6" } }, { "body": "<p>I see a number of things in this code. I'll address all of them, then get to multi-threading. Keep in mind, I'm writing these down as I make changes in the code, so I might suggest something, then change that suggestion.</p>\n\n<ol>\n<li>I like your variable names. Very descriptive and I understand what information they are holding. The only exception is <code>connString</code>, I think it should be make readonly and changed to 'ConnString' indicating a private static readonly variable.</li>\n<li>The declarations of the variables used in the function should be moved closer to where they are being used. This does a couple of things: makes the declaration a little more clear to any other developers, and it ensures the value hasn't been unintentionally altered between declaration and usage.</li>\n<li>Learn about <a href=\"https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp\"><code>var</code></a>. I find that using it really cleans up extra code that just causes clutter.</li>\n<li>I would make the declaration of <code>sql</code> const, and move it to be a class variable. At the same time, it should be renamed <code>SelectFileInformationSql</code></li>\n<li>Good job with the using <code>using</code>.</li>\n<li>The <code>runLoop</code> variable is set in places it is never needed because of the <code>break</code> statements just below it. You can remove this variable, and replace the main loop to a <code>while(true)</code></li>\n<li>The <code>x</code> variable is unused, remove it.</li>\n<li>The variable <code>rootDir</code> should be declared <code>const</code>, moved to a class variable and renamed <code>RootDir</code></li>\n<li>The second declaration of <code>sql</code> should be declared <code>const</code>, moved to a class varible and renamed <code>UpdateDocumentLocationSql</code></li>\n<li>The thrid declaration of <code>sql</code> should be declared <code>const</code>, moved to a class varible and renamed <code>LogIssueSql</code></li>\n<li>I would like to see document moved out into its own class. This way you can do things like <code>FilenameAndPath = Path.Combine(Location, Filename)</code> only once, instead of 2-3 times in the original code. It also packages all the information needed for processing that file into one nice package.</li>\n<li>I find the <code>msg</code> variable to be unneeded. You can just put the string right in the function call.</li>\n</ol>\n\n<p>I will get to multithreading when I found out what version of .Net you are using :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T20:39:05.697", "Id": "51741", "Score": "1", "body": "+1 for #5 alone, along with everything else. I am usually harping on code which ignores `using` or even `Dispose()` in any fashion. It's sad that the MSDN examples are rather lacking in this department." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T20:44:27.030", "Id": "51742", "Score": "0", "body": "Thanks for all of those points. The version I am currently using is .NET Framework 4." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T21:14:13.517", "Id": "51745", "Score": "0", "body": "Also I keep the runLoop in there because this program takes around 45 days to run. I do a break point and change runLoop to false when I need to safely exit the program. Is that still possible with the while(true)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T23:45:49.237", "Id": "51750", "Score": "0", "body": "I'm pretty sure the `break;` that comes in the code 6 lines below makes the runLoop obsolete because the `break;` will end the loop. But test it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T07:45:37.563", "Id": "51763", "Score": "0", "body": "I'm not so sure about moving the SQL strings out, I think it makes sense to have them close to their usage." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T20:36:02.517", "Id": "32394", "ParentId": "32389", "Score": "9" } }, { "body": "<p>Some ideas to speed up and improve your code: </p>\n\n<ol>\n<li><p><strong>Consider refactoring</strong>, i.e. break down the steps in the while loop to individual methods. This will not improve speed, but makes the code even more readable. </p></li>\n<li><p><strong>Read in all data from the database at once</strong>. One <code>SELECT</code> is much faster than 6 million single statements. If the table is too large, use paging. </p></li>\n<li><p><strong>Collect all the <code>FileInfo</code> items and create a list of paths to examine.</strong> A dictionary of destination paths will drastically reduce the amount of calls to <code>Directory.Exists</code>. So, while looping, just collect the path and check (and create) the directory only when a new path is to be put into the dictionary. Also, don't do the other operations within the loop. Just collect. After that step you can safely update your file info and move the files without checking. </p></li>\n<li><p><strong>Avoid updating each record individually. Create a bulk update/insert instead.</strong> I create a temp table on the server using <code>SqlBulkCopy</code> and then do a single <code>UPDATE..FROM tempTable</code>. </p></li>\n</ol>\n\n<p>The bottleneck is for sure the file operations. While multithreading is a nice way to speed up things, I am not sure if this applies to I/O operations in general, as there is usually a single disk spinning which is optimized for carrying out one file operation at a time. But, it's worth a try. </p>\n\n<p>When you collect your <code>FileInfo</code> items (together with the update info items) in a <code>List&lt;FileInfoData&gt;</code>, you can easily use PLINQ to process the updates in parallel <code>FileInfoList.AsParallel().ForAll(..)</code>. Of course, how you exactly use multithreading depends on your .NET version.</p>\n\n<p>An alternative to #3 could be to defer the individual file operations to a worker thread pool, i.e. create a job and let a set of threads to the work. This can be done inside the loop.</p>\n\n<p>Honestly, I am not too familiar with .NET and so I can't tell you if there is something prebuilt regarding worker thread pools.</p>\n\n<p>Here's some pseudocode:</p>\n\n<pre><code>string sql = @\"SELECT ....\"; // without the 'TOP 1'\nusing (var command = new SqlCommand(sql, connection))\n{\n using (var reader = command.ExecuteReader())\n {\n while (reader.read())\n {\n var documentInfo = GetDocumentInfo(reader);\n if (!PathDictionary.Contains(documentInfo.Path))\n {\n EnsureDirectoryExists(documentInfo.Path);\n PathDictionary.Add(documentInfo.Path);\n }\n WorkerThreadPool.AddJob(new WorkerThreadJob(documentInfo));\n }\n }\n}\nPerformBulkUpdateOperation();\n</code></pre>\n\n<p>...</p>\n\n<p>The <code>WorkerThreadJob</code> would also create a dataset containing the <code>UPDATE</code> information. This dataset is used by the <code>PerformBulkUpdateOperation</code> to create the temp table on the server and perform the single <code>UPDATE</code> operation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:55:42.910", "Id": "51835", "Score": "0", "body": "I would combine this answere with the suggestions of Jeff Vanzella and everything should be fine" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:01:24.297", "Id": "51836", "Score": "0", "body": "Nice. Let us know how this improved speed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T06:25:23.583", "Id": "32447", "ParentId": "32389", "Score": "1" } } ]
{ "AcceptedAnswerId": "32393", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T19:16:02.837", "Id": "32389", "Score": "5", "Tags": [ "c#", "performance", "sql", "file-system" ], "Title": "Lattitude document organizer" }
32389
<p>In this scenario I've got a textbox to which I have added autocomplete functionality. The kicker is that I want to dynamically change the source option of the AJAX call based on the value of a dropdown list. To do this I encapsulated the differences between the AJAX calls in an object of type <code>Resolver</code>. The <code>name</code> property of the Resolver object is the same as the text value coming from the dropdown list. I was looking for a way to make this a little cleaner. The code works, just looking for more extensible options as the project grows.</p> <pre><code>$(document).ready(function () { //encapsulate the URL of the AJAX call //the name property maps to a dropdown list value //so if Drugs is chosen from the dropdown menu we look for the name property which = drugs Resolver = function (name, url) { this.name = name; this.url = url; } Resolver.prototype.resolve = function (request, response) { $.ajax( { type: "POST", url: "Service.asmx/" + this.url, data: JSON.stringify({ 'param': $('#auto').val() }), dataType: "json", contentType: "application/json", success: function (data) { response(data.d); }, error: function (xhr) { console.log(xhr.status); } }); } //in the future I expect the Resolver object to have more properties //this is the simplest example I could think of var drugs = new Resolver('drugs', 'GetDrugNames'); var hospitals = new Resolver('hospitals', 'GetHospitalNames'); var resolverArray = []; resolverArray.push(drugs); resolverArray.push(hospitals); //on the change even of the ddl we're looking for the index of the resolverArray //which has the name name property as the value selected in the ddl. $('#ddl').change(function () { var target = $(this).val().toLowerCase(); var index = 0; $.each(resolverArray, function (ix, val) { if (resolverArray[ix].name == target) { index = ix; } }); $('#auto').autocomplete( { source: function (request, response) { resolverArray[index].resolve(request, response); } }); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T09:52:42.390", "Id": "51769", "Score": "0", "body": "You needn't, and probably shouldn't, call `JSON.stringify` when passing an object as the `data` property to jQ's `$.ajax`, jQ will do that for you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T12:36:11.313", "Id": "51772", "Score": "0", "body": "@EliasVanOotegem how else will this work if the data property of the ajax call doesn't know what the name of the parameter in the web method is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T14:53:00.300", "Id": "51780", "Score": "0", "body": "passing `{ param: $('#auto').val() }` to the data property will sent the `$('#auto').val()` value as `$_POST['param']`... the request will look like this: `param=<encodeURI($('#auto').val()>`, so no need to decode/parse the data" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:25:17.737", "Id": "51787", "Score": "0", "body": "@EliasVanOotegem I couldn't get `{ param: $('#auto').val() }` to work. I'm using .NET 4.0 and get an `InvalidJsonPrimitive` error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T15:35:55.883", "Id": "51788", "Score": "0", "body": "That's because jQ doesn't send its data as JSON by default, but defaults to the `x-www-form-urlencoded` mime" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T16:12:35.623", "Id": "51790", "Score": "0", "body": "@EliasVanOotegem this happened even if I set the dataType property to json." } ]
[ { "body": "<p>One way to make it extensible is to make it reusable rather than stick it to one dropdown. You can even make it into a jQuery plugin so that it looks like this:</p>\n\n<pre><code>$('.someAutocompleteBox').dependentAutoComplete({\n\n /* the selector of the element to monitor changes */\n elementToMonitor : '.theElementToMonitor',\n\n /* value set, which correspond to the value of the previous input */\n sets : {\n drugs : DRUG_URL,\n hospitals : HOSPITAL_URL,\n }\n\n /* you can monitor depending on the event and which value to grab */\n triggeringEvent : 'keyup',\n propertyToCheck : 'value'\n});\n</code></pre>\n\n<p>So in this example, I set <code>.someAutocompleteBox</code> to change sets when a <code>keyup</code> event is triggered from <code>.theElementToMonitor</code>. Then the plugin will grab the property defined in <code>propertyToCheck</code> and check it against the <code>sets</code> object which URL to use as source. Pretty simple isn't it?</p>\n\n<p>As for jQuery plugin creation, you can use the <a href=\"https://github.com/jquery-boilerplate/jquery-boilerplate\" rel=\"nofollow\">jQuery Boilerplate</a> to start off with a template. Everything else is self-explanatory, which is:</p>\n\n<ul>\n<li><p>In the <code>init()</code> function of your plugin code, attach an event stated by <code>triggeringEvent</code> to the element stated by <code>elementToMonitor</code>.</p></li>\n<li><p>When the event is fired, the handler should grab the value of the property defined in <code>propertyToCheck</code>.</p></li>\n<li><p>Do a lookup from the passed <code>sets</code> property and grab the URL of the corresponding key (which is the value grabbed from the property earlier)</p></li>\n<li><p>Update the current element's autocomplete source.</p></li>\n</ul>\n\n<p>The plugin code (in the <code>init</code>) should look something like this:</p>\n\n<pre><code>init: function () {\n // nothing to check, nothing to check against\n if(!this.settings.elementToMonitor || !this.settings.sets) return;\n\n // Save the context\n var instance = this;\n\n // Attach the defined event to defined dependency\n $(this.settings.elementToMonitor)\n .on(this.settings.triggeringEvent,function(){\n\n // Get the value at defined property\n var value = $(this).prop(instance.settings.propertyToCheck);\n var url;\n\n // Check if we have that url in the set, return if not\n if(!(url = instance.set[value])) return;\n\n // Update the source accordingly\n $(instance.element).autocomplete({\n source = url;\n });\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T12:33:30.160", "Id": "51771", "Score": "0", "body": "I see several things I can use in here to improve upon. Great stuff!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T05:35:24.873", "Id": "32415", "ParentId": "32392", "Score": "2" } } ]
{ "AcceptedAnswerId": "32415", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T20:26:16.617", "Id": "32392", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Dynamically changing autocomplete source option jQuery" }
32392
<p>I have a pretty interesting problem that I'm trying to solve, and I am kind of stuck.</p> <p>I want to count the triplets of distinct combinations <code>a</code>, <code>b</code>, <code>c</code>, that are smaller than <code>LIMIT</code>have the following properties:</p> <ul> <li><code>a &gt;= b</code>, <code>a &gt;= c</code>, and let's note <code>m = a + b</code> (<code>a</code>, <code>b</code> are integer)</li> <li><code>a</code> and <code>m</code> are the smallest 2 numbers in a Pythagorean triplet (<code>a^2 + m^2 = x^2</code>). <code>m</code> can be bigger than <code>a</code>, but <code>a</code> has to be larger than <code>b</code> or <code>c</code></li> </ul> <p>Here is the code I have so far. First, I generate all Pythagorean tripplets (of which I only use the first 2). The smallest one should be under the limit, but the largest one can be above the limit.</p> <pre><code>LIMIT = 10 pyt = {} for m in xrange(1, LIMIT): for n in xrange(m + 1, LIMIT): k = 1 a = n ** 2 - m ** 2 b = 2 * m * n if (m - n) % 2 == 0 or gcd(m, n) != 1: continue while True: temp_a = a * k temp_b = b * k max_pyt = max(temp_a, temp_b) min_pyt = min(temp_a, temp_b) # I only need the minimum to be smaller than the LIMIT # but the maximum can't be larger than 2*LIMIT (check below) if min_pyt &gt; LIMIT: break pyt[min_pyt, max_pyt] = 1 k += 1 </code></pre> <p>Once I have them, I just loop through them, and count the possible combinations that can be generated.</p> <p>For example:</p> <pre><code># pythagorean numbers: 6, 8 =&gt; (6^2 + 8^2 = 10^2) # we can generate the numbers: # 1, 5, 8 | 2, 4, 8 | 3, 3, 8 (when decomposing 6) # 6, 2, 6 | 6, 3, 5 | 6, 4, 4 (when decomposing 8, although 6, 1, 7 are not good, the largest of the 3 needs to be a member of the Pythagorean triplet ) counter = 0 print pyt for a, b in pyt: # if half of b is bigger than the limit, just continue temp = b // 2 if temp &gt;= LIMIT: continue elif b &lt; LIMIT: # a is smaller than b, so any unordered combination of numbers with the sum a # will be good (4 = 1 + 3 or 4 = 2 + 2, 5 = 1 + 4, 5 = 2 + 3 - ie // works) counter += (a // 2) # at this point we know that temp (half of b) is not higher than the limit # and if it's less than a, there are combinations to be counted if temp &lt;= a: # with the limit 10, we can have the following situation: # a = 8, b = 15, so we can count the set (8, 8, 7) counter += (a - temp) # if (a - temp) % 2 == 0: counter += 1 </code></pre> <p>I hope I explained it well enough. The script seems to be working with lower values, but when going to higher numbers, I'm starting to miss things in limit situations, but I can't figure out what.</p> <p>For example, with <code>LIMIT = 99</code> I should be getting <code>1975</code>, but I get <code>1943</code>. Any ideas what I could be missing ? Any hint is more than welcome.</p> <p>Also, since I'm still learning python, I wouldn't mind some tips on how to improve my code, and follow python coding standards.</p> <p><strong>Edit:</strong> The <code>gcd</code> function is from the fractions module (<code>from fractions import gcd</code>)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T22:18:51.017", "Id": "51746", "Score": "0", "body": "This is Project Euler [problem 86](http://projecteuler.net/problem=86)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T05:55:04.173", "Id": "51756", "Score": "0", "body": "Yes, that's true. And even though there are plenty of solutions out there, I still want to pursue my idea to get the result myself." } ]
[ { "body": "<h3>1. Missing GCD</h3>\n\n<p>You didn't give the code for your <code>gcd</code> function, so I'll assume it's something like this:</p>\n\n<pre><code>def gcd(m, n):\n \"\"\"Return the greatest common divisor of positive integers m and n.\"\"\"\n while n:\n m, n = n, m % n\n return m\n</code></pre>\n\n<h3>2. Decomposition: primitive Pythagorean triples</h3>\n\n<p>You're having trouble finding the error here because your program consists of a single block of code. You have to run <em>all</em> of it in order to run <em>any</em> of it. It would make your program easier to debug if you split it up into functions with straightforward inputs and outputs, that can be tested individually. This technique is known as <a href=\"http://en.wikipedia.org/wiki/Decomposition_%28computer_science%29\"><em>functional decomposition</em></a>.</p>\n\n<p>The first bit of functionality to pull out is the computation of the primitive Pythagorean triples. It's convenient to write this kind of function in the form of a <a href=\"http://docs.python.org/3/tutorial/classes.html#generators\"><em>generator</em></a> — a function that produces its results one by one using the <code>yield</code> statement.</p>\n\n<p>So, we could start with a function like this:</p>\n\n<pre><code>def f(LIMIT):\n for m in xrange(1, LIMIT):\n for n in xrange(m + 1, LIMIT):\n a = n ** 2 - m ** 2\n b = 2 * m * n\n if (m - n) % 2 == 0 or gcd(m, n) != 1:\n continue\n yield a, b\n</code></pre>\n\n<p>There are some immediate improvements that can be made:</p>\n\n<ol>\n<li><p>The function needs a descriptive name and a docstring.</p></li>\n<li><p>It's conventional to use <code>ALL_CAPITALS</code> only for global constants (see the Python style guide, <a href=\"http://www.python.org/dev/peps/pep-0008/#constants\">PEP 8</a>, for this and other recommendations).</p></li>\n<li><p>It would be make sense to generate all three sides of the triangle (you only use two of them here, but the third one is useful for testing, and it \nwill come in handy in other Project Euler problems).</p></li>\n<li><p>The <code>continue</code> statement can be avoided by reversing the sense of the condition.</p></li>\n<li><p><a href=\"http://docs.python.org/3/library/itertools.html#itertools.combinations\"><code>itertools.combinations</code></a> can be used to reduce the two nested loops to one.</p></li>\n</ol>\n\n<p>Here's the improved code:</p>\n\n<pre><code>from itertools import combinations\n\ndef primitive_pythagorean_triples(limit):\n \"\"\"Generate the primitive Pythagorean triples whose shortest side is\n no longer than 2 * limit - 3, together possibly with some other\n primitive Pythagorean triples whose shortest side is longer than\n that.\n\n \"\"\"\n for m, n in combinations(xrange(1, limit), 2):\n if (m - n) % 2 and gcd(m, n) == 1:\n a = n ** 2 - m ** 2\n b = 2 * m * n\n c = n ** 2 + m ** 2\n yield a, b, c\n</code></pre>\n\n<p>The hardest part of doing this was writing the docstring. (<code>a</code> might be as large as <code>(limit - 1) ** 2 - (limit - 2) ** 2</code> which is <code>2 * limit - 3</code>.) When it's hard to write a docstring, this is often a hint that the function is poorly specified. In this case, surely it would be more convenient to pass in the actual maximum shortest side?</p>\n\n<p>Let's check that these are really Pythagorean triples:</p>\n\n<pre><code>&gt;&gt;&gt; all(a ** 2 + b ** 2 == c ** 2 for a, b, c in primitive_pythagorean_triples(100))\nTrue\n</code></pre>\n\n<p>and have a quick look at the output:</p>\n\n<pre><code>&gt;&gt;&gt; list(primitive_pythagorean_triples(8))\n[(3, 4, 5), (15, 8, 17), (35, 12, 37), (5, 12, 13), (21, 20, 29), (45, 28, 53),\n (7, 24, 25), (9, 40, 41), (33, 56, 65), (11, 60, 61), (13, 84, 85)]\n</code></pre>\n\n<p>Does that list include all the primitives triples with shortest side no more than 13? It's hard to tell. It would be easier to read the output if each triple were sorted by side length, so that (15, 8, 17) appears as (8, 15, 17). It would also be convenient to reject triples whose shortest side is too long.</p>\n\n<p>Making these changes gives us a third version of the function:</p>\n\n<pre><code>def primitive_pythagorean_triples(max_side):\n \"\"\"Generate the primitive Pythagorean triples whose shortest side is\n no longer than max_side.\n\n \"\"\"\n for m, n in combinations(xrange(1, max_side // 2 + 3), 2):\n if (m - n) % 2 and gcd(m, n) == 1:\n a = n ** 2 - m ** 2\n b = 2 * m * n\n c = n ** 2 + m ** 2\n if a &lt; b and a &lt;= max_side:\n yield a, b, c\n elif b &lt; a and b &lt;= max_side:\n yield b, a, c\n</code></pre>\n\n<p>And now we can take the output:</p>\n\n<pre><code>&gt;&gt;&gt; sorted(primitive_pythagorean_triples(13))\n[(3, 4, 5), (5, 12, 13), (7, 24, 25), (8, 15, 17), (9, 40, 41), (11, 60, 61),\n (12, 35, 37), (13, 84, 85)]\n</code></pre>\n\n<p>and compare it to, say, <a href=\"http://oeis.org/A020884\">OEIS sequence A020884</a>. This looks good so far, but to be more certain that this is correct, let's write a naïve version of the function (one that would be far too slow to solve the Project Euler problem) and compare the output of the two functions.</p>\n\n<pre><code>from math import hypot\n\ndef primitive_pythagorean_triples_slow(max_side):\n for a in xrange(1, max_side + 1):\n for b in xrange(a + 1, (a ** 2 - 1) // 2 + 1):\n c = hypot(a, b)\n if gcd(a, b) == 1 and c == int(c):\n yield a, b, int(c)\n\n&gt;&gt;&gt; sorted(primitive_pythagorean_triples(300)) == sorted(primitive_pythagorean_triples_slow(300))\nTrue\n</code></pre>\n\n<h3>3. Decomposition: all Pythagorean pairs</h3>\n\n<p>The next bit of functionality to decompose is the computation of the Pythagorean pairs. Your code looks like this:</p>\n\n<pre><code>pyt = {}\nk = 1\nwhile True:\n temp_a = a * k\n temp_b = b * k\n max_pyt = max(temp_a, temp_b)\n min_pyt = min(temp_a, temp_b)\n # I only need the minimum to be smaller than the LIMIT\n # but the maximum can't be larger than 2*LIMIT (check below)\n if min_pyt &gt; LIMIT:\n break\n pyt[min_pyt, max_pyt] = 1\n k += 1\n</code></pre>\n\n<p>There are lots of small improvements we can make here:</p>\n\n<ol>\n<li><p>Make it into a function we can test separately.</p></li>\n<li><p>Write a docstring.</p></li>\n<li><p><em>Generate</em> these pairs instead of storing them in a dictionary.</p></li>\n<li><p>Use <a href=\"http://docs.python.org/3/library/itertools.html#itertools.count\"><code>itertools.count</code></a> to simplify the loop.</p></li>\n<li><p>Choose better names for the variables. For example, what's temporary about <code>temp_a</code> and why is that important? I'd prefer a name like <code>ka</code> to remind us that this variable holds the value <code>k * a</code>.</p></li>\n</ol>\n\n<p>Here's the improved code:</p>\n\n<pre><code>from itertools import count\n\ndef pythagorean_pairs(max_side):\n \"\"\"Generate pairs of integers (a, b), where a is the short leg and b\n the long leg of a Pythagorean triangle, and where a &lt;= max_side\n and b &lt;= 2 * max_side.\n\n \"\"\"\n for a, b, _ in primitive_pythagorean_triples(max_side):\n for k in count(1):\n ka, kb = k * a, k * b\n if ka &gt; max_side or kb &gt; 2 * max_side:\n break\n yield ka, kb\n</code></pre>\n\n<p>Again, at this point it is useful to have a naïve computation of the same set of pairs, to test the faster version of the code.</p>\n\n<pre><code>def pythagorean_pairs_slow(max_side):\n for a in xrange(1, max_side + 1):\n for b in xrange(a + 1, 2 * max_side + 1):\n c = hypot(a, b)\n if c == int(c):\n yield a, b\n\n&gt;&gt;&gt; sorted(pythagorean_pairs(1000)) == sorted(pythagorean_pairs_slow(1000))\nTrue\n</code></pre>\n\n<h3>4. Decomposition: counting cuboids</h3>\n\n<p>Your code for counting the cuboids contains a lot of comments, which is a sign that it's not very clearly written. Let's pull out the body of the loop into a function and see if we can make sense of it:</p>\n\n<pre><code>def count_cuboids(a, b, LIMIT):\n \"\"\"Given a Pythagorean pair (a, b), return the number of cuboids (p, q, r)\n such that 1 &lt;= p, q, r &lt;= LIMIT and ????\n\n \"\"\"\n counter = 0\n temp = b // 2 \n if temp &gt;= LIMIT:\n return 0\n elif b &lt; LIMIT:\n counter += (a // 2)\n if temp &lt;= a:\n counter += (a - temp)\n if (a - temp) % 2 == 0:\n counter += 1\n return counter\n</code></pre>\n\n<p>Now, the problem I have here is that I can't figure out exactly which cuboids this is supposed to count, so I don't know how to write the docstring.</p>\n\n<p>Your comment at the top says:</p>\n\n<pre><code># 1, 5, 8 | 2, 4, 8 | 3, 3, 8 (when decomposing 6)\n# 6, 2, 6 | 6, 3, 5 | 6, 4, 4 (when decomposing 8, although 6, 1, 7 are not\n# good, the largest of the 3 needs to be a member of the Pythagorean triplet)\n</code></pre>\n\n<p>and indeed:</p>\n\n<pre><code>&gt;&gt;&gt; count_cuboids(6, 8, 100)\n6\n</code></pre>\n\n<p>so this suggests that the docstring for <code>count_cuboids</code> might need to be:</p>\n\n<pre><code>\"\"\"Given a Pythagorean pair (a, b), return the number of cuboids (p, q, r)\nsuch that 1 &lt;= p, q, r &lt;= LIMIT and \neither: p &lt;= q &lt;= r and p + q == a and r == b\n or: p == a and q &lt;= r &lt;= p and q + r == b.\"\"\"\n</code></pre>\n\n<p>but then I tried the simplest example:</p>\n\n<pre><code>&gt;&gt;&gt; count_cuboids(3, 4, 100)\n2\n</code></pre>\n\n<p>which doesn't match your specification. According to your specification, there ought to be <em>three</em> possible cuboids here, not two: (1, 2, 4), (3, 1, 3) and (3, 2, 2).</p>\n\n<p>So your code for counting the cuboids does not match your specification. One or both of them is wrong.</p>\n\n<h3>5. Conclusion</h3>\n\n<p>I don't want to spoil the Project Euler problem, so I'll leave you to take it from here. I'll finish by repeating the key points:</p>\n\n<ol>\n<li><p>Use functional decomposition to split your code up into parts that you can test separately.</p></li>\n<li><p>Write docstrings explaining what each function does. If you are having trouble writing concise and clear docstrings, this is a sign that the way you have decomposed your code was poorly chosen and needs to be reconsidered.</p></li>\n<li><p>Make use of generators to produce and consume sequences of results without having to store them in intermediate data structures.</p></li>\n<li><p>When you have a complicated, optimized function, also implement a naïve, straightforward version of the same function that you can use to test it.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T14:19:22.290", "Id": "51778", "Score": "0", "body": "Wow, thank you for the awesome answer. I will review everything tonight, but I just wanted to say that the `gcd` function is from the fractions module (`from fractions import gcd`)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T13:29:55.123", "Id": "32422", "ParentId": "32395", "Score": "5" } } ]
{ "AcceptedAnswerId": "32422", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T20:39:17.567", "Id": "32395", "Score": "1", "Tags": [ "python", "algorithm", "project-euler" ], "Title": "Pythagorean number decomposition" }
32395
<p>I'm new to Haskell. I'm developing a game-like simulation. I try to use lenses to update the state of the world.</p> <p>Current iteration of code works, but looks clumsy. I am trying to improve it, e.g. I would like to:</p> <ol> <li>Get rid of direct enumeration of <code>q1</code> and so on, with usage of <code>quantityPolymorph</code> and others in them. Problem is that partial application won't help since the function which gets applied is "in the middle" of arguments;</li> <li>Get rid of incrementQuantity. I'd like something like <code>fmap (+1)</code>, but since <code>Quantity</code> is not an instance of <code>Functor</code>, I can't do that. I can't make <code>Quantity</code> an instance because it has kind <code>*</code>. Is there a more concise way, w/o lambda?</li> <li>Update world with just lenses, if possible. It looks like simple dispatching and I think it might be possible to move away from direct specification of what lens (i.e. <code>quantityPolymorpth</code>) should be called for which argument (<code>f</code>).</li> </ol> <p><strong>Important note</strong>: however the <code>updateWorld</code> never emits <code>Nothing</code> at the moment, I want to keep it returning a <code>Maybe</code> because later at some point it will return <code>Nothing</code>s as well.</p> <p>How can I refactor my code? Are there other things amiss with it? </p> <p>The source follows.</p> <pre><code>{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TemplateHaskell #-} import Control.Lens import Control.Monad import System.Random data Quantity = Quantity Integer deriving (Show) instance Random Quantity where randomR (Quantity lo, Quantity hi) g = let rand = randomR (lo, hi) g (r, g1) = rand in (Quantity r, g1) random g = let rand = random g (r, g1) = rand in (Quantity r, g1) instance Eq Quantity where (==) (Quantity q1) (Quantity q2) = q1 == q2 instance Ord Quantity where (&lt;=) (Quantity q1) (Quantity q2) = q1 &lt;= q2 instance Num Quantity where (+) (Quantity q1) (Quantity q2) = Quantity (q1 + q2) (*) (Quantity q1) (Quantity q2) = Quantity (q1 * q2) (-) (Quantity q1) (Quantity q2) = Quantity (q1 - q2) abs (Quantity q) = Quantity (abs q) signum (Quantity q) = Quantity (signum q) fromInteger i = Quantity i ------------------------------- data QuantityHolder = QuantityHolder { _quantityPolymorph :: Quantity , _quantityTeamPlayer :: Quantity , _quantityLoneWolf :: Quantity } deriving (Show) $(makeLenses ''QuantityHolder) ------------------------------- data Fighter = TeamPlayer | LoneWolf | Polymorph deriving (Show, Eq, Ord) ------------------------------- data World = World { _quantities :: QuantityHolder } deriving (Show) $(makeLenses ''World) incrementQuantity (Quantity q) = Quantity (q + 1) updateWorld :: Maybe World -&gt; Fighter -&gt; Maybe World updateWorld (Just w) f = case f of Polymorph -&gt; Just $ q1 w TeamPlayer -&gt; Just $ q2 w LoneWolf -&gt; Just $ q3 w where q1 = over quantities . over quantityPolymorph $ incrementQuantity q2 = over quantities . over quantityTeamPlayer $ incrementQuantity q3 = over quantities . over quantityLoneWolf $ incrementQuantity </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T23:10:23.483", "Id": "51817", "Score": "4", "body": "I have taken the liberty to edit the question to make it more suitable for a code review, which I believe is what you were after." } ]
[ { "body": "<blockquote>\n <p>Get rid of direct enumeration of q1 and so on, with usage of quantityPolymorph and others in them. Problem is that partial application won't help since the function which gets applied is \"in the middle\" of arguments</p>\n</blockquote>\n\n<p>That's not a problem, you can do partial application in any order, it's just more verbose.</p>\n\n<blockquote>\n <p>Get rid of incrementQuantity. I'd like something like fmap (+1), but since Quantity is not an instance of Functor, I can't do that. I can't make Quantity an instance because it has kind *. Is there a more concise way, w/o lambda?</p>\n</blockquote>\n\n<p>You don't need <code>fmap</code>, a simple <code>(+1)</code> works. If I'm not mistaken, under the hood the compiler uses <code>fromInteger</code> to convert the <code>1</code> literal to a <code>Quantity</code>.</p>\n\n<hr>\n\n<p>Here is what I have:</p>\n\n<pre><code>{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nimport Control.Lens\nimport System.Random\n\nnewtype Quantity = Quantity Integer\n deriving (Eq,Num,Ord,Random,Show)\n\ndata QuantityHolder = QuantityHolder { _quantityPolymorph :: Quantity\n , _quantityTeamPlayer :: Quantity\n , _quantityLoneWolf :: Quantity\n } deriving (Show)\n$(makeLenses ''QuantityHolder)\n\ndata Fighter = TeamPlayer\n | LoneWolf\n | Polymorph\n deriving (Eq,Ord,Show)\n\ndata World = World { _quantities :: QuantityHolder }\n deriving (Show)\n$(makeLenses ''World)\n\nupdateWorld :: Fighter -&gt; World -&gt; World\nupdateWorld fighter w =\n case fighter of\n Polymorph -&gt; increment quantityPolymorph w\n TeamPlayer -&gt; increment quantityTeamPlayer w\n LoneWolf -&gt; increment quantityLoneWolf w\n where increment field = over quantities . over field $ (+1)\n</code></pre>\n\n<p>I didn't really look into the lens stuff.</p>\n\n<p>Note the use of <code>GeneralizedNewtypeDeriving</code> to get rid of the boring instance declarations.</p>\n\n<p>A main function to do a simple test:</p>\n\n<pre><code>main = do\n let w = World $ QuantityHolder 0 0 0\n print $ updateWorld Polymorph $ updateWorld LoneWolf w\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T15:55:27.707", "Id": "32601", "ParentId": "32397", "Score": "1" } }, { "body": "<p><code>updateWorld</code> of @Changaco can still be improved. I'll show it gradually so you can see what's going on.</p>\n\n<p>Firstly, we can eliminate duplication in <code>case</code> statement and use lens composition to eliminate second <code>over</code>:</p>\n\n<pre><code>quantity Polymorph = quantityPolymorph\nquantity TeamPlayer = quantityTeamPlayer\nquantity LoneWolf = quantityLoneWolf\n\nupdateWorld :: Fighter -&gt; World -&gt; World\nupdateWorld fighter w = increment (quantity fighter) w where\n increment field = over (quantities . field) (+1)\n</code></pre>\n\n<p>Then we can go pointfree. Pointfree is all about readability so don't do it whenever you feel readability is harmed. With coding experience more and more code will become readable for you.</p>\n\n<pre><code>updateWorld = increment . quantity where\n increment field = over (quantities . field) (+1)\n</code></pre>\n\n<p>Then we replace <code>over</code> with a more specialized version of it from <code>Control.Lens.Setter</code>:</p>\n\n<pre><code>updateWorld = increment . quantity where\n increment field = (quantities . field) +~ 1\n</code></pre>\n\n<p>Now it seems beneficial to inline <code>increment</code>. I'll do in 2 steps. First, I make the actual parameter of <code>increment</code> explicit:</p>\n\n<pre><code>updateWorld field = increment $ quantity field where\n increment field = (quantities . field) +~ 1\n</code></pre>\n\n<p>Then I inline:</p>\n\n<pre><code>updateWorld :: Fighter -&gt; World -&gt; World\nupdateWorld field = (quantities . quantity field) +~ 1\n</code></pre>\n\n<p>Another way to improve could be to use a <code>Map</code> or an <code>Array</code> for <code>QuantityHolder</code>:</p>\n\n<pre><code>data World = World { _quantities :: M.Map Fighter Quantity }\n</code></pre>\n\n<p>Below is full source using <code>Map</code>:</p>\n\n<pre><code>{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nimport Control.Lens\nimport System.Random\nimport qualified Data.Map as M\nimport Data.Maybe\n\nnewtype Quantity = Quantity Integer\n deriving (Eq,Num,Ord,Random,Show)\n\ndata Fighter = TeamPlayer\n | LoneWolf\n | Polymorph\n deriving (Eq,Ord,Show)\n\ndata World = World { _quantities :: M.Map Fighter Quantity }\n deriving (Show)\n$(makeLenses ''World)\n\natFighter i = at i . iso fromJust Just\n\nupdateWorld :: Fighter -&gt; World -&gt; World\nupdateWorld field = (quantities . atFighter field) +~ 1\n</code></pre>\n\n<p>But it really depends on the usage scenarios you plan for <code>World</code>.</p>\n\n<p>Also note that lens interact with state monad transformer pretty well, so you may consider </p>\n\n<pre><code>updateWorldS :: Fighter -&gt; State World Quantity\nupdateWorldS field = (quantities . atFighter field) &lt;+= 1\n</code></pre>\n\n<p>Note that <code>World</code> is not passed in explicitly any more. And the type is more general than that, so you can combine state with IO and other monads should you wish:</p>\n\n<pre><code>updateWorldS :: MonadState World m =&gt; Fighter -&gt; m Quantity\n</code></pre>\n\n<p>If you want to be able to report any extra value from <code>updateWorld</code> you can use the existing state monad:</p>\n\n<pre><code>updateWorldS :: Fighter -&gt; State World Bool\nupdateWorldS field = (quantities . atFighter field) &lt;+= 1 &gt;&gt; return errorBool where\n errorBool = False -- or True\n</code></pre>\n\n<p>Or <code>MonadPlus</code> if you don't want to just report failure without extra info:</p>\n\n<pre><code>updateWorldS field = (quantities . atFighter field) &lt;+= 1 &gt;&gt; when errorBool mzero where\n errorBool = False\n</code></pre>\n\n<p>Or <code>MonadError</code> if you want to supply an error value (of any type):</p>\n\n<pre><code>updateWorldS4 field = (quantities . atFighter field) &lt;+= 1 &gt;&gt; when errorBool (throwError \"Game over\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T19:10:35.540", "Id": "52326", "Score": "0", "body": "That's some real Haskell power! However, I want to keep the `Maybe` for `updateWorld` since it will return `Nothing` a bit later, when more logic will be implemented. I believe it complicates the point-free." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T08:12:54.007", "Id": "52346", "Score": "0", "body": "As you accept `Maybe World` and return `Maybe World` there are 4 possible cases (Nonthing - Nothing, Just - Nothing, Nothing-Just and Just-Just). Do you need them all? What does accepting (resp. returning) no world means? Since there have been too many improvements to your code it's better to create a new question for that. Put there a minimal code example that illustrates why you think you need `Nothing` in the first place. The possibilities are numerous - for example, you could have returned id function if you don't want to have world modified,so we want to know your intent and not mere code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T09:56:39.947", "Id": "52351", "Score": "0", "body": "I want to be able to stop updating at some point. In such case I would return `Nothing` and outer loop in `main` would stop calling `updateWorld` then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T10:34:13.623", "Id": "52355", "Score": "1", "body": "Edited my answer to include many ways to return extra data along with modifying world in case of monadic approach." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T09:47:09.887", "Id": "32703", "ParentId": "32397", "Score": "2" } } ]
{ "AcceptedAnswerId": "32703", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T21:33:03.513", "Id": "32397", "Score": "2", "Tags": [ "haskell" ], "Title": "Usage of lens for concise update of records" }
32397
<p>I've decided to improve / test my knowledge so far, as I haven't coded in Java for a while now. Is there anything I can improve in my code? The OOP structure? The code itself? Useless code?</p> <p>Main.java:</p> <pre><code>import java.util.Scanner; class Main { /** * A Simple question-and-answer game based on points. * @author Jony */ /** * Objects */ static Scanner console = new Scanner(System.in); static QuestionHandler handler = new QuestionHandler(); static boolean gameIsActive = true; /** * @main */ public static void main(String[] args) { System.out.println("Welcome to Question &amp; Answer game."); String answer; /** * Game loop */ while (gameIsActive) { /** * If you're NOT in a question, system will generate * a new question, and set inQuestion = true. */ if (!handler.inQuestion) { handler.generateQuestion(); } else { answer = console.nextLine(); if (isset(answer)) { handler.answerQuestion(answer); } } } } /** * isset * Checks if a string was set, and is NOT empty ("") * * @param string The scanner input. * @return boolean */ private static boolean isset(String string) { return (string != ""); } } </code></pre> <p>QuestionHandler.java:</p> <pre><code>import java.util.ArrayList; import java.util.Random; class QuestionHandler { public static boolean inQuestion = false; private static Question currentQnA; private static ArrayList&lt;Question&gt; questions = new ArrayList&lt;Question&gt;(); private static Random rand = new Random(); private static int points = 0; public QuestionHandler() { /** * Initialize questions */ questions.add(new Question("What language is this programmed in?", "java")); questions.add(new Question("What is php?", "hypertext")); questions.add(new Question("Who is daniel?", "someguy")); } /** * generateQuestion * Sets a random index out of the size of the arraylist. * * @return void */ public static void generateQuestion() { int size = questions.size(); int index = rand.nextInt(size); setQuestion(index); } /** * answerQuestion * Player attempts at answering the question... * * @return void */ public static void answerQuestion(String input) { String answer = currentQnA.getAnswer(); if (input.equalsIgnoreCase(answer)) { awardCorrectAnswer(); } else { incorrectAnswer(); } } /** * setQuestion * set the new generated question, make user inQuestion = true * * @return void */ private static void setQuestion(int index) { currentQnA = questions.get(index); inQuestion = true; System.out.println(currentQnA.getQuestion()); } /** * awardCorrectAnswer * Award correct answer &amp; get out of the question. * * @return void */ private static void awardCorrectAnswer() { points++; System.out.println("You have answered correctly! Won 1 point"); System.out.println("You now have " + points + " points."); inQuestion = false; } /** * incorrectAnswer * Take 1 point out of the user, for being clueless &amp; get out of the question. * * @return void; */ private static void incorrectAnswer() { points--; System.out.println("Wrong answer! you lost 1 point."); System.out.println("You now have " + points + " points."); inQuestion = false; } } </code></pre> <p>Question.java:</p> <pre><code>class Question implements QnAInterface { /** * @author Jony &lt;artemkller@gmail.com&gt; */ private String question; private String answer; public Question(String question, String answer) { this.question = question; this.answer = answer; } public String getQuestion() { return this.question; } public String getAnswer() { return this.answer; } } </code></pre>
[]
[ { "body": "<p>Strcuture your classes in packages.</p>\n\n<p>use <code>final</code> in this cases</p>\n\n<pre><code> private static ArrayList&lt;Question&gt; questions = new ArrayList&lt;Question&gt;();\n</code></pre>\n\n<p>I think it is not necessary to have <a href=\"http://martinfowler.com/eaaCatalog/dataTransferObject.html\" rel=\"nofollow\">DTO</a> behind an interface.</p>\n\n<p>Avoid redundant comments as </p>\n\n<pre><code>/**\n * Objects\n */\n</code></pre>\n\n<p>This comment adds no more information then code itself. And read <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\" rel=\"nofollow\">how to use javadoc coments</a>.</p>\n\n<p>And i would separate QuestionHandler and Main into \n<strong>Main</strong> - contains only input/output and QnA game initialization\n<strong>QuestionRepository</strong> - Place where questions are retrieved from (this is the place you should use interface)\nand <strong>QuestionGame</strong> - place where to put logic of you applicaiton.</p>\n\n<p>And one last thing - Do not output Strings directly in your game. You can set output writer (which is initialized in Main) to your game class and then write through it. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T05:22:24.460", "Id": "32413", "ParentId": "32398", "Score": "0" } }, { "body": "<p>In <code>QuestionHandler</code>, everything is <code>static</code>. That means that you are using <code>QuestionHandler</code> more as a namespace than a class. The usual approach is to use the <strong>singleton pattern</strong> instead:</p>\n\n<pre><code>class QuestionHandler {\n private static final QuestionHandler instance = new QuestionHandler();\n\n private Question currentQuestion;\n private List&lt;Question&gt; questions;\n private Random rand;\n private int points;\n\n public static QuestionHandler getInstance() {\n return instance;\n }\n\n private QuestionHandler() { ... }\n public void generateQuestion() { ... }\n ... // etc.\n}\n</code></pre>\n\n<p>There should be <strong>no side-effects in setters and getters</strong>. By convention, setters and getters do just that. In addition to setting and getting, feel free to do whatever it takes to maintain the object in a self-consistent state. However, anything else you do, such as <code>System.out.println()</code> in <code>.setQuestion()</code>, would be considered surprising.</p>\n\n<p>I would push the <strong>responsibility to decide whether an answer is correct</strong> into the <code>Question</code> class. That would give you the flexibility to have questions with multiple correct answers.</p>\n\n<pre><code>class Question {\n public Question(String question, String answer) { ... }\n public String getQuestion() { ... }\n public boolean isCorrectAnswer(String answer) { ... }\n}\n</code></pre>\n\n<p>I think you've <strong>broken up the problem excessively</strong>, creating unnecessary complications. There shouldn't need to be a separate class called <code>Main</code>. The fact that the <code>Main</code> class has a non-descriptive name is a bad sign. Also, there's too much in class variables (which act like global variables and are therefore bad) that could just be local.</p>\n\n<p><strong>Suggested <code>QuestionHandler</code>:</strong></p>\n\n<pre><code>public class QuestionHandler {\n private List&lt;Question&gt; questions;\n private Random rand;\n private Question currentQuestion;\n private int points;\n\n public static QuestionHandler instance = new QuestionHandler();\n\n public static QuestionHandler getInstance() {\n return QuestionHandler.instance;\n }\n\n private QuestionHandler() {\n this.questions = Arrays.asList(new Question[] {\n new Question(\"What language is this programmed in?\", \"java\"),\n new Question(\"What is php?\", \"hypertext\"),\n new Question(\"Who is daniel?\", \"someguy\")\n });\n this.rand = new Random();\n this.points = 0;\n }\n\n public boolean hasMoreQuestions() {\n return true;\n }\n\n public Question nextQuestion() {\n int index = rand.nextInt(questions.size());\n return this.currentQuestion = this.questions.get(index);\n }\n\n public Question getQuestion() {\n return this.currentQuestion;\n }\n\n public int getPoints() {\n return this.points;\n }\n\n public void handleAnswer(String answer) {\n if (this.currentQuestion.isCorrectAnswer(answer)) {\n this.points++;\n this.output(\"You have answered correctly! Won 1 point\");\n } else {\n this.points--;\n this.output(\"Wrong answer! You lost 1 point\");\n }\n this.output(\"You now have \" + this.points + \" points.\");\n }\n\n private void output(String s) {\n System.out.println(s);\n }\n\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n System.out.println(\"Welcome to Question &amp; Answer game.\");\n QuestionHandler handler = QuestionHandler.getInstance();\n loop: while (handler.hasMoreQuestions()) {\n Question q = handler.nextQuestion();\n handler.output(q.getQuestion());\n String answer;\n do {\n if (!input.hasNext()) { break loop; }\n answer = input.nextLine();\n } while (answer.isEmpty());\n handler.handleAnswer(answer);\n }\n }\n}\n</code></pre>\n\n<p><strong>Suggested <code>Question</code>:</strong></p>\n\n<pre><code>class Question {\n private final String question;\n private final String answer;\n\n public Question(String question, String answer) {\n this.question = question;\n this.answer = answer;\n }\n\n public String getQuestion() {\n return this.question;\n }\n\n public boolean isCorrectAnswer(String answer) {\n return this.answer.equalsIgnoreCase(answer);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T07:35:14.493", "Id": "32417", "ParentId": "32398", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T21:43:45.640", "Id": "32398", "Score": "0", "Tags": [ "java", "object-oriented" ], "Title": "Q&A minigame structure" }
32398
<p>I am working on converting a mailing list that has longitude and latitude coordinates within the CSV file. This script I came up with does what I need, but this is my first real-world use of python. I want to know where I am making any mistakes, not using best-practices, and what can be optimized to make it faster.</p> <p>The input.csv file has the following header:</p> <pre><code>"Email Address",MEMBER_RATING,OPTIN_TIME,OPTIN_IP,CONFIRM_TIME,CONFIRM_IP,LATITUDE,LONGITUDE,GMTOFF,DSTOFF,TIMEZONE,CC,REGION,LAST_CHANGED,LEID,EUID </code></pre> <p>And the script:</p> <pre><code>import sys import os import csv import signal import json import urllib import urllib2 import sqlite3 import codecs import cStringIO csv.field_size_limit(sys.maxsize) class EmailList: WEB_SERVICE_URL = 'http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json' def __init__(self, inputFile): signal.signal(signal.SIGINT, self.signal_handler) self.conn = None self.initialize_database(inputFile) self.convert_rows() self.db_to_csv() def signal_handler(self, signal, frame): try: self.conn.commit() self.conn.close() print '[DB changes committed and connection closed.]' except sqlite3.ProgrammingError as e: print '[script stopped]' print e.message sys.exit(0) def initialize_database(self, file): print 'checking for data.db...' if not os.path.isfile('data.db'): print 'data.db does not exist, converting csv to sqlite...' with open(file) as inputFile: reader = UnicodeReader(inputFile) header = reader.next() if self.conn is None: self.conn = sqlite3.connect('data.db') c = self.conn.cursor() c.execute("DROP TABLE IF EXISTS email_list") sql = """CREATE TABLE email_list (\n""" + \ ",\n".join([("%s varchar" % name) for name in header]) \ + ")" c.execute(sql) for line in reader: if line: try: c.execute('INSERT INTO email_list VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', line) except sqlite3.ProgrammingError as e: print e.message print line try: c.execute('ALTER TABLE email_list ADD COLUMN CITY varchar') c.execute('ALTER TABLE email_list ADD COLUMN STATE varchar') c.execute('ALTER TABLE email_list ADD COLUMN COUNTRY varchar') c.execute('ALTER TABLE email_list ADD COLUMN POSTAL_CODE varchar') except sqlite3.OperationalError as e: print 'error creating new columns: ' print e.message self.conn.commit() self.conn.close() print 'converted csv to sqlite, stored in data.db' def convert_rows(self): print 'converting coordinates...' self.conn = sqlite3.connect('data.db') c = self.conn.cursor() results = c.execute('SELECT LATITUDE AS lat, LONGITUDE AS lon, Email as email FROM email_list WHERE POSTAL_CODE IS NULL AND CITY IS NULL AND COUNTRY IS NULL AND STATE IS NULL') rows = [] for row in results: lat, lon, email = row data = {'lat': lat, 'lon': lon, 'email': email} rows.append(data) self.conn.commit() self.conn.close() for item in rows: try: converted = self.convert_coordinates(item['lat'], item['lon']) print str(rows.index(item) + 1) + '/' + str(len(rows)) except TypeError: converted['city': ''] converted['state': ''] converted['country': ''] converted['postal_code': ''] self.conn = sqlite3.connect('data.db') c = self.conn.cursor() try: c.execute('UPDATE email_list SET CITY=?, STATE=?, COUNTRY=?, POSTAL_CODE=? WHERE Email=?', [converted['city'], converted['state'], converted['country'], converted['postal_code'], item['email']]) except KeyboardInterrupt: print 'user quit' self.conn.commit() self.conn.close() print 'converted coordinates.' def convert_coordinates(self, lat, lon): if lat and long: try: values = {'lat': lat, 'lon': lon} data = urllib.urlencode(values) request = urllib2.Request(self.WEB_SERVICE_URL, data) response = urllib2.urlopen(request) except urllib2.HTTPError as e: print 'error loading web service' print e.message json_result = json.load(response) try: city = json_result['address']['city'] except KeyError: city = '' try: state = json_result['address']['state'] except KeyError: state = '' try: cc = json_result['address']['country_code'] except KeyError: cc = '' try: postal_code = json_result['address']['postcode'] except KeyError: postal_code = '' else: city = '' state = '' cc = '' postal_code = '' return {'city': city, 'state': state, 'country': cc, 'postal_code': postal_code} def db_to_csv(self): print 'beginning write to csv...' self.conn = sqlite3.connect('data.db') c = self.conn.cursor() c.execute('SELECT * FROM email_list') with open('output.csv', 'wb') as outputFile: writer = UnicodeWriter(outputFile) writer.writerow([i[0] for i in c.description]) writer.writerows(c) print 'write finished.' self.conn.commit() self.conn.close() print 'done.' # The CSV module has issues with reading/writing unicode, # the following classes were taken from docs.python.org to # help with that: http://docs.python.org/2/library/csv.html class UTF8Recoder: """ Iterator that reads an encoded stream and reencodes the input to UTF-8 """ def __init__(self, f, encoding): self.reader = codecs.getreader(encoding)(f) def __iter__(self): return self def next(self): return self.reader.next().encode("utf-8") class UnicodeReader: """ A CSV reader which will iterate over lines in the CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): f = UTF8Recoder(f, encoding) self.reader = csv.reader(f, dialect=dialect, **kwds) def next(self): row = self.reader.next() return [unicode(s, "utf-8") for s in row] def __iter__(self): return self class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) EmailList('input.csv') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T02:52:49.393", "Id": "51753", "Score": "0", "body": "I like how you did not try to implement CSV parsing yourself." } ]
[ { "body": "<p>Two things that pop out for me immediately:</p>\n\n<ul>\n<li>You named a parameter \"file\", which is a built-in function in python.</li>\n<li>In one of your except blocks, you incorrectly use a dictionary.</li>\n</ul>\n\n<p>See below:</p>\n\n<pre><code>converted['city': '']\nconverted['state': '']\nconverted['country': '']\nconverted['postal_code': '']\n</code></pre>\n\n<p>Note, what that will do is attempt to use the slice operator on the dictionary. I just tried it now and it fails with a TypeError exception. What you want the code to look like is this:</p>\n\n<pre><code>converted['city'] = ''\nconverted['state'] = ''\nconverted['country'] = ''\nconverted['postal_code'] = ''\n</code></pre>\n\n<p>Another thing I've noticed. Dealing with dictionaries, you're not quite sure how to handle getting \"optional\" parameters from them. Have a look at the refactored code I wrote for your json dict handling:</p>\n\n<pre><code>city = json_result['address'].get('city', '')\nstate = json_result['address'].get('state', '')\ncc = json_result['address'].get('country_code', '')\npostal_code = json_result['address'].get('postcode', '')\n</code></pre>\n\n<p>The get method on dictionary objects takes an optional second parameter that specifies a default value to return if the key is not found.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T10:37:30.790", "Id": "81701", "Score": "0", "body": "I don’t think `file` is a keyword in Python. It’s still a bad variable name, but not as bad as, say, `list`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T14:11:00.413", "Id": "81737", "Score": "0", "body": "@alexwlchan Have a look here for the built-ins: https://docs.python.org/2/library/functions.html#file" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T14:12:25.167", "Id": "81739", "Score": "0", "body": "Ah, sorry, I was taking “reserved keyword” a bit too literally, and thought you meant on of the [`keyword` keywords](https://docs.python.org/2/library/keyword.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T14:30:07.713", "Id": "81742", "Score": "0", "body": "@alexwlchan Np, and thanks... I've edited the answer to clarify a little better." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:50:41.830", "Id": "35719", "ParentId": "32400", "Score": "2" } } ]
{ "AcceptedAnswerId": "35719", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T23:38:59.250", "Id": "32400", "Score": "4", "Tags": [ "python", "csv", "sqlite", "geospatial" ], "Title": "Converting latitude and longitude coordinates from CSV using web service" }
32400
<p>Example:</p> <pre><code>try { thisFunctionThrowsAnException(); } catch (someException e) { // handle this exception } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T00:41:06.770", "Id": "32403", "Score": "0", "Tags": null, "Title": null }
32403
The keywords `try` and `catch` are used for exception-handling during program execution. The `try` block contains the code in which an exception occurs. The `catch` block "catches" and handles exceptions from the `try` block.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T00:41:06.770", "Id": "32404", "Score": "0", "Tags": null, "Title": null }
32404
<p>I have the code above in my iOS SDK that I am building that makes it easy for users of the SDK to make API calls. Basically, users can specify an API endpoint and easily make API calls.</p> <p>Is there any way to improve the code above to make it more maintainable and easy for users? Is that the proper way to handle asynchronous networking in iOS?</p> <pre><code>+ (void) makeRequestToEndPoint:(NSString *) endpoint values:(NSMutableDictionary *) params onCompletion:(SDKCompletionBlock) responseHandler { NSString * urlString = [self createApiUrlFromEndpoint: endpoint]; NSURL * url = [NSURL URLWithString: urlString]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url]; request.HTTPMethod = @"POST"; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"charset" forHTTPHeaderField:@"utf-8"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; request.HTTPBody = [[params urlEncodedString] dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSDictionary * dictionary = nil; NSError * returnError = nil; NSString * errorCode = nil; NSString * errorText = nil; NSInteger newErrorCode = 0; if([data length] &gt;= 1) { dictionary = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil]; } if(dictionary != nil) { if([dictionary objectForKey: @"error_code"] != nil) { errorCode = [dictionary objectForKey: @"error_code"]; errorText = [dictionary objectForKey: @"error_description"]; } } NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; if(statusCode &gt;= 400) { if(errorCode == nil) { newErrorCode = -1; errorText = @"There was an unexpected error."; } else { newErrorCode = [errorCode intValue]; } NSMutableDictionary* details = [NSMutableDictionary dictionary]; [details setValue: errorText forKey:NSLocalizedDescriptionKey]; returnError = [NSError errorWithDomain: WPAPPErrorDomain code: newErrorCode userInfo: details]; } responseHandler(dictionary, returnError); }]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-29T08:13:16.303", "Id": "307705", "Score": "0", "body": "`NSURLConnection` is deprecated. You should use `NSURLSession` and not `NSURLConnection`. See https://developer.apple.com/videos/play/wwdc2015/711/" } ]
[ { "body": "<p>This code is nice for asynchronous web service calls. Instead of writing this method every controller of your project, I would suggest writing down this method in another class such as <code>ServerHandler</code>. This class may declare one protocol which will have 2 delegates.</p>\n\n<pre><code>(void) didReceiveResponse:(NSDictionary *)resposneDict;\n</code></pre>\n\n<p></p>\n\n<pre><code>(void) failedToReceiveResponseWithError:(NSError *)error;\n</code></pre>\n\n<p>As per you status code in your code, you can check which delegate needs to be called. Both of these delegates will be overridden in the sender controller which is requesting a web service.</p>\n\n<p>It would help you not to write down this code everywhere in your app. Making the code more modular would help as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T16:45:45.943", "Id": "100888", "Score": "2", "body": "He's not copying this code into every class. The method takes a completion block. He just imports this file wherever he needs it and calls this method, sending a completion block argument to deal with the results." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T06:29:24.190", "Id": "36683", "ParentId": "32405", "Score": "0" } }, { "body": "<pre><code>NSDictionary * dictionary = nil;\nNSError * returnError = nil;\nNSString * errorCode = nil;\nNSString * errorText = nil;\n</code></pre>\n\n<p>This is superfluous and unnecessary. It's more than fine to just declare them. They're <code>nil</code> by default.</p>\n\n<pre><code>NSDictionary *dictionary;\nNSError *returnError;\nNSString *errorCode;\nNSString *errorText;\n</code></pre>\n\n<hr>\n\n<p>You should use modern syntax for your mutable dictionaries.</p>\n\n<p>Rather than <code>[someDictionary setValue:someValue forKey:someKey];</code>, you can and should simply do:</p>\n\n<pre><code>someDictionary[someKey] = someValue;\n</code></pre>\n\n<p>And the same can be done for accessing the variable. Rather than <code>NSString *foo = [someDictionary objectForKey:someKey];</code>, you can and should simply do:</p>\n\n<pre><code>NSString *foo = someDictionary[someKey];\n</code></pre>\n\n<hr>\n\n<p>Most Objective-C programmers I know (and certainly myself included) don't particularly like <code>foo == nil</code> or <code>foo != nil</code>. We can instead use:</p>\n\n<pre><code>if (foo) // foo != nil\n</code></pre>\n\n<p>And</p>\n\n<pre><code>if (!foo) // foo == nil\n</code></pre>\n\n<hr>\n\n<p>I don't know what exactly <code>createApiUrlFromEndpoint:</code> does for you, as it's not included in the review. But I'd argue, strictly speaking, that this method (the one posted for review) should probably take an <code>NSURL</code> for the <code>endpoint</code> argument and <code>createApiUrlFromEndpoint:</code> should be a public method. If for no other reason, it could save multiple calls to <code>createApiUrlFromEndpoint:</code> if a user wants to use the same URL multiple times with a different <code>params</code> dictionary.</p>\n\n<p>Moreover, as the method is called \"create API <strong>URL</strong>\", it should return an <code>NSURL</code> object, not an <code>NSString</code> object.</p>\n\n<hr>\n\n<pre><code>if([data length] &gt;= 1)\n</code></pre>\n\n<p>I personally thing <code>&gt;=</code> and <code>&lt;=</code> are ugly and only use them when there's no alternative (or the alternative is even uglier). In this case, <code>length</code> is an unsigned integer, so <code>if([data length] &gt; 0)</code> is exactly the same... except less ugly in my opinion.</p>\n\n<hr>\n\n<p>Your method is called <code>makeRequestToEndPoint:values:onCompletion:</code></p>\n\n<p>I'm going to argue that <code>values:</code> should be changed to <code>params:</code> since that's what you're naming the the variably internally.</p>\n\n<p>I'm also going to argue that <code>onCompletion:</code> should be changed to <code>completionHandler:</code> or <code>completion:</code> so that it matches every other existing Apple method which takes a completion block as an argument.</p>\n\n<hr>\n\n<pre><code>dictionary = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];\n</code></pre>\n\n<p>You've got an <code>error</code> object. You call a method that could have an error, but you don't care at all about the possible error that could happen within this method? You should send <code>&amp;returnError</code> rather than <code>nil</code> as the last argument, and immediately follow this call with:</p>\n\n<pre><code>if (error) {\n responseHandler(dictionary,returnError);\n return;\n}\n</code></pre>\n\n<p>There's no point in continuing to execute code in the method if all the other code relies on the dictionary being initialized correctly, AND if the dictionary wasn't initialized correctly AND we're going to return some sort of an error, we should at least care about the one that goes with this method and will give a decent description of what problem occurred.</p>\n\n<hr>\n\n<p>To add to the previous point, this is all happening within a <code>completion</code> block which sends as an argument an <code>NSError</code> object. So the absolute first thing we should do before we try to initialize the dictionary is check this error object, and just as before, if it exists, call <code>responseHanlder(nil,error);</code> and <code>return</code> out of the method.</p>\n\n<hr>\n\n<p>As it stands, other than the points I made above, the code seems decent enough. For completeness however, you might implement a way of accomplishing this within the same class with the <code>delegate-protocol</code> pattern, rather than <code>completion</code> blocks.</p>\n\n<p>To do this, you'd need to create a protocol, add a delegate property (which conforms to the protocol and is a weak property), and add a instance method version of this class method--the primary difference being that the instance method doesn't take a <code>completion</code> block argument, and instead of executing a completion block, it calls the delegate methods.</p>\n\n<p>Unlike <em>Ravi D</em>'s answer, however, the delegate methods defined in your protocol need more arguments so they can send more detail.</p>\n\n<p>You could create a single method that's called regardless of whether or not there's an error:</p>\n\n<pre><code>@required - (void)fooBarObject:(FooBarObject *)fooBarObject \n didCompleteRequest:(NSDictionary *)results \n error:(NSError *)error;\n</code></pre>\n\n<p>Where the first part of the method is sending a <code>self</code> argument (similar to <code>tableView:cellForRowAtIndexPath:</code>, etc), the second argument is the results dictionary (though would be <code>nil</code> in the case of an error) and the third argument is the error (and would be <code>nil</code> when there's not an error. These leaves it up to the delegate to handle checking whether or not there was an error in this method.</p>\n\n<p>Alternatively, you can require two methods, one for success and one for failure. You're checking that in your methods, and the delegate doesn't have to do the check--simply has to implement a method for each scenario:</p>\n\n<pre><code>@required - (void)fooBarObject:(FooBarObject *)fooBarObject \n didCompleteRequest:(NSDictionary *)results;\n\n@required - (void)fooBarObject:(FooBarObject *)fooBarObject \n requestDidFail:(NSError *)error;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T23:36:34.320", "Id": "56703", "ParentId": "32405", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T00:57:41.813", "Id": "32405", "Score": "4", "Tags": [ "objective-c", "ios", "networking" ], "Title": "Asynchronous networking iOS API calls" }
32405
<p><a href="http://en.wikipedia.org/wiki/Hash_table" rel="nofollow">Hash tables (wikipedia)</a> are part of the standard libraries for many languages:</p> <ul> <li>C++: <code>std::unordered_map</code></li> <li>C# and other .net languages: <code>Dictionary</code></li> <li>Java: <code>HashMap</code>, <code>ConcurrentHashMap</code>, and others (including the rather aged <code>Hashtable</code>)</li> <li>JavaScript: "Associative Array"</li> <li>Perl: <code>%{hash}</code></li> <li>Python: "Dictionary"</li> </ul> <p>it is a relatively common exercise in computer science courses to reimplement a hash table from first principles.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T01:20:28.373", "Id": "32406", "Score": "0", "Tags": null, "Title": null }
32406
A hash table is a data structure used to implement an associative array (a structure that can map keys to values). It uses a "hash function" to compute an index into an array from which the value can be found.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T01:20:28.373", "Id": "32407", "Score": "0", "Tags": null, "Title": null }
32407
<h3>What is Boost?</h3> <p><a href="http://www.boost.org/" rel="nofollow">Boost</a> is a large collection of high-quality libraries intended for use in C++. They are free and cover a large variety of categories. Boost is often considered a "second standard library", and many C++ problems are resolved by using Boost.</p> <blockquote> <p><strong>Boost</strong> provides free peer-reviewed portable C++ source libraries.</p> <p>We emphasize libraries that work well with the C++ Standard Library. Boost libraries are intended to be widely useful, and usable across a broad spectrum of applications. The Boost license encourages both commercial and non-commercial use.<sup><a href="http://www.boost.org/" rel="nofollow">boost.org</a></sup></p> </blockquote> <h3>What can it do?</h3> <p>Boost covers every corner of programming, and continues to be improved and expanded.</p> <p>It includes libraries for:</p> <ul> <li>String and text processing</li> <li>Containers</li> <li>Iterators</li> <li>Algorithms</li> <li>Function objects and higher-order programming</li> <li>Generic Programming</li> <li>Template Metaprogramming</li> <li>Preprocessor Metaprogramming</li> <li>Concurrent Programming</li> <li>Math and numerics</li> <li>Correctness and testing</li> <li>Data structures</li> <li>Image processing</li> <li>Input/Output</li> <li>Inter-language support</li> <li>Memory</li> <li>Parsing</li> <li>Programming Interfaces</li> <li>Miscellaneous</li> <li>Broken compiler workarounds</li> </ul> <h3>How do I use it?</h3> <p>The best part about Boost is that most of its libraries are <em>header-only</em>, so there's nothing to compile or link to. Simply <a href="http://www.boost.org/users/download/" rel="nofollow">download it</a>, extract it into your favorite directory, tell your compiler where to find it, and use it!</p> <p>However, there are some libraries that need to be compiled. These libraries are generally more heavy-weight, and/or rely heavily on platform-specific functionality. The libraries that need to be compiled are:</p> <ul> <li>Date Time</li> <li>Filesystem</li> <li>Graph</li> <li>Iostreams</li> <li>Math/Special Functions*</li> <li>MPI</li> <li>Program options</li> <li>Regular Expressions</li> <li>Serialization</li> <li>Signals</li> <li>System</li> <li>Test</li> <li>Thread</li> <li>Wave</li> </ul> <p>Boost <a href="http://www.boost.org/doc/libs/1_43_0/more/getting_started/index.html" rel="nofollow">provides instructions</a> on how to do this, and the process is mostly automated. Once built, most libraries will be automatically linked, if possible.</p> <p><sub>*Only when using the C99 math functions in <code>&lt;boost/math/tr1.hpp&gt;</code></sub></p> <h3>Resources</h3> <ul> <li><a href="http://www.boost.org/" rel="nofollow">Boost Homepage</a></li> <li><a href="http://www.boost.org/doc/libs/" rel="nofollow">Boost Library Listing</a></li> <li><a href="http://www.boost.org/doc/" rel="nofollow">Boost Documentation</a></li> <li><a href="http://en.wikipedia.org/wiki/Boost_%28C++_libraries%29" rel="nofollow">Boost (C++ libraries) Wikipedia Article</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T01:27:49.430", "Id": "32408", "Score": "0", "Tags": null, "Title": null }
32408
Boost is a large collection of high-quality libraries intended for use in C++. Boost is free, and is often considered a "second standard library".
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T01:27:49.430", "Id": "32409", "Score": "0", "Tags": null, "Title": null }
32409
<p>Consider the below:</p> <pre><code>public int DoSomethingComplicated(ComplicatedObject input) { try { return input.Analyse(); } catch(CustomExceptionOne ex1) { throw; } catch(CustomExceptionTwo ex2) { Log(ex2.Message); return -1; } } </code></pre> <p>Obviously I have abstracted quite a bit for the example, but the idea is that the try block performs a task which can cause one of two types of runtime exception. </p> <p>In the event that the exception type is <code>CustomExceptionOne</code>, I want to simply throw the exception. For <code>CustomExceptionTwo</code> on the other hand, I want to log the issue but return -1.</p> <p>I do not have access to the <code>input.Analyse()</code> method in order to change it.</p> <p>This all looks fine to me, and works fine, but I get a compiler warning because <code>ex1</code> is technically never used. I don't really want to throw the entire <code>ex1</code> exception, so I am wondering how I can get this warning to go away.</p> <p>I can think of a couple of hacky ways like <code>Console.WriteLine(ex1.Message)</code> or something but that isn't a route I particularly want to go down.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T19:46:31.093", "Id": "51807", "Score": "1", "body": "You should consider logging the entire exception not just the message. Otherwise you throw away the stacktrace and it might be hard to find where it came from." } ]
[ { "body": "<p>You can refactor your code the following way:</p>\n\n<pre><code>public int DoSomethingComplicated(ComplicatedObject input)\n{\n try \n {\n return input.Analyse();\n }\n catch(CustomExceptionTwo ex2)\n {\n Log(ex2.Message);\n return -1;\n }\n}\n</code></pre>\n\n<p><code>throw;</code> re-throws the same exception, so there is no point in such catch block. </p>\n\n<p>Alternatively, you can use <code>catch(CustomExceptionOne)</code> syntax.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T08:11:56.253", "Id": "32419", "ParentId": "32418", "Score": "10" } } ]
{ "AcceptedAnswerId": "32419", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T08:06:05.437", "Id": "32418", "Score": "3", "Tags": [ "c#", "exception-handling", "exception" ], "Title": "Compiler warning on unused exception...need to improve structure?" }
32418
<p>This is part of a class for paginating a Backbone collection.</p> <p>The <code>paginateTo</code> method is for paginating to a model <code>id</code>. It returns the model if it's already in the collection, otherwise it checks with the server that it exists. If so, it requests subsequent pages until it's loaded into the collection.</p> <p>How would you refactor this method to make it clearer?</p> <pre><code>paginateTo: (id, dfd, check) -&gt; dfd ?= new $.Deferred return dfd.resolve(model) if model = @get(id) check ?= @checkModelExists(id) check.done =&gt; @once 'sync', =&gt; @paginateTo(id, dfd, check) @fetchNextPage() check.fail =&gt; dfd.reject() dfd.promise() checkModelExists: (id) -&gt; url = @url() + '/' + id $.get url fetchNextPage: -&gt; @page += 1 @fetch { update: true, remove: false, data: { page: @page }} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T04:16:52.063", "Id": "52057", "Score": "0", "body": "What you you find complicated about it or what do you dislike about this code? The only thing I really dislike is that the internals of the `paginateTo` function are indirectly exposed via the function's signature, which also breaks encapsulation. You should perhaps use an IIFE to declare a private method to be called recursively instead." } ]
[ { "body": "<p>You could do something like this</p>\n\n<pre><code>paginateTo: (id) -&gt;\n deferred = new $.Deferred\n modelCheck = null\n\n modelExists = =&gt;\n modelCheck or= @checkModelExists id\n\n fetchUntilFound = =&gt;\n return deferred.resolve model if model = @get id\n modelExists().fail deferred.reject\n modelExists().done =&gt;\n @fetchNextPage().then fetchUntilFound, deferred.reject\n\n fetchUntilFound()\n deferred.promise()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T13:24:19.867", "Id": "33790", "ParentId": "32423", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T13:30:34.533", "Id": "32423", "Score": "3", "Tags": [ "javascript", "jquery", "coffeescript", "backbone.js", "pagination" ], "Title": "Paginating a Backbone collection" }
32423
<p>This time I'm not here to ask for help with my code, but to ask you to judge my code. Where can I improve? What should I do better? Where did I do things wrong? </p> <p>This is a quiz that I had to do as an assignment today. I'm not a professional. I'm still studying, and at the moment, I'm doing an internship.</p> <pre><code>&lt;? session_start(); ?&gt; &lt;html&gt; &lt;head&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;!--&lt;script type="text/javascript" src="quiz.js" /&gt; --&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="domande"&gt; &lt;p&gt;Sei ...? &lt;/p&gt; &lt;div class="option" value="yes" name="domanda0"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt; &lt;div class="option" value="no" name="domanda0"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="domande"&gt; &lt;p&gt;Sai ...?&lt;/p&gt; &lt;div class="option" value="yes" name="domanda1"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt; &lt;div class="option" value="no" name="domanda1"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="domande"&gt; &lt;p&gt;Ricerchi...?&lt;/p&gt; &lt;div class="option" value="yes" name="domanda1_1"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt; &lt;div class="option" value="no" name="domanda1_1"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="domande"&gt; &lt;p&gt;Finita la spesa, tieni sempre gli scontrini?&lt;/p&gt; &lt;div class="option" value="yes" name="domanda1_2"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt; &lt;div class="option" value="no" name="domanda1_2"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- domanda 2 --&gt; &lt;div class="domande"&gt; &lt;p&gt;Hai già pensato ..?&lt;/p&gt; &lt;div class="option" value="yes" name="domanda2"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt; &lt;div class="option" value="no" name="domanda2"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="domande"&gt; &lt;p&gt;Cerchi di...?&lt;/p&gt; &lt;div class="option" value="yes" name="domanda2_1"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt; &lt;div class="option" value="no" name="domanda2_1"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="domande"&gt; &lt;p&gt;La tua ...?&lt;/p&gt; &lt;div class="option" value="yes" name="domanda2_2"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt; &lt;div class="option" value="no" name="domanda2_2"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;script&gt; var risposte = new Object(); var $domande = $('.domande'); $domande.hide(); var totDomande = $('.domande').size(); var domandaOn = 0; var risultato = ""; var countRisposte = 0; $($domande.get(domandaOn)).fadeIn(); console.log(domandaOn); $('.option').click(function(){ countRisposte = countRisposte+1; console.log(countRisposte); var risposta = ($(this).attr('value')); var domanda = ($(this).attr('name')); if(risposta == "yes"){ risultato += "1"; } if(risposta == "no"){ risultato += "0"; } $($domande.get(domandaOn)).fadeOut(function(){ if(domandaOn == 0){ if(risposta == "yes"){ domandaOn = 4; }else if(risposta == "no"){ domandaOn = 1; } } if((domandaOn == 4 || domandaOn == 1) &amp;&amp; countRisposte &gt;1){ if(risposta == "yes"){ domandaOn = domandaOn+2; }else{ domandaOn = domandaOn+1; } } if((domandaOn == 2 || domandaOn == 5) &amp;&amp; countRisposte &lt;3){ domandaOn = domandaOn+1; } if((domandaOn == 3 || domandaOn == 6) &amp;&amp; countRisposte &gt; 2){ console.log(domandaOn); var resFinale = ""; console.log("risultato into 6: " +risultato); switch (risultato) { case "000": resFinale = "result1"; break; case "001": resFinale = "result2"; break; case "010": resFinale = "result3"; break; case "011": resFinale = "result4"; break; case "100": resFinale = "result5"; break; case "101": resFinale = "result6"; break; case "110": resFinale = "result7"; break; case "111": resFinale = "result8"; break; } console.log(resFinale); alert("risultato : "+resFinale); }else{ $($domande.get(domandaOn)).fadeIn(); } }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:02:29.007", "Id": "51793", "Score": "7", "body": "Uh, well english variable names would be a good start. You won't see me (german) writing code like `gericht.beilage(new Sauerkraut()); gericht.beilage(new Knödel()); if (!achtung) alert(\"Es gibt \" + gericht.bezeichnung);`. In other words, I have no idea *what* your code is supposed to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T06:08:47.677", "Id": "51833", "Score": "1", "body": "I'm Italian but I **never** use Italian names for variables. It makes harder to share code. Next time either ask help on an Italian forum, or write in English. I'd also suggest to avoid Italian in the strings. There are tools such as `gettext` et similia to deal with i18n and l10n." } ]
[ { "body": "<p>You should get into the habit of using English variable names and identifiers. English is the de facto standard language of programming and in most environments there will be people from different nationalities working with the code, and everyone must understand what the names mean. (There's always <em>someone</em> who looks at the code who doesn't understand Italian, if no-one else then people you ask help from on Stack Overflow...)</p>\n\n<pre><code>var risposte = new Object();\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/5513376/502381\">You should use <code>{}</code> instead of <code>new Object()</code></a>.</p>\n\n<pre><code>var totDomande = $('.domande').size();\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/size/\" rel=\"nofollow noreferrer\"><code>.size()</code> is deprecated</a>, you should use <code>.length</code> instead.</p>\n\n<pre><code>$($domande.get(domandaOn)).fadeIn();\n</code></pre>\n\n<p>It would be cleaner to use <code>$domande.eq( domandaOn ).fadeIn()</code> which does the same thing, although you can just reduce that to <code>$domande.eq( 0 ).fadeIn()</code> or <code>$domande.first().fadeIn()</code> since the value of <code>domandaOn</code> is guaranteed to be <code>0</code> at that point.</p>\n\n<pre><code>countRisposte = countRisposte+1;\n</code></pre>\n\n<p>Incrementing by one is usually done with <code>countRisposte++;</code></p>\n\n<pre><code>var risposta = ($(this).attr('value'));\nvar domanda = ($(this).attr('name'));\n</code></pre>\n\n<p>The outer parentheses are unnecessary here.</p>\n\n<pre><code>if(risposta == \"yes\"){\n risultato += \"1\";\n}\nif(risposta == \"no\"){\n risultato += \"0\";\n}\n</code></pre>\n\n<p>I see you're building a kind of binary string from the answers; this kinda works when you have very few questions like the three here, but it's not very flexible or maintainable. You might want to consider storing the answers in an object, along with the questionnaire logic, but going into details might be beyond the scope of this answer (perhaps someone else can come up with something).</p>\n\n<p>It's also a good habit to use strict comparison (<code>===</code>) when the type of the variable is known, e.g. <code>if(risposta === \"yes\"){</code>.</p>\n\n<pre><code>if((domandaOn == 4 || domandaOn == 1) &amp;&amp; countRisposte &gt;1){\n</code></pre>\n\n<p>You could shorten that to <code>if( domandaOn % 3 === 1 &amp;&amp; countRisposte &gt; 1 )</code> although it might sacrifice legibility (the modulo operator evaluates to the remainder after dividing by 3).</p>\n\n<p>I'm not sure why the <code>countRisposte</code> checks are necessary since there doesn't seem to be other than one path through the questionnaire, and the binary-string-mechanism would break if there are more than three answers.</p>\n\n<pre><code>switch (risultato)\n{\ncase \"000\":\n resFinale = \"result1\";\n break;\ncase \"001\":\n ...\n</code></pre>\n\n<p>Instead of this big switch you could save the results in an object:</p>\n\n<pre><code>var results = {\n \"000\": \"result1\",\n \"001\": \"result2\",\n \"010\": \"result3\",\n // ...and so on\n};\n\nresFinale = results[ risultato ];\n</code></pre>\n\n<p>(I'm assuming there will be some actual text there instead of just \"resultX\".)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:20:12.267", "Id": "51795", "Score": "4", "body": "While the use of English in identifiers is often a practical choice, you should remember that the vast majority of people on Earth do not understand English, or understand it very little. There are large communities of programmers that use their own language. Besides, using any other language but English makes it more obvious which words are reserved words or predefined or library names as opposite to identifiers chosen by the programmer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T19:00:17.860", "Id": "51804", "Score": "5", "body": "I'm French-speaking and it KILLS me when I see identifiers in French in someone else's code I have to maintain. Having them in English blends with the language and makes a coherent whole, as opposed to a soup of mixed-up languages. I maintain a code base with mixed English, French and Spanish and it's a nightmare. +1 for keeping the code sane and readable, and for an excellent code review that doesn't deserve a downvote just for the first couple words." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T23:09:24.837", "Id": "51816", "Score": "3", "body": "Once upon a time, I used to mix Portuguese, Spanish and English on my code. Surely enough: *\"um, what was that var name again? Was it a Z or a S or a double S?\"*. . . Sidenote, people who don't speak English doesn't use [codereview.se] - @JukkaK.Korpela" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:13:18.673", "Id": "32427", "ParentId": "32425", "Score": "4" } }, { "body": "<p>By looking at the code, it is not obvious at all what the code is supposed to <em>do</em> (and I do understand Italian sufficiently to undertand the texts and names). You should explain the purpose and logic in prose, or in comments, or both. Primarily, the HTML markup should make it more apparent what is going on, using headings (with appropriate markup), descriptive labels, and other structural elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:27:16.727", "Id": "32428", "ParentId": "32425", "Score": "3" } }, { "body": "<p>For your convenience, here's a <a href=\"http://jsfiddle.net/cTnmN/\">jsFiddle of your original code</a>.</p>\n\n<h1>User Experience</h1>\n\n<p>The user cannot easily amend an accidentally incorrect response, because the question fades away as soon as one clicks \"YES\" or \"NO\". Usually, such user-unfriendliness is not desirable.</p>\n\n<h1>Language</h1>\n\n<p>I'm personally fine with you coding in Italian. However, I find this flavour of inglesiano disturbing. For example, <code>countRisposte</code>, <code>domandaOn</code>, <code>resFinale</code> are all weird mixtures of languages. Another programmer maintaining code like that would be likely to make a spelling mistake because of such odd words.</p>\n\n<h1>PHP</h1>\n\n<p>You called <code>session_start()</code>, so it looks like you are using PHP. In that case, why not also use PHP to render your questions with less redundancy?</p>\n\n<pre><code>&lt;?php\n $domande = array(\n 'domanda0' =&gt; \"Sei ...?\",\n 'domanda1' =&gt; \"Sai ...?\",\n 'domanda1_1' =&gt; \"Ricerchi...?\",\n 'domanda1_2' =&gt; \"Finita la spesa, tieni sempre gli scontrini?\",\n 'domanda2' =&gt; \"Hai già pensato ..?\",\n 'domanda2_1' =&gt; \"Cerchi di...?\",\n 'domanda2_2' =&gt; \"La tua ...?\",\n );\n\n foreach ($domande as $nome =&gt; $domanda) {\n?&gt;\n &lt;div class=\"domande\" id=\"&lt;?php echo $nome ?&gt;\"&gt;\n &lt;p&gt;&lt;?php echo htmlspecialchars($domanda); ?&gt;&lt;/p&gt;\n &lt;div class=\"option\" name=\"&lt;?php echo $nome; ?&gt;\" value=\"yes\"&gt;&lt;button&gt;YES&lt;/button&gt;&lt;/div&gt;\n &lt;div class=\"option\" name=\"&lt;?php echo $nome; ?&gt;\" value=\"no\"&gt;&lt;button&gt;NO&lt;/button&gt;&lt;/div&gt;\n &lt;/div&gt;\n&lt;?php\n }\n?&gt;\n</code></pre>\n\n<p>Also, always use PHP long tags (<code>&lt;?php ... ?&gt;</code>); short tags (<code>&lt;? ... ?&gt;</code>) are officially <a href=\"http://php.net/manual/en/language.basic-syntax.phptags.php\">discouraged</a> in the PHP manual.</p>\n\n<p>Note that I added the <code>id</code> attribute to the outer <code>&lt;div&gt;</code>. I'll use that later in the solution below.</p>\n\n<h1>JavaScript inclusion</h1>\n\n<p>If you omit the <code>http:</code> from the URL, like this:</p>\n\n<pre><code>&lt;script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>then your page will work equally well whether it is served using HTTP or HTTPS.</p>\n\n<h1>Calculation of <code>risultato</code> and <code>resFinale</code></h1>\n\n<p>The way you assemble <code>risultato</code></p>\n\n<pre><code>if (risposta == \"yes\") { risultato += \"1\"; }\nif (risposta == \"no\") { risultato += \"0\"; }\n</code></pre>\n\n<p>… seems rather fragile to me, because you would only arrive at the correct result if those statements are executed in the expected sequence.</p>\n\n<p>You use a long <code>switch</code> block to convert <code>risultato</code> to <code>resFinale</code>. It might be clearer and shorter as:</p>\n\n<pre><code>// Map risultato to resFinale.\n// risultato = \"000\" -&gt; resFinale = \"result1\"\n// risultato = \"001\" -&gt; resFinale = \"result2\"\n// (etc.)\n// risultato = \"111\" -&gt; resFinale = \"result8\"\nif (/^[01][01][01]$/.test(risultato)) {\n resFinale = 'result' + (1 + parseInt(risultato, 2));\n}\n</code></pre>\n\n<p>… but see the solution below for an even better approach.</p>\n\n<h1>Question Dependencies</h1>\n\n<p>The code related to <code>domandaOn</code> is very hard to follow. The magic values you use for <code>domandaOn</code> don't correspond to the <code>name</code>s of the questions, but to their index in the DOM. The whole mechanism is fragile. (Have fun modifying the code if you ever need to insert or remove questions!)</p>\n\n<p>What is particularly bad is that your if-blocks are not mutually exclusive. For example, if <code>domandaOn == 4</code> and <code>risposta == 'no'</code> (i.e., you answer \"NO\" to \"Hai già pensato ..?\", also known as \"domanda2\"), you first assign <code>domandaOn = domandaOn+1</code>, which cascades to <em>another</em> assignment <code>domandaOn = domandaOn+1</code> because <code>domandaOn == 5</code> and <code>countRisposte == 2</code>. I'm pretty sure it's a bug, because your \"Ricerchi...?\" and \"Cerchi di...?\" questions are unreachable. In any case, it's nasty code that should be rethought rather than fixed.</p>\n\n<h1>Usage of variables</h1>\n\n<p>You never use <code>risposte</code> and <code>totDomande</code>.</p>\n\n<p>The outer parentheses are superfluous:</p>\n\n<pre><code>var risposta = ($(this).attr('value'));\nvar domanda = ($(this).attr('name'));\n</code></pre>\n\n<p>Interestingly, while you use <code>risposta</code>, you never use <code>domanda</code>. The code could be a lot more robust and understandable if you used <code>domanda</code>.</p>\n\n<h1>Solution</h1>\n\n<p>Putting all these ideas together and more, I would write the JavaScript code this way:</p>\n\n<pre><code>// Answers to each question add these values to resFinale\nvar valore = {\n 'domanda0' : { no: 0, yes: 4 },\n 'domanda1' : { no: 0, yes: 2 },\n 'domanda1_1' : { no: 0, yes: 1 },\n 'domanda1_2' : { no: 0, yes: 1 },\n 'domanda2' : { no: 0, yes: 2 },\n 'domanda2_1' : { no: 0, yes: 1 },\n 'domanda2_2' : { no: 0, yes: 1 },\n};\n\n// The next question to present after each response\nvar FINE = null;\nvar domandeSeguenti = {\n 'domanda0' : { no: 'domanda1', yes: 'domanda2' },\n 'domanda1' : { no: 'domanda1_1', yes: 'domanda1_2' },\n 'domanda1_1' : { no: FINE, yes: FINE },\n 'domanda1_2' : { no: FINE, yes: FINE },\n 'domanda2' : { no: 'domanda2_1', yes: 'domanda2_2' },\n 'domanda2_1' : { no: FINE, yes: FINE },\n 'domanda2_2' : { no: FINE, yes: FINE },\n};\n\n// Show just the first question\n$('.domande').hide();\n$('#domanda0').fadeIn();\n\nvar risultato = 1;\n\n$('.option').click(function(){\n var risposta = $(this).attr('value');\n var domanda = $(this).attr('name');\n\n risultato += valore[domanda][risposta];\n\n $('#' + domanda).fadeOut(function(){\n var domandaSeguente = domandeSeguenti[domanda][risposta];\n if (domandaSeguente == FINE) {\n var resFinale = 'result' + risultato;\n alert(\"risultato : \" + resFinale);\n } else {\n $('#' + domandaSeguente).fadeIn();\n }\n });\n\n});\n</code></pre>\n\n<p>I've fixed your unreachable-questions bug in the way I think you intended, so it does not behave like the original. Here's a <a href=\"http://jsfiddle.net/4ALdJ/3/\">jsFiddle of my solution</a>.</p>\n\n<p>I would go one step further and rename <code>domanda0</code>, <code>domanda1</code>, etc. to something more descriptive, but I have refrained from doing so in this solution because it would be hard to compare it against the original code.</p>\n\n<h1>Summary</h1>\n\n<p>The code is complex, and needs to be simplified. Instead of hard-coding all the logic, you want to generalize, such that the application is <strong>data-driven</strong>. That way, the questionnaire is largely defined by the data structures, and the code is elegant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T09:28:28.723", "Id": "51841", "Score": "0", "body": "Thanks so much. The main problem i've is to structure the logic before start programming. I coded the thing you read above without structuring the flow before. Today i made some changes before reading your answer but your code is of course better. I appreciate what you did for me. Thanks a lot! I hope to do better next time :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T22:40:45.247", "Id": "32436", "ParentId": "32425", "Score": "18" } } ]
{ "AcceptedAnswerId": "32436", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T16:13:17.353", "Id": "32425", "Score": "7", "Tags": [ "javascript", "jquery", "html" ], "Title": "What do you think about my questionnaire?" }
32425
<p>I'm looking for some general feedback about the layout and structure of my code. Basically just any feedback, as I'm not super happy about this code, but I'm not sure how to improve it further.</p> <pre><code>'use strict'; /* jshint node: true */ var fs = require('fs'); var os = require('os'); var nodemailer = require('nodemailer'); var rimraf = require('rimraf'); var config = require('../config'); var dropbox = require('../lib/dropbox-sync'); var mysql = require('../lib/mysql-backup'); var tarball = require('../lib/tarball'); var transport = nodemailer.createTransport('sendmail'); // This is the FILE name of the backup file var backupFilename = config.dropbox.mysql_prefix + 'backup-' + Date.now(); // This is the absolute file path to save the file to on Dropbox var dropboxFilename = ['', config.server, config.dropbox.mysql_folder, backupFilename].join('/'); // Connect to Dropbox with our credentials try { dropbox.connect({ key: config.dropbox.key, secret: config.dropbox.secret }); } catch (err) { failWithDropboxError(err); } // Connect to MySQL with our credentials try { mysql.connect({ host: config.mysql.hostname, user: config.mysql.username, password: config.mysql.password }); } catch (err) { failWithMySQLError(err); } // Generate a MYSQL backup mysql.backup(backupFilename, function (err, pathname, stats) { if (err) { return failWithMySQLError(err); } tarball.create(pathname, '/tmp/' + backupFilename + '.tar.gz', function (code) { rimraf.sync(pathname); dropbox.send('/tmp/' + backupFilename + '.tar.gz', dropboxFilename, function (err, response) { fs.unlinkSync('/tmp/' + backupFilename + '.tar.gz'); if (err) { failWithDropboxError(err); } else { console.log(response); console.log('The MySQL backup has been completed successfully.\n'); console.log('Backed up %d from %d databases.\n', stats.tables, stats.databases); console.log('The backup file has been saved to your Dropbox: %s', ''); } }); }); }); function failWithMySQLError (err) { console.error('The MySQL backup job has encountered a fatal error and could not continue.\n'); console.error('We were unable to create the MySQL backup.\n'); console.error(err); process.exit(1); }; function failWithDropboxError (err) { console.error('The MySQL backup job has encountered a fatal error and could not continue.\n'); console.error('We were unable to sync the MySQL backup to Dropbox.\n') console.error(err); process.exit(1); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T18:51:41.833", "Id": "51803", "Score": "0", "body": "What are you not happy about? This code looks good enough." } ]
[ { "body": "<p>You code looks good and well formatted. There are only a few minor issues:</p>\n\n<ul>\n<li>It seems that you have tried to check it with JSHint but there are some issues that JSHint reports about your code. In particular, semicolons and unused variables.</li>\n<li>It is not clear when the character \"\\n\" is required in messages, and when it is not. It looks like sometimes you just forgot it.</li>\n<li><p>This one looks inconsistent. It looks like there is an error:</p>\n\n<pre><code>console.log('The backup file has been saved to your Dropbox: %s', '');\n</code></pre></li>\n<li><p>This actually a bad pattern:</p>\n\n<pre><code>if (err) {\n return failWithMySQLError(err);\n}\n</code></pre>\n\n<p>it shortens a code a little but adds impression that the value of the function is important, while it is not.</p></li>\n<li><p>else is redundant here:</p>\n\n<pre><code>if (err) {\n failWithDropboxError(err);\n} else {\n</code></pre></li>\n<li>and as you see, the long lines complicate the code review.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T16:58:03.363", "Id": "33409", "ParentId": "32430", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T18:39:56.623", "Id": "32430", "Score": "2", "Tags": [ "javascript", "node.js" ], "Title": "Node.js backup cron job" }
32430
<p>In my game, there is a terrain generator subsequently resulting in many instances.</p> <p>I have implemented this code:</p> <pre><code>for b in blocklist: if b.rect.left&gt;=0: if b.rect.right&lt;=640: screen.blit(b.sprite, b.rect) </code></pre> <p>It only renders things within the screen (400-500 blocks), but it still runs as if it were rendering all 2000 or so.</p> <p>Why is it so slow? Does it have anything to do with <code>pygame.display.update()</code> or <code>pygame.display.flip()</code>? Is there even a difference?</p> <p>Here is the entire code:</p> <pre><code>#Init stuff import pygame,random from pygame.locals import * from collections import namedtuple import time, string pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=500) f=open('texdir.txt','r') texdir=f.read() f.close() f=open(texdir+"\\splash.txt",'r') splash=f.read() splash=splash.replace('(','') splash=splash.replace(')','') splash=splash.split(',') f.close() splashlen=len(splash) chc=random.randint(0,int(splashlen)) splash=splash[chc-1] f=open(texdir+"//backcolor.txt") pygame.init() clock=pygame.time.Clock() screen=pygame.display.set_mode((640,480)) pygame.display.set_caption("PiBlocks | By Sam Tubb") max_gravity = 100 blocksel=texdir+"\\dirt.png" btype='block' backimg = pygame.image.load(texdir+"\\menu.png").convert() backimg = pygame.transform.scale(backimg, (640,480)) clsimg = pygame.image.load("clear.bmp").convert() clsimg = pygame.transform.scale(clsimg, (640,480)) ingame=0 sbtn=pygame.image.load("startbtn.png").convert() qbtn=pygame.image.load("quitbtn.png").convert() tbtn=pygame.image.load("texbtn.png").convert() sbtnrect=sbtn.get_rect() sbtnrect.x=220 sbtnrect.y=190 qbtnrect=qbtn.get_rect() qbtnrect.x=220 qbtnrect.y=225 tbtnrect=tbtn.get_rect() tbtnrect.x=220 tbtnrect.y=260 go=0 gotime=35 select=1 colliding = False Move = namedtuple('Move', ['up', 'left', 'right']) player=[] blocklist=[] font=pygame.font.Font(None,18) #set cursor curs = pygame.image.load(texdir+"\\cursor.png").convert() curs.set_colorkey((0,255,0)) #set backcolor COLOR=f.read() f.close() COLOR=COLOR.replace('(','') COLOR=COLOR.replace(')','') COLOR=COLOR.split(',') c1=COLOR[0] c2=COLOR[1] c3=COLOR[2] #load sounds place=pygame.mixer.Sound('sound\\place.wav') place2=pygame.mixer.Sound('sound\\place2.wav') place3=pygame.mixer.Sound('sound\\place3.wav') #set sprites and animation frames psprite = pygame.image.load(texdir+"\\player\\playr.png").convert() psprite.set_colorkey((0,255,0)) psprite2 = pygame.image.load(texdir+"\\player\\playr2.png").convert() psprite2.set_colorkey((0,255,0)) psprite3 = pygame.image.load(texdir+"\\player\\playr3.png").convert() psprite3.set_colorkey((0,255,0)) anim=1 class Block(object): def __init__(self,x,y,sprite,btype): if blocksel==texdir+"\\woodslab.png": self.btype='slab' self.sprite = pygame.image.load(sprite).convert() self.rect = self.sprite.get_rect(top=y+16, left=x) else: self.btype='block' self.sprite = pygame.image.load(sprite).convert_alpha() self.rect = self.sprite.get_rect(top=y, left=x) class Player(object): sprite=psprite def __init__(self, x, y): self.rect = self.sprite.get_rect(centery=y, centerx=x) # indicates that we are standing on the ground # and thus are "allowed" to jump self.on_ground = True self.xvel = 0 self.yvel = 0 self.jump_speed = 7 self.move_speed = 3 def update(self, move, blocks): # check if we can jump if move.up and self.on_ground: self.yvel -= self.jump_speed # simple left/right movement if move.left: self.xvel = -self.move_speed if move.right: self.xvel = self.move_speed # if in the air, fall down if not self.on_ground: self.yvel += 0.3 # but not too fast if self.yvel &gt; max_gravity: self.yvel = max_gravity # if no left/right movement, x speed is 0, of course if not (move.left or move.right): self.xvel = 0 # move horizontal, and check for horizontal collisions self.rect.left += self.xvel self.collide(self.xvel, 0, blocks) # move vertically, and check for vertical collisions self.rect.top += self.yvel self.on_ground = False; self.collide(0, self.yvel, blocks) def collide(self, xvel, yvel, blocks): # all blocks that we collide with for block in [blocks[i] for i in self.rect.collidelistall(blocks)]: # if xvel is &gt; 0, we know our right side bumped # into the left side of a block etc. if xvel &gt; 0: self.rect.right = block.rect.left if xvel &lt; 0: self.rect.left = block.rect.right # if yvel &gt; 0, we are falling, so if a collision happpens # we know we hit the ground (remember, we seperated checking for # horizontal and vertical collision, so if yvel != 0, xvel is 0) if yvel &gt; 0: self.rect.bottom = block.rect.top self.on_ground = True self.yvel = 0 # if yvel &lt; 0 and a collision occurs, we bumped our head # on a block above us if yvel &lt; 0: self.rect.top = block.rect.bottom def get_key(): while 1: event = pygame.event.poll() if event.type == KEYDOWN: return event.key else: pass def display_box(screen, message): "Print a message in a box in the middle of the screen" fontobject = pygame.font.Font(None,18) pygame.draw.rect(screen, (0,0,0), ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10, 200,20), 0) pygame.draw.rect(screen, (255,255,255), ((screen.get_width() / 2) - 102, (screen.get_height() / 2) - 12, 204,24), 1) if len(message) != 0: screen.blit(fontobject.render(message, 1, (255,255,255)), ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10)) pygame.display.flip() def ask(screen, question): "ask(screen, question) -&gt; answer" pygame.font.init() current_string = [] display_box(screen, question + ": " + string.join(current_string,"")) while 1: inkey = get_key() if inkey == K_BACKSPACE: current_string = current_string[0:-1] elif inkey == K_RETURN: break elif inkey == K_MINUS: current_string.append("_") elif inkey &lt;= 127: current_string.append(chr(inkey)) display_box(screen, question + ": " + string.join(current_string,"")) return string.join(current_string,"") while True: for block in blocklist: if any(block.rect.colliderect(b.rect) for b in blocklist if b is not block): if b.btype=='slab': blocklist.remove(block) else: blocklist.remove(b) if ingame==1: screen.fill((int(c1),int(c2),int(c3))) mse = pygame.mouse.get_pos() key = pygame.key.get_pressed() if key[K_a]: anim+=1 if anim==9: anim=1 if key[K_d]: anim+=1 if anim==9: anim=1 if key[K_1]: blocksel=texdir+"\\dirt.png" btype='block' select=1 if key[K_2]: blocksel=texdir+"\\stonetile.png" btype='block' select=2 if key[K_3]: blocksel=texdir+"\\stone.png" btype='block' select=3 if key[K_4]: blocksel=texdir+"\\sand.png" btype='block' select=4 if key[K_5]: blocksel=texdir+"\\woodplank.png" btype='block' select=5 if key[K_6]: blocksel=texdir+"\\woodslab.png" btype='slab' select=6 if key[K_LEFT]: try: for b in blocklist: b.rect.left+=32 except: pass try: player.rect.left+=32 except: pass if key[K_RIGHT]: try: for b in blocklist: b.rect.left-=32 except: pass try: player.rect.left-=32 except: pass if key[K_UP]: try: for b in blocklist: b.rect.top+=32 except: pass try: player.rect.top+=32 except: pass if key[K_DOWN]: try: for b in blocklist: b.rect.top-=32 except: pass try: player.rect.top-=32 except: pass if key[K_ESCAPE]: execfile('PiBlocks.pyw') for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == MOUSEBUTTONDOWN: if event.button==4: if select&lt;9: select=select+1 else: select=1 elif event.button==5: if select&gt;1: select=select-1 else: select=9 if select==1: blocksel=texdir+"\\dirt.png" btype='block' if select==2: blocksel=texdir+"\\stonetile.png" btype='block' if select==3: blocksel=texdir+"\\stone.png" btype='block' if select==4: blocksel=texdir+"\\sand.png" btype='block' if select==5: blocksel=texdir+"\\woodplank.png" btype='block' if select==6: blocksel=texdir+"\\woodslab.png" btype='slab' if key[K_LSHIFT]: if event.type==MOUSEMOTION: if not any(block.rect.collidepoint(mse) for block in blocklist): snd=random.randint(1,3) x=(int(mse[0]) / 32)*32 y=(int(mse[1]) / 32)*32 if go==1: if snd==1: place.play() elif snd==2: place2.play() elif snd==3: place3.play() blocklist.append(Block(x,y,blocksel,btype)) if key[K_RSHIFT]: if event.type==MOUSEMOTION: to_remove = [b for b in blocklist if b.rect.collidepoint(mse)] for b in to_remove: if go==1: blocklist.remove(b) else: if event.type == pygame.MOUSEBUTTONUP: if event.button == 1: to_remove = [b for b in blocklist if b.rect.collidepoint(mse)] for b in to_remove: if go==1: blocklist.remove(b) if not to_remove: snd=random.randint(1,3) x=(int(mse[0]) / 32)*32 y=(int(mse[1]) / 32)*32 if go==1: if snd==1: place.play() elif snd==2: place2.play() elif snd==3: place3.play() blocklist.append(Block(x,y,blocksel,btype)) elif event.button == 3: x=(int(mse[0]) / 32)*32 y=(int(mse[1]) / 32)*32 player=Player(x+16,y+16) move = Move(key[K_w], key[K_a], key[K_d]) for b in blocklist: if b.rect.left&gt;=0: if b.rect.right&lt;=640: screen.blit(b.sprite, b.rect) if player: player.update(move, blocklist) if anim==1 or anim==2 or anim==3: screen.blit(psprite, player.rect) elif anim==4 or anim==5 or anim==6: screen.blit(psprite2, player.rect) elif anim==7 or anim==8 or anim==9: screen.blit(psprite3, player.rect) x=(int(mse[0]) / 32)*32 y=(int(mse[1]) / 32)*32 screen.blit(curs,(x,y)) clock.tick(60) x=blocksel.replace(texdir,'') x=x.replace('.png','') vers=font.render('PiBlocks Alpha 0.6',True,(255,255,255)) tex=font.render('Selected Texture Pack: '+texdir,True,(255,255,255)) words=font.render('Selected Block: '+str(x), True, (255,255,255)) screen.blit(vers,(1,1)) screen.blit(tex,(1,12)) screen.blit(words,(1,25)) if gotime==0: go=1 else: gotime-=1 pygame.display.update() elif ingame==0: blocklist=[] mse = pygame.mouse.get_pos() player=[] key = pygame.key.get_pressed() text=font.render(splash, True, (255,255,255)) if key[K_RETURN]: ingame=1 for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: print event.key if sbtnrect.collidepoint(mse): if pygame.mouse.get_pressed()==(1,0,0): ingame='gen' top=(random.randint(5,8)*32) cen=(top+random.randint(4,6)*32) down=15 across=0 blklvl=0 while across&lt;640: while down&gt;0: screen.fill((0,0,0)) if blklvl==top: blocklist.append(Block(across,blklvl,texdir+"\\grass.png",'block')) if blklvl&gt;top: if blklvl&lt;cen: blocklist.append(Block(across,blklvl,texdir+"\\dirt.png",'block')) if blklvl&gt;cen-1: blocklist.append(Block(across,blklvl,texdir+"\\stone.png",'block')) down=down-1 blklvl=blklvl+32 if down==0: if across&lt;1920: per=(across/(32/5)) if per&gt;100: per=100 top=(random.randint(5,8)*32) cen=(top+random.randint(4,6)*32) down=15 blklvl=0 across=across+32 down=15 drawgen=font.render('GENERATION:'+str(per)+'%%', True, (255,255,255)) screen.blit(drawgen,(1,1)) pygame.display.flip() go=0 ingame=1 if qbtnrect.collidepoint(mse): if pygame.mouse.get_pressed()==(1,0,0): exit() if tbtnrect.collidepoint(mse): if pygame.mouse.get_pressed()==(1,0,0): ingame='texsel' screen.blit(backimg,(0,0)) screen.blit(text,(364,76)) screen.blit(sbtn,sbtnrect) screen.blit(qbtn,qbtnrect) screen.blit(tbtn,tbtnrect) pygame.display.flip() elif ingame=='texsel': screen.blit(clsimg,(0,0)) inp = ask(screen, 'Texture Directory') f=open('texdir.txt','w') f.write(str(inp)) f.close() pygame.display.flip() execfile('PiBlocks.pyw') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T01:43:02.367", "Id": "51818", "Score": "0", "body": "Just changed the code to make it load each sprite one time, but it still runs quite slow!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T03:16:35.570", "Id": "51828", "Score": "1", "body": "First thoughts: that's a lot of global variables, this should probably be split up into multiple files, and the indentation appears to be inconsistent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T10:36:44.513", "Id": "51845", "Score": "0", "body": "Do you mean multiple .py files?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T18:51:15.847", "Id": "52104", "Score": "1", "body": "Yes. You may be able to split it up into multiple `.py` files and have them import each-other as modules." } ]
[ { "body": "<p>First of all, a lot of people who would answer this question will not do so because you can't just copy/paste the code and run it. The code depends on a lot of external files, like images and textfiles, and to run your code, you basically have to trial'n'error your way while creating a bunch of placeholder images...</p>\n\n<hr>\n\n<p>I'll try to read your code and comment it step by step.</p>\n\n<pre><code>f=open('texdir.txt','r')\ntexdir=f.read()\nf.close()\nf=open(texdir+\"\\\\splash.txt\",'r')\nsplash=f.read()\nsplash=splash.replace('(','')\nsplash=splash.replace(')','')\nsplash=splash.split(',')\nf.close()\n...\nf=open(texdir+\"//backcolor.txt\") \n</code></pre>\n\n<p>Here you read some settings/configurations. Better use the <a href=\"http://docs.python.org/2/library/configparser.html\"><code>ConfigParser</code></a> module. It will make your code more readable and more easily to follow.</p>\n\n<hr>\n\n<pre><code>splashlen=len(splash)\nchc=random.randint(0,int(splashlen))\nsplash=splash[chc-1]\n</code></pre>\n\n<p>To select a random element from as list, you can just use <code>random.choice</code>.</p>\n\n<hr>\n\n<pre><code>f=open(texdir+\"//backcolor.txt\")\n...\nblocksel=texdir+\"\\\\dirt.png\"\n</code></pre>\n\n<p>Sometimes you use <code>//</code> in a path, sometimes <code>\\\\</code>. Better use <code>os.path.join</code> to create a path so it will work on different operating systems,</p>\n\n<hr>\n\n<pre><code>COLOR=f.read()\nf.close()\nCOLOR=COLOR.replace('(','')\nCOLOR=COLOR.replace(')','')\nCOLOR=COLOR.split(',')\nc1=COLOR[0]\nc2=COLOR[1]\nc3=COLOR[2]\n\n...\n\nif ingame==1:\n screen.fill((int(c1),int(c2),int(c3)))\n</code></pre>\n\n<p>Well, that's a whole lot of code to read a simple tuple. Let be point to <code>ast.literal_eval</code>, which allows you to savely read a string and convert it into a python structure:</p>\n\n<pre><code>line = f.read()\n# assuming 'line' is a string representing a tuple, like (120, 120, 200)\nback_color = literal_eval(line) # now, back_color is a tuple\n\n...\n\nif ingame==1:\n screen.fill(back_color)\n</code></pre>\n\n<hr>\n\n<pre><code>if key[K_1]:\n blocksel=texdir+\"\\\\dirt.png\"\n btype='block'\n select=1\nif key[K_2]:\n blocksel=texdir+\"\\\\stonetile.png\"\n btype='block'\n select=2\n</code></pre>\n\n<p>Here, you have three (maybe four if you count the key) values that are connectet to each other, so you should create a type that represents this:</p>\n\n<pre><code>class BlockType(object):\n def __init__(self, name, type, image_path=None, y_offset=0):\n self.name = name\n self.type = type\n if not image_path:\n image_path = name + '.png'\n self.image = pygame.image.load(image_path).convert()\n self.y_offset = y_offset\n\n def get_rect(self, x, y):\n return self.image.get_rect(top=y+self.y_offset, left=x)\n\n\nclass Block(object):\n def __init__(self, x, y, block_type):\n self.block_type = block_type\n self.image = block_type.image\n self.rect = block_type.get_rect(x, y)\n\n # don't know if we need the information 'block or slab' \ntypes = [BlockType('dirt', 'block'), \n BlockType('stonetile', 'block'), \n BlockType('stone', 'block'),\n BlockType('grass', 'block'),\n BlockType('sand', 'block'),\n BlockType('woodplank', 'block'),\n BlockType('woodslab', 'slab', y_offset=16)]\n\nblock_lookup = {t.name: t for t in types}\nkey_map = dict(zip([K_1, K_2, K_3, K_4, K_5, K_6], types))\n</code></pre>\n\n<p>Also, this will allow to remove <em>a lot</em> of code duplication.</p>\n\n<hr>\n\n<pre><code>if event.button==4:\n if select &lt; 9:\n select=select+1\n else:\n select=1\nelif event.button==5:\n if select&gt;1:\n select=select-1\n else:\n select=9\n</code></pre>\n\n<p>can be simplified to </p>\n\n<pre><code>num_of_types = len(types)\n\nif event.button==4:\n select += 1\nelif event.button==5:\n select -= 1\nselect = max(min(select, num_of_types), 0)\n</code></pre>\n\n<hr>\n\n<pre><code>if blklvl==top:\n blocklist.append(Block(across,blklvl,texdir+\"\\\\grass.png\",'block'))\nif blklvl&gt;top:\n if blklvl&lt;cen:\n blocklist.append(Block(across,blklvl,texdir+\"\\\\dirt.png\",'block'))\nif blklvl&gt;cen-1:\n blocklist.append(Block(across,blklvl,texdir+\"\\\\stone.png\",'block'))\n</code></pre>\n\n<p>Notice how you repeat the filenames to each different block type all over again? Let's fix that by creating a factory method that uses our new <code>block_lookup</code> dictionary:</p>\n\n<pre><code># this lookup could also be directly in the Block class\ndef block_factory(name, x, y):\n return Block(x, y, block_lookup[name])\n\n...\n\nif blklvl == top:\n blocklist.append(block_factory(across, blklvl , 'grass'))\nif blklvl &gt; top and blklvl&lt;cen:\n blocklist.append(block_factory(across, blklvl , 'dirt'))\nif blklvl &gt; cen-1:\n blocklist.append(block_factory(across, blklvl , 'stone'))\n</code></pre>\n\n<hr>\n\n<pre><code>vers=font.render('PiBlocks Alpha 0.6',True,(255,255,255))\ntex=font.render('Selected Texture Pack: '+texdir,True,(255,255,255))\n</code></pre>\n\n<p>You render the text surface once each frame. Text rendering in pygame is quite slow, so you should cache the text surfaces and reuse them.</p>\n\n<hr>\n\n<pre><code>for block in blocklist:\n if any(block.rect.colliderect(b.rect) for b in blocklist if b is not block):\n if b.btype=='slab':\n blocklist.remove(block)\n else:\n blocklist.remove(b)\n</code></pre>\n\n<p>No idea what you try to do here. <code>b</code> is declared in the list comprehension above and should not be used outside of it.</p>\n\n<hr>\n\n<p>There's a lot more what could be improved, but we've already eliminated two performance bottlenecks (reloading images from disk every time a new block is created, text rendering), and I'm running out of space and time, so here's the complete code so far:</p>\n\n<pre><code>#Init stuff\nimport pygame,random\nfrom pygame.locals import *\nfrom collections import namedtuple\nimport time, string\n\nimport ConfigParser\nfrom ast import literal_eval\nfrom functools import partial\nimport os\n\nconfig = ConfigParser.ConfigParser()\nconfig.read(\"settings.cfg\")\noptions = partial(config.get, 'Options')\n\npygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=500)\npygame.init()\npygame.display.set_caption(options('Caption'))\n\nsize = literal_eval(options('ScreenSize'))\nscreen = pygame.display.set_mode(size)\n\nclock = pygame.time.Clock()\nback_color = literal_eval(options('Backcolor'))\nsplash = random.choice(literal_eval(options('Splash')))\n\nmax_gravity = 100\n\ntexdir = options('TextureDir')\n\nbackimg = pygame.image.load(texdir+\"\\\\menu.png\").convert()\nbackimg = pygame.transform.scale(backimg, (640,480))\nclsimg = pygame.image.load(\"clear.bmp\").convert()\nclsimg = pygame.transform.scale(clsimg, (640,480))\ningame=0\nsbtn=pygame.image.load(\"startbtn.png\").convert()\nqbtn=pygame.image.load(\"quitbtn.png\").convert()\ntbtn=pygame.image.load(\"texbtn.png\").convert()\nsbtnrect=sbtn.get_rect()\nsbtnrect.x=220\nsbtnrect.y=190\nqbtnrect=qbtn.get_rect()\nqbtnrect.x=220\nqbtnrect.y=225\ntbtnrect=tbtn.get_rect()\ntbtnrect.x=220\ntbtnrect.y=260\ngo=0\ngotime=35\nselect=1\ncolliding = False\nMove = namedtuple('Move', ['up', 'left', 'right'])\nplayer=[]\nblocklist=[]\nfont=pygame.font.Font(None,18)\n\n#set cursor\ncurs = pygame.image.load(texdir+\"\\\\cursor.png\").convert()\ncurs.set_colorkey((0,255,0))\n\n#load sounds\nplace=pygame.mixer.Sound('sound\\\\place.wav')\nplace2=pygame.mixer.Sound('sound\\\\place2.wav')\nplace3=pygame.mixer.Sound('sound\\\\place3.wav')\n\n#set sprites and animation frames\npsprite = pygame.image.load(texdir+\"\\\\player\\\\playr.png\").convert()\npsprite.set_colorkey((0,255,0))\npsprite2 = pygame.image.load(texdir+\"\\\\player\\\\playr2.png\").convert()\npsprite2.set_colorkey((0,255,0))\npsprite3 = pygame.image.load(texdir+\"\\\\player\\\\playr3.png\").convert()\npsprite3.set_colorkey((0,255,0))\nanim=1\n\nclass BlockType(object):\n def __init__(self, name, type, image_path=None, y_offset=0):\n self.name = name\n self.type = type\n if not image_path:\n image_path = name + '.png'\n self.image = pygame.image.load(image_path).convert()\n self.y_offset = y_offset\n\n def get_rect(self, x, y):\n return self.image.get_rect(top=y+self.y_offset, left=x)\n\nclass Block(object):\n def __init__(self, x, y, block_type):\n self.block_type = block_type\n self.image = block_type.image\n self.rect = block_type.get_rect(x, y)\n\ntypes = [BlockType('dirt', 'block'), \n BlockType('stonetile', 'block'), \n BlockType('stone', 'block'),\n BlockType('grass', 'block'),\n BlockType('sand', 'block'),\n BlockType('woodplank', 'block'),\n BlockType('woodslab', 'slab', y_offset=16)]\n\nblock_lookup = {t.name: t for t in types}\n\ndef block_factory(name, x, y):\n return Block(x, y, block_lookup[name])\n\nnum_of_types = len(types)\n\nkey_map = dict(zip([K_1, K_2, K_3, K_4, K_5, K_6], types))\n\nselected_block_type = next(t for t in types if t.name == options('DefaultBlock'))\nselected_block_index = types.index(selected_block_type) \n\n_text_cache = {}\ndef render_white(text):\n if not text in _text_cache:\n surf = font.render(text ,True,(255,255,255))\n _text_cache[text] = surf\n return surf\n return _text_cache[text]\n\n\nclass Player(object):\n sprite=psprite\n def __init__(self, x, y):\n self.rect = self.sprite.get_rect(centery=y, centerx=x)\n # indicates that we are standing on the ground\n # and thus are \"allowed\" to jump\n self.on_ground = True\n self.xvel = 0\n self.yvel = 0\n self.jump_speed = 7\n self.move_speed = 3\n\n def update(self, move, blocks):\n\n # check if we can jump \n if move.up and self.on_ground:\n self.yvel -= self.jump_speed\n\n # simple left/right movement\n if move.left:\n self.xvel = -self.move_speed\n if move.right:\n self.xvel = self.move_speed\n\n # if in the air, fall down\n if not self.on_ground:\n self.yvel += 0.3\n # but not too fast\n if self.yvel &gt; max_gravity: self.yvel = max_gravity\n\n # if no left/right movement, x speed is 0, of course\n if not (move.left or move.right):\n self.xvel = 0\n\n # move horizontal, and check for horizontal collisions\n self.rect.left += self.xvel\n self.collide(self.xvel, 0, blocks)\n\n # move vertically, and check for vertical collisions\n self.rect.top += self.yvel\n self.on_ground = False;\n self.collide(0, self.yvel, blocks)\n\n def collide(self, xvel, yvel, blocks):\n # all blocks that we collide with\n for block in [blocks[i] for i in self.rect.collidelistall(blocks)]:\n\n # if xvel is &gt; 0, we know our right side bumped \n # into the left side of a block etc.\n if xvel &gt; 0:\n self.rect.right = block.rect.left\n if xvel &lt; 0:\n self.rect.left = block.rect.right\n\n # if yvel &gt; 0, we are falling, so if a collision happpens \n # we know we hit the ground (remember, we seperated checking for\n # horizontal and vertical collision, so if yvel != 0, xvel is 0)\n if yvel &gt; 0:\n self.rect.bottom = block.rect.top\n self.on_ground = True\n self.yvel = 0\n # if yvel &lt; 0 and a collision occurs, we bumped our head\n # on a block above us\n if yvel &lt; 0: self.rect.top = block.rect.bottom\n\ndef get_key():\n while 1:\n event = pygame.event.poll()\n if event.type == KEYDOWN:\n return event.key\n else:\n pass\n\ndef display_box(screen, message):\n \"Print a message in a box in the middle of the screen\"\n fontobject = pygame.font.Font(None,18)\n pygame.draw.rect(screen, (0,0,0),\n ((screen.get_width() / 2) - 100,\n (screen.get_height() / 2) - 10,\n 200,20), 0)\n pygame.draw.rect(screen, (255,255,255),\n ((screen.get_width() / 2) - 102,\n (screen.get_height() / 2) - 12,\n 204,24), 1)\n if len(message) != 0:\n screen.blit(fontobject.render(message, 1, (255,255,255)),\n ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))\n pygame.display.flip()\n\ndef ask(screen, question):\n \"ask(screen, question) -&gt; answer\"\n pygame.font.init()\n current_string = []\n display_box(screen, question + \": \" + string.join(current_string,\"\"))\n while 1:\n inkey = get_key()\n if inkey == K_BACKSPACE:\n current_string = current_string[0:-1]\n elif inkey == K_RETURN:\n break\n elif inkey == K_MINUS:\n current_string.append(\"_\")\n elif inkey &lt;= 127:\n current_string.append(chr(inkey))\n display_box(screen, question + \": \" + string.join(current_string,\"\"))\n return string.join(current_string,\"\")\nwhile True:\n for block in blocklist:\n if any(block.rect.colliderect(b.rect) for b in blocklist if b is not block):\n blocklist.remove(block)\n\n if ingame==1:\n screen.fill(back_color)\n mse = pygame.mouse.get_pos()\n key = pygame.key.get_pressed()\n if key[K_a]:\n anim+=1\n if anim==9:\n anim=1\n if key[K_d]:\n anim+=1\n if anim==9:\n anim=1\n\n if key[K_LEFT]:\n try:\n for b in blocklist:\n b.rect.left+=32\n except:\n pass\n try:\n player.rect.left+=32\n except:\n pass\n if key[K_RIGHT]:\n try:\n for b in blocklist:\n b.rect.left-=32\n except:\n pass\n try:\n player.rect.left-=32\n except:\n pass\n if key[K_UP]:\n try:\n for b in blocklist:\n b.rect.top+=32\n except:\n pass\n try:\n player.rect.top+=32\n except:\n pass\n if key[K_DOWN]:\n try:\n for b in blocklist:\n b.rect.top-=32\n except:\n pass\n try:\n player.rect.top-=32\n except:\n pass\n if key[K_ESCAPE]:\n execfile('PiBlocks.pyw')\n for event in pygame.event.get():\n if event.type == QUIT:\n exit()\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 4:\n selected_block_index += 1\n elif event.button == 5:\n selected_block_index -= 1\n selected_block_index = max(min(selected_block_index, num_of_types-1), 0)\n selected_block_type = types[selected_block_index]\n elif event.type == KEYDOWN:\n if event.key in key_map:\n selected_block_type = key_map[event.key]\n selected_block_index = types.index(selected_block_type)\n elif event.type==MOUSEMOTION:\n if key[K_LSHIFT]:\n if not any(block.rect.collidepoint(mse) for block in blocklist):\n snd=random.randint(1,3)\n x=(int(mse[0]) / 32)*32\n y=(int(mse[1]) / 32)*32\n if go==1:\n if snd==1:\n place.play()\n elif snd==2:\n place2.play()\n elif snd==3:\n place3.play()\n blocklist.append(Block(x,y,selected_block_type))\n elif key[K_RSHIFT]:\n to_remove = [b for b in blocklist if b.rect.collidepoint(mse)]\n for b in to_remove:\n if go==1:\n blocklist.remove(b)\n elif event.type == pygame.MOUSEBUTTONUP:\n if event.button == 1:\n to_remove = [b for b in blocklist if b.rect.collidepoint(mse)]\n for b in to_remove:\n if go==1:\n blocklist.remove(b)\n\n if not to_remove:\n snd=random.randint(1,3)\n x=(int(mse[0]) / 32)*32\n y=(int(mse[1]) / 32)*32\n if go==1:\n if snd==1:\n place.play()\n elif snd==2:\n place2.play()\n elif snd==3:\n place3.play()\n blocklist.append(Block(x,y,selected_block_type))\n\n elif event.button == 3:\n x=(int(mse[0]) / 32)*32\n y=(int(mse[1]) / 32)*32\n player=Player(x+16,y+16)\n\n move = Move(key[K_w], key[K_a], key[K_d])\n\n for b in blocklist:\n if b.rect.left&gt;=0:\n if b.rect.right&lt;=640:\n screen.blit(b.image, b.rect)\n\n if player:\n player.update(move, blocklist)\n if anim==1 or anim==2 or anim==3:\n screen.blit(psprite, player.rect)\n elif anim==4 or anim==5 or anim==6:\n screen.blit(psprite2, player.rect)\n elif anim==7 or anim==8 or anim==9:\n screen.blit(psprite3, player.rect)\n x=(int(mse[0]) / 32)*32\n y=(int(mse[1]) / 32)*32\n screen.blit(curs,(x,y))\n clock.tick(60)\n screen.blit(render_white('PiBlocks Alpha 0.6'), (1,1))\n screen.blit(render_white('Selected Texture Pack: ' + texdir), (1,12))\n screen.blit(render_white('Selected Block: '+ selected_block_type.name), (1,25))\n if gotime==0:\n go=1\n else:\n gotime-=1\n pygame.display.update()\n elif ingame==0:\n blocklist=[]\n mse = pygame.mouse.get_pos()\n player=[]\n key = pygame.key.get_pressed()\n text=font.render(splash, True, (255,255,255))\n if key[K_RETURN]:\n ingame=1\n for event in pygame.event.get():\n if event.type == QUIT:\n exit()\n if event.type == KEYDOWN:\n print event.key\n if sbtnrect.collidepoint(mse):\n if pygame.mouse.get_pressed()==(1,0,0):\n ingame='gen'\n top=(random.randint(5,8)*32)\n cen=(top+random.randint(4,6)*32)\n down=15\n across=0\n blklvl=0\n while across&lt;640:\n while down&gt;0:\n screen.fill((0,0,0))\n if blklvl==top:\n blocklist.append(block_factory('grass', across, blklvl))\n if blklvl&gt;top and blklvl&lt;cen:\n blocklist.append(block_factory('dirt', across, blklvl))\n if blklvl&gt;cen-1:\n blocklist.append(block_factory('stone', across, blklvl))\n down=down-1\n blklvl=blklvl+32\n\n if down==0:\n if across&lt;1920:\n per=(across/(32/5))\n if per&gt;100:\n per=100\n top=(random.randint(5,8)*32)\n cen=(top+random.randint(4,6)*32)\n down=15 \n blklvl=0\n across=across+32\n down=15\n drawgen=font.render('GENERATION:'+str(per)+'%%', True, (255,255,255))\n screen.blit(drawgen,(1,1))\n pygame.display.flip()\n go=0\n ingame=1\n\n if qbtnrect.collidepoint(mse):\n if pygame.mouse.get_pressed()==(1,0,0):\n exit()\n if tbtnrect.collidepoint(mse):\n if pygame.mouse.get_pressed()==(1,0,0):\n ingame='texsel'\n screen.blit(backimg,(0,0))\n screen.blit(text,(364,76))\n screen.blit(sbtn,sbtnrect)\n screen.blit(qbtn,qbtnrect)\n screen.blit(tbtn,tbtnrect)\n pygame.display.flip()\n elif ingame=='texsel':\n screen.blit(clsimg,(0,0))\n inp = ask(screen, 'Texture Directory')\n f=open('texdir.txt','w')\n f.write(str(inp))\n f.close()\n pygame.display.flip()\n execfile('PiBlocks.pyw')\n</code></pre>\n\n<p>and the config file (<code>settings.cfg</code>):</p>\n\n<pre><code>[Options]\nBackcolor: (100, 100, 100)\nTextureDir: .\nDefaultBlock: dirt\nScreenSize: (640, 480)\nCaption: PiBlocks | By Sam Tubb\nSplash: ('Some splash!', 'Play This!', 'Whhooooaaaa!!')\n</code></pre>\n\n<p>Further steps are fixing indentation, clean up the deep nesting of <code>if</code> blocks, maybe introduce classes that represent the different game states, and removing the evil empty try/except blocks. Also, some code of blocks could also extrated to functions to improve readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T10:30:36.680", "Id": "32518", "ParentId": "32434", "Score": "7" } } ]
{ "AcceptedAnswerId": "32518", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T21:24:18.617", "Id": "32434", "Score": "5", "Tags": [ "python", "pygame", "performance" ], "Title": "Terrain generator in a PyGame game" }
32434
<p>I'm working on a writing platform and am using a modified version of <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow">the Levenshtein distance algorithm</a> to track a writer's engagement with their writing. It tracks not only words added to their content, but also rewards editing by including words removed and words substituted in the count.</p> <p>Here's my algorithm in Ruby (which I run between (auto)saves):</p> <pre><code>def words_changed_since(second) first = self.split # array of words in first string second = second.split # array of words in second string # initialize the matrix matrix = [(0..first.length).to_a] (1..second.length).each do |j| matrix &lt;&lt; [j] + [0] * (first.length) end # for each word in the second string (1..second.length).each do |i| # for each word in the first string (1..first.length).each do |j| if first[j-1] == second[i-1] matrix[i][j] = matrix[i-1][j-1] else matrix[i][j] = [ matrix[i-1][j], # word deletion matrix[i][j-1], # word insertion matrix[i-1][j-1] # word substitution ].min + 1 end end end return matrix.last.last end </code></pre> <p><strong>Is this the most efficient way of tracking these changes?</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T02:40:07.310", "Id": "51960", "Score": "0", "body": "Kindly provide some explanation of what you are doing here. For example, I assume from the Wiki you reference that you are using a dynamic programming approach and `matrix[i,j]` equals the Levenshtein distance between the first i characters of `first` the first j characters of `second`. It would help the reader a lot to just know that. Also, it should be noted that the `else` calculation of `matrix[i,j]` corresponds to a deletion, insertion and substitution, respectively. You should not have to be asked for such basic and essential information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T13:49:48.853", "Id": "52090", "Score": "0", "body": "Thanks for the feedback! I added some comments to hopefully make it more clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-18T11:38:13.480", "Id": "52575", "Score": "0", "body": "why not use `diff-lcs` algorithm instead ? see [Diff::LCS](http://rubydoc.info/github/halostatue/diff-lcs)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T15:01:58.027", "Id": "53064", "Score": "0", "body": "Unless I'm misunderstanding, diff-lcs would show me the number of changes made and the changes themselves. I want to track words, specifically, not just substrings, so Levenshteins algorithm seemed more appropriate." } ]
[ { "body": "<p>Ruby is fundamentally more about simplicity (readability) than about time/memory efficiency. Otherwise you should choose another language. There are such high level languages, that can beat Ruby, like for example Javascript. And even Python handle strings faster than Ruby at the cost of eternal problems with encodings (don't waste your time on crutches, choose tools wisely).<br>\nAnd even inside Ruby single replacements of one method chain with another can either be efficient or not, depending on your platform (jruby? rubinius? etc.) while there are still different ways to measure an algorithmic complexity especially for your unique kind of input data.</p>\n\n<p>So anyway.</p>\n\n<ol>\n<li><p>The <code>matrix</code> creation I would write in one of these two ways:</p>\n\n<pre><code>matrix = (0..second.size).map{ |i|\n (0..first.size).map{ |j|\n i==0 ? j : j == 0 ? i : 0\n }\n}\n\nmatrix = (0..second.size).map{ |i|\n i==0 ? (0..first.size).to_a : [i]+[0]*first.size\n}\n</code></pre>\n\n<p>There is also a solution via <code>transpose</code>, but not functional, and one via <code>zip</code> in which I doubt.</p></li>\n<li><p>You can omit the <code>return</code> keyword at the last line in Ruby functions.</p></li>\n</ol>\n\n<p>And this is not Ruby-related, but in the main loop try to iterate through <code>0...second.length</code> instead of <code>1..second.length</code> (same for <code>first</code>). In that way you'll swap <code>i-1</code> with <code>i</code> and <code>i</code> with <code>i+1</code>, getting rid of two decrements in total.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T14:28:52.457", "Id": "52091", "Score": "0", "body": "Is the alternative code in (1) actually more efficient, or just fewer characters? Efficiency is the only thing I'm really worried about. As for (2), I know there's that option in Ruby, but for methods that are more than one line, I personally like to include the return, just to be explicit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T14:33:32.960", "Id": "52092", "Score": "0", "body": "As for your first comments, I'm using ruby 2.0.0p247 and am running this on rails, so ruby or javascript are probably my best options. I suppose I could handle this operation client-side with js, so I'll keep that in mind if this turns out to be a bottleneck in production." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T01:57:41.047", "Id": "52158", "Score": "0", "body": "@ChrisFritz, I didn't benchmark, but your way looks faster. But it is more iterative, than functional -- it is just not Ruby style." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T10:52:54.217", "Id": "32460", "ParentId": "32437", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T22:48:36.157", "Id": "32437", "Score": "2", "Tags": [ "algorithm", "ruby", "strings", "parsing", "edit-distance" ], "Title": "Is this the most efficient way to track word changes in a string?" }
32437
<p>I have this annoying problem in PHP with faking overloading constructors. I understand the concept, but the code I produce feels kind of ugly. It isn't a lot of code, just bad code. Any ideas on how to make this sane?</p> <pre><code>/** * Instantiate Fencer object from user meta database. * * If fencer data does not exist in database and USFA ID is provided, * it will automatically update from API * * If USFA ID is not provided, will throw exception * * If API data is provided, a user ID must also be provided * that way we can save the data from the API to the user. * * @param int|null $user_id * @param string|null $usfa_id * @param array|null $raw_data * * @throws InvalidArgumentException * 1. If the user does not exist and USFA ID not provided * 2. Raw API data is provided, but not a User ID to save it to */ private function __construct( $user_id = null, $usfa_id = null, $raw_data = null ) { if ( $raw_data === null ) { if ( null === $user_id ) { $user_id = self::get_user_id_from_usfa_id( $usfa_id ); } $this-&gt;wp_id = $user_id; $fencerdata = get_user_meta( $user_id, 'fence_plus_fencer_data', true ); if ( ! empty( $fencerdata ) ) { foreach ( $fencerdata as $key =&gt; $data ) { call_user_func( array( $this, 'set_' . $key ), $data ); // set all properties by calling internal setters based on fencer user meta data key } } else if ( $usfa_id != null ) { $this-&gt;usfa_id = $usfa_id; $this-&gt;update(); $this-&gt;save(); } else { throw new InvalidArgumentException( "Fencer data does not exist. Instantiate with USFA ID", 1 ); } } else { if ( null == $user_id ) { throw new InvalidArgumentException( "User ID must be provided when instantiating with raw API data", 2 ); } $this-&gt;wp_id = $user_id; $this-&gt;process_api_data( array( $raw_data ) ); $this-&gt;interpret_data(); $this-&gt;save(); } } </code></pre>
[]
[ { "body": "<p>It is a bad idea for a constructor to contain non-trivial code. \nConstructors should assign values to fields or another simple actions.\nIf you need complex initialization, you should use factory object or <a href=\"http://sourcemaking.com/design_patterns/factory_method\" rel=\"nofollow\">factory method</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:25:56.360", "Id": "51881", "Score": "0", "body": "Yes I understand that. The idea of the constructor is to make sure that all of the fields are populated, and that is what my constructor accomplishes. After the constructor runs, the object has the same state, regardless of how it was instantiated. This seems like a different problem, than one a factory method would solve, as the output is the same class. Am I missing something with my idea of a factory?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T06:19:31.973", "Id": "51967", "Score": "0", "body": "The main problem is calling methods like these `get_user_id_from_usfa_id` and throwing exceptions in constructor. \n1) it is not readable. When i call new i dont expect some db queries or any other side effects\n2) when you call `new` object is created, but when you throw exception in constructor you dont get that object. I dont know how php handle this problem, but for example in C you wold have memory leak. \n3) it is hard to test. If i want to test some method i have to mock some DB/net connection" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T06:22:07.567", "Id": "51968", "Score": "1", "body": "and 4) constructors are not part of the inheritance. So if you put some logic in construcotr you have to create constructor and call super constructor in it but there is no other way to invoke this logic if it is in constructor (sorry if it is in php, i am not familiar with php so much)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:06:21.697", "Id": "32469", "ParentId": "32438", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T23:05:31.960", "Id": "32438", "Score": "1", "Tags": [ "php", "object-oriented", "constructor" ], "Title": "Cleaning up PHP object constructors" }
32438
<p>There's a bit of a weird piece in my API that I'm not too happy about, but I can't seem to see any other way of going about.</p> <p>It involves a <code>IFunctionalityFactory</code> abstract factory:</p> <pre><code>public interface IFunctionalityFactory { IFunctionality Create(); } </code></pre> <p>An <code>IFunctionality</code> interface:</p> <pre><code>public interface IFunctionality { void Execute(); string AuthId { get; } bool IsAuthorised { get; } } </code></pre> <p>Sample implementation - I don't like that, because most functionalities will have pretty much exactly the same identical code, except for the type name... although I like how simple and straightforward this code has become:</p> <pre><code>public class SomeFunctionality : FunctionalityBase { private readonly IView _view; public SomeFunctionality(bool canExecute, IView view) : base(canExecute) { _view = view; } public override void Execute() { _view.ShowDialog(); } } </code></pre> <p>Here's the base class:</p> <pre><code>public abstract class FunctionalityBase : IFunctionality { private bool _canExecute; protected FunctionalityBase(bool canExecute) { _canExecute = canExecute; } public virtual void Execute() { // Templated method. // Must override in all derived classes. throw new NotImplementedException(); } void IFunctionality.Execute() { if (_canExecute) { Execute(); } else { // client code should catch and gracefully handle this exception: throw new NotAuthorizedException(resx.Functionality_Execute_NotAuthorised); } } string IFunctionality.AuthId { get { return GetType().FullName; } } bool IFunctionality.IsAuthorised { get { return _canExecute; } } } </code></pre> <p>Also involves a <code>IFunctionalityAuthorisation</code> interface:</p> <pre><code>public interface IFunctionalityAuthorisation { bool IsAuthorised(string authId); } </code></pre> <p>The idea is that there's a database table that associates a string (<code>AuthId</code>) with zero or more ActiveDirectory groups; if there's no entry for a given AuthId, then the functionality is authorised for everyone. If there's one or more entries, it's only authorised for the users in the listed groups.</p> <p>Here's a sample implementation:</p> <pre><code>public class SomeFunctionalityFactory : IFunctionalityFactory { private readonly IFunctionalityAuthorisation _auth; private readonly IView _view; private readonly ISomeFunctionalityViewModel _viewModel; public SomeFunctionalityFactory(IFunctionalityAuthorisation auth, IView view, ISomeFunctionalityViewModel viewModel) { _auth = auth; _view = view; _viewModel = viewModel; } public IFunctionality Create() { var canExecute = _auth.IsAuthorised(typeof(SomeFunctionality).FullName); _view.DataContext = _viewModel; return new SomeFunctionality(canExecute, _view); } } </code></pre> <p>If a functionality factory has a <code>IFunctionalityAuthorisation</code> in its constructor, it receives this implementation:</p> <pre><code>public class FunctionalityAuthorisation : IFunctionalityAuthorisation { private readonly ICurrentUser _user; private readonly ISecurityModel _model; public FunctionalityAuthorisation(ICurrentUser user, ISecurityModel model) { _user = user; _model = model; } public bool IsAuthorised(string authId) { var authorizedGroups = _model.AuthorizedRoles(authId); var result = !authorizedGroups.Any() || _user.Groups.Any(authorizedGroups.Contains); return result; } } </code></pre> <p>The main issue I'm having with this approach, is that since I'm going to be injecting dozens of <code>IFunctionalityFactory</code> into the constructors of many modules, so I need to tell my IoC container to differenciate between them, and I'm using Ninject so I'm using <code>InjectAttribute</code>:</p> <pre><code>_kernel.Bind&lt;IFunctionalityFactory&gt;() .To&lt;SomeFunctionalityFactory&gt;() .WhenTargetHas&lt;SomeAttribute&gt;(); // SomeAttribute : InjectAttribute _kernel.Bind&lt;IFunctionalityFactory&gt;() .To&lt;AnotherFunctionalityFactory&gt;() .WhenTargetHas&lt;AnotherAttribute&gt;(); // AnotherAttribute : InjectAttribute </code></pre> <p>And so on and so forth. If I have 200 functionalities to implement, I'm going to have 200 kernel bindings, and I hate that. Especially when the rest of the assembly's dependencies are configured like this:</p> <pre><code>_kernel.Bind(t =&gt; t.From(_businessLayerAssembly) .SelectAllClasses() .BindDefaultInterface()); </code></pre> <p>Another issue I'm having with this approach (perhaps the main one), is that a functionality gets fully resolved, View, ViewModel, Model and all, even if it's never called, even if the user isn't even authorised to execute it. With the 3 functionalities I have now it's not much of an issue, but when I get to 200 it's certainly going to bite me, and if someone takes over my code in 5 years it will be one of the first things they WTF over, I'm sure.</p> <p>Might be worth saying that this project is a C# rewrite (.net 4.0 / VS2010 with EF 4.4) of a crippled VB6 app that needs to be done while keeping the VB6 code in production, as it is business-critical code; it will be rewritten in small chunks, one functionality at a time - hence the "functionality" approach. The VB6 code needs to know if a functionality can or can't be executed, because until the "switchboard" forms that hold all the functionalities are redone in XAML, I want them to use the COM-visible <code>IFunctionality</code> interface to determine whether or not to draw the associated button.</p> <p>Lastly, this is what the code is like after major refactorings, which have greatly simplified lots of things. I believe there's still a few layers of useless complexity, but I need your help to see where it's at, at this point. I'm not asking for specific answers regarding how I could address some of the specific issues I'm having (e.g. the <code>NinjectAttribute</code> issue), rather to be told exactly what's wrong with this approach (I might "not like" something that's just the way it has to be), why, and what would be a better way.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T02:04:27.070", "Id": "51822", "Score": "2", "body": "Small note, I'd make `private bool _canExecute;` in `FunctionalityBase` `readonly`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T02:07:30.377", "Id": "51823", "Score": "0", "body": "Dang, how did I miss that!! Thanks! ...that's all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T02:11:21.410", "Id": "51824", "Score": "1", "body": "Well, likely not all, but I thought I'd mention that quickly :) I do find the general approach rather clean though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T03:13:01.353", "Id": "51827", "Score": "4", "body": "If `FunctionalityBase`'s `Execute` only throws a `NotImplementedException`, why not make the `Execute` within `FunctionalityBase` abstract?" } ]
[ { "body": "<p>First: Don't create a base class with a virtual method which simply throws. This moves problem detection from compile time (abstract member not implemented won't compile) to run time (forgotten to override or accidentally called base throws) - usually undesirable. Virtual method says \"You can override me if you want but you don't have to\".</p>\n\n<p>Now your actual problem.</p>\n\n<p>Let me see if I understand correctly what you are saying:</p>\n\n<ul>\n<li>You have N classes of type <code>XyzFunctionality</code></li>\n<li>You also have N corresponding factory classes of type <code>XyzFunctionalityFactory</code> each responsible of creating the specific <code>XyzFunctionality</code></li>\n<li>You also have N corresponding <code>RequiresXyzFunctionality</code> attributes which you use to inject the specific <code>XyzFunctionalityFactory</code> for <code>IFunctionalityFactory</code> members</li>\n</ul>\n\n<p>Is that basically correct? If yes then this smells to me:</p>\n\n<p>If you have a member in a class of type <code>IFunctionalityFactory</code> then this basically says: \"I want a factory which can create <code>IFunctionality</code> objects for me and do not care what they actually do\" while in fact this is big fat lie - why else would you decorate with an attribute saying \"actually this requires a very specific functionality factory\"? </p>\n\n<p>If the application requires that object Foo gets injected with a specific functionality factory then express it by making the type <code>SomeFunctionalityFactory</code> rather then <code>IFunctionalityFactory</code> - no 200 attributes, no 200 kernel bindings.</p>\n\n<p>Now you will probably say \"What about unit testing\"?</p>\n\n<ol>\n<li>You could make a <code>FunctionalityFactoryBase</code> class similar to your <code>FunctionalityBase</code> class with a virtual <code>Create</code> however that's not a good idea for the same reasons why it's not a good idea for <code>FunctionalityBase</code>.</li>\n<li>Make <code>Create</code> virtual in all factories. Easy to forget.</li>\n<li>Create a marker interface <code>IXyzFunctionalityFactory</code> and use that instead. Smells.</li>\n</ol>\n\n<p>I think I'd go with the first option. The factories are all very light and really only contain <code>Create</code> so it's unlikely the implementer will forget to overwrite it. Unit tests should catch inadvertent calls of the base class method.</p>\n\n<p>I might have assumed totally incorrectly though so please correct me if I'm wrong in my assumptions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:06:18.810", "Id": "51856", "Score": "0", "body": "I remember having a fight with myself at one point over the virtual vs abstract Execute method. I should have commented the why of this because now I can't remember but I think it has to do with calling it from the explicit interface implementation, but I've just tested it through COM interop with the `abstract` method and it works, so I'll change that! Your assumptions are correct :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:10:51.440", "Id": "51868", "Score": "0", "body": "So I end up with `ISomeFunctionalityFactory` and I can bind to default interface, this solves the InjectAttribute issue but I end up with abstract factory galore... There has to be a design flaw I'm not seeing that can be reworked so as to not need those factories at all, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T22:55:06.097", "Id": "51915", "Score": "0", "body": "Hmm the way I have it, if auth configs are modified the app needs to be restarted to take effect, since functionalities are auhorised at composition. So I can make IFunctionalityAuthorisation a dependency of functionalities and evaluate IsAuthorised during CanExecute and then I don't need factories anymore, but I do need ISomeFunctionality for kernel bindings to go by convention... and that's a marker interface, but benefits outweight the smell I find." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:14:52.577", "Id": "51971", "Score": "0", "body": "@retailcoder: Well, if you got rid of the factories and leave your virtual `Execute` and possibly `CanExecute` in your functionality base class then you could simply spell out the dependency `SomeFunctionality` explicitly and stub the concrete class in your unit tests by overriding them. Saves you a ton of marker interfaces." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:17:10.310", "Id": "32452", "ParentId": "32440", "Score": "7" } } ]
{ "AcceptedAnswerId": "32452", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T00:10:14.053", "Id": "32440", "Score": "11", "Tags": [ "c#", ".net", "dependency-injection", "ninject" ], "Title": "Having trouble with KISSing" }
32440
<p>I have written a PHP class called "graph". It is a class that performs RESTful-like commands to a MySQL database. I have posted the <a href="https://github.com/vealdaniel/graph" rel="nofollow">GitHub repo</a>.</p> <p>Here is the code as well:</p> <p>config.php</p> <pre><code>&lt;?php //standard database connection data //these obviously need to be changed.... define("DBHOST","localhost"); define("DBUSERNAME","user"); define("DBPASSWORD","password"); define("MAIN_DB","main"); ?&gt; </code></pre> <p>database.class.php</p> <pre><code>&lt;?php require_once('config.php'); //set your database settings in this class database{ public static function dbConnect($db){ $link = mysql_connect(DBHOST, DBUSERNAME, DBPASSWORD); if (!$link) { $response = array( "object" =&gt; "database", "instrcut" =&gt; "dbConnect", "status" =&gt; "fail", "message" =&gt; mysql_error() ); } if($db == ''){ //sets the $db var to the constant MAIN_DB if not otherwise set. $db = MAIN_DB; $db_select = mysql_select_db($db); }else{ $db_select = mysql_select_db($db); } if(!$db_select){ $response = array( "object" =&gt; "database", "instrcut" =&gt; "dbConnect", "status" =&gt; "fail", "message" =&gt; mysql_error() ); }else{ $response = array( "object" =&gt; "database", "instrcut" =&gt; "dbConnect", "status" =&gt; "pass", "message" =&gt; "The database '$db' was connected to successfully." ); } return $response; } public static function conQuer($sql,$db){ $query = self::dbConnect($db); $result = mysql_query($sql); if($query&amp;&amp;$result){ $response = array( "object" =&gt; "database", "instrcut" =&gt; "conQuer", "status" =&gt; "pass", "message" =&gt; "The connection was established and the query was run successfully.", "data" =&gt; $result ); }else{ $response = array( "object" =&gt; "database", "instrcut" =&gt; "conQuer", "status" =&gt; "fail", "message" =&gt; "The conQuer method failed because there was a bad query." ); } return $response; } //end database class } ?&gt; </code></pre> <p>Finally, the big one:</p> <p>graph.class.php</p> <pre><code> &lt;?php //PHP-GRAPH class require_once('database.class.php'); class graph{ //used to retrieve existing data public static function get($data){ $jsonData = json_encode($data); //decode json data $data = json_decode($jsonData); ////////////////////////////// $db = $data-&gt;db; $table = $data-&gt;table; $field = $data-&gt;field; $value = $data-&gt;value; $request = array($field,$value); ////////////////////////////// if($db&amp;&amp;$table&amp;&amp;$field&amp;&amp;$value){ ////////////GET ALL THE AVAILABLE FIELDS FROM SELECTED TABLE//////////// //query to get the available fields $result = database::conQuer("SHOW COLUMNS FROM $table",$db); $result = $result['data']; if (!$result) { //return the failure response $response = array("obj"=&gt;"graph","instruct"=&gt;"get","status"=&gt;"fail","msg"=&gt;mysql_error()); } if (mysql_num_rows($result) &gt; 0) { while ($row = mysql_fetch_assoc($result)) { $field_array[] = $row['Field']; } } ///////////////////////////////////////////////////////////////////////////// ////////////GET ALL THE DATA FROM THE SELECTED FIELDS //////////// $getQuery = database::conQuer("SELECT * FROM $table WHERE $field = '$value'",$db); $getQuery = $getQuery['data']; $queryCount = mysql_numrows($getQuery); while($row = mysql_fetch_array($getQuery)){ foreach($field_array as $fa){ $value = $row["$fa"]; //get the value of the field $field = $fa; //get the actual field name //store in an array to be easily accessable if($queryCount &gt; 1){ $getInfo[$field][] = $value; }else{ $getInfo[$field] = $value; } } } //need to check if any data was actually recieved if(empty($getInfo)){ $response = array("obj"=&gt;"$table","instruct"=&gt;"get","status"=&gt;"pass","msg"=&gt;"Graph ran successfully, but no data was retrieved. Check the graph coordinates and try again.","data"=&gt;"empty"); }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"get","request"=&gt;$request,"data"=&gt;$getInfo,"status"=&gt;"pass","msg"=&gt;"Data was successfully retrieved."); } }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"get","status"=&gt;"fail","msg"=&gt;"Graph couldn't get any data because all required parameters weren't passed."); } //if successful, this will return a JSON array, with the final value of "data". return json_encode($response); } public static function post($data){ //used to create new data //required parameters $db = $data['db']; $table = $data['table']; $fieldData = $data['field']; if($db&amp;&amp;$table){ if($fieldData){ //need to create the new record here $field_id = $table."_id"; //apart of the naming standards setup that the system must use to work... $createNewRecord = database::conQuer("INSERT INTO `$db`.`$table` (`$field_id`) VALUES (NULL);",$db); if($createNewRecord){ $newFieldId = mysql_insert_id(); //gets the lasat id of the query foreach($fieldData as $value){ $field = array_search("$value", $fieldData); $insert = database::conQuer("UPDATE `$db`.`$table` SET `$field` = '$value' WHERE `$table`.`$field_id` =$newFieldId LIMIT 1 ;",$db); } $response = array("obj"=&gt;"$table","instruct"=&gt;"post","data"=&gt;$fieldData,"status"=&gt;"pass","msg"=&gt;"Graph posted the data successfully."); }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"post","status"=&gt;"fail","msg"=&gt;"Graph didn't run because there was a query error when creating a new value."); } }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"post","status"=&gt;"fail","msg"=&gt;"Graph didn't run because no data values were passed."); } }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"post","status"=&gt;"fail","msg"=&gt;"Graph didn't run because the required parameters were not passed."); } return json_encode($response); } public static function put($data){ //used to update existing data $db = $data['db']; $table = $data['table']; $field = $data['field']; $value = $data['value']; $ref = $data['ref']; $refval = $data['refval']; if($db&amp;&amp;$table&amp;&amp;$field&amp;&amp;$value&amp;&amp;$ref&amp;&amp;$refval){ $put = database::conQuer("UPDATE `$db`.`$table` SET `$field` = '$value' WHERE `$table`.`$ref` = '$refval';",$db); if($put){ $putData = array($field,$value,$ref,$refval); $response = array("obj"=&gt;"$table","instruct"=&gt;"put","data"=&gt;$putData,"status"=&gt;"pass","msg"=&gt;"Graph updated the data successfully."); }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"put","status"=&gt;"fail","msg"=&gt;"Graph didn't put any data in because the query failed."); } }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"put","status"=&gt;"fail","msg"=&gt;"Graph didn't put any data in because the required parameters were not passed."); } return json_encode($response); } public static function delete($data){ //used to remove existing data //used to update existing $db = $data['db']; $table = $data['table']; $ref = $data['ref']; $refval = $data['refval']; if($db&amp;&amp;$table&amp;&amp;$ref&amp;&amp;$refval){ $delete = database::conQuer("DELETE FROM `$table` WHERE `$table`.`$ref` = '$refval'",$db); if($delete){ $deleteData = array($ref,$refval); $response = array("obj"=&gt;"$table","instruct"=&gt;"delete","data"=&gt;$deleteData,"status"=&gt;"pass","msg"=&gt;"Graph deleted the data successfully."); }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"delete","status"=&gt;"fail","msg"=&gt;"Graph didn't delete any data in because the query failed."); } }else{ $response = array("obj"=&gt;"$table","instruct"=&gt;"delete","status"=&gt;"fail","msg"=&gt;"Graph didn't delete any data in because the required parameters were not passed."); } return json_encode($response); } //end graph class } ?&gt; </code></pre> <p>I would really appreciate the community's view on the class. What do you guys think about it? What can I do better? Critiques are welcome.</p> <p>I have used the class in several sites that I've built and it really seemed to help me. I hope that maybe it could help someone else.</p> <p>Please post any comments, suggestions, etc.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T01:45:24.040", "Id": "51819", "Score": "0", "body": "Looks clean but not sure about `mysql_*`. Users on newer versions of PHP are going to get deprecated warnings everywhere, I'd switch to PDO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T01:46:45.543", "Id": "51820", "Score": "0", "body": "Please include the code you'd like to have reviewed. The link could die at any time, rendering the question useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T01:46:53.183", "Id": "51821", "Score": "0", "body": "Yes. That is a good idea. I will update that..." } ]
[ { "body": "<p>A few points:</p>\n\n<ol>\n<li>You should avoid <code>mysql_query</code>. It's deprecated. Use PDO or mysqli.\n<ul>\n<li>Read up on SQL injection attacks and use parametrized queries.</li>\n</ul></li>\n<li>Your indentation seems to be all over the place (not sure if that's a result of copy-n-paste, haven't checked the github sources)\n<ul>\n<li>Use more spaces - they are cheap (e.g. <code>}else{</code> should be at least <code>} else {</code>);</li>\n</ul></li>\n<li><p>Comments should mainly describe reasons for non-obvious decision. Most of your comments seem to just describe what the code below is doing which you can see by looking at the code. Example:</p>\n\n<pre><code>//decode json data\n$data = json_decode($jsonData);\n</code></pre>\n\n<p>Those comments add no value. Furthermore reiterating what the code does in the comments will usually lead to comments conflicting with code once a few rounds of refactoring have taken place.</p></li>\n<li>Why is this called <code>Graph</code>? Graph means usually one of two things to me: Either a data structure with nodes and edges connecting the nodes or the visualization of some data. I can see neither of those here really.</li>\n<li>You repeat a lot of string literals in your response creation. This should be refactored into a method. Makes refactoring later easier and avoids typos. Maybe even create a class encapsulating the response so you can do <code>r = response::build(...); r.Add(key, value); r.toJson();</code> or something along those lines.\n<ul>\n<li>Most prominently you use <code>instrcut</code> in your database class but <code>instruct</code> in your graph class. I'd actually use <code>command</code> (instructions in computer terms are usually associated with more low level operations but YMMV)</li>\n</ul></li>\n<li><p>Consider dealing with error cases first to reduce nesting. This makes the code easier to read when there are multiple levels. E.g.:</p>\n\n<pre><code>if (!$db || !$table)\n{\n return response::build(...).toJson();\n}\nif (!$fieldData)\n{\n return response::build(...).toJson();\n}\n\n// handle the main case\n\nreturn response::build().toJson();\n</code></pre></li>\n</ol>\n\n<p><strong>In regards to the response refactoring</strong>: </p>\n\n<pre><code>class response\n{\n private data = array();\n\n public static function build($object, $command, $status, $message)\n {\n $res = new response();\n $res-&gt;data['object'] = $object;\n ...\n return $res;\n }\n\n public function toJson()\n {\n return json_encode($this-&gt;data);\n }\n}\n</code></pre>\n\n<p>Disclaimer: Above code might not be 100% correct but should get the idea across. It's been a long time since I worked with PHP.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T02:43:33.580", "Id": "51825", "Score": "0", "body": "Thanks for the help Chris Wue! To answer your question about why I named it graph. Originally I visualized the setup like this : The database represented a x value, the table represented a y value, and the field represented a z value. In my mind, I was in a way, building a graph of a database. It could be called anything really... I just left it what I had originally called it. You are the 2nd person to mention the switch to PDO. I will be adding that, and then uploading it again. Also, I copied and pasted the code so thats why the indenting is crazy. It looked fine in my editor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T03:12:29.487", "Id": "51826", "Score": "0", "body": "On point # 5. Could you please be more specific? What should a response look like? What do you mean it should be a method? Show me what you are talking about. I want to make this class better, for sure. So that others can use it. Do you like the idea of being able to perform rest commands to a database? Thanks, Dan" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T03:37:42.527", "Id": "51829", "Score": "0", "body": "@DanielSikes: Fair enough. I updated my answer" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T02:35:46.997", "Id": "32442", "ParentId": "32441", "Score": "2" } } ]
{ "AcceptedAnswerId": "32442", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T01:42:26.067", "Id": "32441", "Score": "3", "Tags": [ "php", "mysql", "classes", "graph" ], "Title": "Review/rate my new graph class" }
32441
<p>I'm trying to learn PHP/MySQL and the likes, so I've been reading tutorials for PHP login systems. My current iteration is based heavily on one from <a href="http://forum.codecall.net/topic/69771-creating-a-simple-yet-secured-loginregistration-with-php5/" rel="nofollow noreferrer">this website</a> and contains the accepted answer for random salts <a href="https://stackoverflow.com/questions/2235434/how-to-generate-a-random-long-salt-for-use-in-hashing">here</a>. This is my first thing I've done in MySQL, and my first attempt at PHP besides a tiny Tic-Tac-Toe game.</p> <p><strong>config.php:</strong></p> <pre><code>&lt;?php //set off all error for security purposes error_reporting(E_ALL); //define some contstant define( "DB_DSN", "mysql:host=localhost;dbname=gryp" ); define( "DB_USERNAME", "root" ); define( "DB_PASSWORD", "" ); define( "CLS_PATH", "class" ); //include the classes include_once( CLS_PATH . "/user.php" ); ?&gt; </code></pre> <p><strong>user.php:</strong></p> <pre><code>&lt;?php class Users { public $username = null; public $password = null; public $salt = null; public function __construct( $data = array() ) { if( isset( $data['username'] ) ) $this-&gt;username = mysql_real_escape_string( htmlspecialchars( strip_tags( $data['username'] ) ) ); if( isset( $data['password'] ) ) $this-&gt;password = mysql_real_escape_string( htmlspecialchars( strip_tags( $data['password'] ) ) ); } public function storeFormValues( $params ) { //store the parameters $this-&gt;__construct( $params ); } public function userLogin() { $success = false; try{ $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $con-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $sql = "SELECT * FROM users WHERE username = :username LIMIT 1"; $fetch = $con-&gt;prepare( $sql ); $fetch-&gt;bindValue( "username", $this-&gt;username, PDO::PARAM_STR ); $fetch-&gt;execute(); $row = $fetch-&gt;fetch(PDO::FETCH_ASSOC); if($row){ $this-&gt;salt=$row['salt']; if ( hash("sha256", $this-&gt;password . $this-&gt;salt) == $row['password']) { $success = true; $sql = "UPDATE users SET lastlogin=NOW() WHERE username=:username"; $fetch = $con-&gt;prepare($sql); $fetch-&gt;bindValue( "username", $this-&gt;username, PDO::PARAM_STR ); $fetch-&gt;execute(); } } $con = null; return $success; }catch (PDOException $e) { echo $e-&gt;getMessage(); return $success; } } public function register() { $correct = false; try { $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $con-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $this-&gt;salt = $this-&gt;unique_md5(); $sql = "INSERT INTO users(username, password,salt,registerdate) VALUES(:username, :password,:salt,NOW())"; $fetch = $con-&gt;prepare( $sql ); $fetch-&gt;bindValue( "username", $this-&gt;username, PDO::PARAM_STR ); $fetch-&gt;bindValue( "password", hash("sha256", $this-&gt;password . $this-&gt;salt), PDO::PARAM_STR ); $fetch-&gt;bindValue( "salt", $this-&gt;salt, PDO::PARAM_STR ); $fetch-&gt;execute(); return "Registration Successful &lt;br/&gt; &lt;a href='index.php'&gt;Login Now&lt;/a&gt;"; }catch( PDOException $e ) { return $e-&gt;getMessage(); } } public function unique_md5() { mt_srand(microtime(true)*100000 + memory_get_usage(true)); return md5(uniqid(mt_rand(), true)); } } ?&gt; </code></pre> <p>Table structure:</p> <blockquote> <pre class="lang-none prettyprint-override"><code># name type collation null default extra 1 userID int(11) No None AUTO_INCREMENT 2 username varchar(50) latin1_swedish_ci No None 3 password varbinary(250) No None 4 salt varbinary(32) No None 5 registerdate datetime No None 6 lastlogin datetime No None </code></pre> </blockquote> <p>I think that my input is sanitized, that I'm safe from SQL injections, and that I'm safe from XSS attacks. But before I move on with what I'm doing and learn more, I figure that it's better to assume my code is insecure and ask for help, than to assume it is secure and find out it isn't.</p> <p>I feel that</p> <pre class="lang-php prettyprint-override"><code>$this-&gt;salt=$stmt-&gt;fetchColumn(3); </code></pre> <p>shouldn't be what I'm doing. Also that I have 3 queries for login, which seems wasteful. But that was the least I could do it in. </p> <p>Is my code going in the right direction? What can I do better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T06:21:08.953", "Id": "51834", "Score": "0", "body": "The indentation doesn't look too good, make sure to convert tabs to spaces when copy/pasting if it looks correct in your editor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T10:42:55.143", "Id": "51847", "Score": "0", "body": "Use the build in PHP Functions for password hashing. http://php.net/manual/en/function.password-hash.php or if you don't have PHP 5.5 use the backport https://github.com/ircmaxell/password_compat" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T11:36:41.373", "Id": "51850", "Score": "0", "body": "I would select only user only by username and then check password in php code. You can find some discussion about this topic at http://stackoverflow.com/questions/5978539/when-users-login-to-a-site-should-i-select-by-the-username-and-password-or-ju" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:17:46.687", "Id": "51916", "Score": "0", "body": "elclanrs fixed a few spaces in editor, but copy/pasting here messed a bit more of it up.\nAlucardTheRipper I'm pretty sure mine work adequately, but I'll look into using the built in functions over built in hash.\n@DominikM did just that. Looks cleaner and I think its faster. Thank you." } ]
[ { "body": "<p>For hashing passwords, I use the code below. Note, I need to support running on older versions of PHP, so that is why I have the different checks for available features.</p>\n\n<pre><code>static function hashPassword($pwd) {\n $salt = self::secure_rand(16);\n $salt = str_replace('+', '.', base64_encode($salt));\n if (CRYPT_BLOWFISH == 1) {\n $salt = substr($salt, 0, 22);\n $cost = \"07\";\n $hash = crypt($pwd, '$2a$' . $cost . '$' . $salt);\n return $hash;\n } else {\n $salt = substr($salt, 0, 8);\n $hash = crypt($pwd, '$1$' . $salt . '$');\n return $hash;\n }\n}\nprivate static function secure_rand($length) {\n if(function_exists('openssl_random_pseudo_bytes')) {\n $rnd = openssl_random_pseudo_bytes($length, $strong);\n if ($strong === TRUE)\n return $rnd;\n }\n $sha =''; $rnd ='';\n for ($i=0; $i&lt;$length; $i++) {\n $sha = hash('md5',$sha.mt_rand());\n $char = mt_rand(0,62);\n $rnd .= chr(hexdec($sha[$char].$sha[$char+1]));\n }\n return $rnd;\n}\n</code></pre>\n\n<p>The valid password is checked by fetching the user by username from database, and then comparing the entered password with the encrypted password using the crypt function.</p>\n\n<pre><code>static function checkPassword($pwd, $hash) {\n return $hash == crypt($pwd, $hash);\n}\n</code></pre>\n\n<p>I have these methods in a Utils class. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T10:55:06.327", "Id": "32461", "ParentId": "32443", "Score": "0" } }, { "body": "<p>Depending on the size of your application, it could be a good idea to abstract away the user information to a DAO (data access object). This object would contain the methods needed for handling user information.</p>\n\n<p>For instance like the following:</p>\n\n<pre><code>class UserDAO {\n\n private $dbh;\n\n//$dbh is the dbhandle you get from new PDO(…)\nfunction __construct( $dbh ) {\n $this-&gt;dbh = $dbh;\n}\n\nfunction save( $user ) {\n if ( !isset( $user-&gt;id ) || $user-&gt;id == 0 ) {\n $this-&gt;insert( $user );\n } else {\n $this-&gt;update( $user );\n }\n}\n\nfunction getByUsername( $username ) {\n $stmt = $this-&gt;dbh-&gt;prepare( \"SELECT * FROM user WHERE username = ?\" );\n if ( !$stmt ) {\n echo 'Error in fetch query';\n die();\n }\n $stmt-&gt;setFetchMode( PDO::FETCH_CLASS, \"User\" );\n $stmt-&gt;execute( array( $username ) );\n $user = $stmt-&gt;fetch();\n return $user\n}\n\nprivate function insert( $user ) {\n $stmt = $this-&gt;dbh-&gt;prepare( \"INSERT INTO\n user (username, email, password)\n VALUES (:username, :email, :password)\" );\n if ( !$stmt ) {\n echo 'Error in saving query.';\n die();\n }\n $stmt-&gt;bindParam( ':username', $user-&gt;username );\n $stmt-&gt;bindParam( ':email', $user-&gt;email );\n $stmt-&gt;bindParam( ':password', $user-&gt;password );\n if ( !$stmt-&gt;execute() ) {\n echo 'Error saving user data. ';\n echo $stmt-&gt;errorCode();\n print_r( $stmt-&gt;errorInfo() );\n die();\n }\n $user-&gt;id = $this-&gt;dbh-&gt;lastInsertId();\n}\n\nprivate function update( $user ) {\n $stmt = $this-&gt;dbh-&gt;prepare( \"UPDATE user\n SET username = :username,\n email = :email,\n password = :password\n WHERE\n id = :id\" );\n if ( !$stmt ) {\n echo 'Error in update query';\n die();\n }\n $stmt-&gt;bindParam( ':username', $user-&gt;username );\n $stmt-&gt;bindParam( ':email', $user-&gt;email );\n $stmt-&gt;bindParam( ':password', $user-&gt;password );\n $stmt-&gt;bindParam( ':id', $user-&gt;id );\n if ( !$stmt-&gt;execute() ) {\n echo 'Error updating user';\n echo $stmt-&gt;errorCode();\n print_r( $stmt-&gt;errorInfo() );\n die();\n }\n</code></pre>\n\n<p>The the login code on your php page would just be:</p>\n\n<pre><code> $dao = DAOFactory::getDAO(\"user\");\n if ($user = $dao-&gt;getByUsername($this-&gt;username)) {\n if (Utils::checkPassword($password, $user-&gt;password)) {\n $_SESSION['username'] = $user-&gt;username;\n $user-&gt;last_login = date(\"Y-m-d H:i:s\");\n $dao-&gt;save($user);\n header('Location: info.php');\n return;\n }\n }\n $this-&gt;errors[] = \"Invalid username or password\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T18:29:20.877", "Id": "52504", "Score": "0", "body": "You mix PHP4 and PHP5 code. [`var`](http://docs.php.net/manual/en/language.oop5.visibility.php) was deprecated in PHP5 and [`__constructor`](http://php.net/manual/en/language.oop5.decon.php) was introduced in PHP5. Decide if you are writing PHP4 or PHP5 code and stick to that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T12:20:41.027", "Id": "54105", "Score": "0", "body": "As of PHP 5.1.3 it is no longer deprecated. If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public. But you are correct in saying that it has a PHP4 smell to it. [Source](http://www.php.net/manual/en/language.oop5.properties.php)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T17:11:56.697", "Id": "56953", "Score": "0", "body": "Supporting `var` declaration can be stopped or changed at any time and the property declared it will be public. So it is better to consider `var` deprecated and let it die in peace." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T13:10:08.997", "Id": "57130", "Score": "0", "body": "Edited code to change `var` to `private` as pointed out by @AlexandruG." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-23T12:21:19.897", "Id": "63150", "Score": "0", "body": "It is the implementer's decision what to do when an error occurs, not the library itself. So you should not interrupt the process when something has gone haywire, but throw an exception or return something, so that the implementer can decide what to do next. ( *see `exit` from your example* )" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T11:25:14.367", "Id": "32463", "ParentId": "32443", "Score": "1" } }, { "body": "<p>For logging in and registering it does what it should. You may want to consider beyond the act of logging in and registering though.</p>\n\n<ol>\n<li>If this user object is something that will be used after someone has logged in to do other things, the password and salt are probably not going to be something you need to keep track of beyond the login request.</li>\n<li>Keeping item 1 in mind, I would restructure this to use a static method to do the login and registration since those are things that are typically self contained. So instead of passing the $data array into the construct you would do <code>Users::userLogin($data)</code></li>\n<li>I'm not a huge fan of calling the construct from other methods. When you resort to that I think it is a sign that you need to make a change. The construct is intended to run once, if you need to use it a second time you should move the logic into it's own method. If you kept your code \"as is\", I would swap the construct for storeFromValues like this:</li>\n</ol>\n\n<hr>\n\n<pre><code>public function __construct( $data = array() ) {\n $this-&gt;storeFormValues( $data ); \n }\n\n public function storeFormValues( $params ) {\n //store the parameters\n if( isset( $params['username'] ) ) $this-&gt;username = mysql_real_escape_string( htmlspecialchars( strip_tags( $params['username'] ) ) );\n if( isset( $params['password'] ) ) $this-&gt;password = mysql_real_escape_string( htmlspecialchars( strip_tags( $params['password'] ) ) );\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T23:15:02.473", "Id": "35458", "ParentId": "32443", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T05:30:25.523", "Id": "32443", "Score": "3", "Tags": [ "php", "mysql", "security" ], "Title": "PHP MySQL login" }
32443
<p>I wrote 2 filters in C for the Altera DE2 Nios II FPGA, one floating-point and one fixed-point. I've verified that they perform correctly and now I wonder if you can give examples for improvement or optimization? I'll reduce the C library to a small library and turn on optimization, and perhaps you can suggest how to do other improvements?</p> <p>The floating-point program:</p> <pre><code>#include &lt;stdio.h&gt; #include "system.h" #include "alt_types.h" #include &lt;time.h&gt; #include &lt;sys/alt_timestamp.h&gt; #include &lt;sys/alt_cache.h&gt; float microseconds(int ticks) { return (float) 1000000 * (float) ticks / (float) alt_timestamp_freq(); } void start_measurement() { /* Flush caches */ alt_dcache_flush_all(); alt_icache_flush_all(); /* Measure */ alt_timestamp_start(); time_1 = alt_timestamp(); } void stop_measurement() { time_2 = alt_timestamp(); ticks = time_2 - time_1; } float floatFIR(float inVal, float* x, float* coef, int len) { float y = 0.0; int i; start_measurement(); for (i = (len-1) ; i &gt; 0 ; i--) { x[i] = x[i-1]; y = y + (coef[i] * x[i]); } x[0] = inVal; y = y + (coef[0] * x[0]); stop_measurement(); printf("%5.2f us", (float) microseconds(ticks - timer_overhead)); printf("(%d ticks)\n", (int) (ticks - timer_overhead)); printf("Sum: %f\n", y); return y; } int main(int argc, char** argv) { /* Calculate Timer Overhead */ // Average of 10 measurements */ int i; timer_overhead = 0; for (i = 0; i &lt; 10; i++) { start_measurement(); stop_measurement(); timer_overhead = timer_overhead + time_2 - time_1; } timer_overhead = timer_overhead / 10; printf("Timer overhead in ticks: %d\n", (int) timer_overhead); printf("Timer overhead in ms: %f\n", 1000.0 * (float)timer_overhead/(float)alt_timestamp_freq()); float coef[4] = {0.0299, 0.4701, 0.4701, 0.0299}; float x[4] = {0, 0, 0, 0}; /* or any other initial condition*/ float y; float inVal; while (scanf("%f", &amp;inVal) &gt; 0) { y = floatFIR(inVal, x, coef, 4); } return 0; } </code></pre> <p>The fixed-point program:</p> <pre><code>#include &lt;stdio.h&gt; #include "system.h" #include "alt_types.h" #include &lt;time.h&gt; #include &lt;sys/alt_timestamp.h&gt; #include &lt;sys/alt_cache.h&gt; #define TIME 1 signed char input[4]; /* The 4 most recent input values */ char get_q7( void ); void put_q7( char ); void firFixed(signed char input[4]); const int c0 = (0.0299 * 128 + 0.5); /* Converting from float to Q7 by multiplying by 2^n i.e. 128 = 2^7 since we use Q7 and round to the nearest integer by multiplying with 0.5. The fraction will be truncated. */ const int c1 = (0.4701 * 128 + 0.5); const int c2 = (0.4701 * 128 + 0.5); const int c3 = (0.0299 * 128 + 0.5); const int half = (0.5000 * 128 + 0.5); enum { Q7_BITS = 7 }; alt_u32 ticks; alt_u32 time_1; alt_u32 time_2; alt_u32 timer_overhead; float microseconds(int ticks) { return (float) 1000000 * (float) ticks / (float) alt_timestamp_freq(); } void start_measurement() { /* Flush caches */ alt_dcache_flush_all(); alt_icache_flush_all(); /* Measure */ alt_timestamp_start(); time_1 = alt_timestamp(); } void stop_measurement() { time_2 = alt_timestamp(); ticks = time_2 - time_1; } void firFixed(signed char input[4]) { int sum = c0*input[0] + c1*input[1] + c2*input[2] + c3*input[3]; signed char output = (signed char)((sum + half) &gt;&gt; Q7_BITS); stop_measurement(); if (TIME) { printf("(%d ticks)\n", (int) (ticks - timer_overhead)); } put_q7(output); } int main(void) { printf("c0 = c3 = %3d = 0x%.2X\n", c0, c0); printf("c1 = c2 = %3d = 0x%.2X\n", c1, c1); if (TIME) { /* Calculate Timer Overhead */ // Average of 10 measurements */ int i; timer_overhead = 0; for (i = 0; i &lt; 10; i++) { start_measurement(); stop_measurement(); timer_overhead = timer_overhead + time_2 - time_1; } timer_overhead = timer_overhead / 10; printf("Timer overhead in ticks: %d\n", (int) timer_overhead); printf("Timer overhead in ms: %f\n", 1000.0 * (float)timer_overhead/(float)alt_timestamp_freq()); } int a; while(1) { if (TIME) { start_measurement(); } for (a = 3 ; a &gt; 0 ; a--) { input[a] = input[a-1]; } input[0]=get_q7(); firFixed(input); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:48:02.017", "Id": "51859", "Score": "0", "body": "Try using doubles. They might be faster on your platform." } ]
[ { "body": "<p>With the float version, I would make the <code>coef</code> parameter <code>const</code> and add <code>restrict</code> to both parameters. But that is unlikely to make much difference to speed.</p>\n\n<p>For the integer version, I would make the coefficients bigger than 8 bit. You lose a lot of the accuracy of the coefficients by reducing them to 8 bits and as you are accumulating using <code>int</code>, that seems unnecessary. This will improve the characteristics of the filter although the performance will depend upon the CPU - on a desktop type processor using <code>int</code> rather than <code>char</code> is likely to be faster, but for your processor that might not be true. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:54:48.320", "Id": "32538", "ParentId": "32444", "Score": "1" } }, { "body": "<p>A good first approach is always to look for a library call that already does what you need and that was optimized for your platform. For a FIR filter, that might e.g. be <code>cblas_sdot</code> in the BLAS library.</p>\n\n<p>For a hand written approach, the key issues are picking the right data types (as discussed by @WilliamMorris) and exploiting the parallelism of the target platform. Since you’re targeting an FPGA, you even get to <em>pick</em> the level of parallelism. On the other hand, FPGAs are not necessarily great with arbitrary loops, so I would take a very close look at whether you can get away with using a constant number of coefficients.</p>\n\n<p>Once you’ve decided on an appropriate level of parallelism, break up the data dependency in your loop. Right now, every iteration needs to wait for the previous iteration to complete. If you, e.g., want to have 4-way parallelism, something like this might work (assuming the # of coefficients is divisible by 4):</p>\n\n<pre><code>float y0=0.0f, y1=0.0f, y2=0.0f, y3=0.0f;\nmemmov(&amp;x[1], &amp;x[0], (len-1)*sizeof(x[0]));\nx[0] = inVal;\nfor (int i=len; i&gt;0; i-=4) {\n y0 += x[i-4]*coeff[i-4];\n y1 += x[i-3]*coeff[i-3];\n y2 += x[i-2]*coeff[i-2];\n y3 += x[i-1]*coeff[i-1];\n}\ny0 += y2;\ny1 += y3;\n\nreturn y0+y1;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T20:22:11.877", "Id": "32544", "ParentId": "32444", "Score": "3" } } ]
{ "AcceptedAnswerId": "32544", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T05:38:39.017", "Id": "32444", "Score": "5", "Tags": [ "c", "comparative-review", "signal-processing", "fpga" ], "Title": "FIR filters in C" }
32444
<p>I have a file with just 3500 lines like these:</p> <pre><code>filecontent= "13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234" </code></pre> <p>Then I want to grab every line from the <code>filecontent</code> that matches a certain string (with python 2.7):</p> <pre><code>this_item= "IBMlalala123" matchingitems = re.findall(".*?;.*?;.*?;.*?;.*?;.*?;.*?"+this_item,filecontent) </code></pre> <p>It needs 17 seconds for each <code>findall</code>. I need to search 4000 times in these 3500 lines. It takes forever. Any idea how to speed it up?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T09:52:58.180", "Id": "51842", "Score": "6", "body": "In Python it's not possible to avoid backtracking in regexps. If you can't fix the problem by modifying your regexp, then try to use the non-regexp `str.split` on the large string, and run the regexp on the small individual strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T11:46:19.317", "Id": "51851", "Score": "2", "body": "As a general rule if you can, try to avoid non-greedy matches(i.e. the `?` in `.*?`). The regexes are easier to match if they can simply match whatever they want, without thinking of finding the minimum match that works. In some situations finding a \"greedy pattern\" becomes really complex, in which case it depends on the speed you need to have as a requirement and the readability you want to achieve." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T18:03:21.173", "Id": "51885", "Score": "0", "body": "There are several good answers below, but I'm curious what the impact of compiling the regular expression would be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T18:13:29.557", "Id": "51886", "Score": "2", "body": "Looks like you've run into the O(n^2) \"edge case\" for backtracking regex engines: http://swtch.com/~rsc/regexp/regexp1.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T19:15:10.823", "Id": "51898", "Score": "0", "body": "@kojiro: not much. using an other regexp engine helps a lot. Tcl matches that regexp in 24.73725 microseconds on my machine." } ]
[ { "body": "<p><code>.*?;.*?</code> will cause <a href=\"http://www.regular-expressions.info/catastrophic.html\" rel=\"nofollow noreferrer\">catastrophic backtracking</a>.</p>\n<p>To resolve the performance issues, remove <code>.*?;</code> and replace it with <code>[^;]*;</code>, that should be much faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:35:18.953", "Id": "51840", "Score": "2", "body": "Thanks alot. I didn't got the fact at first, that I have to replace each old element with your new lement. Worked, when I did it like that :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:11:40.400", "Id": "51860", "Score": "7", "body": "Also, one other thing you should do here, is rather than repeating it, as `[^;]*;[^;]*;[^;]*;[^;]*;[^;]*;[^;]*;[^;]*`, you should shrink it down to something more concise, for instance `[^;]*(?:;[^;]*){6}`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T21:38:07.453", "Id": "530450", "Score": "0", "body": "Another option (a fairly big shift) would be to use a regex engine other than the standard library one, which doesn't backtrack." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-09T07:53:31.477", "Id": "32450", "ParentId": "32449", "Score": "35" } }, { "body": "<blockquote>\n <p>Some people, when confronted with a problem, think \"I know, I'll use regular expressions.\" Now they have two problems. -- Jamie Zawinski</p>\n</blockquote>\n\n<p>A few things to be commented :</p>\n\n<ol>\n<li><p>Regular expressions might not be the right tool for this.</p></li>\n<li><p><code>.*?;.*?;.*?;.*?;.*?;.*?;.*?\"</code> is potentially very slow and might not do what you want it to do (it could match many more <code>;</code> than what you want). <code>[^;]*;</code> would most probably do what you want.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:14:44.210", "Id": "51838", "Score": "0", "body": "The actual expression would be:\n .*?;.*?;.*?;.*?;.*?;.*?;.*?IBMlalala123\n\n Mind being a bit more explicit? I tried some variations to replace my version with yours, but failed... (should return the whole line, [^;]*;IBMlalala123 just returns the id string)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:56:29.723", "Id": "32451", "ParentId": "32449", "Score": "17" } }, { "body": "<p>Some thoughts:</p>\n\n<p>Do you need a regex? You want a line that contains the string so why not use 'in'?</p>\n\n<p>If you are using the regex to validate the line format, you can do that after the less expensive 'in' finds a candidate line reducing the number of times the regex is used.</p>\n\n<p>If you do need a regex then what about replacing '.<em>?;' with '[^;]</em>;' ?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:43:20.077", "Id": "32472", "ParentId": "32449", "Score": "2" } }, { "body": "<p>Use split, like so:</p>\n\n<pre><code>&gt;&gt;&gt; filecontent = \"13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234\";\n&gt;&gt;&gt; items = filecontent.split(\";\");\n&gt;&gt;&gt; items;\n['13P397', 'Fotostuff', 't', 'IBM', 'IBM lalala 123|IBM lalala 1234', '28.000 things', '', 'IBMlalala123|IBMlalala1234']\n&gt;&gt;&gt; \n</code></pre>\n\n<p>I'm a bit unsure as what you wanted to do in the last step, but perhaps something like this?</p>\n\n<pre><code>&gt;&gt;&gt; [(i, e) for i,e in enumerate(items) if 'IBMlalala123' in e]\n[(7, 'IBMlalala123|IBMlalala1234')]\n&gt;&gt;&gt; \n</code></pre>\n\n<p>UPDATE: \nIf I get your requirements right on the second attempt: To find all lines in file having 'IBMlalala123' as any one of the semicolon-separated fields, do the following:</p>\n\n<pre><code>&gt;&gt;&gt; with open('big.file', 'r') as f:\n&gt;&gt;&gt; matching_lines = [line for line in f.readlines() if 'IBMlalala123' in line.split(\";\")]\n&gt;&gt;&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:17:42.527", "Id": "51880", "Score": "1", "body": "+1: split is usually much faster than regex for these kind of cases. Especially if you need to use the captured field values aftwerward." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T18:36:54.137", "Id": "51889", "Score": "0", "body": "Yup, +1 for split. Regex doesn't appear to be the best tool for this job." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T13:44:37.137", "Id": "57136", "Score": "0", "body": "In my case it was about getting every full line (from some thousand lines) that has a certain string in it. Your solution gives back a part of the line, and would need some enhancements to work with some thousand files. I imagine you would suggest splitting by '\\n' and then checking each line with 'if string in line' and putting that into a list then? Don't know if this would be faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T14:46:42.827", "Id": "57145", "Score": "0", "body": "@Mike: Ok, but in your example I don't see any reference to newlines, did you mean that semicolon should signify newlines? Anyway, there is no \"fast\" way of splitting lines. The OS does not keep track of where newlines are stored, so scanning for newline chars is the way any row-reading lib works AFAIK. But you can of course save a lot of mem by reading line by line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T15:17:33.993", "Id": "57288", "Score": "0", "body": "It wasn't in the example, but in the text before and after it ;) ...file with just 3500 lines... ...want to grab every line from the filecontent that matches a certain string..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T15:30:47.630", "Id": "57293", "Score": "0", "body": "@Mike: So \"filecontent\" actually signifies the content of one line in the file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T15:54:58.790", "Id": "57301", "Score": "0", "body": "Hallo Alexander, \n...file with just 3500 lines... ...want to grab every line from the filecontent that matches a certain string...\nThis means: the file has 3500 lines in it. I refer to these 3500 lines as filecontent, as it is the content of the file...\nThe phrase 'every line' wouldn't make sense, if we were talking about one-line files." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T16:02:03.143", "Id": "57303", "Score": "0", "body": "Your solution is close, but if you look closer at my first attempt (that awful slow one), you will see, I tried to match the entry in the last field. Your last solution would have to look only for the last filed, e.g. line.split(\";\")[5] (if I counted right). It's a nice solution, thanks!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:56:41.627", "Id": "32477", "ParentId": "32449", "Score": "16" } } ]
{ "AcceptedAnswerId": "32450", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:47:42.643", "Id": "32449", "Score": "22", "Tags": [ "python", "performance", "regex", "csv", "python-2.x" ], "Title": "Regex to parse semicolon-delimited fields is too slow" }
32449
<p>I'm using a very lightweight <a href="https://github.com/grantschulte/accordion-lite" rel="nofollow">jQuery accordion</a> with some tweaks and it's working nicely. Is there anything to improve?</p> <p><strong>JS</strong></p> <pre><code>;(function($, doc, win) { "use strict"; $.fn.accordionLite = function(){ var sections = this.children(), trigger = sections.find('.accordion_trigger'), allContent = sections.find('.accordion_content'); allContent.hide(); $('.accordion_trigger.active').next('.accordion_content').show(); trigger.click(function(){ var activeContent = $(this).next('.accordion_content'); if (activeContent.is(':hidden')) { allContent.slideUp('fast'); activeContent.slideDown('fast'); trigger.removeClass('active'); $(this).addClass('active'); } else { allContent.slideUp('fast'); trigger.removeClass('active'); } }); } })(jQuery, document, window); </code></pre> <p><strong>Markup</strong></p> <pre><code>&lt;ul class="accordion"&gt; &lt;!-- Accordion Element --&gt; &lt;li&gt; &lt;!-- Section Wrapper --&gt; &lt;a class="accordion_trigger"&gt;Trigger 1&lt;/a&gt; &lt;!-- Trigger --&gt; &lt;p class="accordion_content"&gt;Content Area 1&lt;/p&gt; &lt;!-- Content --&gt; &lt;/li&gt; &lt;li&gt; &lt;a class="accordion_trigger"&gt;Trigger 2&lt;/a&gt; &lt;p class="accordion_content"&gt;Content Area 2&lt;/p&gt; &lt;/li&gt; &lt;li&gt; &lt;a class="accordion_trigger"&gt;Trigger 3&lt;/a&gt; &lt;p class="accordion_content"&gt;Content Area 3&lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre>
[]
[ { "body": "<p>This is awesome code,</p>\n\n<p>I would have added an s to <code>var trigger</code> since you are counting on more than 1 trigger.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T20:36:49.853", "Id": "68442", "ParentId": "32459", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T10:47:41.710", "Id": "32459", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Lightweight accordion script" }
32459
<p>How could the following code be made more concise?</p> <p><strong>HTML structure</strong></p> <pre><code>&lt;body&gt; &lt;header&gt; &lt;ul id="main-nav"&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/header&gt; &lt;section&gt; &lt;div class="toggle"&gt; &lt;div class="secondState"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;section&gt; &lt;div class="toggle"&gt; &lt;div class="secondState"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;section&gt; &lt;div class="toggle"&gt; &lt;div class="secondState"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/body&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>$('#main-nav li:eq(0)').on({ mouseenter: function () { $('body section:eq(0)').find('.secondState').stop().fadeIn(600); }, mouseleave: function () { if ($('body section:eq(0) .toggle').hasClass('current')) { return false; } else { $('body section:eq(0)').find('.secondState').stop().fadeOut(600); } } }); $('#main-nav li:eq(1)').on({ mouseenter: function () { $('body section:eq(1)').find('.secondState').stop().fadeIn(600); }, mouseleave: function () { if ($('body section:eq(1) .toggle').hasClass('current')) { return false; } else { $('body section:eq(1)').find('.secondState').stop().fadeOut(600); } } }); $('#main-nav li:eq(2)').on({ mouseenter: function () { $('body section:eq(2)').find('.secondState').stop().fadeIn(600); }, mouseleave: function () { if ($('body section:eq(2) .toggle').hasClass('current')) { return false; } else { $('body section:eq(2)').find('.secondState').stop().fadeOut(600); } } }); </code></pre>
[]
[ { "body": "<p>The only part of the code that changes are the index values. What if you don't specific the index yourself, but use the <a href=\"http://api.jquery.com/index/\" rel=\"nofollow\">indexof()</a> to let it determ the index itself:</p>\n\n<pre><code>var index;\n$('#main-nav li').on({\n mouseenter: function () {\n //alert($(this).index());\n index = $(this).index();\n $('body section:eq(' + index +')').find('.secondState').stop().fadeIn(600);\n },\n mouseleave: function () {\n if ($('body section:eq(' + index +') .toggle').hasClass('current')) {\n return false;\n } else {\n $('body section:eq(' + index +')').find('.secondState').stop().fadeOut(600);\n }\n }\n});\n</code></pre>\n\n<p>I place the index into a variabe so the code doesnt have to determ the index over and over. Now i only fill the index when the mouseenters, because you will have the index of the element were you entered with.</p>\n\n<p><strong><a href=\"http://jsfiddle.net/ydXHV/1/\" rel=\"nofollow\">jsFiddle</a></strong></p>\n\n<p>I hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T12:44:24.617", "Id": "51853", "Score": "0", "body": "well it is not so simple, i added html structure to my question, as you see $(this) cannot reefer to ('#main-nav') i think that index num is the key to optimize this code, and of course your code is not working" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T12:54:32.477", "Id": "51854", "Score": "1", "body": "@gidzior wat? `#main-nav` is not quite the same as `#main-nav li`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T12:58:55.597", "Id": "51855", "Score": "0", "body": "@Jan Dvorak well it is obvious, it was my shorthand, sorry for that, nevertheless nkmol example is wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:15:56.147", "Id": "51857", "Score": "0", "body": "I do apologize. I did not fully acknowledge the code. Check my update!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:26:20.060", "Id": "51858", "Score": "0", "body": "this is exactly what i meant, thx a lot for your help and sorry for not completely question" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T12:30:50.973", "Id": "32467", "ParentId": "32465", "Score": "2" } } ]
{ "AcceptedAnswerId": "32467", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T12:10:33.467", "Id": "32465", "Score": "0", "Tags": [ "javascript", "jquery", "html" ], "Title": "Specifying that one set of HTML elements controls a corresponding set" }
32465
<p>I have created a function in C on OSX in Xcode which captures the screen, adds the mouse pointer to the image, rescales the image to fit a certain width X height requirement, and puts the rescaled image in a "bounding box", and finally converts the image from RGBA to RGB.</p> <p>Is there a kind and experienced OSX developer out there who could review the code and tell me what I should change to make it execute faster?</p> <p>But most importantly, I'm interested in hearing if I overlooked something and calling the function is generating memory leaks.</p> <p>The code is here: </p> <p><a href="http://pastebin.com/rJ34vB1B" rel="nofollow">VIEW</a></p> <p><a href="http://wikisend.com/download/358390/screenshot.c" rel="nofollow">DOWNLOAD</a></p> <pre><code>void screenCapture(void) { int rc; NSRect e; int H; int W; CGRect rect; CGImageRef image; float screenshotWidth; float screenshotHeight; float requestedWidth; float requestedHeight; NSPoint mouseLoc; NSImage *overlay; NSPoint offset; int x; int y; int w; int h; int org_x; int org_y; size_t height; size_t width; size_t bytesPerRow; unsigned int * imgData; CGRect bgBoundingBox; CGContextRef context; CGImageRef imageWithMousePointer; CGImageRef imageWithMousePointerRescaled; CGImageRef imageWithMousePointerRescaledInBox; CFDataRef rawData; float wscale; float hscale; float scale; float newWidth; float newHeight; float rescaledWidth; float rescaledHeight; float origX; float origY; size_t boundingBoxWidth; size_t boundingBoxHeight; float imageWidth; float imageHeight; UInt8* buf; unsigned long byteLen; unsigned long bmpIdx; void* bitmapData; int bitmapByteCount; int bitmapBytesPerRow; int n_width; int n_height; CGColorSpaceRef colorspace; rc = 1; e = [[NSScreen mainScreen] frame]; H = (int)e.size.height; W = (int)e.size.width; screenshotWidth = (float) W; screenshotHeight = (float) H; rect.size.height = H; rect.size.width = W; rect.origin.x = 0; rect.origin.y = 0; requestedWidth = 1280.0f; requestedHeight = 720.0f; /***************************** Screenshot *************************************/ image = CGWindowListCreateImage(rect, kCGWindowListOptionIncludingWindow|kCGWindowListOptionOnScreenBelowWindow, 0, kCGWindowImageDefault); /***************************** Render cursor *************************************/ mouseLoc = [NSEvent mouseLocation]; overlay = [[[NSCursor arrowCursor] image] copy]; offset = [[NSCursor arrowCursor] hotSpot]; x = (int)mouseLoc.x; y = (int)mouseLoc.y; w = (int)[overlay size].width; h = (int)[overlay size].height; org_x = (x - w/2) - offset.x; org_y = (y - h/2) - offset.y; height = CGImageGetHeight(image); width = CGImageGetWidth(image); bytesPerRow = CGImageGetBytesPerRow(image); imgData = (unsigned int*)malloc(height*bytesPerRow); bgBoundingBox = CGRectMake (0, 0, width,height); context = CGBitmapContextCreate(imgData, width, height, 8, bytesPerRow, CGImageGetColorSpace(image), CGImageGetBitmapInfo(image)); CGContextDrawImage(context,bgBoundingBox,image); CGContextDrawImage(context,CGRectMake(0, 0, width,height),image); CGContextDrawImage(context,CGRectMake(org_x, org_y, w,h),[overlay CGImageForProposedRect: NULL context: NULL hints: NULL] ); imageWithMousePointer = CGBitmapContextCreateImage(context); CGContextRelease(context); free(imgData); /***************************** Rescale *************************************/ wscale = requestedWidth / screenshotWidth; hscale = requestedHeight / screenshotHeight; scale = hscale; if (wscale &lt; hscale) scale = wscale; newWidth = ((float) CGImageGetWidth(imageWithMousePointer)) * scale; newHeight = ((float) CGImageGetHeight(imageWithMousePointer)) * scale; n_width = CGImageGetWidth(imageWithMousePointer) * scale; n_height = CGImageGetHeight(imageWithMousePointer) * scale; bitmapBytesPerRow = (n_width * 4); bitmapByteCount = (bitmapBytesPerRow * n_height); bitmapData = malloc( bitmapByteCount ); colorspace = CGImageGetColorSpace(imageWithMousePointer); context = CGBitmapContextCreate (bitmapData,n_width,n_height,8,bitmapBytesPerRow, colorspace,kCGImageAlphaNoneSkipFirst); //CGColorSpaceRelease(colorspace); CGContextDrawImage(context, CGRectMake(0,0,n_width, n_height), imageWithMousePointer); imageWithMousePointerRescaled = CGBitmapContextCreateImage(context); CGContextRelease(context); free(bitmapData); origX = (requestedWidth - newWidth) / 2.0f; origY = (requestedHeight - newHeight) / 2.0f; /************** Insert in box ********************************/ boundingBoxWidth = (size_t) requestedWidth; boundingBoxHeight = (size_t) requestedHeight; bytesPerRow = boundingBoxWidth * (8 + 8 + 8 + 8) / 8; imgData = (unsigned int*)malloc(boundingBoxHeight*bytesPerRow); imageWidth = (float) CGImageGetWidth(imageWithMousePointerRescaled); imageHeight = (float) CGImageGetHeight(imageWithMousePointerRescaled); memset(imgData, 0, boundingBoxHeight*bytesPerRow); context = CGBitmapContextCreate(imgData, boundingBoxWidth, boundingBoxHeight, 8, bytesPerRow, CGImageGetColorSpace(imageWithMousePointerRescaled), CGImageGetBitmapInfo(imageWithMousePointerRescaled)); CGContextDrawImage(context, CGRectMake(origX,origY,imageWidth, imageHeight), imageWithMousePointerRescaled); imageWithMousePointerRescaledInBox = CGBitmapContextCreateImage(context); CGContextRelease(context); free(imgData); /*********** Convert from RGBA to RGB **********/ rawData = CGDataProviderCopyData(CGImageGetDataProvider(imageWithMousePointerRescaledInBox)); buf = (UInt8*) CFDataGetBytePtr(rawData); for (int x = 0; x &lt; 1280; x++) { for (int v = 0; v &lt; 720; v++) { int pixelStartIndex = (x + (v * 1280)) * 4; int newPixelStartIndex = (x + (v * 1280)) * 3; UInt8 R = buf[pixelStartIndex + 1]; UInt8 G = buf[pixelStartIndex + 2]; UInt8 B = buf[pixelStartIndex + 3]; bmpimg[newPixelStartIndex] = R; bmpimg[newPixelStartIndex + 1] = G; bmpimg[newPixelStartIndex + 2] = B; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T12:34:00.060", "Id": "51852", "Score": "0", "body": "Please include the code that you would like us to review in your question ([see here](http://codereview.stackexchange.com/help/on-topic))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:01:16.350", "Id": "51866", "Score": "0", "body": "Here you go...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T19:02:38.527", "Id": "51894", "Score": "0", "body": "Does OSX really use floats for width/height/etc... ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T07:44:39.870", "Id": "64682", "Score": "0", "body": "Yeah, the coordinate system is all floats. It allows for handling the difference between retina and non-retina displays better. It follows that view frames are all in floats." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T00:33:52.140", "Id": "94980", "Score": "0", "body": "@technosaurus They're not floats at all. They're CGFloats. On a 32-bit system, they're floats. On a 64-bit system, they're doubles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-17T05:35:16.107", "Id": "102294", "Score": "0", "body": "One way to speed this up is to only create and draw to a single bitmap context. Rather than creating one bitmap for the screenshot and another for the screenshot plus border, just create the one for the border. Also, don't clear the whole thing. Draw the screenshot, then draw the border (or the reverse) and you'll have covered every pixel. Don't bother doing the `memset()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-17T17:28:15.993", "Id": "102394", "Score": "0", "body": "@ user1118321 : Please modify the code and show me how you think it should be done. Thanks." } ]
[ { "body": "<p>Please make everyone (including yourself) a favor :</p>\n\n<ul>\n<li><p>Declare your variable in the smallest possible scope. Also define them as your declare them if you can (and you usually can).</p></li>\n<li><p>Split your code into smaller entities - smaller functions, smaller structures, etc.</p></li>\n<li><p>Enable every single warning your compiler supports. Here you have loads of unused variables. Keeping them is just a way to make things even harder to read.</p></li>\n<li><p>Avoid magic numbers.</p></li>\n</ul>\n\n<p>Here's what I have after declaring and defining variables in the same time :</p>\n\n<pre><code>void screenCapture(void)\n{\n // unused ? int rc = 1;\n // unused ? float rescaledWidth;\n // unused ? float rescaledHeight;\n // unused ? unsigned long byteLen;\n // unused ? unsigned long bmpIdx;\n\n NSRect e = [[NSScreen mainScreen] frame];\n int H = (int)e.size.height;\n int W = (int)e.size.width;\n float screenshotWidth = (float) W;\n float screenshotHeight = (float) H;\n CGRect rect;\n rect.size.height = H;\n rect.size.width = W;\n rect.origin.x = 0;\n rect.origin.y = 0;\n\n float requestedWidth = 1280.0f;\n float requestedHeight = 720.0f;\n\n /***************************** Screenshot *************************************/ \n CGImageRef image = CGWindowListCreateImage(rect, kCGWindowListOptionIncludingWindow|kCGWindowListOptionOnScreenBelowWindow, 0, kCGWindowImageDefault);\n\n\n /***************************** Render cursor *************************************/ \n NSPoint mouseLoc = [NSEvent mouseLocation];\n NSImage *overlay = [[[NSCursor arrowCursor] image] copy];\n NSPoint offset = [[NSCursor arrowCursor] hotSpot];\n int x = (int)mouseLoc.x;\n int y = (int)mouseLoc.y;\n int w = (int)[overlay size].width;\n int h = (int)[overlay size].height;\n int org_x = (x - w/2) - offset.x;\n int org_y = (y - h/2) - offset.y;\n size_t height = CGImageGetHeight(image);\n size_t width = CGImageGetWidth(image);\n size_t bytesPerRow = CGImageGetBytesPerRow(image);\n unsigned int * imgData = (unsigned int*)malloc(height*bytesPerRow);\n GCRect bgBoundingBox = CGRectMake (0, 0, width,height);\n CFDataRef context = CGBitmapContextCreate(imgData, width, height, 8, bytesPerRow, CGImageGetColorSpace(image), CGImageGetBitmapInfo(image));\n CGContextDrawImage(context,bgBoundingBox,image);\n CGContextDrawImage(context,CGRectMake(0, 0, width,height),image);\n CGContextDrawImage(context,CGRectMake(org_x, org_y, w,h),[overlay CGImageForProposedRect: NULL context: NULL hints: NULL] );\n CGImageRef imageWithMousePointer = CGBitmapContextCreateImage(context);\n CGContextRelease(context);\n free(imgData);\n\n\n /***************************** Rescale *************************************/ \n float wscale = requestedWidth / screenshotWidth;\n float hscale = requestedHeight / screenshotHeight;\n float scale = hscale;\n if (wscale &lt; hscale) scale = wscale;\n float newWidth = ((float) CGImageGetWidth(imageWithMousePointer)) * scale;\n float newHeight = ((float) CGImageGetHeight(imageWithMousePointer)) * scale;\n int n_width = CGImageGetWidth(imageWithMousePointer) * scale;\n int n_height = CGImageGetHeight(imageWithMousePointer) * scale;\n int bitmapBytesPerRow = (n_width * 4);\n int bitmapByteCount = (bitmapBytesPerRow * n_height);\n void* bitmapData = malloc( bitmapByteCount );\n CGColorSpaceRef colorspace = CGImageGetColorSpace(imageWithMousePointer);\n context = CGBitmapContextCreate (bitmapData,n_width,n_height,8,bitmapBytesPerRow, colorspace,kCGImageAlphaNoneSkipFirst);\n //CGColorSpaceRelease(colorspace);\n CGContextDrawImage(context, CGRectMake(0,0,n_width, n_height), imageWithMousePointer);\n CGImageRef imageWithMousePointerRescaled = CGBitmapContextCreateImage(context);\n CGContextRelease(context);\n free(bitmapData);\n float origX = (requestedWidth - newWidth) / 2.0f;\n float origY = (requestedHeight - newHeight) / 2.0f;\n\n /************** Insert in box ********************************/\n size_t boundingBoxWidth = (size_t) requestedWidth;\n size_t boundingBoxHeight = (size_t) requestedHeight;\n bytesPerRow = boundingBoxWidth * (8 + 8 + 8 + 8) / 8;\n imgData = (unsigned int*)malloc(boundingBoxHeight*bytesPerRow);\n float imageWidth = (float) CGImageGetWidth(imageWithMousePointerRescaled);\n float imageHeight = (float) CGImageGetHeight(imageWithMousePointerRescaled);\n memset(imgData, 0, boundingBoxHeight*bytesPerRow);\n context = CGBitmapContextCreate(imgData, boundingBoxWidth, boundingBoxHeight, 8, bytesPerRow, CGImageGetColorSpace(imageWithMousePointerRescaled), CGImageGetBitmapInfo(imageWithMousePointerRescaled));\n CGContextDrawImage(context, CGRectMake(origX,origY,imageWidth, imageHeight), imageWithMousePointerRescaled);\n CGImageRef imageWithMousePointerRescaledInBox = CGBitmapContextCreateImage(context);\n CGContextRelease(context); \n free(imgData);\n\n /*********** Convert from RGBA to RGB **********/\n CFDataRef rawData = CGDataProviderCopyData(CGImageGetDataProvider(imageWithMousePointerRescaledInBox));\n UInt8* buf = (UInt8*) CFDataGetBytePtr(rawData);\n\n for (int x = 0; x &lt; 1280; x++)\n {\n for (int v = 0; v &lt; 720; v++)\n {\n int pixelStartIndex = (x + (v * 1280)) * 4;\n int newPixelStartIndex = (x + (v * 1280)) * 3;\n UInt8 R = buf[pixelStartIndex + 1];\n UInt8 G = buf[pixelStartIndex + 2];\n UInt8 B = buf[pixelStartIndex + 3];\n bmpimg[newPixelStartIndex] = R;\n bmpimg[newPixelStartIndex + 1] = G;\n bmpimg[newPixelStartIndex + 2] = B;\n }\n }\n}\n</code></pre>\n\n<p>Now, I realise that I miss some information to go any further. For instance, what is bmpimg ?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T18:24:33.927", "Id": "51887", "Score": "0", "body": "Yeah, I'm sorry for the messy function. I realize that it needs a clean-up. So I appreciate your feedback a lot! To answer your question, bmpimg is a global variable (char array). I intend to change that so that the function has this signature instead : void screenCapture(char* bmpimg)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T18:25:58.810", "Id": "51888", "Score": "0", "body": "My bigger concern is if the function is generating memory leaks. I'm not sure what I have to free and when to do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T10:24:44.860", "Id": "51983", "Score": "0", "body": "Just free whatever you malloc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T20:40:33.190", "Id": "52037", "Score": "0", "body": "I know that I should free whatever I directly malloc. What I'm not sure about is those SDK calls that I'm making. For example: Should I call release on 'image' which holds the stuff returned by CGWindowListCreateImage ???" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T17:43:19.530", "Id": "32487", "ParentId": "32466", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T12:28:43.223", "Id": "32466", "Score": "2", "Tags": [ "objective-c", "cocoa", "osx" ], "Title": "Reviewing C function which captures the screen" }
32466
<p>This script creates an adhoc network using hostapd. I have tested it and seems to work reliably. I am new to linux networking and not sure if this is a recommended way to create an adhoc network this way.</p> <pre><code>#!/bin/bash #set -x DEVICE=wlan0 CONFIG_FILE=./hostapd.conf ConfigureDevice() { if ! sudo iwconfig 2&gt;/dev/null | grep $DEVICE &gt;/dev/null;then echo $DEVICE not found! exit -1 fi #Ensure config file exists if [ ! -e $CONFIG_FILE ] then echo "Can't find hostapd config file" exit -1 fi sudo service isc-dhcp-server stop sudo pkill hostapd sudo ifdown $DEVICE sudo ifconfig $DEVICE up 192.168.1.100 netmask 255.255.255.0 sudo service isc-dhcp-server start sudo hostapd -B $CONFIG_FILE } cd ${0%/*} #make current working directory the directory of the bash script ConfigureDevice </code></pre>
[]
[ { "body": "<p>Not answering your actual question, but offering a couple of code comments:</p>\n\n<p>use <code>cd -- \"$(dirname -- \"$0\")\"</code></p>\n\n<ul>\n<li>if the script is in the PATH and someone just enters the script name, you will try to cd to the (probably non-existant) \"script name\" directory in the current dir.</li>\n</ul>\n\n<p>use <code>grep -q $DEVICE</code></p>\n\n<ul>\n<li>that is a bit speedier since, if it finds a match, it exits immediately instead of having to read the entire input looking for all matches.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T10:43:18.917", "Id": "32519", "ParentId": "32470", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:09:00.133", "Id": "32470", "Score": "2", "Tags": [ "bash", "linux", "networking" ], "Title": "Bash script to set up an ad hoc wireless network" }
32470
<p>Is there is a better way of selecting the span tag that I'm dynamically adding?</p> <p>Here's what I'm trying to do:</p> <p>If you click the <code>.toggle</code> div, it shows a detailed div with the <code>id</code> that matches the <code>href</code> of the anchor tag in the particular <code>.toggle</code> div.</p> <pre><code>$('.toggle').click(function (e) { e.preventDefault(); var elemHref = $(this).find("a").attr("href"); var id = elemHref.replace('#', ''); $("#"+id).toggle(); }); </code></pre> <p>Before you click, when you hover over the <code>.toggle</code> div, it shows <code>expand</code> in a span tag if the details div is hidden. When you are not hovering over the appropriate <code>.toggle</code> div, it shows nothing if the details div is hidden and close if the details div is visible.</p> <pre><code>$('.toggle').hover(function(e) { $(this).find("a:not(:has(span))").append('&lt;span class="expand"&gt;expand&lt;/span&gt;'); $('.expand').eq(0).css({"position":"absolute", "bottom":"0", "right":"-5px"}); }, function() { var elem = $(this).find("a"); var elemHref = elem.attr("href"); var visibleDetail = $(elemHref).is(":visible"); if(visibleDetail) { $('.expand').text('close'); } else { elem.empty(); } } ); </code></pre> <p>I've thought that using <code>.children</code> might help, but is there a better way altogether than with <code>.find()</code>/<code>.children()</code>?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:33:50.850", "Id": "32471", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Checking if a child element exists" }
32471
<p>I've just solve one problem that notifies users if their password is going to expire in 14 days. The script is working fine. I just want to improve my code and desire some suggestions.</p> <pre><code>#!/usr/bin/env python # Author :- Rahul Patil&lt;linuxian.com&gt; # import sys import os #----------------------------------------------------------------- # Provide Ldap DN Details to Perform Ldap Search using anonymouse #----------------------------------------------------------------- Domain = 'linuxian.com' EmailDomain = 'abc.om' # if your mail domain is different this will becom user@abc.com ConnectDC = 'ldap://localhost:389' # if 14 days remains to expire password then it will send email to that user # until user update the new password PwdWarnDays = 14 pwdMaxAge = 45 # default password expire in 45 days as per ldap ppolicy Subject = "Ldap Password Expiry Details" MsgBody = """ Dear %s, Your Password Will be Expire in %s, we request you to please change your password, your last password change date is %s Best Regards, Linux Admin """ def GetUserDetails(): """ This Function Will save all details in file it will use ldap search query for the same.""" # Create bind dn eg. dc=example,dc=com BindDN = ','.join([ 'dc=' + d for d in Domain.split('.') ]) # import ldap l = ldap.initialize(ConnectDC) # Perform Ldap Search return l.search_s( BindDN, ldap.SCOPE_SUBTREE, '(uid=*)',['uid','pwdChangedTime'] ) def CheckExpiry(): """ This Function will Check each user ExpiryWarning if it more thans WarningDays then it will send Emails to that particuler user """ import datetime for k,v in Users: uid = ''.join(v['uid']) if 'pwdChangedTime' not in v: pass #print "User " + uid + " not Updated Password" try: l = ''.join(v['pwdChangedTime']) except: pass if 'pwdChangedTime' in v: # To extrace year month day d1 = datetime.date.today() d2 = datetime.date(int(l[0:4]),int(l[4:6]),int(l[6:8])) DaysOfPasswordChange = (d1 - d2).days d2 = d2.strftime('%d, %b %Y') ExpireIn = pwdMaxAge - DaysOfPasswordChange # if password not changed before 14 days if ExpireIn &lt;= PwdWarnDays: SendMail = "echo '" + MsgBody % (uid,ExpireIn,d2) + "' \ mail -s " + '"' + Subject + '"' + ' ' + \ uid + '@' + EmailDomain #os.system(SendMail) print SendMail if __name__ == '__main__': Users = GetUserDetails() CheckExpiry() </code></pre>
[]
[ { "body": "<p>You should read through the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">Python Style Guide</a>. You code does not follow the naming conventions most Python code uses.</p>\n\n<hr>\n\n<p>Single letter variables should be used sparingly because they might not be as intuitive as you think. A more descriptive name is better.</p>\n\n<hr>\n\n<p>Imports should generally be done at the top of the file.</p>\n\n<hr>\n\n<p><a href=\"http://docs.python.org/2/library/string.html#formatstrings\" rel=\"nofollow\"><code>string.format()</code></a> would likely me more readable than the string concatenation you are doing at the end of <code>CheckExpiry()</code>.</p>\n\n<hr>\n\n<p>Your docstrings start with \"This Function Will\". This is unnecessary since documentation will always be describing what the function does.</p>\n\n<hr>\n\n<p>At the beginning of your script, you define constants that set the date boundaries. This is good. However, you then repeatably use the value in comments. This is bad because if the policy changes to warn at 21 days, the comments need to be updated in addition to the constant's value.</p>\n\n<hr>\n\n<p>You don't need a comment for every operation. In general, comments are better at saying <strong>why</strong> you are doing something, not saying <strong>what</strong> you are doing.</p>\n\n<pre><code># if password not changed before 14 days \nif ExpireIn &lt;= PwdWarnDays:\n</code></pre>\n\n<p>You have good variable names, so this line of code explains itself, the comment doesn't add anything. If you have a line of code that is complicated enough that you feel you need to document <strong>what</strong> it is doing, this is an indication that there <em>might</em> be a better way to do it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:58:43.623", "Id": "51865", "Score": "0", "body": "Thank you very much.., Amazing answer, I will follow that" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:46:26.183", "Id": "32476", "ParentId": "32473", "Score": "4" } }, { "body": "<p>I'm just going to comment on these three lines:</p>\n\n<pre><code>SendMail = \"echo '\" + MsgBody % (uid,ExpireIn,d2) + \"' \\\n mail -s \" + '\"' + Subject + '\"' + ' ' + \\\n uid + '@' + EmailDomain \n#os.system(SendMail)\nprint SendMail\n</code></pre>\n\n<ol>\n<li><p><em>This doesn't work!</em> You've commented out the line that sends the e-mail. Now, I understand that you did this so that you can test the script without spamming your users with these messages, and that you intend to uncomment the line when you deploy the script. But this isn't the best approach.</p>\n\n<p>The first problem is that the need to test the script will come up again after you deploy it — you'll need to revise the text of the messages or change some other aspect the way it works, and then you'll want to test it again. So it would be worth your while to build in a permanent testing mechanism that's better than commenting out a line.</p>\n\n<p>The second problem is that just printing the <code>mail</code> command doesn't actually constitute a test. You have to read the output in order to check that it's correct, and you could easily miss a problem.</p>\n\n<p>What I suggest is that you have a setting that can be turned on and off to indicate whether the script is in testing or deployment:</p>\n\n<pre><code>deployed = False # Is script deployed?\ntest_uid = 'rahul.patil' # Send e-mail to this user if not deployed.\n</code></pre>\n\n<p>and that you send the e-mail to the test user when testing:</p>\n\n<pre><code>if not deployed:\n uid = test_uid\nSendMail = \"echo '\" + MsgBody % (uid,ExpireIn,d2) + \"' \\\n mail -s \" + '\"' + Subject + '\"' + ' ' + \\\n uid + '@' + EmailDomain \nos.system(SendMail)\n</code></pre>\n\n<p>Ideally you would provide a way to set the <code>deployed</code> flag (and the <code>test_uid</code>) through the script's command-line interface — see the <a href=\"http://docs.python.org/3/library/argparse.html\"><code>argparse</code></a> module for one approach to doing this.</p></li>\n<li><p>When you run a command using <a href=\"http://docs.python.org/3/library/os.html#os.system\"><code>os.system</code></a>, the command gets interpreted by the shell. This is risky, because the shell has complicated quoting and evaluation rules that you may not understand. For example, suppose that you edited <code>MsgBody</code> like this:</p>\n\n<pre><code>MsgBody = \"\"\"\nDear %s,\n Your password will expire in %s day(s). We're sorry for the\ninconvenience, but we need you to change your password by %s.\n\"\"\"\n</code></pre>\n\n<p>Looks good, right? But if you actually try this, you'll find that the call to <code>os.system</code> fails with an error like this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>sh: line 3: inconvenience,: command not found\nsh: -c: line 4: unexpected EOF while looking for matching `''\nsh: -c: line 5: syntax error: unexpected end of file\n</code></pre>\n\n<p>That's because the single quote in <code>We're</code> was interpreted by the shell as terminating the argument to <code>echo</code>.</p>\n\n<p>In order to avoid problems like this (where data gets wrongly interpreted as code by the shell), you should avoid passing the arguments to the shell. Instead of <code>os.system</code>, you should use the functions in the <a href=\"http://docs.python.org/3/library/subprocess.html\"><code>subprocess</code></a> module. For example, like this:</p>\n\n<pre><code>import subprocess\n\np = subprocess.Popen(['mail', '-s', Subject, uid + '@' + EmailDomain],\n stdin=subprocess.PIPE)\np.communicate(MsgBody % (uid, ExpireIn, d2))\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:06:47.197", "Id": "51876", "Score": "0", "body": "thanks for your reply , it is useful, but I want to say that mail command is working without any issue, I have tested.. may be because of my Luck :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:08:15.803", "Id": "51877", "Score": "1", "body": "That's fine for now, but what about later, after you or some other developer makes a change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:11:59.217", "Id": "51878", "Score": "1", "body": "Better yet, send mail using a [library call](http://docs.python.org/2/library/email-examples.html) instead of a shell command." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:15:46.543", "Id": "51879", "Score": "1", "body": "@200_success: I did consider that, but it's not all that compelling in a simple case like this one. (A couple of lines with `subprocess` versus eight lines with `email` and `smtplib`.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:33:39.973", "Id": "51882", "Score": "0", "body": "@GarethRees I'm adopting your suggestion into my code, that's working, can you please help me with print that mail command on terminal" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T15:59:13.107", "Id": "32480", "ParentId": "32473", "Score": "6" } }, { "body": "<p>I would add \"bind_s\" to connect to ldap with a user</p>\n\n<pre><code>user_dn = 'someuser'\nuser_pwd = 'somepassword'\nl = ldap.initialize(ConnectDC)\nl.bind_s(user_dn, user_pwd) #LDAP admin would not allow to query pwdChangedTime as anonymous\n</code></pre>\n\n<p>and change some code to make it more beautiful when sending mail:</p>\n\n<pre><code>return l.search_s(bind_dn, ldap.SCOPE_SUBTREE, '(uid=*)', ['displayName', 'pwdChangedTime', 'uid'])\n\nfor k, v in Users:\n uid = ''.join(v['uid'])\n if 'displayName' in v:\n displayname = ''.join(v['displayName'])\n else:\n displayname = uid\n...\nif 'pwdChangedTime' in v:\n...\nelse:\n d2 = '[You have not changed your password since account created]'\n...\nprint mail_body % (displayname, pwd_expire_in_days, d2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T06:57:13.370", "Id": "35667", "ParentId": "32473", "Score": "2" } }, { "body": "<p>I would separate the function definitions from the script functionality with <code>if __name__ == '__main__':</code> as is customary for Python. Also I would have <code>CheckExpiry()</code> take \"Users\" as an argument and return a list of expired users (or a tuple of name and e-mail address for each). So that would read more like:</p>\n\n<pre><code>#!python\n# ....\nif __name__ == '__main__':\n userdata = GetUserDetails()\n expired = CheckExpiry(userdata)\n# ...\n</code></pre>\n\n<p>From there I'd create a template (perhaps as simple as one using <a href=\"https://docs.python.org/2/library/string.html#template-strings\" rel=\"nofollow\">string.Template</a> from the Python standard libraries, or possibly using something like <a href=\"http://jinja.pocoo.org/docs/dev/\" rel=\"nofollow\">Jinja2</a> ... and use it to generate the messages to each user.</p>\n\n<p>If you really want to get fancy you could track the number of warnings you've sent to each user, perhaps in a very simple local flat file database using <a href=\"https://docs.python.org/2/library/sqlite3.html\" rel=\"nofollow\">SQLite3</a> (also from the standard library).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-20T05:24:10.840", "Id": "84549", "ParentId": "32473", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:02:29.203", "Id": "32473", "Score": "2", "Tags": [ "python", "beginner", "ldap" ], "Title": "Password expiry notification script" }
32473
<p>In C++11 we have the option of using <code>std::unordered_set</code> if we require a list of elements that have no duplicates but order is not important.</p> <p>In C++03 we don't have this options, although we can use the <code>std::set</code> to achieve something similar. Let's consider the following code:</p> <pre><code>std::set&lt;ElementType, std::NotEqualTo&lt;ElementType&gt;&gt; unorderedSet; unorderedSet.insert(some_element); unorderedSet.insert(other_element); unorderedSet.insert(some_element); //... more stuff with the set </code></pre> <p>This will, basically produce a set that will store the elements in the order they were inserted while preventing duplicates. Note that <code>ElementType</code> simply <b> can't </b> have less than or greater than operator. It doesn't make sense, semantically speaking.</p> <p>Anyway, since I am using <code>std::NotEqualTo</code> instead of a <code>LessThan</code> functor, as it is requested by the set, I am not feeling very comfortable with this code. I do know that set is using something such as </p> <pre><code>if first element &lt; second element //insert accordingly else if second element &lt; first element //insert accordingly else //they are equal </code></pre> <p>but in the same time, theoretically, my code will be failing if the checks were more strict such as</p> <pre><code>if first element &lt; second element AND !(second element &lt; first element) //... </code></pre> <p>My questions are:</p> <ol> <li>There are any potentially problems that could arise from using this construct?</li> <li>What other alternatives I have to achieve the same thing in a more readable form? I do not plan to write my own unordered set just for this scenario and can't really use any external libraries. Only standard library available in C++03.</li> </ol> <p>Edit: I am unable to make use of "less than" operator between my elements. I can decide if they are equal or not but I can't say which one is smaller than other. With the default set functor the code won't even compile as "operator&lt;" is not found. This is why I wanted to model the functor with equal operator in the first case.</p> <p>I am also aware that it is not valid, however, the code will produce the desired results. From my understanding it will expand to something such as:</p> <pre><code>if first element != second element // place first element else if second element != first element // this is buggy, but should never be executed; first condition will always be true, unless the elements are equal. else //here the elements are equal . </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T20:43:36.317", "Id": "51905", "Score": "3", "body": "Using `std::NotEqualTo` is not valid. The comparator must generate a **strict weak ordering** for the code to work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T20:45:38.733", "Id": "51906", "Score": "0", "body": "see: http://www.sgi.com/tech/stl/set.html About half way down the page you will see the requirements on comparator `Compare The key comparison function, a Strict Weak Ordering whose argument type is key_type; it returns true if its first argument is less than its second argument, and false otherwise. This is also defined as set::key_compare and set::value_compare. less<Key>`. Then http://www.sgi.com/tech/stl/StrictWeakOrdering.html is defined here." } ]
[ { "body": "<blockquote>\n<p>My questions are:</p>\n<p>There are any potentially problems that could arise from using this construct?</p>\n</blockquote>\n<p>Its not valid.<br />\nThe code will not work as expected as the <code>std::set</code> requires the comparator type to generate a strict weak ordering between elements.</p>\n<blockquote>\n<p>What other alternatives I have to achieve the same thing in a more readable form? I do not plan to write my own unordered set just for this scenario and can't really use any external libraries. Only standard library available in C++03.</p>\n</blockquote>\n<p>You can use <code>std::set</code> as an unordered container as is. If you have an unordered container it does not matter to you what order the elements are in. If they just happen to be ordered does that matter?</p>\n<p>The reason for using <code>std::unordred_set</code> is that it provides faster access to the elements. You give up an ordered property to get better performance.</p>\n<pre><code>Container: Insert find\nstd::set O(ln(n)) O(ln(n))\nstd::unordered_Set O(1) O(1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T20:55:37.187", "Id": "32494", "ParentId": "32475", "Score": "6" } } ]
{ "AcceptedAnswerId": "32494", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:15:22.493", "Id": "32475", "Score": "4", "Tags": [ "c++", "c++03" ], "Title": "Using set for unordered, unique list of elements" }
32475
<p>I have the code below:</p> <pre><code>&lt;?php $i = array(1, 2, 3); $w = array(1 =&gt; '11', 2 =&gt; '22', 3 =&gt; '33'); foreach ($i as $f) { $ws = $w[$f]; $file_names[] = array( 'fn' =&gt; 'fname', 'sn' =&gt; 'sname', 'is' =&gt; 'is', 'rv' =&gt; 'rv' ); foreach ($file_names as $k =&gt; $v) { if (!isset($file_names[$k]['mod'])) { $file_names[$k]['mod'] = array( 'ct', 'pt' ); } if (!isset($file_names[$k]['pw'])) { $file_names[$k]['pw'] = array( 'task' =&gt; '3', 'min' =&gt; 'min', 'max' =&gt; 'max', 'value' =&gt; "" . $ws . "" ); } } } print_r($file_names); ?&gt; </code></pre> <p>What I’m trying to do is add new elements to an array in some particular conditions. The only thing that I don’t like is the second <code>foreach</code> loop part. I.e.:</p> <pre><code> foreach ($file_names as $k =&gt; $v) { if (!isset($file_names[$k]['mod'])) { $file_names[$k]['mod'] = array( 'ct', 'pt' ); } if (!isset($file_names[$k]['pw'])) { $file_names[$k]['pw'] = array( 'task' =&gt; '3', 'min' =&gt; 'min', 'max' =&gt; 'max', 'value' =&gt; "" . $ws . "" ); } } </code></pre> <p>Is there any way to write this in a more elegant manner?</p>
[]
[ { "body": "<p>maybe I am missing something, but why do you even need to have two different arrays $i and $w? second thing, <code>$file_names</code> array should go outside of the foreach loop since this array doesn't depend on the iteration of the first foreach loop.</p>\n\n<p>I am not sure about the exact output which you expect but it seems that you can only iterate through the file names array and when you need to update this line </p>\n\n<p><code>'value' =&gt; \"\" . $ws . \"\"</code> , you could just look up the value of $ws in the particular array rather than iterating the entire array every time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T09:57:55.410", "Id": "32517", "ParentId": "32482", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:23:06.793", "Id": "32482", "Score": "2", "Tags": [ "php" ], "Title": "Add elements to an array inside a foreach loop" }
32482
<p>My database (SQL Server 2008) looks like this:</p> <blockquote> <p>People 1 -- * TaskPersons * -- 1 Tasks * -- 1 Project</p> </blockquote> <p>The <code>GROUP BY</code> part of the query is quite long, all because of the <code>COUNT</code> aggregate. This seems to perform reasonably well. I would like to know if there is a more concise way of writing this.</p> <pre><code>use Projects SELECT COUNT(t.id), ppl.Name, ppl.Birthdate, ppl.Title, ppl.Role, ppl.Status, ppl.Warehouse, ppl.StartDate, ppl.SalaryBand, ppl.Salary,p.Title FROM People ppl JOIN TaskPersons tp On tp.PersonId = ppl.Id JOIN Tasks t ON t.Id = tp.TaskId JOIN Projects p ON p.Id = t.ProjectId GROUP BY ppl.Name, ppl.Name, ppl.Birthdate, ppl.Title, ppl.Role, ppl.Status, ppl.Warehouse, ppl.StartDate, ppl.SalaryBand, ppl.Salary, p.Title </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T03:48:55.700", "Id": "51964", "Score": "1", "body": "If you group by project title, and there is a one-to-one correspondence between projects and tasks, then won't the count of tasks be 1 for every row?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T19:55:13.370", "Id": "52034", "Score": "0", "body": "Thank you, my relationship is listed in correctly, I have revised." } ]
[ { "body": "<p>Try putting <code>GROUP BY</code> in a sub-select.</p>\n\n<pre><code>SELECT personTaskProject.TaskCount,\n ppl.Name,\n ppl.Birthdate,\n ppl.Title,\n ppl.Role,\n ppl.Status,\n ppl.Warehouse,\n ppl.StartDate,\n ppl.SalaryBand,\n ppl.Salary,\n personTaskProject.Title\n FROM\n People ppl,\n (SELECT COUNT(t.id) TaskCount, tp.PersonId, p.Title\n FROM TaskPersons tp\n JOIN Tasks t\n ON t.Id = tp.TaskId\n JOIN Projects p\n ON p.Id = t.ProjectId\n GROUP BY tp.PersonId, p.Title) AS personTaskProject\n WHERE ppl.Id = personTaskProject.PersonId;\n</code></pre>\n\n<p><a href=\"http://sqlfiddle.com/#!3/1ffc5/2\" rel=\"nofollow\">SQL Fiddle</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T20:19:24.147", "Id": "53533", "Score": "0", "body": "I did not test this to see if there was any performance difference, but it definitely looks cleaner." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T23:26:37.933", "Id": "32548", "ParentId": "32484", "Score": "3" } } ]
{ "AcceptedAnswerId": "32548", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:55:03.323", "Id": "32484", "Score": "3", "Tags": [ "sql", "sql-server" ], "Title": "Listing employees and their project tasks" }
32484
<p>The main purpose of Ruby is to be readable. I hope I did a good job with this gem I made. If there's any kind of suggestion of how to make this better, then please tell me.</p> <pre><code>class Trigger def initialize event, *callbacks @callbacks = callbacks @event = event if @callbacks[0].is_a? TrueClass @progression = true @callbacks.delete_at(0) elsif @callbacks[0].is_a? FalseClass @progression = false @callbacks.delete_at(0) else @progression = false end end def trigger(*args) case @event when Proc event_data = @event.call when Method event_data = @event.call else event_data = self.method(@event).call(*args) end @callbacks.each do |callback| if callback.instance_of? Trigger if @progression callback.trigger(*args, event_data) else callback.trigger(*args) end else case callback when Proc if @progression callback.call(*args, event_data) else callback.call(*args) end when Method if @progression callback.call(*args, event_data) else callback.call(*args) end else if @progression method(callback).call(*args, event_data) else method(callback).call(*args) end end end end end #triggers the callbacks without executing the original method def silent_trigger(*args) @callbacks.each do |callback| if callback.instance_of? Trigger callback.trigger(*args) else case callback when Proc callback.call when Method callback.call else method(callback).call(*args) end end end end # add callback(s) to instance def add(*callbacks) @callbacks.concat callbacks end def insert(index, *callbacks) @callbacks.insert(index, callbacks) end # remove callback(s) from instance def remove(*callbacks) callbacks.each do |callback| @callbacks.delete_at(@callbacks.index(callback) || @callbacks.length) end end def delete_at(index) @callbacks.delete_at(index) end def remove_all @callbacks = [] end # fetch info from instance def index(callback) @callbacks.index(callback) end def event_name @event end def list @callbacks end end </code></pre> <p>And if you want to try it out, here's a quick little console program to show you how it works:</p> <pre><code>$foobar = 0 def foo $foobar += 1 end def bar puts $foobar end # create Trigger and callback, then trigger the Trigger _foo = Trigger.new(:foo, :bar) _foo.trigger # create a method to determine if bar has been called before $bar_called? = false def bar_called $bar_called = true end # create a callback for the callback _bar = Trigger.new(:bar, :bar_called) # replace old callback with new one (note: you can use Methods, Procs, Symbols, Strings, or other Triggers too) _foo.remove(:bar) _foo.add(_bar) # methods are not called when added to Trigger callbacks, only when triggered puts $bar_called? _foo.trigger puts $bar_called? </code></pre> <p>You can find the gem <a href="https://rubygems.org/gems/triggerful" rel="nofollow">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-20T12:51:44.933", "Id": "52707", "Score": "0", "body": "added an answer, but now that i check your console example, I think you have a mistake on your logic : when you pass in a symbol as a callback, the method will be called on the `Trigger` instance, not on the caller's context as your console code suggests. It's better to use a proc or block in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-20T18:06:49.757", "Id": "52727", "Score": "0", "body": "Andrew, have a close look at @m_x's answer. I think it's very nice, preferable to mine. If you agree, feel free to change your preferred answer selection." } ]
[ { "body": "<p>Here a some suggestions for the first three methods:</p>\n\n<pre><code> def initialize event, *callbacks\n @callbacks = callbacks\n @event = event\n\n case @callbacks[0]\n when TrueClass\n @progression = true\n @callbacks.delete_at(0)\n when FalseClass\n @progression = false\n @callbacks.delete_at(0)\n else\n @progression = false\n end\n end\n\n def trigger(*args)\n arguments = args.dup\n if @progression\n arguments &lt;&lt; case @event\n when Proc, Method\n @event.call\n else\n method(@event).call(*args)\n end\n end\n silent_trigger(*arguments)\n end\n\n #triggers the callbacks without executing the original method\n def silent_trigger(*args)\n @callbacks.each do |callback|\n case callback\n when Trigger\n callback.trigger(*args)\n when Proc, Method\n callback.call\n else\n method(callback).call(*args)\n end\n end\n end\n</code></pre>\n\n<p>I didn't check the code carefully, so there could be a few minor problems to fix.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:54:49.667", "Id": "52009", "Score": "0", "body": "I see a problem in the `if @progression` right there. It won't trigger the event if you have `@progression` set to `false`. I'm also guessing that `@progression` isn't exactly self-explanatory without knowing what it does (seeing as I didn't use an example of it in my original question), but also after reviewing what you wrote, I found some typos in my own script. Thanks for spending some of your time on me!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T21:36:24.540", "Id": "52040", "Score": "1", "body": "When you're finished with mods, consider editing your question to include the GitHub address." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T22:13:43.083", "Id": "32495", "ParentId": "32485", "Score": "2" } }, { "body": "<h3>1) get rid of conditionals</h3>\n\n<p>I think your main problem here is the nested conditionals that litter your code. This increases complexity and tends to be less readable.</p>\n\n<p>You can get rid of those conditionals using a method like this :</p>\n\n<pre><code>def make_callable(object)\n case object\n when Proc, Method then object\n when Trigger then -&gt;(*args){ object.trigger(*args) }\n else -&gt;(*args){ public_send object, *args }\n end\nend\n</code></pre>\n\n<p>so you can do things like : </p>\n\n<pre><code>@event = make_callable(event)\n@callbacks = callbacks.map{ |c| make_callable c }\n</code></pre>\n\n<p>This way, all your callbacks will respond to <code>call</code> uniformly, so you won't need conditionals anymore.</p>\n\n<h3>2) use inheritance</h3>\n\n<p>As i see it, your <code>@progression</code> instance variable masks the need for two different behaviors, which means two different classes : a \"silent\" trigger, and a \"verbose\" one that extends the former.</p>\n\n<pre><code>class Trigger\n\n # factory method to instantiate the right type of callback.\n # I slightly changed the signature from the original #initialize\n # as I thought it would make more sense this way, \n # but it is possible to keep the original one with minor tweaks\n #\n def self.factory(verbose, event, *callbacks)\n verbose ? Verbose.new(event, *callbacks) : new(event, *callbacks)\n end\n\n def initialize(event, *callbacks)\n @event = make_callable(event)\n @callbacks = callbacks.map{ |c| make_callable c }\n end\n\n # SNIP : this class would also expose add_callback, remove_callback, etc.\n\n def trigger(*args)\n @callbacks.each{ |c| c.call(*args) }\n end\n\n private \n\n def make_callable(object)\n case object\n when Proc, Method then object\n when Trigger then -&gt;(*args){ object.trigger(*args) }\n else -&gt;(*args){ public_send object, *args }\n end\n end\nend\n\nclass Trigger::Verbose &lt; Trigger\n def trigger(*args)\n event_data = @event.call(*args)\n super(*args, event_data)\n end\nend\n</code></pre>\n\n<p>As you can see, this simplifies the logic a lot, and makes clear that we have two different behaviors, which is invaluable for consumers of your API.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T20:44:25.527", "Id": "53087", "Score": "0", "body": "About the super in the Verbose class, doesn't it need to have the name of the method to invoke? Or does it by default invoke the same method in it's superclass?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T20:49:58.900", "Id": "53088", "Score": "1", "body": "`super` just tells ruby to invoke the same method up the inheritance chain. if you use `super` alone, it will call the parent class' method with the same arguments as the caller, that's why i pass in the extra argument, and that's why you sometimes see `super()` (to force calling without arguments)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T20:56:02.103", "Id": "53089", "Score": "0", "body": "And by the last statement \"to force calling without arguments\" you mean the arguments being which methods to call, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T21:04:21.393", "Id": "53090", "Score": "0", "body": "no. `super` is a bit peculiar, it's not a method, it's a [reserved word](http://zenspider.com/Languages/Ruby/QuickRef.html#reserved-words) (a built-in feature of the language). Think about `super`as a sort of placeholder for \"the same method in the _super_class\". See [this](http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html) (section \"inheritance and messages\") for more in-depth information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T21:15:26.613", "Id": "53091", "Score": "0", "body": "Oh, I misread what you were intending to saying in the other post. Also, to further explain, `@progression` doesn't differentiate between a \"silent\" trigger and a \"verbose\" trigger. It defines whether or not to pass the return value of the event to its callbacks. The reason why I didn't really explain this in the question is because I wanted to see if people could understand what it does from the code itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T21:19:11.707", "Id": "53093", "Score": "0", "body": "feel free to edit the post and rename the class then. Maybe something like `Trigger::WithProgression` ? I don't know, everyone has their own way to name things :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T21:45:18.013", "Id": "53095", "Score": "0", "body": "I don't think that the behavior of the progression really needs a new class. It's pretty much just a setting for the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T21:56:01.420", "Id": "53097", "Score": "0", "body": "I'll update the question with my current code after I put everything together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-24T07:25:16.187", "Id": "53124", "Score": "0", "body": "maybe, it's up to you. in this case, just do something like : `def trigger(*args); @callbacks.each{ |c| a = args.dup; a << @event.call(*args) if @progression; c.call(*a)}; end`" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-20T12:09:20.717", "Id": "32962", "ParentId": "32485", "Score": "4" } } ]
{ "AcceptedAnswerId": "32962", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T17:24:10.530", "Id": "32485", "Score": "3", "Tags": [ "ruby" ], "Title": "Triggerful Ruby Gem: create dynamic callbacks to methods" }
32485
<p>What would be the fastest way of skipping certain values in a for loop? This is what I intend to do in its most basic form, with about 20 more keys to omit.</p> <pre><code>for (var key in arr ) { if ( key != 'ContentType' &amp;&amp; key != 'FileRef' ) { arrayPushUnknown( columns, formatTitle( key ), true, key ) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T17:51:57.127", "Id": "51884", "Score": "2", "body": "I'm a big fan of 'continue'. `if( wanting_to_skip_condition ) continue;` then the rest of the code you want run during a good loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T18:56:48.310", "Id": "51890", "Score": "0", "body": "could you elaborate a little more on what you are doing and what you want? what you are doing currently?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T19:02:50.480", "Id": "51895", "Score": "0", "body": "Sure, the keys in the object are fields in a SharePoint document library. There are a lot of default fields that I do not need, so I wish to skip the keys I do not need and add the rest to a fresh object. The function \"arrayPushUknown\" just adds the keys I need to the new object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T19:42:00.700", "Id": "51899", "Score": "1", "body": "@Skarven: Make an array containing all the keys you want to skip and then `if (keysToBeOmitted.Contains(key)) continue`. If you are concerned about performance then make sure your `keysToBeOmitted` array is sorted and do a binary search on it (`localCompare()` should help with that)" } ]
[ { "body": "<p>There are several possible approaches:</p>\n\n<p>1) The straightforward:</p>\n\n<pre><code>function contains(array,element){\n return array.indexOf(element)!=-1;\n}\n\nfunction filter(unfilteredArray){\n var filteredArray=[];\n for(var i=0; i&lt;unfilteredArray.length; i+=1){\n if(contains(omitted,unfilteredArray[i])) continue;\n filteredArray.push(unfilteredArray[i]);\n }\n return filteredArray;\n}\n</code></pre>\n\n<p>Looping over your array and sorting out, which ones you don't like.\nYou could play with this <a href=\"http://jsfiddle.net/4T4JL/\" rel=\"nofollow\">Fiddle</a></p>\n\n<p>2) The \"functional\" approach</p>\n\n<pre><code>function omitting_1_to_10(element){\n return [1,2,3,4,5,6,8,9,10].indexOf(element)==-1;\n}\n\nconsole.log([1,2,3,4,11].filter(omitting_1_to_10));\n</code></pre>\n\n<p>Define your omitting filter and apply it to your array.\nFor <code>Array.filter</code> read the according <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow\">MDN</a>-article.</p>\n\n<p>3) Doing it with a RegEx:</p>\n\n<pre><code>function filter(unfilteredArray){\n var filteredArray=[];\n for(var i in unfilteredArray){ \n if(/\\b1\\b|\\b2\\b|\\b3\\b|\\b4\\b|\\b5\\b|\\b6\\b|\\b7\\b|\\b8\\b|\\b9\\b|\\b10\\b/.test(unfilteredArray[i])) continue;\n filteredArray.push(unfilteredArray[i]);\n }\n return filteredArray;\n}\nconsole.log(filter([1,2,3,4,11]));\n</code></pre>\n\n<p>Here is the <a href=\"http://jsfiddle.net/c4hpf/1/\" rel=\"nofollow\">Fiddle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T20:21:34.467", "Id": "32493", "ParentId": "32486", "Score": "2" } }, { "body": "<p>A switch block works about 4% faster on a pre-release Safari 6.1, but is 11% slower on Firefox 17. Regardless of performance, I like the switch block better stylistically, especially if there are more exceptional keys.</p>\n\n<p><a href=\"http://jsperf.com/codereview-32486\" rel=\"nofollow\">http://jsperf.com/codereview-32486</a></p>\n\n<pre><code>for (var key in arr) {\n switch (key) {\n case 'ContentType':\n case 'FileRef':\n break;\n default:\n arrayPushUnknown(columns, formatTitle(key), true, key);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T14:16:10.570", "Id": "51995", "Score": "0", "body": "Thanks, I extended your test with some more exceptions, and the performance increase on Safari grew to 23% faster. As the code will iterate through thousands of items and iPhone performance is central, this is very helpful.\n\nhttp://jsperf.com/codereview-32486/3" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:01:41.793", "Id": "52010", "Score": "1", "body": "@200_success http://stackoverflow.com/questions/18076238/continue-allways-illegal-in-switch-in-js-but-break-works-fine . Then a for-in loop as an optimization? http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:09:55.843", "Id": "52012", "Score": "0", "body": "@Skarven Have you tested mine? I modified your test case -> http://jsperf.com/codereview-32486/4 Also, make sure to test in **multiple browsers**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T22:54:54.170", "Id": "52041", "Score": "0", "body": "Corrected `continue` to `break`. Thanks, @technosaurus." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T04:40:33.813", "Id": "52059", "Score": "0", "body": "@plalx - Thanks for setting up the test, and the results are interesting, your object map approach outperforms the switch approach by a massive 42% in IE 9 and by 12% in FireFox 24. In Safari 5.1.7 (PC), however - the switch is 12% faster than the object map, and in Chrome, the object map is 24% slower than both the switch and the \"if foo not bar\" approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T04:51:59.773", "Id": "52060", "Score": "0", "body": "@Skarven Yeah, I was quite sure that it wouldn't be consistent however as far as I can see, the map has a better overall performance. Also I just ran the tests on my computer with Chrome 30.0.1599 and the map performed better. Anyway, do not forget we speak about millions of OP/S with average computers. I would rather choose the most readable and flexible method since you will not notice any difference between the 3 methods. Personnaly, I like the map approach way better than others." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T02:31:22.840", "Id": "32505", "ParentId": "32486", "Score": "2" } }, { "body": "<p>One of the simplest and probably fastest way to do it would be to store the keys to ignore in a fast lookup structure, such as using an object as a map.</p>\n\n<p>First you need to build the map, which takes O(n) time based on the number of keys to ignore, but allows you to ignore keys with a condition that will take O(1) time to compute.</p>\n\n<pre><code>var keysToIgnore = ['ContentType', 'FileRef'].reduce(function (res, key) {\n res[key] = true;\n return res;\n}, {});\n</code></pre>\n\n<p>Then within the loop, if the key should be ignored, just continue.</p>\n\n<pre><code>if (keysToIgnore[key]) continue;\n</code></pre>\n\n<p>The algorithm will probably not be an order of magnitude faster (slower? could be!) than a bunch of ifs or a switch statement, but it will definitely be more readable. It also has the advantage of being dynamic, since you can add or remove keys from keysToIgnore.</p>\n\n<p><em>Note: If you have to perform the iteration process many times, it could be faster to simply filter out the keys using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow\"><code>Array.prototype.filter</code></a> and the algorithm described above.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T03:13:11.247", "Id": "51961", "Score": "1", "body": "I like how this way (`continue` + reversed OP's condition) removes needless nesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T14:03:01.587", "Id": "51994", "Score": "0", "body": "Thanks, I am trying this out along with other solutions - but yes, my goal is performance, as I will be iterating through thousands of elements (documents in the Document Library)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:11:11.803", "Id": "52013", "Score": "0", "body": "@Skarven Have you tested mine? I modified your test case -> http://jsperf.com/codereview-32486/4 Also, make sure to test in **multiple browsers**." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T02:56:44.657", "Id": "32506", "ParentId": "32486", "Score": "2" } }, { "body": "<ul>\n<li>Tests across various browser has shown a reverse while loop is fastest.</li>\n<li>Accessing array.length is slower than storing it in a variable to iterate on.</li>\n<li>You can just \"push\" to an array by storing the value in the last element which is conveniently at .length</li>\n<li>A switch may not be much faster in this case (though it can be with other data) than a bunch of &amp;&amp;s and ||s, but its much easier to read and the fallthrough characteristic allows you to write like code in groupings. In this case we only have 2 groups: do nothing (<code>break;</code>) and the default \"push\"</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>var i=arr.length;\nvar newarr=[];\nwhile (i--){\n switch (arr[i].key){\n case 'ContentType' :\n case 'FileRef' :\n case (other) :\n case (cases) :\n case (here) :\n break;\n default: newarr[newarr.length]=arr[i];\n }\n}\n</code></pre>\n\n<p>On a few newer browsers (Chrome for one), push is faster than direct assignment. Note that this will be reversed from the original array, but if you need to keep them in the same order using <code>for(var i=0,len=arr.length;i&lt;len;i++)</code>, I caution you <strong>not</strong> to be tempted to use <code>newarr[i]=arr[i]</code> or you will get empty slots where your keys match your blacklist.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T03:40:24.510", "Id": "51963", "Score": "0", "body": "@200_success No, the break is for the switch, not the while." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T03:10:37.190", "Id": "32507", "ParentId": "32486", "Score": "3" } } ]
{ "AcceptedAnswerId": "32506", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T17:42:54.603", "Id": "32486", "Score": "2", "Tags": [ "javascript", "performance" ], "Title": "Optimal way of skipping certain values in a for loop" }
32486
<p>I'm trying to write a short function which takes a list (<code>a</code>) and returns another list which only contains the elements (<code>x</code>) such that <code>-x</code> is also in <code>a</code>. I've done that, and it works, but it runs really slowly. I know why it does, and I know the second <code>for</code> loop is unnecessary, but I don't know how to fix it without breaking the function.</p> <pre><code>def negated(a): mark = set() add_mark = mark.add b = [] c = [] for i in a: if i not in mark and not add_mark(i): b.append(i) for i in b: if -i in b: c.append(i) return c </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:29:33.923", "Id": "51917", "Score": "0", "body": "How big are your lists? How fast is this code? Can you provide some more details?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:32:29.213", "Id": "51918", "Score": "2", "body": "Add the whole of `a` to your set, then do all of your membership checks against that. Set lookups are O(1) time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:33:52.127", "Id": "51919", "Score": "0", "body": "One thing you could do is split the list into positive and negative number lists beforehand, and iterate through only one of them, checking whether the corresponding value is present in the other list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:34:53.090", "Id": "51920", "Score": "2", "body": "This is a two-liner if you just build the set directly from the list. `mark = set(a); return [x for x in a if -x in mark]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:36:48.073", "Id": "51922", "Score": "0", "body": "@PeterDeGlopper That is concise, but the OP is looking for efficiency. With every iteration in that comprehension, you are wasting time checking against values of the same sign as x, and you are also performing twice as many searches as is necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:37:04.380", "Id": "51923", "Score": "1", "body": "Are you answering the same assignment that Nolan Hodge had [a few hours ago](http://stackoverflow.com/questions/19279449/return-values-in-list-that-also-have-a-negated-value/19279505#19279505)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:37:56.367", "Id": "51925", "Score": "0", "body": "@Asad: If you just change the `for x in a` to `for x in mark`, Peter DeGlopper's answer is likely as fast as possible. (That assumes that order doesn't matter, and that there are no duplicates or they don't matter, but that was true for the near-identical question I linked to)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:38:15.300", "Id": "51926", "Score": "0", "body": "And yeah, it looks that way Abarnert. Didnt see it in the search" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:40:20.597", "Id": "51927", "Score": "0", "body": "@abarnert For an input set `[1, 2, 3, 4, 5, -3]`, it is more efficient to separate the negatives from the positives in bulk, so that when checking for the presence of any negative, you don't have to compare against `1,2,3,4,5` on every iteration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:41:01.320", "Id": "51928", "Score": "0", "body": "@Asad: A lookup against a set of size N is just as fast as against a set of size N/2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:41:51.120", "Id": "51929", "Score": "0", "body": "@abarnert But it isn't 1 lookup. It is N lookups, since you're going through the entire list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:42:23.307", "Id": "51930", "Score": "0", "body": "@Asad - correct on the twice as many comparisons - I consider that acceptable in order to get the syntax benefits of a comprehension - but I'm not sure what you mean about 'checking against values of the same sign as x'. I doubt that the speed gains of having two different half-sized sets to check for membership in outweigh the time needed to split the list in two to construct the sets. I'd also want to profile the comprehension against an explicit for loop that avoids the extra comparisons - I suspect the comprehension is implemented faster even if it's technically doing more work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:43:02.293", "Id": "51931", "Score": "0", "body": "@PeterDeGlopper I'll get back to you with a perf on that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:44:16.743", "Id": "51932", "Score": "0", "body": "@Asad: Well, you're saving N/2 O(1) lookups by doing an extra N O(1) lookups…" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:52:36.040", "Id": "51936", "Score": "0", "body": "What is the correct output if the input is `[-1, -1, 1]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:37:15.107", "Id": "51953", "Score": "0", "body": "@Alex: I just realized we spent an hour arguing about trivial tweaks without anyone ever pointing out the basic flaw in your original version, which is what you asked for… I'll edit my answer to explain that." } ]
[ { "body": "<p>For the sake of clarity, here is a solution that keeps duplicates and retains the original order of elements in <code>a</code>.</p>\n\n<pre><code>def negated_stable(a):\n '''Take a list a and returns another list which only contains the elements x such that -x is also in a'''\n b = set(a)\n return [i for i in a if -i in b]\n</code></pre>\n\n<p>This was my original solution, which is a little slower than other solutions here, but I'll keep it around for posterity.</p>\n\n<pre><code>def negated_posterity(a):\n '''Take a list a and returns another list which only contains the elements x such that -x is also in a'''\n neg, pos = set(), set()\n for i in a:\n if i &lt; 0:\n neg.add(-1*i)\n else:\n pos.add(i)\n mark = pos &amp; neg\n return [i for i in a if abs(i) in mark]\n</code></pre>\n\n<p>If you can sacrifice order and/or duplication this becomes a trivial problem, as demonstrated by the five or so <code>set</code> solutions in abarnert's answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:49:23.970", "Id": "51933", "Score": "0", "body": "This takes almost two orders of magnitude longer than Peter DeGlopper's one-liner (aka hcwhsa's answer on the earlier question)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:50:37.840", "Id": "51934", "Score": "0", "body": "I think you want `return list(pos & neg)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:51:34.473", "Id": "51935", "Score": "0", "body": "@BiRico I thought of that, but OP may not want to eliminate dupes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:04:37.477", "Id": "51944", "Score": "0", "body": "The first problem with this solution is that it's evaluating `pos&neg` N times instead of once outside the loop. Fix that, and it becomes competitive with the others. But still not as fast, because making a set all at once, and a negated set with a comprehension, is so much faster than looping explicitly in Python that it swamps the cost of the repeated elements that you're trying to save." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:10:47.153", "Id": "51947", "Score": "0", "body": "@abarnert I wondered if that was it. Thanks, fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:16:34.513", "Id": "51948", "Score": "0", "body": "I just realized another cost of this partitioning: because you throw out the useless negative numbers that the other solution keeps, you have to do `abs(i)` instead of `-i`. Which makes me wonder… what if we just kept the negated set around (`mark = {-i for i in a}`) and then you could do `[i for i in a if i in mark]`, or possibly even bind `mark.__contains__` to a local variable? I'll test those…" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:44:02.157", "Id": "32497", "ParentId": "32496", "Score": "1" } }, { "body": "<p>First, let's get this out of the way:</p>\n\n<p>The reason the OP version is slow is that, to decide whether to insert elements into <code>c</code>, it checks each one of them against <code>b</code>—a list, rather than a set. That means it's quadratic when it could be linear.</p>\n\n<p>You could fix that by making another set, call it <code>mark2 = set(b)</code>, then using <code>if -i in mark2</code> instead of <code>if -i in b</code>.</p>\n\n<p>That means your code is no longer quadratic, it's linear. Which is probably all you cared about.</p>\n\n<p>However, it's looping twice as much as it needs to, and it's doing all of the looping in Python rather than finding ways to push it into C. That <code>add_mark = mark.add</code> optimization implies that you might be looking for more such tricks, and you should be able to cut the time to about a third.</p>\n\n<p>But just fixing that isn't good enough once you get the community going, so a number of variations have been suggested both here and on <a href=\"https://stackoverflow.com/questions/19279449/return-values-in-list-that-also-have-a-negated-value/19279505#19279505\">a previous SO question</a>. Which one is actually \nfastest?</p>\n\n<hr>\n\n<p>Instead of just guessing, let's actually write and test some implementations and see. Of course for real answers we need your real data, but I'll make up some data, and that should be enough to show you how to do it yourself.</p>\n\n<pre><code># my answer on the earlier question, and my comment above\ndef negated_0(a):\n a = set(a)\n return [i for i in a if -i in a]\n\n# Peter DeGlopper's comment, and hcwhsa's on the earlier question\ndef negated_1(a):\n s = set(a)\n return [i for i in a if -i in s]\n\n# one suggestion I made on the earlier question\ndef negated_2(a):\n return set(a) &amp; {-i for i in a}\n\n# another suggestion I thought my be a little faster but not worth it\ndef negated_3(a):\n return {-i for i in a}.intersection(a)\n\n# a possibly-improved version of #3 that I just thought of\ndef negated_4(a):\n a = set(a)\n return a &amp; {-i for i in a}\n\n# kojiro's posted answer\ndef negated_kojiro(a):\n '''Take a list a and returns another list which only contains the elements x such that -x is also in a'''\n neg, pos = set(), set()\n for i in a:\n if i &lt; 0:\n neg.add(-1*i)\n else:\n pos.add(i)\n return [i for i in a if abs(i) in pos &amp; neg]\n\nimport timeit\nimport random\n\na = [random.randint(-10000,10000) for _ in range(1000)]\nfor func in dir(sys.modules('__main__')):\n if func.startswith('negated_'):\n f = getattr(sys.modules('__main__'), func)\n print('{}: {}'.format(func, timeit.timeit(lambda: f(a), number=10000))\n</code></pre>\n\n<p>Here's the output on one laptop with Apple's Python 2.7.2:</p>\n\n<pre><code>negated_0: 1.50614500046\nnegated_1: 1.45001101494\nnegated_2: 1.79172492027\nnegated_3: 1.29876303673\nnegated_4: 1.92844605446\nnegated_kojiro: 84.5585548878\n</code></pre>\n\n<p>… and with a default-configured local build of Python 3.4 trunk:</p>\n\n<pre><code>negated_0: 1.5246370710083283\nnegated_1: 1.420855167991249\nnegated_2: 1.7558801580162253\nnegated_3: 1.297387560014613\nnegated_4: 1.8665565319824964\nnegated_kojiro: 72.18082603899529\n</code></pre>\n\n<p>… and with PyPy 2.1.0/2.7.3:</p>\n\n<pre><code>negated_0: 0.595048904419\nnegated_1: 0.405268907547\nnegated_2: 0.815263032913\nnegated_3: 0.878368139267\nnegated_4: 0.910092115402\nnegated_kojiro: 49.3969540596\n</code></pre>\n\n<hr>\n\n<p>Comparing the fixed version of the OP's implementation:</p>\n\n<pre><code>negated_op: 4.76454496384\nnegated_op: 3.3227077620103955\nnegated_op: 0.87509393692\n</code></pre>\n\n<p>(The original, unfixed version took over 79 seconds before I killed it in 2.7.2.)</p>\n\n<p>We've improved it by 3x in CPython 2.7.2, but only 2x in the other implementations. Not quite what I'd hoped, but not bad.</p>\n\n<hr>\n\n<p>It looks like <code>negated_3</code> actually <em>is</em> a decent-sized win over the obvious implementation, but nothing else is. (And #4 actually makes things worse.)</p>\n\n<p>Wrapping #2-#4 in <code>list(…)</code> so they return the same type as the others shows virtually no difference:</p>\n\n<pre><code>negated_0: 1.54194092751\nnegated_1: 1.44428801537\nnegated_2: 1.78255009651\nnegated_3: 1.29559803009\nnegated_4: 1.90534591675\n</code></pre>\n\n<hr>\n\n<p>Fixing the most serious problem with kojiro's answer, by evaluating <code>pos &amp; neg</code> once outside the listcomp instead of for each element, gives me:</p>\n\n<pre><code>negated_kojiro_fix: 2.11841907501\nnegated_kojiro_fix: 3.84713697433\nnegated_kojiro_1: 0.739408969879\n</code></pre>\n\n<p>So, it's still significantly slower than <code>negated_1</code> (which, like it, preserves duplicates and order) everywhere. Why?</p>\n\n<p>It <em>could</em> be that it's doing twice as much setup work and not getting a comparable amount of savings in the actual comprehension. It may be simpler work, but still, adding O(N) loops in Python to speed up an O(N) list comprehension might be costly.</p>\n\n<p>But there's also the fact that the listcomp filter is more complicated: <code>abs(i) in mark</code> instead of the <code>-i in mark</code>. So, if we could make it even simpler, would that make the listcomp even faster? Just keep the <em>negated</em> set around, and do <code>i in mark</code>. Which means you can replace the listcomp with a <code>filter</code> by using <code>mark.__contains__</code> as the argument:</p>\n\n<pre><code>def negated_3b(a):\n mark = {-i for i in a}\n return filter(mark.__contains__, a)\n</code></pre>\n\n<p>(For Python 3, you have to make that <code>list(filter(…))</code> of course, or it'll return almost instantly, having built an iterable but not iterated it.)</p>\n\n<p>The results with the same three Python implementations are:</p>\n\n<pre><code>negated_3b: 1.39607014656\nnegated_3b: 1.8215457699843682\nnegated_3b: 0.51006603241\n</code></pre>\n\n<p>So… it beats all of the other order-and-dups-preserving methods in 2.x, CPython or PyPy, but not the set-returning <code>negated_3</code> (which is obvious, when you think about it).</p>\n\n<p>However, it's <em>slower</em> in 3.x. Maybe that's just because of the necessity of calling <code>list</code>? If you don't actually <em>need</em> a list, let's see how long it takes to iterate it, by just feeding the iterator into <code>deque(maxlen=0)</code>:</p>\n\n<pre><code>negated_3b: 1.6808519120211713\n</code></pre>\n\n<p>Better, but still not as good as <code>negated_1</code> in Python 3. Maybe it's just that 3.x's <code>filter</code> hasn't been improved since the original version was written as 2.x's <code>itertools.ifilter</code>, but listcomps have been improved multiple times over the years?</p>\n\n<hr>\n\n<p>So, conclusions—if your data are very similar to mine (which is very unlikely!):</p>\n\n<ul>\n<li>Unless this is such a bottleneck in your code that a few microseconds one way or the other actually make a difference, use whichever one is most readable.</li>\n<li>If you don't need to preserve order and duplicates, use <code>negated_3</code>.</li>\n<li>If you're using Python 2.x, use <code>negated_3b</code>.</li>\n<li>Otherwise, use <code>negated_1</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:53:05.760", "Id": "51937", "Score": "0", "body": "I contend that answers that eliminate duplicate values or return a non-list are illegitimate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:56:02.407", "Id": "51938", "Score": "0", "body": "@kojiro: On what basis? A previous user with exactly the same assignment said there were no duplicate values; this user hasn't said otherwise. Meanwhile, tossing on a `list(…)` isn't going to make up the 50x slowdown, but I'll do it if you insist." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:57:41.240", "Id": "51940", "Score": "0", "body": "It also matters whether or not maintaining order is required. I think all the ones with reasonable performance except `negated_1` don't necessarily maintain order even if you put a `list()` around them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:59:14.657", "Id": "51942", "Score": "0", "body": "@PeterDeGlopper: Please see [the original question](http://stackoverflow.com/questions/19279449/return-values-in-list-that-also-have-a-negated-value/19279505#19279505), where the OP's desired output is not in the same order as the original input. So, I doubt maintaining order is important. (If so, then we have to figure out _what_ order is important, because it's not the _input_ order, which is what `negated_1` maintains…)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:01:46.047", "Id": "51943", "Score": "0", "body": "@abarnert - thanks for the link. The OP for this question didn't specify. I generally assume that when the input and output are stated to be lists, the output should maintain the input order, but it's certainly not specified one way or the other here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:07:46.460", "Id": "51945", "Score": "0", "body": "@PeterDeGlopper: Yeah, also note that the other OP's own attempt to solve it started by converting the list to a set. Of course it's possible that the other OP didn't understand the assignment, and this one does…" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:10:20.200", "Id": "51946", "Score": "0", "body": "@abarnert just on the basis that (no offense to OP) I think that if you can eliminate repetition and order the problem isn't interesting anymore. Sets are great, but they make some problems too easy. :P" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:46:55.130", "Id": "32498", "ParentId": "32496", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:27:54.207", "Id": "32496", "Score": "2", "Tags": [ "python", "performance" ], "Title": "Returning elements in a list also found in another list" }
32496
<p>I wrote a bash completion script for the <code>cpupower</code> command but I feel that it sucks. It's too long for such a simple task and have too much case/if-else nesting.</p> <p>It supports all the subcommands of <code>cpupower</code> and their options but not the values. It also support the incompatibilities between some options.</p> <pre><code>## Autocompletion bash for the command 'cpupower' ## This software is released into the public domain ## Known bugs, incomplete stuff: ## #000001. Doesn't complete, or validate at all, the cpu list accepted by -c|--cpu ## #000002. There are no man page for 'cpupower idle-info', so his parameters are not supported ## #000003. Doesn't complete or validate any of the command arguments' values ## * The governor option in frequency-set command is now supported # Indicate if an item is present in an array # Usage: in_array "$ITEM" "${ARRAY[@]}" in_array() { local ITEM for ITEM in "${@:2}"; do [[ "$ITEM" == "$1" ]] &amp;&amp; return 0; done return 1 } _cpupower() { # Global flags local FLAG_DEBUG=1 local FLAG_CPU=2 local FLAG_COMPGEN_COMMAND=4 local FLAGS=0 # frequency-info command flags local FLAG_FREQINFOSET_OUTPUT=1 local FLAG_FREQINFOSET_HUMAN=2 local FLAG_FREQINFOSET_PROC=4 local FLAGS_FREQINFO=0 # frequency-set command flags local FLAG_FREQSET_MIN=1 local FLAG_FREQSET_MAX=2 local FLAG_FREQSET_GOV=4 local FLAG_FREQSET_FREQ=8 local FLAG_FREQSET_RELATED=16 local FLAGS_FREQSET=0 # info &amp; set command flags local FLAG_INFOSET_PERFBIAS=1 local FLAG_INFOSET_SCHEDMC=2 local FLAG_INFOSET_SCHEDSMT=4 local FLAGS_INFOSET=0 # monitor command flags local FLAG_MONITOR_LIST=1 local FLAG_MONITOR_INTERVAL=2 local FLAG_MONITOR_ONLY=4 local FLAG_MONITOR_SCHED=8 local FLAG_MONITOR_VERBOSE=16 local FLAGS_MONITOR=0 # States local STATE_BASE=0 # Initial local STATE_CPU_WAITING=1 # Waiting Cpu list local STATE_COMMAND_WAITING=2 # Waiting command argument local STATE_COMMAND_VALUE_WAITING=3 # Waiting command argument value # Current state local STATE=$STATE_BASE # Debug parameters local -a DEBUG_OPTS=("-d" "--debug") # Cpu parameters local -a CPU_OPTS=("-c" "--cpu") # Help parameters (basic help) local -a HELP_OPTS=("-h" "--help") # Show version parameters local -a VERSION_OPTS=("-v" "--version") # Commands parameters local -a COMMAND_OPTS=("frequency-info" "frequency-set" "idle-info" "info" "set" "monitor" "help") # frequency-info command parameters (output, only one allowed) # The -s|--stats parameter it's not an "output" parameters in the docs, but cpupower throws the error "You can't specify more than one --cpu parameter and/or more than one output-specific argument". local -a FREQINFOSET_OUTPUT_OPTS=("-e" "--debug" "-a" "--related-cpus" "--affected-cpus" "-g" "--governors" "-p" "--policy" "-d" "--driver" "-l" "--hwlimits" "-f" "--freq" "-y" "--latency" "-w" "--hwfreq" "-s" "--stats") # frequency-info individual options local -a FREQINFOSET_HUMAN_OPTS=("-m" "--human") # this frequency-info option is incompatible with the global -c|--cpu option local -a FREQINFOSET_PROC_OPTS=("-o" "--proc") # frequency-set command individual parameters local -a FREQSET_MIN_OPTS=("-d" "--min") local -a FREQSET_MAX_OPTS=("-u" "--max") local -a FREQSET_GOV_OPTS=("-g" "--governor") local -a FREQSET_FREQ_OPTS=("-f" "--freq") local -a FREQSET_RELATED_OPTS=("-r" "--related") # frequency-set -g valid values (governors) local -a FREQSET_GOV_VALUES=("ondemand" "performance" "conservative" "powersave" "userspace") # info command individual parameters local -a INFOSET_PERFBIAS_OPTS=("-b" "--perf-bias") local -a INFOSET_SCHEDMC_OPTS=("-m" "--sched-mc") local -a INFOSET_SCHEDSMT_OPTS=("-s" "--sched-smt") # monitor command individual parameters local -a MONITOR_LIST_OPTS=("-l") local -a MONITOR_INTERVAL_OPTS=("-i") local -a MONITOR_ONLY_OPTS=("-m") local -a MONITOR_SCHED_OPTS=("-c") local -a MONITOR_VERBOSE_OPTS=("-v") # Current word local CUR_WORD="${COMP_WORDS[COMP_CWORD]}" # Last word to process local -i LAST_WORD=$COMP_CWORD-1 # 'compgen' extra arguments local COMPGEN_EXTRA="" local WORD OPTS CUR_COMMAND CUR_OPT for WORD in "${COMP_WORDS[@]:1:$LAST_WORD}"; do [ -z "$WORD" ] &amp;&amp; continue case $STATE in $STATE_BASE) in_array "$WORD" "${HELP_OPTS[@]}" &amp;&amp; return 0 in_array "$WORD" "${VERSION_OPTS[@]}" &amp;&amp; return 0 if in_array "$WORD" "${DEBUG_OPTS[@]}"; then (( $FLAGS &amp; $FLAG_DEBUG )) &amp;&amp; return 1 (( FLAGS |= $FLAG_DEBUG )) elif in_array "$WORD" "${CPU_OPTS[@]}"; then (( $FLAGS &amp; $FLAG_CPU )) &amp;&amp; return 1 STATE=$STATE_CPU_WAITING elif in_array "$WORD" "${COMMAND_OPTS[@]}"; then CUR_COMMAND="$WORD" STATE=$STATE_COMMAND_WAITING fi ;; $STATE_CPU_WAITING) (( FLAGS |= $FLAG_CPU )) STATE=$STATE_BASE ;; $STATE_COMMAND_VALUE_WAITING) STATE=$STATE_COMMAND_WAITING ;; $STATE_COMMAND_WAITING) CUR_OPT="$WORD" case "$CUR_COMMAND" in help) return 0 ;; frequency-info) if in_array "$WORD" "${FREQINFOSET_OUTPUT_OPTS[@]}"; then (( $FLAGS_FREQINFO &amp; $FLAG_FREQINFOSET_OUTPUT )) &amp;&amp; return 1 (( FLAGS_FREQINFO |= $FLAG_FREQINFOSET_OUTPUT )) elif in_array "$WORD" "${FREQINFOSET_HUMAN_OPTS[@]}"; then (( $FLAGS_FREQINFO &amp; $FLAG_FREQINFOSET_HUMAN )) &amp;&amp; return 1 (( FLAGS_FREQINFO |= $FLAG_FREQINFOSET_HUMAN )) elif in_array "$WORD" "${FREQINFOSET_PROC_OPTS[@]}"; then (( $FLAGS_FREQINFO &amp; $FLAG_FREQINFOSET_PROC )) &amp;&amp; return 1 (( $FLAGS_FREQINFO &amp; $FLAG_FREQINFOSET_OUTPUT )) &amp;&amp; return 1 (( FLAGS_FREQINFO |= ( $FLAG_FREQINFOSET_OUTPUT | $FLAG_FREQINFOSET_PROC ) )) fi ;; frequency-set) # The -f|--freq option is incompatible with ALL the other parameters (( $FLAGS_FREQSET &amp; $FLAG_FREQSET_FREQ )) &amp;&amp; return 1 if in_array "$WORD" "${FREQSET_MIN_OPTS[@]}"; then (( $FLAGS_FREQSET &amp; $FLAG_FREQSET_MIN )) &amp;&amp; return 1 (( FLAGS_FREQSET |= $FLAG_FREQSET_MIN )) elif in_array "$WORD" "${FREQSET_MAX_OPTS[@]}"; then (( $FLAGS_FREQSET &amp; $FLAG_FREQSET_MAX )) &amp;&amp; return 1 (( FLAGS_FREQSET |= $FLAG_FREQSET_MAX )) elif in_array "$WORD" "${FREQSET_GOV_OPTS[@]}"; then (( $FLAGS_FREQSET &amp; $FLAG_FREQSET_GOV )) &amp;&amp; return 1 (( FLAGS_FREQSET |= $FLAG_FREQSET_GOV )) STATE=$STATE_COMMAND_VALUE_WAITING elif in_array "$WORD" "${FREQSET_RELATED_OPTS[@]}"; then (( $FLAGS_FREQSET &amp; $FLAG_FREQSET_RELATED )) &amp;&amp; return 1 (( FLAGS_FREQSET |= $FLAG_FREQSET_RELATED )) elif in_array "$WORD" "${FREQSET_FREQ_OPTS[@]}"; then (( FLAGS_FREQSET |= $FLAG_FREQSET_FREQ )) fi ;; idle-info) return 0 ;; 'set'|'info') if in_array "$WORD" "${INFOSET_PERFBIAS_OPTS[@]}"; then (( $FLAGS_INFOSET &amp; $FLAG_INFOSET_PERFBIAS )) &amp;&amp; return 1 (( FLAGS_INFOSET |= $FLAG_INFOSET_PERFBIAS )) elif in_array "$WORD" "${INFOSET_SCHEDMC_OPTS[@]}"; then (( $FLAGS_INFOSET &amp; $FLAG_INFOSET_SCHEDMC )) &amp;&amp; return 1 (( FLAGS_INFOSET |= $FLAG_INFOSET_SCHEDMC )) STATE=$STATE_COMMAND_VALUE_WAITING elif in_array "$WORD" "${INFOSET_SCHEDSMT_OPTS[@]}"; then (( $FLAGS_INFOSET &amp; $FLAG_INFOSET_SCHEDSMT )) &amp;&amp; return 1 (( FLAGS_INFOSET &amp; $FLAG_INFOSET_SCHEDSMT )) STATE=$STATE_COMMAND_VALUE_WAITING fi ;; monitor) (( $FLAGS_MONITOR &amp; $FLAG_MONITOR_LIST )) &amp;&amp; return 1 if in_array "$WORD" "${MONITOR_LIST_OPTS[@]}"; then (( FLAGS_MONITOR |= $FLAG_MONITOR_LIST )) elif in_array "$WORD" "${MONITOR_INTERVAL_OPTS[@]}"; then (( $FLAGS_MONITOR &amp; $FLAG_MONITOR_INTERVAL )) &amp;&amp; return 1 (( FLAGS_MONITOR |= $FLAG_MONITOR_INTERVAL )) STATE=$STATE_COMMAND_VALUE_WAITING elif in_array "$WORD" "${MONITOR_ONLY_OPTS[@]}"; then (( $FLAGS_MONITOR &amp; $FLAG_MONITOR_ONLY )) &amp;&amp; return 1 (( FLAGS_MONITOR |= $FLAG_MONITOR_ONLY )) STATE=$STATE_COMMAND_VALUE_WAITING elif in_array "$WORD" "${MONITOR_SCHED_OPTS[@]}"; then (( $FLAGS_MONITOR &amp; $FLAG_MONITOR_SCHED )) &amp;&amp; return 1 (( FLAGS_MONITOR |= $FLAG_MONITOR_SCHED )) elif in_array "$WORD" "${MONITOR_VERBOSE_OPTS[@]}"; then (( $FLAGS_MONITOR &amp; $FLAG_MONITOR_VERBOSE )) &amp;&amp; return 1 (( FLAGS_MONITOR |= $FLAG_MONITOR_VERBOSE )) fi ;; esac ;; esac done OPTS="" case $STATE in $STATE_BASE) OPTS="${COMMAND_OPTS[@]} ${HELP_OPTS[@]} ${VERSION_OPTS[@]}" (( ~$FLAGS &amp; $FLAG_DEBUG )) &amp;&amp; OPTS="$OPTS ${DEBUG_OPTS[@]}" (( ~$FLAGS &amp; $FLAG_CPU )) &amp;&amp; OPTS="$OPTS ${CPU_OPTS[@]}" ;; $STATE_CPU_WAITING) ;; $STATE_COMMAND_VALUE_WAITING) case "$CUR_OPT" in "${FREQSET_GOV_OPTS[@]}") OPTS="${FREQSET_GOV_VALUES[@]}" ;; esac ;; $STATE_COMMAND_WAITING) case "$CUR_COMMAND" in help) OPTS="${COMMAND_OPTS[@]}" ;; frequency-info) if (( ~$FLAGS_FREQINFO &amp; $FLAG_FREQINFOSET_OUTPUT )); then # The -o|--proc option is incompatible with the -c|--cpu global option if (( ~$FLAGS_FREQINFO &amp; $FLAG_FREQINFOSET_PROC )); then (( ~$FLAGS &amp; $FLAG_CPU )) &amp;&amp; OPTS="$OPTS ${FREQINFOSET_PROC_OPTS[@]}" fi OPTS="$OPTS ${FREQINFOSET_OUTPUT_OPTS[@]}" fi (( ~$FLAGS_FREQINFO &amp; $FLAG_FREQINFOSET_HUMAN )) &amp;&amp; OPTS="$OPTS ${FREQINFOSET_HUMAN_OPTS[@]}"; ;; frequency-set) (( $FLAGS_FREQSET &amp; $FLAG_FREQSET_FREQ )) &amp;&amp; return 0 (( ~$FLAGS_FREQSET &amp; $FLAG_FREQSET_MIN )) &amp;&amp; OPTS="$OPTS ${FREQSET_MIN_OPTS[@]}" (( ~$FLAGS_FREQSET &amp; $FLAG_FREQSET_MAX )) &amp;&amp; OPTS="$OPTS ${FREQSET_MAX_OPTS[@]}" (( ~$FLAGS_FREQSET &amp; $FLAG_FREQSET_GOV )) &amp;&amp; OPTS="$OPTS ${FREQSET_GOV_OPTS[@]}" (( ~$FLAGS_FREQSET &amp; $FLAG_FREQSET_RELATED )) &amp;&amp; OPTS="$OPTS ${FREQSET_RELATED_OPTS[@]}" [ $FLAGS_FREQSET -eq 0 ] &amp;&amp; OPTS="$OPTS ${FREQSET_FREQ_OPTS[@]}" ;; idle-info) return 0 ;; 'set'|'info') (( ~$FLAGS_INFOSET &amp; $FLAG_INFOSET_PERFBIAS )) &amp;&amp; OPTS="$OPTS ${INFOSET_PERFBIAS_OPTS[@]}" (( ~$FLAGS_INFOSET &amp; $FLAG_INFOSET_SCHEDMC )) &amp;&amp; OPTS="$OPTS ${INFOSET_SCHEDMC_OPTS[@]}" (( ~$FLAGS_INFOSET &amp; $FLAG_INFOSET_SCHEDSMT )) &amp;&amp; OPTS="$OPTS ${INFOSET_SCHEDSMT_OPTS[@]}" ;; monitor) (( $FLAGS_MONITOR &amp; $FLAG_MONITOR_LIST )) &amp;&amp; return 0 if (( ~$FLAGS_MONITOR &amp; $FLAG_MONITOR_INTERVAL )); then OPTS="$OPTS ${MONITOR_INVERVAL_OPTS[@]}" # The monitor command accepts a command as an argument. (( FLAGS |= $FLAG_COMPGEN_COMMAND )) fi (( ~$FLAGS_MONITOR &amp; $FLAG_MONITOR_ONLY )) &amp;&amp; OPTS="$OPTS ${MONITOR_ONLY_OPTS[@]}" (( ~$FLAGS_MONITOR &amp; $FLAG_MONITOR_SCHED )) &amp;&amp; OPTS="$OPTS ${MONITOR_SCHED_OPTS[@]}" (( ~$FLAGS_MONITOR &amp; $FLAG_MONITOR_VERBOSE )) &amp;&amp; OPTS="$OPTS ${MONITOR_VERBOSE_OPTS[@]}" [ $FLAGS_MONITOR -eq 0 ] &amp;&amp; OPTS="$OPTS ${MONITOR_LIST_OPTS[@]}" ;; esac ;; esac (( $FLAGS &amp; $FLAG_COMPGEN_COMMAND )) &amp;&amp; COMPGEN_EXTRA="$COMPGEN_EXTRA -c" COMPREPLY=( $(compgen $COMPGEN_EXTRA -W "${OPTS}" -- ${CUR_WORD}) ) return 0 } complete -r cpupower 2&gt;/dev/null complete -F _cpupower cpupower </code></pre> <p>I have two questions:</p> <ol> <li>Is this a bit overkill for a bash completion script?</li> <li>Any ideas on how to refactor it without losing functionality?</li> </ol>
[]
[ { "body": "<ol>\n<li><p>Yes this starts to look a bit like godzilla, no dealbreaker though.</p>\n</li>\n<li><p>Divide this bulk in several parts. Here some tips to get started:</p>\n</li>\n</ol>\n<hr />\n<ol>\n<li><p>Start moving all your variable declarations to a separate file which you will source. This is going to be your <em>config file</em>.</p>\n<p>We are talking about the first 80 lines of your <code>_cpupower()</code> function here. That is almost 30% of your total amount of lines (!)</p>\n</li>\n<li><p>Move big items you have in your outer <code>case</code> construct, to separate functions. Especially the nested case and the big <code>if</code>/<code>elif</code> parts.\nSo you get <code>case</code> and <code>esac</code> at least on the same page. This will make debugging a lot easier.</p>\n</li>\n<li><p>Big static sequences of commands feel best at home in a function.</p>\n<p>What they do can easily be described in a few words. So these words can be the name of the function. This way the blocks are easy to manouver inside the code.</p>\n</li>\n<li><p>If you grow a lot of (small and clear) functions, put them in a separate file which you can source, and sort them in categories alphabetically. This way you can find them quickly. Consider this file as a &quot;library&quot; so you have a sort of a guideline how to handle it. It also makes it very easy to add or remove extra functionality without hacking away in the <em>one-big-file</em></p>\n</li>\n</ol>\n<p>If you do these things you will see that it will not only look much smaller and easier to handle but also that you can enable and disable entire parts on the fly with a single <code>#</code>. Also is this the best starting position if you want to slim down the code effectively. By having a better overview you will spot optimization possibilities sooner and with more ease</p>\n<hr />\n<h2>tl:dr</h2>\n<ol>\n<li>every <code>case</code> - <code>esac</code> in its own function (possibly a separate file)</li>\n<li>every big <code>if</code>/<code>elif</code> sequence in its own function (possibly a separate file)</li>\n<li>every simple sequence or stanza of commands in its own function</li>\n<li>all 80 declarations together in a config file</li>\n<li>all functions together in a library file</li>\n</ol>\n<p>Above tips creates a construction/framework that makes slimming down the code selectively a much easier task. It also makes you more efficient in optimizing a thing or two.</p>\n<p>Well, these were the answers to your questions. If these answers brought you some more questions, don't hesitate to ask.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T03:47:39.420", "Id": "36443", "ParentId": "32499", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-10T00:08:10.097", "Id": "32499", "Score": "4", "Tags": [ "bash" ], "Title": "cpupower bash completion script" }
32499
<p>I have tried to mimic Golang channels in C# and its performance is pretty good compared to golang itself. On my machine, each channel operation of Golang takes ~75 nano-sec and each <code>Chan&lt;T&gt;</code> (in C#) operation takes ~90 nano-sec.</p> <p>Please let me know if this code can be improved in any way.</p> <pre><code>class Chan&lt;T&gt; { readonly int size; T[] buffer; long head = -1; long tail = -1; long closed = 0; public Chan() { this.size = 0; } public Chan(int size) { if (size &lt; 0) throw new ArgumentOutOfRangeException(); this.size = size; this.buffer = new T[this.size]; } object headLock = new object(); public bool To(T t) { lock (headLock) { long localClosed = 0L; if (tail - head == buffer.Length) SpinWait.SpinUntil(() =&gt; (localClosed = Interlocked.Read(ref closed)) &gt; 0 || tail - head &lt; buffer.Length); if (localClosed &gt; 0) return false; var newTail = Interlocked.Increment(ref tail); buffer[newTail % buffer.Length] = t; return true; } } object tailLock = new object(); public bool From(out T val) { lock (tailLock) { long localClosed = 0L; if (tail - head == 0) SpinWait.SpinUntil(() =&gt; (localClosed = Interlocked.Read(ref closed)) &gt; 0 || tail - head &gt; 0); if (localClosed &gt; 0) { val = default(T); return false; } var newHead = Interlocked.Increment(ref head); val = buffer[newHead % buffer.Length]; return true; } } public void Close() { Interlocked.Increment(ref closed); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T23:55:56.770", "Id": "51950", "Score": "0", "body": "Have you tried TPL Dataflow? I think `BufferBlock` is quite similar to Go channel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T00:27:19.247", "Id": "51951", "Score": "0", "body": "No, I have not tried it; Thanks for mentioning it. But as far as I know `BufferBlock` does not provide the concept of 'closing' a channel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T09:44:52.250", "Id": "51978", "Score": "0", "body": "@KavehShahbazian It does, that's what the `Complete()` method is for. Though it does it differently than your code: after completing a block, you can't add new items to it, but the items that are already in it can still be processed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T09:55:25.727", "Id": "51979", "Score": "0", "body": "@svick I'll look into it (I can not find it in .NET framework so I guess there should be a NuGet for it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T07:18:26.560", "Id": "52071", "Score": "0", "body": "[Link for TPL Dataflow](http://msdn.microsoft.com/en-us/library/hh228603.aspx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T22:10:47.367", "Id": "95210", "Score": "0", "body": "Thank you. You inspired me to try this out for myself. I used a slightly different approach, you can check it out here: https://github.com/jonlt/Rumle.Golang" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-18T13:10:15.773", "Id": "95358", "Score": "0", "body": "@jolt That's interesting. But I finally decided to use Rx. It has tools to implement channel multiplexing (Go's select) too. Take a look at it. Yet; reinventing the wheel from time to time is necessary IMHO!" } ]
[ { "body": "<p>I would not use <code>SpinWait</code>, since this basically runs a small loop that checks the condition over and over again. This means a lot of CPU cycles are wasted. I would suggest a signalling construct like the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.manualreseteventslim.aspx\"><code>ManualResetEventSlim</code></a> class. </p>\n\n<p>You can read about this class and similar constructs on <a href=\"http://www.albahari.com/threading/part2.aspx#_Signaling_with_Event_Wait_Handles\">this excellent page</a> about threading in C#.</p>\n\n<p>Note: the <code>SpinWait</code> class is only preferred when you know in advance that the wait times will be very small (smaller than time it takes to do a thread context switch). You can configure the <code>ManulResetEventSlim</code> class to spin for a short time and then fall back to a kernel-based wait operation, by setting the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.manualreseteventslim.spincount.aspx\"><code>SpinCount</code></a> property. This is usefull if you expect a very short wait time, but don't want to waste a too manu CPU cylces when it turns out that you have to wait longer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T11:27:35.153", "Id": "51987", "Score": "0", "body": "agreed - spinning is almost never the right solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T01:32:39.737", "Id": "32504", "ParentId": "32500", "Score": "5" } }, { "body": "<ol>\n<li><code>Chan</code> sounds like the abbreviated name for <code>Channel</code> and apparently it's a channel. So I'd use <code>Channel</code> or maybe even <code>GoChannel</code>.</li>\n<li>The most commonly used naming convention I have seen for private members is to prefix them with an underscore. This way you can see at the first glance whether it's a local variable or a class member. This also means you can get rid of <code>this.</code> most of the time.</li>\n<li>I really prefer to spell out the access modifier even if <code>private</code> is default but YMMV.</li>\n<li>Method names should describe actions or operations (because they operate on data and sometimes modify the state of the object). <code>To</code> and <code>From</code> are not actions or operations. <s>That being said: The channel seems to have fixed size queue semantics (FIFO) so I'd consider calling the operations <code>Enqueue</code> and <code>Dequeue</code> which would make it immediately clear how the data is being processed.</s> (The semantic of the underlying data structure should not be exposed. Don't know what I was thinking there.) Rather use the <code>Send</code> and <code>Receive</code> semantics from the go definition.</li>\n<li><s>Given the previous point it could be useful to have a <code>Peek</code> method to check what will come next.</s></li>\n<li><code>_head</code> and <code>_tail</code> are longs and access is not guaranteed to be atomic so you should use <code>Interlocked.Read</code> to obtain them.</li>\n<li><p>Also the implementation is actually broken. Assume two threads A and B, A calls <code>Send()</code> and B calls <code>Receive()</code>, first execution <code>_head == _tail == -1</code>:</p>\n\n<ul>\n<li>A: execute <code>Interlocked.Increment(_tail)</code> (<code>_tail</code> is now 0)</li>\n<li>B: <code>_tail - _head &gt; 0</code> is true (<code>0 - -1 == 1</code>), leaves spinlock</li>\n<li>B: execute <code>Interlocked.Increment(_head)</code> (<code>_head</code> is now 0)</li>\n<li>B: read <code>_buffer[_head]</code></li>\n<li>A: write <code>_buffer[_tail]</code></li>\n<li>B has read from buffer before element was written.</li>\n<li><p>This problem can be easily reproduced with this test case (almost every iteration results in dupes): </p>\n\n<pre><code>[TestCase]\npublic void TestSPSC()\n{\n int numItems = 10000;\n int numIterations = 100;\n\n for (int i = 0; i &lt; numIterations; ++i)\n {\n var channel = new Channel&lt;int&gt;(100);\n var writer = Task.Factory.StartNew(() =&gt; { foreach (var num in Enumerable.Range(1, numItems)) { channel.Send(num); } channel.Close(); });\n var reader = Task.Factory.StartNew&lt;List&lt;int&gt;&gt;(() =&gt; { \n var numbers = new List&lt;int&gt;(numItems);\n for (int idx = 1; idx &lt;= numItems; ++idx)\n {\n int num;\n var res = channel.Receive(out num);\n numbers.Add(num);\n }\n return numbers.OrderBy(x =&gt; x).ToList();\n });\n Task.WaitAll(writer, reader);\n var dupes = reader.Result.GroupBy(x =&gt; x).Where(g =&gt; g.Count() &gt; 1).ToList();\n if (dupes.Count &gt; 0)\n {\n Console.WriteLine(\"{0}: {1} DUPES!\", i, dupes.Count);\n }\n }\n}\n</code></pre></li>\n</ul></li>\n</ol>\n\n<p>I changed the implementation to use .NET's <a href=\"http://msdn.microsoft.com/en-us/library/dd267301.aspx\"><code>BlockingCollection&lt;T&gt;</code></a> wrapped around a <a href=\"http://msdn.microsoft.com/en-us/library/dd267265.aspx\"><code>ConcurrentQueue&lt;T&gt;</code></a>:</p>\n\n<pre><code>public class Channel&lt;T&gt;\n{\n private BlockingCollection&lt;T&gt; _buffer;\n\n public Channel() : this(1) { }\n public Channel(int size)\n {\n _buffer = new BlockingCollection&lt;T&gt;(new ConcurrentQueue&lt;T&gt;(), size);\n }\n\n public bool Send(T t)\n {\n try\n {\n _buffer.Add(t);\n }\n catch (InvalidOperationException)\n {\n // will be thrown when the collection gets closed\n return false;\n }\n return true;\n }\n\n public bool Receive(out T val)\n {\n try\n {\n val = _buffer.Take();\n }\n catch (InvalidOperationException)\n {\n // will be thrown when the collection is empty and got closed\n val = default(T);\n return false;\n }\n return true;\n }\n\n public void Close()\n {\n _buffer.CompleteAdding();\n }\n\n public IEnumerable&lt;T&gt; Range()\n {\n T val;\n while (Receive(out val))\n {\n yield return val;\n }\n }\n}\n</code></pre>\n\n<p>The code is much easier to read and has probably less bugs than your self implemented one. It's also fast. I can pump 10,000,000 items (I tested with <code>int</code>) through a channel (buffer size 100) with single producer single consumer in 5sec. That's 0.5ns per item.</p>\n\n<pre><code> [TestCase]\n public void TestSPSC_Performance()\n {\n int numItems = 10000000;\n int numIterations = 10;\n\n var stopWatch = new Stopwatch();\n stopWatch.Start();\n for (int i = 0; i &lt; numIterations; ++i)\n {\n var channel = new Channel&lt;int&gt;(100);\n var writer = Task.Factory.StartNew(() =&gt; { foreach (var num in Enumerable.Range(1, numItems)) { channel.Send(num); } channel.Close(); });\n var reader = Task.Factory.StartNew&lt;List&lt;int&gt;&gt;(() =&gt; { var res = new List&lt;int&gt;(numItems); foreach (var num in channel.Range()) { res.Add(num); } return res; });\n Task.WaitAll(writer, reader);\n }\n stopWatch.Stop();\n\n var elapsedMs = stopWatch.Elapsed.TotalMilliseconds;\n Console.WriteLine(\"SPSC N = {0}: {1:.00}ms/iteration, {2:.00}ns/item (tx+rx)\", numItems, elapsedMs / numIterations, elapsedMs * 1000.0 / numItems / numIterations);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T10:16:56.803", "Id": "51981", "Score": "0", "body": "I was trying to mimic golang chan. But in C# land you are right about naming; I've done some modifications based on your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T11:35:27.313", "Id": "51989", "Score": "0", "body": "A Peek method is not in general a good idea because it's ok for several receivers to use the channel at once, in which case Peek cannot necessarily provide an accurate prediction of what you will read, because another process might have read the value first. That's why Go's channels do not provide that primitive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T18:48:18.013", "Id": "52029", "Score": "0", "body": "@rog, sure but if you only have 1 consumer then it might be" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T12:35:21.560", "Id": "52081", "Score": "0", "body": "If you've got only one consumer *and* the buffer size is greater than zero *and* you must avoid actually reading the value. Better to leave it out IMHO - it's a misleading operation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T07:17:03.963", "Id": "52297", "Score": "0", "body": "@KavehShahbazian: Found a problem with your implementation. I got interested in this and started implementing `Select` and wrote a bunch of unit tests for the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T12:37:15.330", "Id": "52302", "Score": "0", "body": "@ChrisWue Yeah; I started `Select` and I have used `WaitHandle` but performance is far worse than Go itself." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:08:22.773", "Id": "32510", "ParentId": "32500", "Score": "13" } }, { "body": "<p>Without the select operator, you haven't got Go channels - you've just got buffered queues, which are much easier to implement but much less useful.</p>\n\n<p>Also, it's important to allow channels with a zero size buffer - in that\ncase the sender should synchronise with the receiver.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T11:35:00.050", "Id": "51988", "Score": "0", "body": "Ouch! I totally forgot select!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T14:05:35.043", "Id": "81735", "Score": "1", "body": "It may be worth to mention that the default constructor of `Chan` should set the buffer size to zero, not one. The default buffer size of a `chan` in Go is zero." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T11:33:15.553", "Id": "32521", "ParentId": "32500", "Score": "11" } } ]
{ "AcceptedAnswerId": "32521", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T22:44:16.940", "Id": "32500", "Score": "14", "Tags": [ "c#", "go" ], "Title": "Golang channel in C#" }
32500
<p>I just started with Python a month ago, and with Flask this week. <a href="https://github.com/mrichman/nhs-listpull" rel="nofollow">This</a> is my first project.</p> <p>I am curious about general style, proper use of Python idioms, and Flask best-practices.</p> <p><strong>run.py:</strong></p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import os import sqlite3 import StringIO import time from ConfigParser import SafeConfigParser from emailvision.restclient import RESTClient from flask import Flask, request, g, render_template, flash, send_file, \ redirect from mom import MOMClient from zlib import compress, decompress app = Flask(__name__) app.config.update(dict( DATABASE='/tmp/nhs-listpull.db', DEBUG=True, SECRET_KEY='\xeb\x12A;\x8b\x0c$\xf4&gt;O\xb6\x9c\x15y=&gt;\x0cU&lt;Kzp&gt;\xe9', USERNAME='admin', PASSWORD='default' )) app.config.from_envvar('NHS-LISTPULL_SETTINGS', silent=True) def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv def init_db(): """Creates the database tables.""" app.logger.info("Initializing database") with app.app_context(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: sql = f.read() app.logger.debug(sql) db.cursor().executescript(sql) db.commit() def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def get_mom(): """Opens a new MOM db connection if there is none yet for the current application context. """ if not hasattr(g, 'mom'): config_ini = os.path.join(os.path.dirname(__file__), 'config.ini') config = SafeConfigParser() config.read(config_ini) mom_host = config.get("momdb", "host") mom_user = config.get("momdb", "user") mom_password = config.get("momdb", "password") mom_database = config.get("momdb", "db") g.mom = MOMClient(mom_host, mom_user, mom_password, mom_database) return g.mom def get_ev_client(): """Gets an instance of the EmailVision REST client.""" if not hasattr(g, 'ev'): config_ini = os.path.join(os.path.dirname(__file__), 'config.ini') config = SafeConfigParser() config.read(config_ini) ev_url = config.get("emailvision", "url") ev_login = config.get("emailvision", "login") ev_password = config.get("emailvision", "password") ev_key = config.get("emailvision", "key") g.ev = RESTClient(ev_url, ev_login, ev_password, ev_key) return g.ev @app.teardown_appcontext def close_db(error): """Closes the database again at the end of the request.""" if error is not None: app.logger.error(error) if hasattr(g, 'sqlite_db'): g.sqlite_db.close() def query_db(query, args=(), one=False): cur = get_db().execute(query, args) rv = cur.fetchall() cur.close() return (rv[0] if rv else None) if one else rv @app.route('/') def show_jobs(): app.logger.debug("show_jobs()") db = get_db() sql = ''' select j.id, j.record_count, j.ev_job_id, j.created_at, j.csv, t.name, case when j.status = 0 then 'Pending' when j.status = 1 then 'Complete' end status from job_status j inner join list_types t on (j.list_type_id = t.id) order by j.id desc''' cur = db.execute(sql) jobs = cur.fetchall() app.logger.debug("Found {} jobs".format(len(jobs))) return render_template('job_status.html', jobs=jobs) @app.route('/list', methods=['POST']) def create_list(): # curl --data "list_type_id=1" http://localhost:5000/list app.logger.debug("create_list()") list_type_id = request.form['list_type_id'] app.logger.debug("list_type_id=" + list_type_id) mom = get_mom() app.logger.debug("mom.get_customers()") csv, count = mom.get_customers() app.logger.debug("CSV is {} bytes".format(len(csv))) csv = buffer(compress(csv)) app.logger.debug("Compressed CSV is {} bytes".format(len(csv))) db = get_db() db.execute(('insert into job_status ' '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'), (list_type_id, count, 0, csv)) db.commit() flash('List successfully generated with {:,} records'.format(count)) return redirect('/') @app.route('/list-noas', methods=['POST']) def create_list_no_autoship(): app.logger.debug("create_list_no_autoship()") list_type_id = request.form['list_type_id'] app.logger.debug("list_type_id=" + list_type_id) mom = get_mom() app.logger.debug("mom.get_customers_excl_autoship()") csv, count = mom.get_customers_excl_autoship() app.logger.debug("CSV is {} bytes".format(len(csv))) csv = buffer(compress(csv)) app.logger.debug("Compressed CSV is {} bytes".format(len(csv))) db = get_db() db.execute(('insert into job_status ' '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'), (list_type_id, count, 0, csv)) db.commit() flash('List successfully generated with {:,} records'.format(count)) return redirect('/') @app.route('/list-reengagement', methods=['POST']) def create_list_reengagement(): app.logger.debug("create_list_reengagement()") list_type_id = request.form['list_type_id'] app.logger.debug("list_type_id=" + list_type_id) mom = get_mom() app.logger.debug("mom.get_customers_reengagement()") csv, count = mom.get_customers_reengagement() app.logger.debug("CSV is {} bytes".format(len(csv))) csv = buffer(compress(csv)) app.logger.debug("Compressed CSV is {} bytes".format(len(csv))) db = get_db() db.execute(('insert into job_status ' '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'), (list_type_id, count, 0, csv)) db.commit() flash('List successfully generated with {:,} records'.format(count)) return redirect('/') @app.route('/csv/&lt;int:job_id&gt;', methods=['GET']) def get_csv(job_id): db = get_db() cur = db.execute('select csv from job_status where id = {}'.format(job_id)) csv = cur.fetchone()[0] csv = decompress(csv) sio = StringIO.StringIO() sio.write(csv) sio.seek(0) return send_file(sio, attachment_filename= "{}_{}.txt".format(job_id, time.strftime("%Y%m%d%H%M%S")), as_attachment=True) @app.route('/send/&lt;int:job_id&gt;', methods=['GET']) def send_to_emailvision(job_id): """ Sends raw CSV to EmailVision """ db = get_db() cur = db.execute('select csv from job_status where id = {}'.format(job_id)) csv = cur.fetchone()[0] logging.info("Got {} bytes of compressed CSV".format(len(csv))) csv = decompress(csv) logging.info("Sending {} bytes of raw CSV to EmailVision".format(len(csv))) ev_job_id = get_ev_client().insert_upload(csv) if ev_job_id &gt; 0: db.execute('update job_status set ev_job_id = ?, status=1 ' 'where id = ?', (ev_job_id, job_id)) db.commit() flash("List successfully sent to EmailVision (Job ID {}).".format( ev_job_id)) else: flash("Something went horribly wrong.", "error") return redirect('/') @app.route('/delete/&lt;int:job_id&gt;', methods=['GET']) def delete_job(job_id): """Delete a job""" try: db = get_db() db.execute('delete from job_status where id = {}'.format(job_id)) db.commit() flash("Job {} successfully deleted".format(job_id)) except Exception as e: flash("Something went horribly wrong. {}".format(e), "error") return redirect('/') @app.route('/list-as', methods=['POST']) def create_list_autoships(): app.logger.debug("create_list_autoships()") list_type_id = request.form['list_type_id'] app.logger.debug("list_type_id=" + list_type_id) app.logger.debug("mom.get_autoships()") csv, count = get_mom().get_autoships() app.logger.debug("CSV is {} bytes".format(len(csv))) csv = buffer(compress(csv)) app.logger.debug("Compressed CSV is {} bytes".format(len(csv))) db = get_db() db.execute(('insert into job_status ' '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'), (list_type_id, count, 0, csv)) db.commit() flash('List successfully generated with {:,} records'.format(count)) return redirect('/') @app.route('/list-cat-x-sell', methods=['POST']) def create_list_cat_x_sell(): app.logger.debug("create_list_cat_x_sell()") list_type_id = request.form['list_type_id'] category_list = request.form.getlist('category-list') product_list = request.form.getlist('product-list') app.logger.debug("list_type_id=" + list_type_id) app.logger.debug("category_list=" + ','.join(category_list)) app.logger.debug("product_list=" + ','.join(product_list)) app.logger.debug("mom.get_cat_x_sell()") csv, count = get_mom().get_cat_x_sell() app.logger.debug("CSV is {} bytes".format(len(csv))) csv = buffer(compress(csv)) app.logger.debug("Compressed CSV is {} bytes".format(len(csv))) db = get_db() db.execute(('insert into job_status ' '(list_type_id, record_count, status, csv) VALUES (?,?,?,?)'), (list_type_id, count, 0, csv)) db.commit() flash('List successfully generated with {:,} records'.format(count)) return redirect('/') @app.errorhandler(404) def page_not_found(e): return render_template('404.html', e=e), 404 @app.errorhandler(500) def internal_error(e): return render_template('500.html', e=e), 500 if __name__ == '__main__': app.logger.debug(__name__) #init_db() FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(filename='nhs-listpull.log', level=logging.DEBUG, format=FORMAT) app.run() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T01:02:28.890", "Id": "32502", "Score": "3", "Tags": [ "python", "flask" ], "Title": "Providing a daily feed of current segmented customer data for targeted email campaigns" }
32502
<p>How can I most effectively refactor the code in these 2 <code>ViewController</code>s?</p> <p>I'm familiar with subclassing in Objective-C and have used it extensively else where with <code>NSObject</code>s and <code>UIView</code>s, but I'm not sure how to approach doing so with <code>ViewController</code>s. </p> <p>The rooms have fairly similar functions, but I think are different enough to warrant 2 separate VCs.</p> <p><strong>Note:</strong> I plan to make more descriptive variable names and change a lot of the <code>NSString</code> messages with constants, those are just place holders for now. Also, you can ignore the log statements.</p> <p><strong>Edit:</strong></p> <p>Overview &amp; Screenshot</p> <ul> <li><em>Overview:</em> This is a video conferencing app. Both VC's are pushed by a tableview. </li> <li><em>In <code>DetailVC</code>:</em> User is matched up against an opponent and they talk for 60 seconds in a "SRRoom". </li> <li><em>In Observe:</em> A user joins a <code>SRRoom</code> where 2 people are already matched up and can watch them talk. </li> </ul> <p><code>TacoVideoHandler</code> abstracts all the nitty gritty video methods.</p> <p><img src="https://i.stack.imgur.com/Yo7zN.png" alt="enter image description here"></p> <h2>SRObserveViewController.h:</h2> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "SRTacoVideoHandler.h" #import "SRAPI.h" #import "SRRoom.h" #import "SRAnimationHelper.h" @interface SRObserveViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *roomTitle; @property (weak, nonatomic) IBOutlet UIView *agreeShoutContainer; @property (weak, nonatomic) IBOutlet UIView *disagreeShoutContainer; @property (weak, nonatomic) IBOutlet UILabel *statusLabel; @property (weak, nonatomic) NSTimer *retryTimer; @property (strong, nonatomic) SRTacoVideoHandler *TacoHandler; @property (strong, nonatomic) SRRoom *room; @end </code></pre> <h2>SRObserveViewController.m:</h2> <pre><code>#import "SRObserveViewController.h" @interface SRObserveViewController () @property (strong, nonatomic) NSString *kApiKey; @property (strong, nonatomic) NSString *kSessionId; @property (strong, nonatomic) NSString *kToken; @end @implementation SRObserveViewController - (void)viewDidLoad { [super viewDidLoad]; [self configOpentTok]; [self performGetRoomRequest]; [self configNavBar]; [self configNotifcations]; } - (void)configOpentTok { self.TacoHandler.shouldPublish = NO; self.TacoHandler.isObserving = YES; [self.TacoHandler registerUserVideoStreamContainer:self.agreeShoutContainer]; [self.TacoHandler registerOpponentOneVideoStreamContainer:self.disagreeShoutContainer]; } - (NSString *)opposingPosition:(NSString *)position { return ([position isEqualToString:@"agree"]) ? @"disagree" : @"agree"; } - (void)configNavBar { self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pressBackButton)]; UIImage *backButtonImage = [UIImage imageNamed:@"backButton"]; UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom]; [backButton setFrame:CGRectMake(0, 0, 47, 32)]; [backButton setImage:backButtonImage forState:UIControlStateNormal]; [backButton addTarget:self action:@selector(pressBackButton) forControlEvents:UIControlEventAllEvents]; UIBarButtonItem *navBackButton = [[UIBarButtonItem alloc] initWithCustomView:backButton]; [self.navigationItem setLeftBarButtonItem:navBackButton]; } - (void)pressBackButton { self.navigationItem.leftBarButtonItem.enabled = NO; [self doCloseRoom]; [self.TacoHandler safetlyCloseSession]; double delayInSeconds = 3; //[self updateStatusLabel:@"Disconnecting" withColor:[UIColor grayColor]]; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void) { [self.navigationController popViewControllerAnimated:YES]; }); } - (void)configNotifcations { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recieveNotifications:) name:kSRTacoVideoHandlerNotifcations object:nil ]; } - (void)recieveNotifications:(NSNotification *)notification { if ([[notification name] isEqualToString:kSRTacoVideoHandlerNotifcations]) { NSDictionary *userInfo = notification.userInfo; NSNumber *message = [userInfo objectForKey:@"message"]; [self statusMessage:message]; } } - (void)statusMessage:(NSNumber *)message { NSString *result = nil; switch ([message intValue]) { case 0: [self startRetryTimer]; result = @"Disconnected"; break; case 1: [self stopRetryTimer]; result = @"Connecting..."; break; case 3: result = @"Searching for Idiots..."; [self startRetryTimer]; break; case 4: [self stopRetryTimer]; result = @"Wow, look at that guy..."; break; case 88: [self stopRetryTimer]; result = @"Observing specimens"; break; case 5: [self stopRetryTimer]; [self performSelector:@selector(retry) withObject:nil afterDelay:6]; result = @"Match Over! Will start searching for new room shortly..."; break; case 6: //[self stopProgressBar]; result = @"Disconnecting..."; [self stopRetryTimer]; break; case 7: [self startRetryTimer]; result = @"Opponent failed to Join. Will start searching for new room shortly..."; break; case 77: //Call succeedded but no rooms are available result = @"Searching for Idiots..."; [self startRetryTimer]; break; case 99: [self stopRetryTimer]; result = @"Everyone Left! Will start searching for new room shortly..."; [self performSelector:@selector(retry) withObject:nil afterDelay:6]; break; default: result = @"Retry"; } [self updateStatusLabel:result withColor:[self statusLabelColorPicker:message] animated:YES]; NSLog(@"STATUS LABEL UPDATE: %@", message); } - (void)startRetryTimer { NSLog(@"Timer Started"); [self stopRetryTimer]; self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(retry) userInfo:nil repeats:YES]; } - (void)stopRetryTimer { [self.retryTimer invalidate]; self.retryTimer = nil; } - (void)retry { [self doCloseRoom]; [self.TacoHandler safetlyCloseSession]; [self performSelector:@selector(performGetRoomRequest) withObject:nil afterDelay:4]; } - (UIColor *)statusLabelColorPicker:(NSString *)Message { //will change this later return [UIColor blackColor]; } - (void)performGetRoomRequest { //parameter with session __weak typeof(self) weakSelf = self; [[RKObjectManager sharedManager] getObject:weakSelf.room path:nil parameters:nil success: ^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { weakSelf.roomTitle.text = weakSelf.room.title; if (weakSelf.room.token.length &lt; 5 || weakSelf.room.sessionId.length &lt; 5) { [weakSelf statusMessage:@77]; return; } weakSelf.TacoHandler.kToken = weakSelf.room.token; weakSelf.TacoHandler.kSessionId = weakSelf.room.sessionId; [weakSelf.TacoHandler doConnectToRoomWithSession]; } failure: ^(RKObjectRequestOperation *operation, NSError *error) { //Retry? [weakSelf startRetryTimer]; NSLog(@"failed"); }]; } - (void)dealloc { [[RKObjectManager sharedManager].operationQueue cancelAllOperations]; self.TacoHandler = nil; self.room = nil; NSLog(@"*******deallocated**********"); } - (void)doCloseRoom { if (self.room.roomId.intValue &lt; 1) { return; } __weak typeof(self) weakSelf = self; [[RKObjectManager sharedManager] deleteObject:weakSelf.room path:nil parameters:nil success:nil failure:nil ]; } #pragma mark - label - (void)updateStatusLabel:(NSString *)message withColor:(UIColor *)color animated:(bool)animated { self.statusLabel.text = message; if (animated) { [self fadeOutFadeInAnimation:self.statusLabel andColor:color]; } else { [SRAnimationHelper stopAnimations:self.statusLabel]; } } - (void)fadeOutFadeInAnimation:(UILabel *)label andColor:(UIColor *)color { //add animation [label.layer addAnimation:[SRAnimationHelper fadeOfRoomStatusLabel] forKey:nil]; //change label color label.textColor = color; } </code></pre> <h2>SRDetailViewController.h</h2> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "SRRoom.h" #import "SRAPI.h" #import "SRTacoVideoHandler.h" #import "SRSocialSharing.h" #import "SRAnimationHelper.h" @interface SRDetailViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *roomTitle; @property (weak, nonatomic) IBOutlet UIView *userScreenContainer; @property (weak, nonatomic) IBOutlet UIView *opponentScreenContainer; @property (weak, nonatomic) IBOutlet UILabel *statusLabel; @property (weak, nonatomic) IBOutlet UIButton *retryButton; @property (weak, nonatomic) IBOutlet UIProgressView *progressBar; @property (strong, nonatomic) NSTimer *progressTimer; @property (strong, nonatomic) NSTimer *retryTimer; @property (weak, nonatomic) IBOutlet UIView *bottomViewContainer; @property (strong, nonatomic) SRRoom *room; @property (strong, nonatomic) SRTacoVideoHandler *TacoHandler; @end </code></pre> <h2>SRDetailViewController.m</h2> <pre><code>#import "SRDetailViewController.h" #import &lt;QuartzCore/QuartzCore.h&gt; @interface SRDetailViewController () @property (strong, nonatomic) NSString *kApiKey; @property (strong, nonatomic) NSString *kSessionId; @property (strong, nonatomic) NSString *kToken; @end @implementation SRDetailViewController - (void)viewDidLoad { [super viewDidLoad]; [self configOpentTok]; [self performGetRoomRequest]; [self configNavBar]; [self configNotifcations]; [self configProgressBar]; } - (void)configSocialSharing { //check if it already exists for (UIView *subview in self.view.subviews) { if ([subview isKindOfClass:[SRSocialSharing class]]) { return; } } //add off screen CGRect frame = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width, 44); SRSocialSharing *share = [[SRSocialSharing alloc] initWithFrame:frame]; [self.view addSubview:share]; share.sharingURL = [self createUrlForSharing]; //animate in frame = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 100, [[UIScreen mainScreen] bounds].size.width, 44); [UIView animateWithDuration:3 delay:2 options:UIViewAnimationOptionCurveEaseOut animations: ^{ share.frame = frame; } completion:nil]; } - (NSURL *)createUrlForSharing { NSString *urlString = [NSString stringWithFormat:@"MyUrl/room/%@/%@?session=%@", self.room.topicId, [self opposingPosition:self.room.position], self.room.sessionId]; NSURL *url = [NSURL URLWithString:urlString]; return url; } - (NSString *)opposingPosition:(NSString *)position { return ([position isEqualToString:@"agree"]) ? @"disagree" : @"agree"; } - (void)configOpentTok { [self.tacoHandler registerUserVideoStreamContainer:self.userScreenContainer]; self.tacoHandler.userVideoStreamConatinerName = self.room.position; [self.tacoHandler registerOpponentOneVideoStreamContainer:self.opponentScreenContainer]; self.tacoHandler.opponentOneVideoStreamConatinerName = [self opposingPosition:self.room.position]; self.TacoHandler.shouldPublish = YES; self.TacoHandler.isObserving = NO; } - (void)configNavBar { UIImage *backButtonImage = [UIImage imageNamed:@"backButton"]; UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom]; [backButton setFrame:CGRectMake(0, 0, 47, 32)]; [backButton setImage:backButtonImage forState:UIControlStateNormal]; [backButton addTarget:self action:@selector(pressBackButton) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *navBackButton = [[UIBarButtonItem alloc] initWithCustomView:backButton]; [self.navigationItem setLeftBarButtonItem:navBackButton]; self.title = [self.room.position stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[self.room.position substringToIndex:1] capitalizedString]]; } - (void)pressBackButton { self.navigationItem.leftBarButtonItem.enabled = NO; [self manageSafeClose]; [self stopTimer:self.retryTimer]; [self stopTimer:self.progressTimer]; [self.TacoHandler safetlyCloseSession]; double delayInSeconds = 3; //[self updateStatusLabel:@"Disconnecting" withColor:[UIColor grayColor]]; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void) { [self.navigationController popViewControllerAnimated:YES]; }); } - (void)configNotifcations { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recieveNotifications:) name:kSRTacoVideoHandlerNotifcations object:nil ]; } - (void)recieveNotifications:(NSNotification *)notification { if ([[notification name] isEqualToString:kSRTacoVideoHandlerNotifcations]) { NSDictionary *userInfo = notification.userInfo; NSNumber *message = [userInfo objectForKey:@"message"]; [self statusMessage:message]; } } - (void)statusMessage:(NSNumber *)message { NSString *result = nil; switch ([message intValue]) { case 0: result = @"Disconnected"; break; case 1: result = @"Connecting..."; [self startRetryTimer]; break; case 2: result = @"Publishing Your Video..."; break; case 3: result = @"Searching for Idiots..."; break; case 4: result = @"Start Shouting!"; [self startProgressBar]; [self stopTimer:self.retryTimer]; break; case 5: [self stopTimer:self.progressTimer]; result = @"Opponent Stopped Shouting! You Win!"; break; case 6: [self stopTimer:self.progressTimer]; result = @"Disconnecting..."; break; case 7: result = @"Opponent failed to join. Retrying..."; [self performSelector:@selector(retry) withObject:nil afterDelay:4]; break; default: result = @"Retry"; } [self updateStatusLabel:result withColor:[self statusLabelColorPicker:message] animated:YES]; NSLog(@"STATUS LABEL UPDATE: %@", message); } - (UIColor *)statusLabelColorPicker:(NSString *)Message { return [UIColor whiteColor]; } - (void)performGetRoomRequest { [[RKObjectManager sharedManager] getObject:self.room path:nil parameters:nil success: ^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { self.TacoHandler.kToken = self.room.token; self.TacoHandler.kSessionId = self.room.sessionId; self.roomTitle.text = self.room.title; self.navigationController.title = self.room.position; [self configSocialSharing]; [self.TacoHandler doConnectToRoomWithSession]; } failure: ^(RKObjectRequestOperation *operation, NSError *error) { //Retry? }]; } - (void)dealloc { [self stopTimer:self.retryTimer]; [self stopTimer:self.progressTimer]; [[RKObjectManager sharedManager].operationQueue cancelAllOperations]; self.TacoHandler = nil; self.room = nil; [[NSNotificationCenter defaultCenter] removeObserver:self]; NSLog(@"*******deallocated**********"); } - (void)manageSafeClose { [self doCloseRoom]; } - (void)doCloseRoom { [[RKObjectManager sharedManager] deleteObject:self.room path:nil parameters:nil success:nil failure:nil ]; } - (void)startRetryTimer { NSLog(@"Timer Started"); self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:(60 * 5) target:self selector:@selector(retry) userInfo:nil repeats:YES]; } - (void)retry { [self doCloseRoom]; [self stopTimer:self.progressTimer]; [self stopTimer:self.progressTimer]; [self.TacoHandler safetlyCloseSession]; [self performSelector:@selector(performGetRoomRequest) withObject:nil afterDelay:4]; } #pragma mark - label - (void)updateStatusLabel:(NSString *)message withColor:(UIColor *)color animated:(bool)animated { self.statusLabel.text = message; if (animated) { [self fadeOutFadeInAnimation:self.statusLabel andColor:color]; } else { [SRAnimationHelper stopAnimations:self.statusLabel]; } } - (void)fadeOutFadeInAnimation:(UILabel *)label andColor:(UIColor *)color { //add animation [label.layer addAnimation:[SRAnimationHelper fadeOfRoomStatusLabel] forKey:nil]; //change label color label.textColor = color; } #pragma mark - Progress Bar - (void)configProgressBar { self.progressBar.progressTintColor = [UIColor orangeColor]; } - (void)startProgressBar { self.progressBar.hidden = NO; self.progressBar.progress = 0; self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(changeProgressValue) userInfo:nil repeats:YES]; } - (void)stopTimer:(NSTimer *)timer { [timer invalidate]; timer = nil; } - (void)changeProgressValue { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ float progressValue = self.progressBar.progress; progressValue += .00834; if (progressValue &gt; .99) { progressValue = 1; [self stopTimer:self.progressTimer]; return; } NSString *time = [NSString stringWithFormat:@"%.0f", 60 - ceil(progressValue * 60)]; NSLog(@"Progress Value %f Time %@", progressValue, time); NSString *message = [NSString stringWithFormat:@"Time Left: %@", time]; dispatch_async(dispatch_get_main_queue(), ^(void) { self.progressBar.progress = progressValue; [self updateStatusLabel:message withColor:[UIColor whiteColor] animated:NO]; }); }); } @end </code></pre>
[]
[ { "body": "<p>From your description your approach with two different ViewControllers seems about right. It <em>might</em> make sense to base them of another baseClass, but I find that too busy base-classes often reduce readability at the altar of reusing code. I guess this part boils down to your personal preferences and the complexity of your project.</p>\n\n<p>One part that do seems ripe for improvements is the statusMessage methods in both classes. First of the name indicates that they return a value, displayStatusMessageForNumber (or similar) makes more sense. </p>\n\n<p>Also using a dictionary, matching the numbers and messages would allow a lot less logic inside each switch-statement. As almost every single option either calls stopRetryTimer or startRetryTimer this will simplify things quite a lot. Finally using an enum for the status-codes would make the statement a lot more readable to people without detailed knowledge about each code...</p>\n\n<pre><code>NS_ENUM(NSInteger, statusKey){\n SRStatusKeyDisconnected = 0,\n SRStatusKeyConnecting = 1,\n SRStatusKeySearchingForIdiots = 3,\n SRStatusKeyWowLookAtThatGuy = 4,\n SRStatusKeyMatchOver = 5,\n SRStatusKeyDisconnecting = 6,\n SRStatusKeyOpponentFailed = 7,\n SRStatusKeySearchSucceededNoRooms = 77,\n SRStatusKeyObservingSpecimens = 88,\n SRStatusKeyEveryoneLeftWillRestart = 99\n};\n</code></pre>\n\n<p>...</p>\n\n<pre><code> - (NSDictionary *)statusKeysAndMessages{\n NSDictionary *statusKeysAndMessages = @{ @0 : @\"Disconnected\",\n @1 : @\"Connecting...\",\n @3 : @\"Searching for Idiots...\",\n @4 : @\"Wow, look at that guy...\",\n @5 : @\"Match Over! Will start searching for new room shortly...\",\n @6 : @\"Disconnecting...\",\n @7 : @\"Opponent failed to Join. Will start searching for new room shortly...\",\n @77 : @\"Searching for Idiots...\",\n @88 : @\"Observing specimens\" ,\n @99 : @\"Everyone Left! Will start searching for new room shortly...\"};\n return statusKeysAndMessages;\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>- (void)displayStatusMessageForNumber:(NSNumber *)message {\n NSString *result = [[self statusKeysAndMessages] objectForKey:message];\n\n switch ([message intValue]) {\n case SRStatusKeyDisconnected:\n case SRStatusKeySearchingForIdiots:\n case SRStatusKeyOpponentFailed:\n case SRStatusKeySearchSucceededNoRooms:\n [self startRetryTimer];\n break;\n case SRStatusKeyConnecting:\n case SRStatusKeyWowLookAtThatGuy:\n case SRStatusKeyDisconnecting:\n case SRStatusKeyObservingSpecimens:\n [self stopRetryTimer];\n break;\n case SRStatusKeyMatchOver:\n case SRStatusKeyEveryoneLeftWillRestart:\n [self stopRetryTimer];\n [self performSelector:@selector(retry) withObject:nil afterDelay:6];\n break;\n default:\n break;\n }\n\n if (!result) {\n result = @\"Retry\";\n }\n\n [self updateStatusLabel:result withColor:[self statusLabelColorPicker:message] animated:YES];\n NSLog(@\"STATUS LABEL UPDATE: %@\", message);\n}\n</code></pre>\n\n<p>From what I can see the code handling the status messages in both viewControllers have a lot in common. Perhaps this might warrant creating an own class handling the messages. The more I look at you code, the more this makes sense. As the status messages are mostly(?) married to the video stuff and is handled through a notification pattern you could also move this part of the code into such a handler-class...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T12:22:20.247", "Id": "33702", "ParentId": "32509", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T03:57:56.440", "Id": "32509", "Score": "5", "Tags": [ "objective-c", "ios" ], "Title": "iOS App ViewController" }
32509
<p>I wrote this Ruby code that takes data from a survey. Seeing as it is my first Ruby project, I know it can be written much better. How could some of this code be written in more idiomatic Ruby? This code is extracted from a Rails model (the rest of the model is tame).</p> <pre><code>def prepare_anova_data n = surveys_completed (1..n).each do |i| anova_summary = create_anova_summary!(no_clusters: i) Axis.all.each do |axis| clusters_for_axis = cluster(axis.id, i) clusters_for_axis.each_with_index do |cluster_axis_summary, index| cluster_name = cluster_axis_summary[:name] scores = cluster_axis_summary[:data] scores.each do |key, value| anova_summary.anova_datas.create!(no_clusters: i, cluster_no: index, question_code: key, mean_score: value) end end end end end def cluster(axis_id, no_clusters) # Get all the questions for the axis specified @questions ||= self.survey.questions.where(axis_id: axis_id).pluck('id') clusterer =diana_clusterer(@questions, no_clusters) # Calculate the mean scores per cluster, eg. Cluster 1: question 1: 2, question 2, 3.5 etc. series_data = [] clusterer.clusters.each_with_index do |cluster, index| question_means_for_cluster = {} # For every question, go through the current cluster and add up all of the scores to # caluculate the cluster mean for i in 0...@questions.count sum = 0 count = 0 # data_items is an array containing each respondent's survey scores (as an array) cluster.data_items.each do |item| sum += item[i] count += 1 end question_means_for_cluster[Question.survey_code(@questions[i])] = (sum.to_d / count).round(2) end # Chartkick requires a hash in this format series_data &lt;&lt; {name: "Cluster #{ index + 1 }", data: question_means_for_cluster} end # Don't forget to add the overall mean scores to the result. series_data &lt;&lt; overall_mean_values(clusterer, @questions) end def overall_mean_values(clusterer, questions) overall_question_means = {} # For each question, go through every item (array of individual survey scores) in every cluster and add up the scores # This gets the Survey Group average for each question in the survey for i in 0...questions.count sum = 0 count = 0 # Unpack the clusters here, we don't need the clusters, we just want to use the already retrieved data for # this survey group and merely sum it all up by question. clusterer.clusters.each do |cluster| cluster.data_items.each do |item| sum += item[i] count += 1 end end overall_question_means[Question.survey_code(questions[i])] = sum.to_d / count end # This format is required for the Chartkick libary { name: 'Overall', data: overall_question_means } end private def diana_clusterer(questions, no_clusters) # Get all the responses for the survey group into an array (of arrays) answers = [] self.members.each do |member| answers &lt;&lt; member.responses.where(question_id: questions).pluck('score') end # Use the AI4R library to create a cluster using the Diana Algorithm data_set = DataSet.new(data_items: answers, data_labels: questions) Diana.new.build(data_set, no_clusters) end </code></pre>
[]
[ { "body": "<p>Thanks for posting your code. You've done a good job with:</p>\n\n<ul>\n<li>formatting</li>\n<li>variable and method names</li>\n<li>relatively small, focused methods</li>\n</ul>\n\n<p>You may be new to Ruby, but I don't think you're new to programming.</p>\n\n<p>There's not much to be improved here. A few Ruby idioms you missed, and a few matters of style that aren't all that important.</p>\n\n<h1>Matters of Style</h1>\n\n<h2>Line width</h2>\n\n<p>Some of the lines are a bit long. While there is no longer universal agreement that lines of code should be kept to less than 80 characters, there are many benefits to doing so. One of them is that, when you paste code into StackOverflow, the reader won't have to bother with horizontal scroll bars. Consider breaking long lines up. Usually, you can just hit enter where you want it, indent, and the code will still work fine. Sometimes, you'll need to add a \\ (continuation) to the end of a line to let Ruby know that the rest of the statement is on the following line.</p>\n\n<p>For example, this:</p>\n\n<pre><code>series_data &lt;&lt; {name: \"Cluster #{ index + 1 }\", data: question_means_for_cluster}\n</code></pre>\n\n<p>could be formatted like this:</p>\n\n<pre><code>series_data &lt;&lt; {\n name: \"Cluster #{ index + 1 }\",\n data: question_means_for_cluster\n}\n</code></pre>\n\n<h2>Vertical white space</h2>\n\n<p>There's more vertical white space than I'd use. I'd get rid of most, if not all of it. For example, instead of this:</p>\n\n<pre><code> clusters_for_axis = cluster(axis.id, i)\n\n clusters_for_axis.each_with_index do |cluster_axis_summary, index|\n\n cluster_name = cluster_axis_summary[:name]\n</code></pre>\n\n<p>this:</p>\n\n<pre><code> clusters_for_axis = cluster(axis.id, i)\n clusters_for_axis.each_with_index do |cluster_axis_summary, index|\n cluster_name = cluster_axis_summary[:name]\n</code></pre>\n\n<p>In general, I don't consider vertical white space within a method bad, in itself, but when it is used to separate lines into groups that have some similar purpose, I wonder if those lines could be moved into separate methods.</p>\n\n<h2>Code comments</h2>\n\n<p>Similarly, comments that say what the code is doing, while not bad, are better if they can be replaced with code that says what the comment used to say. Often the lines after a comment can be moved into a method with the method name serving the purpose the comment used to serve.</p>\n\n<h1>Ruby idioms</h1>\n\n<p>Let's let Ruby do some of the busywork for us.</p>\n\n<h2>Replacing a loop with <em>reduce</em></h2>\n\n<p>In this code:</p>\n\n<pre><code> sum = 0\n count = 0\n\n # data_items is an array containing each respondent's survey scores (as an array)\n cluster.data_items.each do |item|\n sum += item[i]\n count += 1\n end\n</code></pre>\n\n<p>We are calculating a sum and a count. The count doesn't need to be calculated: just use <code>cluster.data_items.size</code>. To calculate the sum, this code using <a href=\"https://stackoverflow.com/q/12046673/238886\">reduce</a> is idiomatic Ruby:</p>\n\n<pre><code> sum = cluster.data_items.reduce(:+)\n</code></pre>\n\n<h2>Map</h2>\n\n<p>Ruby has a wonderful idiom for transforming one sequence to another, <a href=\"https://stackoverflow.com/q/12084507/238886\">map</a>. Whenever you see code like this:</p>\n\n<pre><code> series_data = []\n clusterer.clusters.each_with_index do |cluster, index|\n ...\n series_data &lt;&lt; {\n name: \"Cluster #{ index + 1 }\",\n data: question_means_for_cluster\n }\n end\n</code></pre>\n\n<p>You can do this instead:</p>\n\n<pre><code> series_data = clusterer.clusters.map.with_index do |cluster, index|\n series_data &lt;&lt; {\n name: \"Cluster #{ index + 1 }\",\n data: question_means_for_cluster\n }\n end\n</code></pre>\n\n<p>Ruby frees you from the bother of creating the array and adding elements to it. <em>map</em> can also be used in #diana_clusterer.</p>\n\n<h2>self</h2>\n\n<p>There are a few uses of <code>self</code> that you don't need. For example, this:</p>\n\n<pre><code>self.members.each do |member|\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>members.each do |member|\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/q/4699687/238886\">this SO question</a> for more.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T02:59:20.827", "Id": "39259", "ParentId": "32511", "Score": "3" } } ]
{ "AcceptedAnswerId": "39259", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:15:54.953", "Id": "32511", "Score": "5", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Taking data from a survey" }
32511
<p>I'm writing a simple JavaScript game, which uses a 2-dimensional array as the main data structure. I wrote this function-class-thing that allows me to give any two integers, positive or negative. This class <em>should</em> "wrap" those integers back onto the game grid.</p> <p>For example:</p> <pre><code>var g = new Grid(10, 10) g.set(15, -2, "hello") g.get(5, 8); //should be "hello" </code></pre> <p>Anyway, I'm striving to improve my JavaScript, so I'm wondering if there are any improvements (performance, "javascriptness", etc.) that I might be able to make.</p> <pre><code>var Grid = (function(w, h){ this._width = w; this._height = h; this._grid = new Array((this._width * this._height) | 0); this.get = function(x, y){ var coords = _normalize(x, y); return this._grid[(coords.y * coords.x) + coords.x]; } this.set = function(x, y, item){ var coords = _normalize(x, y); this._grid[(coords.y * coords.x) + coords.x] = item; } this._normalize = function(x, y){ if(x &lt; 0) x = (this._width + x) % this._width; else if(x &gt;= this._width) x = x % this._width ; if(y &lt; 0) y = (this._height + y) % this._height; else if(y &gt;= this._height) y = y % this._height; return {'x': x, 'y': y}; } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:29:54.440", "Id": "51972", "Score": "0", "body": "What should happen if x = -11 and width = 10?" } ]
[ { "body": "<p>I can't say, that my variant of normalize function is easier to understand, but at least it is linear and it works correct (as i think) with <code>x</code>, that is less than <code>-width</code> </p>\n\n<pre><code>this._normalize = function(x, y) {\n x = x % this._width;\n y = y % this._height;\n\n x = (this._width + x) % this._width;\n y = (this._height + y) % this._height;\n\n return {'x': x, 'y': y};\n}\n</code></pre>\n\n<p>Also, you missed <code>this</code> statement in <code>get</code> and <code>set</code> functions (looks like a typo):</p>\n\n<pre><code>this.get = function(x, y){\n var coords = this._normalize(x, y);\n return this._grid[(coords.y * coords.x) + coords.x];\n}\nthis.set = function(x, y, item){\n var coords = this._normalize(x, y);\n this._grid[(coords.y * coords.x) + coords.x] = item;\n}\n</code></pre>\n\n<p>It is better to move <code>get</code>, <code>set</code> and <code>normalize</code> functions to Grid <code>prototype</code>.\nPutting these functions in prototype will increase execution speed and require less memory for creating an instance of <code>Grid</code> because these functions will not\nbe created every time <code>Grid</code> instance is created.\nLike this:</p>\n\n<pre><code>var Grid = function(w, h){\n this._width = w;\n this._height = h;\n this._grid = new Array((this._width * this._height) | 0);\n};\nGrid.prototype.get = function(x, y) {\n // get code\n};\nGrid.prototype.set = function(x, y, item){\n // set code\n};\nGrid.prototype._normalize = function(x, y){\n // normalize code\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:42:24.603", "Id": "51973", "Score": "0", "body": "Come to think of it, adding this._width to x right before taking the modulo with this._width doesn't actually do anything, right? So: ```x = (this._width) + x) % this._width``` is the same as ```x %= this._width```." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:48:28.633", "Id": "51974", "Score": "0", "body": "It makes sense, when x < 0... But separating behavior for positive and negative values by `if` statements is also ok." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:51:40.893", "Id": "51975", "Score": "0", "body": "Ohh right, 'cause it's negative. Thank you :D" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:38:47.807", "Id": "32513", "ParentId": "32512", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:21:09.803", "Id": "32512", "Score": "4", "Tags": [ "javascript", "array", "game" ], "Title": "2-dimensional \"wrapping\" array" }
32512
<p>Is this a good/correct way to write a robust C program?</p> <pre><code>//File1 =&gt; Module1.c static int Fun(int); struct{ int (*pFn)(int) }Interface; static int Fun(int){ //do something } Interface* Init(void) { Interface *pInterface = malloc(sizeof(Interface)); pInterface-&gt;pFn = Fun; return pInterface; } //File 2 main() { Interface *pInterface1 = Init(); pInterface1-&gt;pFn(5); } </code></pre> <p>My intention is to make each module expose an interface. Give your thoughts.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T19:04:11.557", "Id": "73071", "Score": "0", "body": "This question appears to be off-topic because it is primarily a design review." } ]
[ { "body": "<p>As it stands it won't compile. The <code>Interface</code> structure is not in a header file and so <code>main</code> has no knowledge of it. Also your <code>malloc(sizeof(Interface))</code> will not compile as C (C++ will be happy) as it needs <code>struct</code> before the <code>Interface</code>, which makes me think you are using C++. And with C++ you can define interfaces, classes that implement interfaces, and objects that instantiate the classes, so you seem to be reinventing things.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:26:34.060", "Id": "32536", "ParentId": "32516", "Score": "1" } }, { "body": "<ol>\n<li><p>You probably intended to write</p>\n\n<pre><code>typedef struct {\n int (*pFn)(int)\n} Interface;\n</code></pre></li>\n<li>Use member names which are more descriptive than <code>pFn</code>. I hope that this was just as an example to post here.</li>\n<li>Yes this approach can work well. I have worked on a bigger project where we used this OO-light approach for C by having an interface struct and each backend would fill it with it's own implementation.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T19:13:49.970", "Id": "32722", "ParentId": "32516", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T09:33:17.543", "Id": "32516", "Score": "2", "Tags": [ "c" ], "Title": "Making each module expose an interface" }
32516
<pre><code>$(document).on('dblclick', '#li', function () { oriVal = $(this).text(); $(this).text(""); input = $("&lt;input type='text'&gt;"); input.appendTo('#li').focus(); }); $(document).on('focusout', 'input', function () { if (input.val() != "") { newInput = input.val(); $(this).hide(); $('#li').text(newInput); } else { $('#li').text(oriVal); } }); </code></pre> <p>So far, I still can't do OOP in jQuery. Can you improve the above code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T03:54:49.987", "Id": "52056", "Score": "0", "body": "Do not listen to such a ridiculous statement and instead have a look at these articles, they should greatly help you. http://alistapart.com/article/writing-testable-javascript\nhttp://addyosmani.com/resources/essentialjsdesignpatterns/book/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T14:39:49.163", "Id": "61191", "Score": "0", "body": "Does this code work? You don't explain what you're trying to do, and the code and question title don't seem to match." } ]
[ { "body": "<p>I wasn't sure how to answer this, so I went with what your code does...</p>\n\n<ol>\n<li>Scope your variables.</li>\n<li>Change your code to target all <code>li</code> instead of one element with the id <code>li</code>.</li>\n<li>Use <code>this</code> when events are triggered to make sure you have the correct element.</li>\n<li>Remove the added elements instead of hiding them.</li>\n<li>Remember to call <code>on</code> using the smallest possible parent container. Possibly a <code>&lt;ul&gt;</code> or <code>&lt;ol&gt;</code>?</li>\n<li>Use short circuiting where appropriate.</li>\n<li>Use <code>jQuery.parent()</code> to get the appended elements parent.</li>\n</ol>\n\n<p>Putting all those change together:</p>\n\n<pre><code>var oriVal;\n$(\"#parentUL\").on('dblclick', 'li', function () {\n oriVal = $(this).text();\n $(this).text(\"\");\n $(\"&lt;input type='text'&gt;\").appendTo(this).focus();\n});\n$(\"#parentUL\").on('focusout', 'li &gt; input', function () {\n var $this = $(this);\n $this.parent().text($this.val() || oriVal); // Use current or original val.\n $this.remove(); // Don't just hide, remove the element.\n});\n</code></pre>\n\n<p>Here's the <a href=\"http://jsfiddle.net/wabLp/1/\" rel=\"nofollow\">JSFiddle</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T15:08:50.120", "Id": "37135", "ParentId": "32520", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T11:00:22.300", "Id": "32520", "Score": "3", "Tags": [ "javascript", "jquery", "object-oriented" ], "Title": "Double click to edit and add new value to li" }
32520
<p>I'm working on mobile app which doing requests to a server's API. I want to develop module that doing following:</p> <ul> <li>get authorization key already exists in previous session</li> <li>connect to server api and read server StatusLine answer code</li> <li>if answer code is 403 then try to re authorize</li> <li>when authorization is passed process server answer body</li> </ul> <p>I implement this with state-machine:</p> <pre><code>enum ConnectionState { checkAnswer, reAuth, processLinks, endProcess } </code></pre> <p>And made process in while-loop:</p> <pre><code> int authCount = 0; HttpResponse httpResponse = null; ConnectionState state = ConnectionState.checkAnswer; boolean processConnect = true; while (processConnect) { switch (state) { case checkAnswer: httpResponse = client.execute(httpGet); final int serverAnswer = httpResponse.getStatusLine().getStatusCode(); if (403 == serverAnswer) { state = ConnectionState.reAuth; } else { state = ConnectionState.processLinks; } break; case reAuth: if (++authCount &gt; MAX_AUTH_ATTEMPTS) { state = ConnectionState.endProcess; break; } auth.invalidateAuth(); if (!auth.doAuth()) { Utils.log("could not authorize api"); } else { state = ConnectionState.checkAnswer; } break; case processLinks: if (null == httpResponse) throw new RuntimeException("HttpResponse is null"); processLinks(httpResponse, imgLinks); state = ConnectionState.endProcess; break; case endProcess: processConnect = false; break; default: throw new RuntimeException("Finded impossible state: " + state.toString()); } } </code></pre> <p>What do you think about such code organization for this task? How to write it more elegantly?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T04:53:16.067", "Id": "52061", "Score": "1", "body": "It is common to name enum elements in capital case such as CHECK_ANSWER." } ]
[ { "body": "<p>I would consider the <a href=\"http://en.wikipedia.org/wiki/State_pattern\" rel=\"nofollow\">state pattern</a>. The actual state-dependent code could be handled in the enum.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T15:52:15.563", "Id": "32532", "ParentId": "32525", "Score": "1" } }, { "body": "<p>I agree with Ibalazscs that <a href=\"http://en.wikipedia.org/wiki/State_pattern\" rel=\"nofollow\">StatePattern</a> makes sense - using a switch to drive changes in behavior is a code smell.</p>\n\n<p>Given that this state machine has only one end state, you could ditch the processConnect boolean, and just check for end state...</p>\n\n<pre><code>ConnectionState state = ConnectionState.checkAnswer;\nwhile(! ConnectionState.endProcess.equals(state) {\n ...\n}\n</code></pre>\n\n<p>You also might want to consider whether ConnectionState should implement an interface to make it extensible. See Item #34 \"Emulate extensible enums with interfaces\", Effective Java Second Edition, by Joshua Bloch</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:13:51.360", "Id": "32534", "ParentId": "32525", "Score": "3" } } ]
{ "AcceptedAnswerId": "32534", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T14:24:36.190", "Id": "32525", "Score": "1", "Tags": [ "java", "session", "state-machine" ], "Title": "Performing API calls from a mobile client, reauthorizing the session if necessary" }
32525
<p>I just finished a little game of Tic-Tac-Toe for a class I'm in, and I think it looks alright, but I'm pretty fresh, so I would like to know how I might be able to improve it, given the situation I'm in. I'd like to host it on my website and I'd like it to be safe and expandable.</p> <p>Please let me know where I'm off (or gone wrong) in terms of best practices and if you feel like being nice, what looks OK. I know I've got three global variables, but the program is small, so I let them stay there. If you can think of a way to easily eliminate those variables without drastically changing the rest of the code, I'd be interested. Again, I'd like this to become something else (a more complicated game of Tic-Tac-Toe) so if you can think of ways of making the code more usable at a future time, I'd also be interested.</p> <p><strong>JS:</strong></p> <pre><code> &lt;script type="text/javascript"&gt; // Global variables var firstGame = true; var turnNum; var squareTaken = new Array(); //functions function newGame(firstGame){ //starts a new game by turnNum = 0; //setting the turn number to 0 for (var i=0; i&lt;9; i++){ //populating squareTaken array squareTaken[i] = ""; //with "", as in no X or O } if (firstGame !== true){ //if this is not the first game var canvasID; var c; var cxt; for (var i= 0; i&lt;9; i++){ //loop through the canvas contexts and erase their current drawings. canvasID = "canvas" + i; c = document.getElementById(canvasID); cxt = c.getContext("2d"); cxt.clearRect(0,0,50,50); //Clear the rectangle starting at 0,0 and going to the width and height of each. } } } function canvasClicked(canvasNum){ //handles canvas clicks var canvasID; var c; var cxt; canvasID = "canvas" + canvasNum; c = document.getElementById(canvasID); cxt = c.getContext("2d"); if (squareTaken[canvasNum] == ""){ if (turnNum % 2 == 0){ cxt.beginPath(); cxt.moveTo(10,10); cxt.lineTo(40,40); cxt.moveTo(10,40); cxt.lineTo(40,10); cxt.stroke(); cxt.closePath(); squareTaken[canvasNum] = "X"; turnNum++; } else { cxt.beginPath(); cxt.arc(25,25,15,0,2*Math.PI) cxt.stroke(); cxt.closePath(); squareTaken[canvasNum] = "O"; turnNum++; } } if (turnNum &gt; 4){ checkWin(squareTaken, canvasNum); } } function checkWin(squareTaken, canvasNum){ //returns true if game over if ( //If any of the following combinations are true, someone has won. last &amp;&amp; checks for non-occupied squares. (squareTaken[0]===squareTaken[1] &amp;&amp; squareTaken[1]===squareTaken[2] &amp;&amp; squareTaken[0] != "") || (squareTaken[3]===squareTaken[4] &amp;&amp; squareTaken[4]===squareTaken[5] &amp;&amp; squareTaken[3] != "") || (squareTaken[6]===squareTaken[7] &amp;&amp; squareTaken[7]===squareTaken[8] &amp;&amp; squareTaken[6] != "") || (squareTaken[0]===squareTaken[3] &amp;&amp; squareTaken[3]===squareTaken[6] &amp;&amp; squareTaken[0] != "") || (squareTaken[1]===squareTaken[4] &amp;&amp; squareTaken[4]===squareTaken[7] &amp;&amp; squareTaken[1] != "") || (squareTaken[2]===squareTaken[5] &amp;&amp; squareTaken[5]===squareTaken[8] &amp;&amp; squareTaken[2] != "") || (squareTaken[0]===squareTaken[4] &amp;&amp; squareTaken[4]===squareTaken[8] &amp;&amp; squareTaken[0] != "") || (squareTaken[2]===squareTaken[4] &amp;&amp; squareTaken[4]===squareTaken[6] &amp;&amp; squareTaken[2] != "") ) { //Declare winner alert(squareTaken[canvasNum] + " wins!\nStarting a new game!"); if (firstGame === true){ firstGame = false; } newGame(firstGame); } else if ( //Check for tie squareTaken[0]!="" &amp;&amp; squareTaken[1]!="" &amp;&amp; squareTaken[2]!="" &amp;&amp; squareTaken[3]!="" &amp;&amp; squareTaken[4]!="" &amp;&amp; squareTaken[5]!="" &amp;&amp; squareTaken[6]!="" &amp;&amp; squareTaken[7]!="" &amp;&amp; squareTaken[8]!="" ) { //Declare tie alert("It's a tie! \n Starting new game!"); if (firstGame === true){ firstGame = false; } newGame(firstGame); } } //Start the game newGame(firstGame); &lt;/script&gt; </code></pre> <p><strong>Related HTML:</strong></p> <pre><code> &lt;canvas id="canvas0" width="50" height="50" onClick="canvasClicked(0)"&gt;&lt;/canvas&gt; &lt;canvas id="canvas1" width="50" height="50" onClick="canvasClicked(1)"&gt;&lt;/canvas&gt; &lt;canvas id="canvas2" width="50" height="50" onClick="canvasClicked(2)"&gt;&lt;/canvas&gt; &lt;br /&gt; &lt;canvas id="canvas3" width="50" height="50" onClick="canvasClicked(3)"&gt;&lt;/canvas&gt; &lt;canvas id="canvas4" width="50" height="50" onClick="canvasClicked(4)"&gt;&lt;/canvas&gt; &lt;canvas id="canvas5" width="50" height="50" onClick="canvasClicked(5)"&gt;&lt;/canvas&gt; &lt;br /&gt; &lt;canvas id="canvas6" width="50" height="50" onClick="canvasClicked(6)"&gt;&lt;/canvas&gt; &lt;canvas id="canvas7" width="50" height="50" onClick="canvasClicked(7)"&gt;&lt;/canvas&gt; &lt;canvas id="canvas8" width="50" height="50" onClick="canvasClicked(8)"&gt;&lt;/canvas&gt; </code></pre>
[]
[ { "body": "<p>To start with, you can eliminate all your global variables by putting your code in an anonymous function, and then immediate invoke that function: </p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n(function () {\n // all of your code\n}());\n&lt;/script&gt;\n</code></pre>\n\n<p>Note that your functions are global variables too, and pollute the global namespace just as much. To illustrate, this:</p>\n\n<pre><code>function foo () { ... };\n</code></pre>\n\n<p>Is practically the same thing as this:</p>\n\n<pre><code>var foo = function () { ... };\n</code></pre>\n\n<p>Also, you might know this, but I'll mention it anyway: unlike C++ or Java, javascript is function-scoped, so any variables you declare in conditionals or loops are accessible in the enclosing function. So, this:</p>\n\n<pre><code>var canvasID;\nvar c;\nvar cxt;\nvar i;\n\nif (firstGame !== true){ //if this is not the first game\n for (i= 0; i&lt;9; i++){ //loop through the canvas contexts and erase their current drawings.\n canvasID = \"canvas\" + i;\n c = document.getElementById(canvasID);\n cxt = c.getContext(\"2d\");\n cxt.clearRect(0,0,50,50); //Clear the rectangle starting at 0,0 and going to the width and height of each.\n }\n}\n</code></pre>\n\n<p>Is equivalent, in terms of scope, to your code:</p>\n\n<pre><code>if (firstGame !== true){ //if this is not the first game\n var canvasID;\n var c;\n var cxt;\n for (var i= 0; i&lt;9; i++){ //loop through the canvas contexts and erase their current drawings.\n canvasID = \"canvas\" + i;\n c = document.getElementById(canvasID);\n cxt = c.getContext(\"2d\");\n cxt.clearRect(0,0,50,50); //Clear the rectangle starting at 0,0 and going to the width and height of each.\n }\n}\n</code></pre>\n\n<p>(After the if statement the variable canvaseID, for example, still exists can still be used--in both your code and mine above.) Not understanding this can cause bewildering bugs. When I was first getting used to function-scoped variables I would declare all variables in one <code>var</code> statement at the top of the function.</p>\n\n<p>On using canvas: instead of have 9 canvas elements, I would use one canvas element, and divide it up into 9 squares in code. The way you've done it is fine, though.</p>\n\n<p>If you're really interested in best practices with javascript, you may be interested in using <a href=\"http://www.jslint.com/\" rel=\"nofollow\">jslint</a>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T18:40:57.290", "Id": "52212", "Score": "0", "body": "Half of your review is about putting code into a private scope, which is very important when developing a JavaScript library, but a non-issue if it's the main code to be run on the page. There's no need to complicate things like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T19:08:07.177", "Id": "52213", "Score": "0", "body": "it would be an issue if the main code on a page uses libraries." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T18:15:16.557", "Id": "32648", "ParentId": "32528", "Score": "1" } }, { "body": "<p>As @Robz says I would have a single canvas element and detect the mouse position. This will make it easier to draw a grid and to blank the canvas when restarting the game. It's also easier to track event handling in the javascript (e.g. <code>canvas.onclick = canvasClicked</code>) rather than in the HTML.</p>\n\n<p>For any more complicated programme you would probably want to separate the drawing from the game logic by having a set of functions, or better, a module object, that takes care of drawing.</p>\n\n<p>I would tend to have a <code>for</code> loop to check the different possible ways of winning or drawing rather than one very long <code>if</code> condition, although your way of doing it is at least simple and transparent.</p>\n\n<p>You start a new game from within the <code>checkWin</code> function, which in turn is called from <code>canvasClicked</code>. This is okay but could get confusing if you put code after the call to <code>newGame</code>, which will then be carried out after the new game has been set up. </p>\n\n<p>Finally</p>\n\n<pre><code>if (firstGame === true){\n firstGame = false;\n }\n</code></pre>\n\n<p>can be simplified to</p>\n\n<pre><code>firstGame = false\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/GRU72/9/\" rel=\"nofollow\">Here is a version</a> illustrating the points about the drawing and event handling, replacing the lengthy <code>if</code> conditions with loops, and showing how you could have separate canvas and game modules.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T00:39:52.703", "Id": "52289", "Score": "0", "body": "Thanks for the helpful answer. I'll update my code to reflect some of the changes you've suggested. That example you gave is also extremely useful! Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T18:45:18.950", "Id": "32650", "ParentId": "32528", "Score": "1" } } ]
{ "AcceptedAnswerId": "32650", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T15:05:41.027", "Id": "32528", "Score": "4", "Tags": [ "javascript", "game", "html5", "canvas" ], "Title": "JavaScript Tic-Tac-Toe review: best practices, correctness, and any other improvements/suggestions" }
32528
<p>At the request of my father, I've adapted some C# code he wrote which uses a timer to display the true and approximate solutions of the ODE y' = -lambda*y in real time to do the same in java and then graph the solutions using JFreeChart. The approximate solution is Euler's (first order) method. I don't have much programming experience and I'm looking for some feedback (efficiency, best practice, layout, design). One question in particular I'd like to know the answer to is whether or not JFreeChart is a good choice? Is there a better one? I'm also particularly interested in receiving feedback concerning the efficiency and quality of my design and layout. Here's the code, which takes the form of 2 classes (ODESolver and Graph) which use JCommon-1.0.20 and JFreeChart-1.0.16:</p> <p>ODESolver.java:</p> <pre><code>import java.awt.Component; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.Timer; import javax.swing.border.EmptyBorder; import org.eclipse.wb.swing.FocusTraversalOnArray; /** * * @author George and Stephen Tomlinson */ public class ODESolver extends JFrame { // Declarations. // serialVersionUID sets the version number. private static final long serialVersionUID = 1L; // Declare a JPanel to define and manipulate the contents of the ODESolver GUI. private JPanel contentPane; private static JTextField a0; private static JTextField lambda; private static JTextField timeStep; private static final int TOTAL_SECONDS = 20; private double elapsedSeconds = 0; private Timer myTimer = new Timer(0, (ActionListener) null); JTextArea timerLabel = new JTextArea(); JTextArea trueSol = new JTextArea(); static JTextArea apprxSol = new JTextArea(); double aoD; double lambdaD; double timeStepD, state1, state2, ans1, timeLeft; double roundOff, roundOffA; String t, tA; ArrayList&lt;Double&gt; true_A = new ArrayList&lt;Double&gt;(); ArrayList&lt;Double&gt; apprx_A = new ArrayList&lt;Double&gt;(); private static JTextField timerInterval; int timerInt; /** * Launch the application. */ public static void main(String[] args) { // Run the ODESolver code in the Event-dispatching thread for thread-safety EventQueue.invokeLater(new Runnable() { public void run() { // try to create an instance of ODESolver (which extends JFrame) and make it visible // print the StackTrace if there's a problem try { ODESolver frame = new ODESolver(); // let the constructor do the work frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * This is the constructor method. It creates the frame. (ODESolver extends the class JFrame). */ public ODESolver() { // Form specification (what to do when form is closed, dimensions, instantiate contentPane, // dimensions of contentPane, set ContentPane property (hover over it for more details). setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 892, 400); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); // Create text field for entering a0 (10 columns by default). a0 = new JTextField(); a0.setColumns(10); // Create label for text field ao. JLabel lblA = new JLabel("a0"); lblA.setLabelFor(a0); lblA.setFont(new Font("Tahoma", Font.PLAIN, 20)); // Create label for text field lambda. JLabel lblNewLabel = new JLabel("lambda"); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 20)); // Create text field for entering lambda. lambda = new JTextField(); lblNewLabel.setLabelFor(lambda); lambda.setColumns(10); // Create label for text field time step. JLabel lblTimeStep = new JLabel("time step"); lblTimeStep.setFont(new Font("Tahoma", Font.PLAIN, 20)); // Create text field for entering time step. timeStep = new JTextField(); lblTimeStep.setLabelFor(timeStep); timeStep.setColumns(10); // Create label for 'Simulation time' text area. JLabel lblSimulationTime = new JLabel("Simulation time"); lblSimulationTime.setFont(new Font("Tahoma", Font.PLAIN, 20)); // Create text area to show true soln and prevent the user form being able to edit it. trueSol.setEditable(false); trueSol.setFont(new Font("Monospaced", Font.PLAIN, 20)); // Create label for text area true soln. JLabel lblSolutiontrue = new JLabel("Solution 1 (true)"); lblSolutiontrue.setLabelFor(trueSol); lblSolutiontrue.setFont(new Font("Tahoma", Font.PLAIN, 20)); // Create text area apprx soln. //JT[2] = apprxSol; apprxSol.setEditable(false); apprxSol.setFont(new Font("Monospaced", Font.PLAIN, 20)); // Create label for text area apprx soln. JLabel lblSolutionapprx = new JLabel("Solution 2 (apprx)"); lblSolutionapprx.setLabelFor(apprxSol); lblSolutionapprx.setFont(new Font("Tahoma", Font.PLAIN, 20)); // Create 'Start the simulation' button. JButton btnStartTimer = new JButton("Start the simulation"); btnStartTimer.setFont(new Font("Tahoma", Font.PLAIN, 20)); /* * Set its function. The ActionListener class possesses one method (by the name of 'ActionPerformed') which is invoked when an action occurs i.e. the button is clicked. This is in java.awt: one of the 2 packages in the standard library (Java Standard Edition 7 API (Java SE 7 API for short)) used for creating GUIs. The other one is called javax.swing. * */ btnStartTimer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Parse and store user input. aoD = Double.parseDouble(getA0().getText()); lambdaD = Double.parseDouble(getLambda().getText()); timeStepD = Double.parseDouble(getTimeStep().getText()); timerInt = Integer.parseInt(getTimerInterval().getText()); // If the button has been pressed and the timer is already running, stop the timer, // initialise myTimer and instruct user to press the button again to start a new simulation. if (myTimer != null &amp;&amp; myTimer.isRunning()) { myTimer.stop(); myTimer = null; timerLabel.setText("Press again for new sim"); // Else initialise elapsedSeconds, create a new timer and start it. } else { elapsedSeconds = 0; /* Create a new Timer which uses the subclass TimerListener to compute and store the exact and approximate solutions of the differential equation (see further down for definition of TimerListener. */ myTimer = new Timer(timerInt, new TimerListener()); myTimer.start(); } } }); // End of code relating to 'Start the simulation' button. // Create a label for the timer. timerLabel = new JTextArea(); timerLabel.setFont(new Font("Monospaced", Font.PLAIN, 20)); timerLabel.setEditable(false); // Create 'Draw graph' button. JButton btnDraw = new JButton("Draw graph"); btnDraw.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { // Store the true and apprx solution data sets in an ArrayList array called i. ArrayList[] i = new ArrayList[2]; i[0] = true_A; i[1] = apprx_A; // Instantiate a Graph object and call its createAndShowGUI method to produce the GUI // containing the desired graph. Graph graph = new Graph(); graph.createAndShowGUI(i); } }); btnDraw.setFont(new Font("Tahoma", Font.PLAIN, 20)); // End of code relating to 'Draw Graph' button. // Create label for timer interval text field. JLabel lblTimerInterval = new JLabel("timer interval"); lblTimerInterval.setFont(new Font("Tahoma", Font.PLAIN, 20)); // Create timer interval JTextField. timerInterval = new JTextField(); timerInterval.setColumns(10); /* The following code is automatically generated by WindowBuilderPro in response to operations performed using the visual editor (the equivalent of the Designer code in C#). Actually some of the other code is also generated by WBP in the same way: i.e. declaration and specification of JTextFields, JButtons and JTextAreas above and below. The definitions of the methods (except methods like getTimeStep() below) are left to the programmer. * */ GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(139) .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addComponent(lblTimerInterval) .addComponent(lblTimeStep) .addComponent(lblNewLabel) .addComponent(lblA)) .addGap(18) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(a0, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lambda, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(timeStep, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(37) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(trueSol, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(apprxSol, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(timerLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addComponent(timerInterval, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(btnStartTimer, GroupLayout.PREFERRED_SIZE, 226, GroupLayout.PREFERRED_SIZE) .addComponent(btnDraw))) .addGap(83) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(lblSolutiontrue) .addComponent(lblSimulationTime) .addComponent(lblSolutionapprx)) .addContainerGap(362, Short.MAX_VALUE)) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(11) .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(lblA) .addComponent(a0, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSimulationTime)) .addGap(17)) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(timerLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED))) .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(lambda, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(trueSol, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE) .addComponent(lblSolutiontrue)) .addComponent(lblNewLabel)) .addGap(14) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(timeStep, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSolutionapprx) .addComponent(apprxSol, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE) .addComponent(lblTimeStep)) .addGap(18) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(lblTimerInterval) .addComponent(timerInterval, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(45) .addComponent(btnStartTimer, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE) .addGap(29) .addComponent(btnDraw) .addGap(27)) ); contentPane.setLayout(gl_contentPane); contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{a0, lambda, timeStep})); } // method to get JTextField ao. public static JTextField getA0() { return a0; } // Method to get JTextField lambda. public static JTextField getLambda() { return lambda; } // Method to get JTextField timeStep. public static JTextField getTimeStep() { return timeStep; } // Subclass TimerListener used to compute and store exact and approximate solutions of the // differential equation when 'Start the simulation' button is pressed. public class TimerListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (elapsedSeconds == TOTAL_SECONDS) { myTimer.stop(); timerLabel.setText("end"); } else { String text = String.valueOf(elapsedSeconds); timerLabel.setText(text); timeLeft = 20.0-elapsedSeconds; if (elapsedSeconds != 20.0) { ans1 = Math.exp(-lambdaD * elapsedSeconds); state1 = aoD * ans1; true_A.add(state1); // true_A and apprx_A are objects of type ArrayList. // true_A.add(state1) just stores the value of state1 at the next available // space in true_A, which resizes dynamically. if (elapsedSeconds == 0.0) { // First point to add to the ArrayList containing the approx // solution is the initial condition. state2 = aoD; apprx_A.add(state2); } else if (elapsedSeconds!=(0.0)) { // Compute and add next point in approximate solution. // Compute approximate 1st order Euler solution. state2 = state2 - lambdaD * timeStepD * state2; // Add the next point in the apprx solution. apprx_A.add(state2); } else { /* If this point is reached, the method's not working properly, so display an error message detailing this and stop the computation (return). */ System.out.println("problem in if/else part of Start the simulation" + " method"); return; } // Display the true and approximate solutions after first rounding // them to 2 decimal places. roundOff = Math.round(state1 * 100.0) / 100.0; t = String.valueOf(roundOff); trueSol.setText(t); roundOffA = Math.round(state2 * 100.0) / 100.0; tA = String.valueOf(roundOffA); apprxSol.setText(tA); } else { /* If this point is reached, the method's not working properly, so display an error message detailing this and stop the computation (return). */ System.out.println("problem: else part of Start the simulation" + " method reached"); return; } } // Increment elapsedSeconds by time step. elapsedSeconds+=timeStepD; } } // Method to get JTextField timerInterval. public static JTextField getTimerInterval() { return timerInterval; } } </code></pre> <p>Graph.java</p> <pre><code>import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Color; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.xy.XYSplineRenderer; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /** * * @author George and Stephen Tomlinson */ public class Graph extends Applet{ // set version number private static final long serialVersionUID = 1L; /* Method which takes an ArrayList array defining 2 data sets and produces a JFreeChart graphing them and adds this to a JPanel which is then used by the createandShowGUI method to define the contents of a JFrame GUI and then display it. The method returns this JPanel. */ public JPanel createContentPane(ArrayList[] in){ JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); XYSeries seriesTrue = new XYSeries("True"); XYSeries seriesApprx = new XYSeries("Approx"); // Read input arguments and store in XYSeries objects. for(int i=0;i&lt;in[0].size();i++) { double item = (double)in[0].get(i); seriesTrue.add(i,item); } for(int i=0;i&lt;in[1].size();i++) { double item = (double)in[1].get(i); seriesApprx.add(i,item); } XYSeriesCollection dataset = new XYSeriesCollection(); XYSeriesCollection datasetApprx = new XYSeriesCollection(); dataset.addSeries(seriesTrue); datasetApprx.addSeries(seriesApprx); // Create a chart from the first data set (the true solution). JFreeChart chart = ChartFactory.createXYLineChart( "Plot of true and approx solns of y' = -lambda*y", "time", "y", dataset, PlotOrientation.VERTICAL, true, true, false ); ChartPanel chartPanel = new ChartPanel(chart); // Add the second data set (the approximate solution) to the chart (the first is at index 0). chart.getXYPlot().setDataset(1, datasetApprx); /* Create a separate renderer for each data set (otherwise they won't be recognised as separate data sets, so the JFreeChart object won't give them different colours for example, as it only sees one data set, so refuses to assign any more than one colour to it. * */ XYSplineRenderer SR0 = new XYSplineRenderer(1000); XYSplineRenderer SR1 = new XYSplineRenderer(1000); chart.getXYPlot().setRenderer(0, SR0); chart.getXYPlot().setRenderer(1, SR1); // Set colours for each data set. chart.getXYPlot().getRendererForDataset(chart.getXYPlot().getDataset(0)).setSeriesPaint(0, Color.BLUE); chart.getXYPlot().getRendererForDataset(chart.getXYPlot().getDataset(1)).setSeriesPaint(0, Color.RED); panel.add(chartPanel); panel.setOpaque(true); return panel; } // Method to create the GUI upon which the graph is displayed, which takes an ArrayList array (called i) // of length 2 containing the 2 data sets to be graphed. public void createAndShowGUI(ArrayList[] i) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame(" ODESolver "); // Create and set up the content pane. Graph demo = new Graph(); frame.setContentPane(demo.createContentPane(i)); // The other bits and pieces that define how the JFrame will work and what it will look like. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1300, 650); frame.setVisible(true); } } </code></pre>
[]
[ { "body": "<p>Your Graph class does not compile in the line</p>\n\n<pre><code>double item = (double)in[1].get(i);\n</code></pre>\n\n<p>you cannot convert Object to double. <strong>You should make sure that the code compiles before you show it to code review</strong>. Other notes:</p>\n\n<ul>\n<li>You should not use unreadable constructs like the first element of an\narray means something and the other elements mean something\ndifferent. </li>\n<li>Always use generics, not ArrayLists without a type</li>\n<li>JFreeChart is fine. </li>\n<li>You are also using\norg.eclipse.wb.swing.FocusTraversalOnArray as an external dependency\n(probably inserted by your GUI designer). GUI designers make your life easier when you are starting, but harder when you need to maintain/deploy your programs.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:24:06.240", "Id": "52003", "Score": "0", "body": "Yes. I had noted the ArrayList without type as an area to improve. Actually, the ArrayList does have a type. It's the ArrayList array which stores these ArrayLists that I haven't worked out how to give a matching type to yet (it should be Double). I don't think I have any cases where the first element of an array means something different to the others. If so, where?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:32:17.907", "Id": "52005", "Score": "0", "body": "It may be worth my pointing out that it's ODESolver.java that is supposed to be run. This then instantiates a Graph object. Graph does still compile for me though and even runs an applet, not that the applet does anything much. I guess the first element of an array maening something different to the others you wrote of might be apprx_A which stores the approximate solution in which case the first element must store the initial condition which is why it's not dealt wqith the same as the other elements. teh initial conditon is specified by the user, whilst the other elements of the approximate" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:37:42.900", "Id": "52006", "Score": "0", "body": "solution are computed within ODESolver using Euler's (first order) method. I'm not sure if there' a better way of dealing with this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:54:16.913", "Id": "52008", "Score": "1", "body": "The problems are in the createContentPane method of Graph. The argument is an array of ArrayLists, but these ArrayLists have raw type, not a generic declaration. (See http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). Perhaps you already corrected the declaration to createContentPane(ArrayList<Double>[] in) -- **note the Double!!** -- but posted some old code, while your version is working. I suppose in[0] means something else here than in[1]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:04:04.787", "Id": "52011", "Score": "0", "body": "That's got rid of the protocol warning (probably not the correct term: I mean the yellow warnings which don't prevent compilation) in Graph, but for the corresponding statement in ODESolver (ArrayList[] i = new ArrayList[2];) in the actionPerormed method of the button btnDraw I did try to change it accordingly before I posted this question to ArrayList<Double>[] i = new ArrayList<Double>[2]; but this results in the error 'cannot create a generic array of type Double'. I guess I might be forced to use a 2dArrayList if I want to get rid of the yellow warning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:15:39.120", "Id": "52014", "Score": "0", "body": "in[0] is an ArrayList containing the 20 Doubles which store the y coordinates of the true solution. in[1] is the equavalent for the approximate solution. I realise I could make this clearer by choosing a better name than in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:24:41.693", "Id": "52019", "Score": "1", "body": "I could compile and start your program after I changed to ArrayList<Double>[] in. I use Intellij Idea (not Eclipse) and Java 7. I would consider using a Point class that has getX and getY methods - it would improve the readability a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:36:32.033", "Id": "52021", "Score": "0", "body": "The x points are straight forward actually: since time is on the x axis, the x point is just the index in the ArrayList, so in[0].get(5) returns the y coordinate for the true solution at time 5 seconds (or more precisely 5 time units, since the timer interval can be changed by the user). I suppose it may be helpful to have the Point class and getY method though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:42:34.267", "Id": "52024", "Score": "0", "body": "(time unit = timer interval)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:16:57.453", "Id": "32535", "ParentId": "32531", "Score": "3" } }, { "body": "<p>In addtion to @lbalazscs answers:</p>\n\n<ol>\n<li>Your constructor is a gazillion lines long. Constructors should be kept short and precise so your can see quickly what it is doing. I'd move the code creating the UI out of there into one or more separate methods.</li>\n<li>You mix UI and processing code. <code>ODESolver</code> should just do the processing of the values (basically do what the name of the class implies) and you should have a separate class (like <code>SolverDisplay</code>) dealing with the display concerns. Right now if someone wanted to change your solver or add stuff to it he'd have to wade through a ton of unrelated UI code just to find where you do the calculations. Not sure what the idiomatic Java approach for patterns like MVP or MVVM is but I'm sure there is information out there.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T19:29:17.670", "Id": "52032", "Score": "0", "body": "I don't actually know that I can reduce the constructor by that much: maybe the actionPerformed methods of the buttons could instantiate objects which deal with the workings of these methods. The rest of it is just declaring and setting up the various components of the UI and it was virtually all done automatically by the visual editor in WindowBuilderPro." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T20:03:29.223", "Id": "52035", "Score": "1", "body": "@bluesh34: In Winforms the designer generates a separate method `InitializeComponents()` where all the auto generated stuff is located in. Not sure how the WindowsBuilderPro would react if you were to do a similar thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T20:05:41.317", "Id": "52036", "Score": "0", "body": "I can just do the reverse anyway, as you suggest: move everything else elsewhere. Actually I think a more precise explanation of what happens with Winforms is that the auto-generated stuff is located in Designer.cs which is then called by InitializeComponent(), which is in Form.cs, but point taken: it may be possible to do the same in java." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T19:10:10.527", "Id": "32543", "ParentId": "32531", "Score": "2" } } ]
{ "AcceptedAnswerId": "32535", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T15:38:12.833", "Id": "32531", "Score": "1", "Tags": [ "java", "beginner", "layout" ], "Title": "How's my and my father's java ODE Solving and Graphing Program?" }
32531
<p>I have a requirement where there are 3 selection criteria user selects countries from a map displayed as lets say in 3 categories , i am maintaining 3 arraylist for the same.Each time he selects a country i have to display list of country names displayed in Alphabetical order in a bottom bar with font color distinguishing each category .I have written a code which will add all the values of arraylist in a different arraylist and sort it and then based on category it will create font for each and display them in the bottom so each time user selects a country this method is called.Please review and let me know if i can improve the performance.Below is the code</p> <p>Lets say issuingOffice,selectedCountries and deSelectedCountries are arraylist declared in global scope and have values.</p> <pre><code>function updateBottomBar(){ var initalContent="Countires: &lt;label&gt;"; require(["dojox/collections/ArrayList"],function(arrayList){ var bottomBar = new arrayList(); var it = issuingOffice.getIterator(); while (!it.atEnd()) { var country = it.get(); bottomBar.add(country); } var scit = selectedCountries.getIterator(); while (!scit.atEnd()) { var country = scit.get(); bottomBar.add(country); } var descit = deSelectedCountries.getIterator(); while (!descit.atEnd()) { var country = descit.get(); bottomBar.add(country); } bottomBar.sort(); var bbit = bottomBar.getIterator(); while (!bbit.atEnd()) { var country = bbit.get(); if(selectedCountries.contains(country)){ initalContent!="&lt;font&gt;"+country+"&lt;/font&gt;"; }else if(selectedCountries.contains(country)){ initalContent!="&lt;font&gt;"+country+"&lt;/font&gt;"; } else{ initalContent!="&lt;font&gt;"+country+"&lt;/font&gt;"; } } initalContent+="&lt;/label&gt;"; dojo.byId("displayCountryName")=initalContent; }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T00:24:24.887", "Id": "52048", "Score": "0", "body": "Should that be a `+=` in here: `initalContent!=\"<font>\"+country+\"</font>\";`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T03:49:24.890", "Id": "52055", "Score": "0", "body": "@ChrisWue Thanks for reminding me, I've seen it but totally forgot to include it in the answer. Done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T13:45:50.443", "Id": "52088", "Score": "0", "body": "sorry it is += not !=" } ]
[ { "body": "<p>There are many improvements that can be done, but here are a few things I identified:</p>\n\n<ol>\n<li>I wouldn't have the <code>require</code> call within the function itself. I would rather create a top-level module with all listed dependencies. The <code>updateBottomBar</code> function would be defined in this module:</li>\n</ol>\n\n\n\n<pre><code>require([\"dojox/collections/ArrayList\"/*, other deps...*/], function(ArrayList) {\n function updateBottomBar() {\n //...\n }\n});\n</code></pre>\n\n<p><em>Have a look at <a href=\"https://dojotoolkit.org/documentation/tutorials/1.8/modules/\" rel=\"nofollow\">https://dojotoolkit.org/documentation/tutorials/1.8/modules/</a></em></p>\n\n<ol>\n<li><p>It's very inefficient to merge the multiple arrays every-time. You should rather maintain an additional array that stays in sync with the others. When a new item is pushed in one of the other arrays, you reflect the changes in that additional array directly (same logic with removal). However, if you can, I would rather have a single collection to maintain and use a discriminator such as a <code>category</code> property to categorize items, so instead of holding strings, the collection would contain <code>{ country: String, category: String }</code> objects.</p></li>\n<li><p>With your current implementation, you also <strong>throw away some useful information that you need to recompute later</strong>. For example <code>if(selectedCountries.contains(country))</code> shouldn't be necessary since you had that knowledge when you pushed the items in the <code>bottomBar</code> list. Instead of pushing a simple string, push an object like proposed in point #2. Then you will be able to check if the items belongs to the selected category in O(1) time by doing something like:</p>\n\n<pre><code>switch (country.category) {\n 'selected': //do something break;\n}\n</code></pre></li>\n<li><p>Concatenating multiple strings with the <code>+</code> operator isin't the most efficient way. Instead you should push your strings in an array and then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow\"><code>theArray.join('')</code></a> to perform the concatenation. </p>\n\n<p>Also note that you can create DOM elements dynamically with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/document.createElement\" rel=\"nofollow\"><code>document.createElement</code></a> and make the process efficient by using document fragments (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment\" rel=\"nofollow\"><code>document.createDocumentFragment</code></a>).</p></li>\n<li><p>You have a typo -> <code>var initalContent=\"Countires: &lt;label&gt;\";</code></p></li>\n<li><p><code>initalContent != ...</code> Did you mean <code>+=</code> ?</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T00:07:03.573", "Id": "52045", "Score": "0", "body": "Keeping data in sync in different data structures is not a good idea, so I'd definitely go with the single source option." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T03:00:05.447", "Id": "52054", "Score": "0", "body": "@ChrisWue Well that might not be possible for the OP, that's why I've made that suggestion. However, why do you think it's such a bad idea?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T06:47:55.140", "Id": "52069", "Score": "1", "body": "Keeping data in sync requires more code and more decisions to make, more places to check, more things you can forget when extending the code more bugs to be put in. It will get you in trouble sooner or later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T13:47:03.467", "Id": "52089", "Score": "0", "body": "@plalx can you please explain me 1 point" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T23:38:28.177", "Id": "52119", "Score": "0", "body": "@VIckyb Added some precisions ;)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T18:45:26.630", "Id": "32542", "ParentId": "32533", "Score": "2" } } ]
{ "AcceptedAnswerId": "32542", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T15:56:06.497", "Id": "32533", "Score": "1", "Tags": [ "javascript", "optimization", "sorting" ], "Title": "Sorting Each Entry (code review + optimization)" }
32533
<p>I have this <a href="http://en.wikipedia.org/wiki/Crazy_Eights" rel="noreferrer">Crazy Eights</a> game (which at the moment does not include crazy cards):</p> <pre><code>class Card(object): RANKS = ("2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A") SUITS = ("c", "d", "h", "s") def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): return self.rank + self.suit def __eq__(self, other): return self.rank == other.rank and self.suit == other.suit def canPlayOn(self, other): return self.rank == other.rank or self.suit == other.suit class Hand(object): def __init__(self): self.cards = [] def __str__(self): return " ".join([str(card) for card in self.cards]) def __bool__(self): return bool(self.cards) def give(self, other, card): self.remove(card) other.add(card) def add(self, card): self.cards.append(card) def remove(self, card): self.cards.remove(card) class Pile(Hand): @property def topCard(self): return self.cards[-1] class DrawPile(Pile): def populate(self): for rank in Card.RANKS: for suit in Card.SUITS: self.add(Card(rank, suit)) def deal(self, others, cards = 7): import random random.shuffle(self.cards) for _ in range(cards): for hand in others: self.give(hand, self.topCard) class Player(Hand): def playMove(self, discardPile, drawPile): card = self.getCard(discardPile.topCard) self.give(discardPile, card) if card else \ drawPile.give(self, drawPile.topCard) def getCard(self, topCard): card = input("This is your hand: " + str(self) + ". The is the top card: " + str(topCard) + ". Enter your card (enter PU to pick up a card): ") while self.isInvalid(card, topCard): card = input("Invalid input. Enter your card: ") return Card(card[0], card[1]) if card != "PU" else None def isInvalid(self, card, topCard): if card == "PU": return False elif len(card) != 2 or card[0] not in Card.RANKS or \ card[1] not in Card.SUITS or \ Card(card[0], card[1]) not in self.cards or \ not Card(card[0], card[1]).canPlayOn(topCard): return True return False class Computer(Hand): def playMove(self, discardPile, drawPile): card = self.getCard(discardPile.topCard) if card: self.give(discardPile, card) print("Computer plays " + str(card), end = ". ") else: drawPile.give(self, drawPile.topCard) print("Computer picks up.", end = " ") print("Computer has " + str(len(self.cards)) + " cards remaining.") def getCard(self, topCard): for card in self.cards: if card.canPlayOn(topCard): return card return None def main(): drawPile = DrawPile() drawPile.populate() player = Player() computer = Computer() playerList = [player, computer] drawPile.deal(playerList) discardPile = Pile() drawPile.give(discardPile, drawPile.topCard) playerIndex = 0 while isStillPlaying(playerList): playerList[playerIndex].playMove(discardPile, drawPile) if playerIndex &lt; len(playerList) - 1: playerIndex += 1 else: playerIndex = 0 print("Computer wins!" if player else "You win!") def isStillPlaying(playerList): for player in playerList: if not player: return False return True if __name__ == "__main__": main() </code></pre> <p>Can someone provide a code review (particularity on my OOP skills)? Also, what would be the most object oriented way to implement "crazy cards"?</p>
[]
[ { "body": "<p>Generally speaking, the code seems quite good. However, there are some parts that could be a little bit enhanced. I did not try to understand the whole thing, but I can give you some pointers.</p>\n\n<pre><code>for _ in range(cards):\n</code></pre>\n\n<p>The name name <code>_</code> is often imported is the built-in functions as an alias for the <code>gettext</code> function. Using it to discard unwanted variables could result in surprising errors.</p>\n\n<pre><code>self.give(discardPile, card) if card else \\\n drawPile.give(self, drawPile.topCard)\n</code></pre>\n\n<p>This line is so long that you had to split it. The inline <code>if ... else</code> does not add anything to the code or the readability here. Just go back to a regular <code>if ... else</code>:</p>\n\n<pre><code>if card:\n self.give(discardPile, card)\nelse:\n drawPile.give(self, drawPile.topCard)\n</code></pre>\n\n<p>Also, your class <code>Hand</code> is nothing but a list of cards. Instead of having to always index <code>self.cards</code>, you could probably have <code>Hand</code> inherit from <code>list</code>. Not sure whether you would want to do this or not, but it could be pretty handful to avoid having one more layer of indirection every time you want to access your list of cards. On the other hand, all the classes derived from <code>Hand</code> would be unable to derive from a second built-in type. I'm not saying it is a good idea, but it may be worth trying. Also, if you do this, you can get rid of <code>Hand.remove</code> and <code>Hand.add</code> since the methods <code>remove</code> and <code>append</code> would be directly inherited from <code>list</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T07:47:39.350", "Id": "32561", "ParentId": "32537", "Score": "5" } }, { "body": "<p>I'm just going to look at your OOP design for this review, as you requested.</p>\n\n<p>Your <code>canPlayOn()</code> method does not belong in the <code>Card</code> class. The purpose of your <code>Card</code> class should be to represent a card, and nothing more. You should be able to use the same <code>Card</code> class for Blackjack, Bridge, or any other card game. Logic specific to Crazy Eights does not belong there, and should probably be moved into the <code>Player</code> class.</p>\n\n<p>I was initially thinking that your <code>Hand</code> should consist of a <code>set</code> of cards rather than an array, since the items are distinct and order doesn't matter. Then I saw that your <code>Pile</code> derives from <code>Hand</code>, and in <code>Pile</code>, order does matter. Maybe using an array is OK after all, if you accept that a <code>Pile</code> is a subclass of <code>Hand</code>. I think that such an inheritance relationship is more of a hack than an accurate model, but I can let it slide because it seems to work in this case.</p>\n\n<p>In <code>DrawPile.deal()</code>, I would rename the <code>others</code> parameter to <code>recipient_hands</code>. Also <code>import</code>s should go at the beginning of the file.</p>\n\n<p>I take issue with <code>Player(Hand)</code> and <code>Computer(Hand)</code>. First of all, I would say that a player <em>has</em> a hand rather than a player <em>is</em> a hand. That suggest that composition should be favoured over inheritance. Also, the computer <em>is</em> a kind of player, so there should be an inheritance relationship there. Furthermore, there is a lot of redundant code between <code>Player</code> and <code>Computer</code>, differing mainly in what the output looks like. Perhaps your <code>Player</code> and <code>Computer</code> classes could be merged into a <code>Crazy8Player</code> class, with the constructor taking <code>name</code>, <code>narrator</code>, and <code>strategy</code> arguments.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T11:04:28.020", "Id": "32566", "ParentId": "32537", "Score": "8" } }, { "body": "<ol>\n<li><p>What happens if the <code>drawPile</code> runs out of cards? It looks to me as though eventually you'll get</p>\n\n<pre><code>IndexError: list index out of range\n</code></pre>\n\n<p>when trying to return the <code>topCard</code> of an empty <code>Pile</code>. You need to check at the end of the main loop to see if the draw pile is empty, and take some action accordingly. For example, you could shuffle the discard pile into the draw pile. (But this might still leave the draw pile empty, so you need a fallback for that case, unlikely as it might be.)</p></li>\n<li><p>You ask, \"what would be the most object oriented way to implement this?\" but is that really the right question to ask? Object-orientation is a technique, not a goal in itself.</p></li>\n<li><p>I'm not convinced that you gain anything by having a <code>Card</code> class. What would you lose if you represented a card as a two-character string like <code>\"8h\"</code>?</p></li>\n<li><p>Since all the ranks are one letter long, instead of:</p>\n\n<pre><code>RANKS = (\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\")\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>RANKS = '23456789TJQKA'\n</code></pre>\n\n<p>(and similarly for the suits).</p></li>\n<li><p>Transferring the top card from one pile to another is such a common operation that it would simplify your code if you special-cased it in the <code>give</code> method.</p></li>\n<li><p>I'm not convinced that you gain anything by having separate <code>Hand</code> and <code>Pile</code> classes. Logically speaking you're right that a pile differs from a hand in that it has a top card, but this has no practical effect (you never call the <code>topCard</code> method on a <code>Hand</code> object and nothing would go wrong if you did). So it's just added complexity for no benefit.</p>\n\n<p>(If you really wanted to apply strict object-oriented logic, you wouldn't subclass <code>Player</code> from <code>Hand</code> since a player <em>has</em> a hand of cards, not \"<em>is</em> a hand of cards\".)</p></li>\n<li><p>I'm not convinced that you gain anything by having a <code>DrawPile</code> class. There is only ever one object of this class, and moreover its <code>populate</code> and <code>deal</code> methods are only called from one place.</p></li>\n<li><p>I <a href=\"https://codereview.stackexchange.com/a/32561/11728\">concur with Morwenn</a> that the code would be much simplified by inheriting <code>Hand</code> from <code>list</code>.</p></li>\n<li><p>Whenever you have two nested loops, as in your <code>deal</code> method, consider using <a href=\"http://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a> to simplify them to a single loop.</p></li>\n<li><p>When you iterate over a sequence repeatedly (as in your main loop where you are iterating over the players), consider using <a href=\"http://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.cycle</code></a>.</p></li>\n</ol>\n\n<p>Here's a revised version of the code that implements the suggestions above, and contains a few other changes too.</p>\n\n<pre><code>from abc import abstractmethod, ABCMeta\nfrom itertools import cycle, product\nfrom random import shuffle\n\nRANKS = '23456789TJQKA'\nSUITS = 'CDHS'\nINITIAL_CARDS = 7\n\nclass Pile(list):\n \"\"\"An ordered sequence of cards.\"\"\"\n def __str__(self):\n return ' '.join(self)\n\n @property\n def top(self):\n \"\"\"The top card of the pile.\"\"\"\n return self[-1]\n\n def transfer(self, dest, card=None):\n \"\"\"Transfer card (or top card if omitted) to dest and return it.\"\"\"\n if card is None:\n card = self.top\n self.remove(card)\n dest.append(card)\n return card\n\nclass Player(object, metaclass=ABCMeta):\n def __init__(self, game):\n self.game = game\n self.hand = Pile()\n\n def can_play_on(self, card, other):\n \"\"\"Return True iff card can legally be played on other.\"\"\"\n return any(c == o for c, o in zip(card, other))\n\n def draw(self):\n \"\"\"Draw a card and return it.\"\"\"\n return self.game.draw.transfer(self.hand)\n\n def discard(self, card=None):\n \"\"\"Discard a card and return it.\"\"\"\n return self.hand.transfer(self.game.discard, card)\n\n @abstractmethod\n def play(self):\n \"\"\"Play one turn.\"\"\"\n pass\n\nclass Human(Player):\n win_message = \"You win!\"\n\n def play(self):\n print(\"This is your hand: {}.\\n\"\n \"This is the top card: {}.\"\n .format(self.hand, self.game.discard.top))\n cmd = input(\"Enter your card (or P to pick up a card): \")\n while True:\n cmd = cmd.upper()\n if cmd.startswith('P'):\n print(\"You pick up {}.\".format(self.draw()))\n return\n elif cmd not in self.hand:\n cmd = input(\"You don't have that card. Try again: \")\n elif not self.can_play_on(cmd, self.game.discard.top):\n cmd = input(\"You can't play that card. Try again: \")\n else:\n self.discard(cmd)\n return\n\nclass Computer(Player):\n win_message = \"Computer wins!\"\n\n def play(self):\n for card in self.hand:\n if self.can_play_on(card, self.game.discard.top):\n self.discard(card)\n print(\"Computer plays {}.\".format(card))\n break\n else:\n self.draw()\n print(\"Computer picks up.\")\n cards = len(self.hand)\n print(\"Computer has {} card{} remaining.\"\n .format(cards, '' if cards == 1 else 's'))\n\nclass Game(object):\n def __init__(self):\n self.draw = Pile(''.join(card) for card in product(RANKS, SUITS))\n self.discard = Pile()\n self.players = [Human(self), Computer(self)]\n shuffle(self.draw)\n for _, player in product(range(INITIAL_CARDS), self.players):\n player.draw()\n self.draw.transfer(self.discard)\n\n def play(self):\n for player in cycle(self.players):\n player.play()\n if not player.hand:\n print(player.win_message)\n break\n if not self.draw:\n print(\"Draw pile is empty!\\n\"\n \"Shuffling discard pile into draw pile.\")\n self.draw, self.discard = self.discard, self.draw\n shuffle(self.draw)\n self.draw.transfer(self.discard)\n if not self.draw:\n print(\"Out of cards! Let's call it a tie.\\n\")\n break\n\nif __name__ == \"__main__\":\n Game().play()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T11:27:41.260", "Id": "32568", "ParentId": "32537", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T16:54:47.400", "Id": "32537", "Score": "7", "Tags": [ "python", "object-oriented", "game", "playing-cards" ], "Title": "How object oriented is my Crazy Eights game?" }
32537
<p>I have the following JavaScript code to work out the angle between two points (clockwise). The code I have seems a bit "hacky" to me, as I have a while loop ensuring the number is not negative (to make the range 0-360), as well as I have to subtract 270 degrees to get it to work correctly. Is there a better way to do this?</p> <pre><code>this.angle = function(point) { var delta = point.subtract(this); var aR = Math.atan2(delta.y, delta.x); var aD = aR * (180 / Math.PI); aD -= 270; while (aD &lt; 0) { aD += 360; } return aD; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:19:15.400", "Id": "52015", "Score": "2", "body": "The angle relative to what?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:20:06.383", "Id": "52016", "Score": "0", "body": "@Shmiddty That code snippet works out the angle between itself (this) and point. I should have made that clearer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:21:17.600", "Id": "52017", "Score": "3", "body": "The angle has to be relative to something. The angle between two points is always 0. I assume you want the angle relative to the horizontal axis." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:21:40.170", "Id": "52018", "Score": "3", "body": "Oh for the love of pedanticism" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:37:11.350", "Id": "52022", "Score": "0", "body": "@JoeFrambach It's important to know what he's expecting the angle to be relative to. If, for example, he's expecting it to be relative to the positive y-axis (12 o'clock), moving clockwise, that changes the calculation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T18:05:28.073", "Id": "52026", "Score": "0", "body": "@Shmiddty You are correct in believing I am expecting it to be relative to 12 o'clock, and for it to move clockwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T18:10:41.667", "Id": "52027", "Score": "0", "body": "@jackwilsdon FYI: The JavaScript coordinate system has the origin at the top-left corner of the screen. Also, angles will be relative to the positive x-axis (3 o'clock), so you're going to have to rotate by -90 degrees to make the angle relative to 12 o'clock. Take a look here: http://jsfiddle.net/RmyZg/ I shifted the origin, and flipped the y-axis, so that resembles the standard Cartesian coordinate-system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T23:57:45.203", "Id": "52044", "Score": "0", "body": "Why the `a` prefix? How about meaningful names instead of `aR` and `aD`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T17:30:58.977", "Id": "57312", "Score": "1", "body": "@retailcoder \"Angle in radians\" and \"angle in degrees\", I believe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-05T04:47:20.537", "Id": "154884", "Score": "1", "body": "These aren't javascript, but you may want to look at these implementations: http://stackoverflow.com/questions/4633177/c-how-to-wrap-a-float-to-the-interval-pi-pi" } ]
[ { "body": "<p>First of all, let's define the problem precisely. According to your comment, this is the behavior you want:</p>\n\n<blockquote>\n <p>You are correct in believing I am expecting it to be relative to 12 o'clock, and for it to move clockwise.</p>\n</blockquote>\n\n<p>However, your code doesn't actually behave that way. Your <code>angle()</code> function, as written, computes the orientation of <code>point</code> relative to <code>this</code>, with 6 o'clock being 0°, angles increasing counterclockwise, with return values in the range [0, 360). (Alternatively stated, your <code>angle()</code> computes the orientation of <code>this</code> relative to <code>point</code>, with 12 o'clock being 0°, angles increasing counterclockwise, with return values in the range [0, 360).) So, I'm reviewing erroneous code.</p>\n\n<p>As evidenced by the comments, many people had problems understanding what you meant by the \"angle between two points\". That's a vocabulary problem. I suggest that you borrow a term from navigation: <a href=\"http://en.wikipedia.org/wiki/Bearing_%28navigation%29\" rel=\"noreferrer\"><strong>bearing</strong></a>. In this review, I'll use the term \"bearing\" to refer to your desired behavior: when <code>point</code> is taken relative to <code>this</code>, 12 o'clock is considered to have a bearing of 0°, with values increasing clockwise, up to 360°. I'll continue to use the term <em>angle</em> to refer to the erroneous behavior of your <code>angle()</code> function.</p>\n\n<hr>\n\n<p>First of all, let's see how we can calculate the angle without having to do <code>aD -= 270</code>. We can accomplish this by mapping the axes strategically when calling <code>atan2()</code>. The direction for which we want the arctangent to be 0 is an \"x′ axis\" of our mapped plane, and the direction for which we want the arctangent to be π/2 we will call our \"y′ axis\".</p>\n\n<p><img src=\"https://i.stack.imgur.com/7tNuO.png\" alt=\"Axis-mapping diagram for nicerAngle()\"></p>\n\n<p>Here it is written out:</p>\n\n<pre><code>// Same behavior as angle(), but implemented without aD -= 270.\nPoint.prototype.nicerAngle = function(point) {\n var delta = point.subtract(this);\n var aR = Math.atan2(delta.x, -delta.y); // Mapped axes!\n var aD = aR * (180 / Math.PI);\n if (aD &lt; 0) {\n aD += 360;\n }\n return aD;\n};\n</code></pre>\n\n<p>Note that your <code>while</code> loop can simply be an <code>if</code> conditional.</p>\n\n<hr>\n\n<p>Note that <code>Math.atan2()</code> is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2\" rel=\"noreferrer\">guaranteed</a> to return a value in the range <code>[-Math.PI, +Math.PI]</code>. (See footnote below.) We should now ask, is it possible to get rid of the conditional altogether?</p>\n\n<p>One reason to get rid of the conditional is to reduce the number of code paths — fewer code paths means fewer cases to worry about in code-coverage tests. Another reason is performance — if the CPU can always execute the code sequentially, then it doesn't have to do branch prediction. When faced with a branch, CPUs speculatively execute code in advance, then throw away the results from the branch not taken. (That's true for a low-level language like C. It probably wouldn't matter at all for a naïve JavaScript interpreter. It might make a difference on a highly optimized JavaScript JIT. Anyway, the code-path-reduction argument alone should be a good reason to try to eliminate the conditional.)</p>\n\n<p>Well, if we always add π to the value returned by <code>Math.atan2()</code>, then the result would be in the range <code>[0, 2 * Math.PI]</code>. It's a simple matter of mapping the axes to make that work for us. We want to map the axes such that 12 o'clock yields an <code>atan2</code> of 0° (our x″ axis), increasing counterclockwise such that 9 o'clock is 90° (our y″ axis). If we can accomplish that, then adding 180° would map 6 o'clock to 0° and 3 o'clock to 90°. Here is a diagram:</p>\n\n<p><img src=\"https://i.stack.imgur.com/pzaHt.png\" alt=\"Axis-mapping diagram for unconditionalAngle()\"></p>\n\n<p>… and a solution:</p>\n\n<pre><code>// Same behavior as nicerAngle(), but implemented without if-statement.\nPoint.prototype.unconditionalAngle = function(point) {\n var delta = point.subtract(this);\n var aR = Math.atan2(-delta.x, delta.y);\n return 180 + aR * (180 / Math.PI);\n};\n</code></pre>\n\n<hr>\n\n<p>So, what about computing bearing? Once again, we simply have to remap the axes when calling <code>atan2()</code>. Using the same ideas as before,</p>\n\n<p><img src=\"https://i.stack.imgur.com/u9M92.png\" alt=\"Axis-mapping diagram for bearing()\"></p>\n\n<pre><code>// Computes orientation of point relative to this, with 12 o'clock being 0 degrees, angles\n// increasing clockwise, with return values in the range [0, 360]. Implemented like\n// unconditionalAngle().\nPoint.prototype.bearing = function(point) {\n var delta = point.subtract(this);\n return 180 + 180 / Math.PI * Math.atan2(-delta.x, -delta.y);\n};\n</code></pre>\n\n<p>Of course, if you really wanted top performance, you could make this a one-liner by doing away with the intermediate <code>delta</code> object.</p>\n\n<hr>\n\n<p><strong>Footnote about <code>unconditionalAngle()</code> and my unconditional implementation of <code>bearing()</code></strong></p>\n\n<p>Note that I said that <code>Math.atan2()</code> returns values in the range <code>[-Math.PI, +Math.PI]</code>, not <code>[-Math.PI, +Math.PI)</code>. Therefore, with the unconditional implementations, it <em>is</em> possible to get a result of 360°, for example, with <code>ORIGIN.unconditionalAngle(new Point(-0, -1))</code> and <code>ORIGIN.bearing(new Point(-0, 1))</code>. All I'll say here is that proper IEEE floating point math has a useful concept of negative zero. I'll leave it to you to decide whether you want to deliberately stamp out this manifestation of that concept.</p>\n\n<hr>\n\n<p>Here's a <a href=\"http://jsfiddle.net/zvmMN/\" rel=\"noreferrer\">jsFiddle</a> of all the code above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T06:44:10.933", "Id": "32558", "ParentId": "32539", "Score": "15" } } ]
{ "AcceptedAnswerId": "32558", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T17:06:11.830", "Id": "32539", "Score": "10", "Tags": [ "javascript", "computational-geometry", "mathematics" ], "Title": "Best way to work out angle between points?" }
32539
<p>The game I am working with is a block game. It generates terrain and then allows you to freely mine and place blocks as you wish (sound familiar Cx) BUT! there is a problem. I have a code that snaps the mouse to a 32x32 grid:</p> <pre><code>mse=pygame.mouse.get_pos() mse=(((mse[0])/32)*32,((mse[1])/32)*32) cursrect.x,cursrect.y=mse screen.blit(curs,cursrect) </code></pre> <p>This draws the cursor and snaps it to 32x32 grid. But the problem is, I have the sidescrolling code:</p> <pre><code>for p in players: if p.rect.right&gt;=576: for b in instancelist: b.rect.right-=4 p.rect.right-=4 if p.rect.left&lt;=64: for b in instancelist: b.rect.left+=4 p.rect.left+=4 </code></pre> <p>Now when the player moves the screen, the mouse is offset from the rest of the world and doesn't place the blocks to a 32x32 grid relative to the rest of the blocks.. so.. how can I fix this?</p> <p>Here is the whole code: import pygame,random from collections import namedtuple from pygame.locals import * pygame.init() pygame.display.set_caption('PiBlocks 0.1| By Sam Tubb') screen=pygame.display.set_mode((640,480)) instancelist=[] players=[] clock=pygame.time.Clock() texdir='org_texture' Move = namedtuple('Move', ['up', 'left', 'right']) ingame=0 max_gravity = 100</p> <pre><code>#load sprites grass=pygame.image.load(texdir+'\\grass.png').convert() dirt=pygame.image.load(texdir+'\\dirt.png').convert() stone=pygame.image.load(texdir+'\\stone.png').convert() psprite=pygame.image.load(texdir+'\\player.png').convert() curs=pygame.image.load(texdir+'\\cursor.png').convert() curs.set_colorkey((0,255,0)) cursrect=curs.get_rect(x=32,y=32) blocksel=dirt class Player(object): sprite=psprite def __init__(self, x, y): self.rect = self.sprite.get_rect(centery=y, centerx=x) # indicates that we are standing on the ground # and thus are "allowed" to jump self.on_ground = True self.xvel = 0 self.yvel = 0 self.jump_speed = 7 self.move_speed = 3 def update(self, move, blocks): # check if we can jump if move.up and self.on_ground: self.yvel -= self.jump_speed # simple left/right movement if move.left: self.xvel = -self.move_speed if move.right: self.xvel = self.move_speed # if in the air, fall down if not self.on_ground: self.yvel += 0.3 # but not too fast if self.yvel &gt; max_gravity: self.yvel = max_gravity # if no left/right movement, x speed is 0, of course if not (move.left or move.right): self.xvel = 0 # move horizontal, and check for horizontal collisions self.rect.left += self.xvel self.collide(self.xvel, 0, blocks) # move vertically, and check for vertical collisions self.rect.top += self.yvel self.on_ground = False; self.collide(0, self.yvel, blocks) def collide(self, xvel, yvel, blocks): # all blocks that we collide with for block in [blocks[i] for i in self.rect.collidelistall(blocks)]: # if xvel is &gt; 0, we know our right side bumped # into the left side of a block etc. if xvel &gt; 0: self.rect.right = block.rect.left if xvel &lt; 0: self.rect.left = block.rect.right # if yvel &gt; 0, we are falling, so if a collision happpens # we know we hit the ground (remember, we seperated checking for # horizontal and vertical collision, so if yvel != 0, xvel is 0) if yvel &gt; 0: self.rect.bottom = block.rect.top self.on_ground = True self.yvel = 0 # if yvel &lt; 0 and a collision occurs, we bumped our head # on a block above us if yvel &lt; 0: self.rect.top = block.rect.bottom class Block(object): def __init__(self,x,y,sprite): self.x=x self.y=y self.sprite=sprite self.rect=self.sprite.get_rect(x=self.x,y=self.y) top=(random.randint(5,8)*32) cen=(top+random.randint(4,6)*32) down=15 across=0 blklvl=0 while across&lt;3200: while down&gt;0: screen.fill((0,0,0)) if blklvl==top: blocksel=grass instancelist.append(Block(across,blklvl,blocksel)) if blklvl&gt;top: if blklvl&lt;cen: blocksel=dirt instancelist.append(Block(across,blklvl,blocksel)) if blklvl&gt;cen-1: blocksel=stone instancelist.append(Block(across,blklvl,blocksel)) down=down-1 blklvl=blklvl+32 if down==0: if across&lt;3200: per=(across/(32/5)) if per&gt;100: per=100 top=(random.randint(5,8)*32) cen=(top+random.randint(4,6)*32) down=15 blklvl=0 across=across+32 down=15 #print 'GENERATION:'+str(per)+'%' pygame.display.flip() players.append(Player(640/2,20)) blocksel=dirt #mainloop while True: #block select key=pygame.key.get_pressed() if key[K_1]: blocksel=grass if key[K_2]: blocksel=dirt if key[K_3]: blocksel=stone #manual camera if key[K_UP]: for b in instancelist: b.rect.top+=32 for p in players: p.rect.top+=32 if key[K_DOWN]: for b in instancelist: b.rect.bottom-=32 for p in players: p.rect.bottom-=32 if key[K_RIGHT]: for b in instancelist: b.rect.right-=32 for p in players: p.rect.right-=32 if key[K_LEFT]: for b in instancelist: b.rect.left+=32 for p in players: p.rect.left+=32 screen.fill((20,70,255)) mse=pygame.mouse.get_pos() move = Move(key[K_w], key[K_a], key[K_d]) for e in pygame.event.get(): if e.type==QUIT: exit(1) if e.type==MOUSEBUTTONUP: to_remove = [b for b in instancelist if b.rect.collidepoint(mse)] for b in to_remove: instancelist.remove(b) if not to_remove: mse=(((mse[0])/32)*32,((mse[1])/32)*32) instancelist.append(Block(mse[0],mse[1],blocksel)) for inst in instancelist: screen.blit(inst.sprite,inst.rect) clock.tick(60) for p in players: if p.rect.right&gt;=576: for b in instancelist: b.rect.right-=4 p.rect.right-=4 if p.rect.left&lt;=64: for b in instancelist: b.rect.left+=4 p.rect.left+=4 p.update(move, instancelist) for b in instancelist: if p.rect.colliderect(b.rect): p.ground=1 mse=pygame.mouse.get_pos() mse=(((mse[0])/32)*32,((mse[1])/32)*32) cursrect.x,cursrect.y=mse screen.blit(curs,cursrect) screen.blit(psprite,p.rect) pygame.display.flip() </code></pre> <p>Thanks :)</p>
[]
[ { "body": "<p>Here are some suggestions to get you going:</p>\n\n<ul>\n<li>Don't keep blocks in the list. Perhaps, create some ordered structure (e.g. Grid) where you can easily insert or query blocks (and you'll need that for faster collision detection later on)?</li>\n<li>Create camera and decouple it, don't change position of the items in the world. You should add some methods which would transform your screen coordinates to world coordinates, and vice-versa.</li>\n</ul>\n\n<p>For the second part as it relates to your question,\nin your camera class:</p>\n\n<pre><code>class Camera:\n def __init__(self, x, y)\n self.xPos = x\n self.yPos = y\n def pointToWorld(self, screenX, screenY):\n return {'x': screenX + self.xPos, 'y': screenY + self.yPos} #you should use and return Point\n</code></pre>\n\n<p>Here's the flow:</p>\n\n<ol>\n<li>Obtain your click location</li>\n<li>use pointToWorld to convert it to world location</li>\n<li>use world location to figure out where in the world have you clicked and do something accordingly.</li>\n</ol>\n\n<p>Naturally, first thing to do is create a camera class that you can move, implement complementary function (worldToScreen?), and change your rendering code to reflect that. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T10:34:31.660", "Id": "52075", "Score": "0", "body": "I'll see what I can do with it. I'm not to skilled at this yet though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T13:28:00.493", "Id": "52133", "Score": "1", "body": "You already have everything in place basically. For start, try changing the lines which draw blocks to use camera, and go from there." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T07:30:15.413", "Id": "32560", "ParentId": "32545", "Score": "2" } } ]
{ "AcceptedAnswerId": "32560", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T20:47:29.200", "Id": "32545", "Score": "1", "Tags": [ "python", "pygame", "mathematics" ], "Title": "Pygame snap mouse to grid?" }
32545
<p>In a web application I am writing, I have used the following:</p> <pre><code>def dbgmsg(lvl, fmt, ...): if dbglvl &gt;= lvl: # ... format and write the message pass # just here for correctness </code></pre> <p>Which is then used inside the code as:</p> <pre><code>dbgmsg(3, "Something happened") </code></pre> <p>Since there is no thing such as a the <code>#ifdef</code> in Python to my knowledge, I need to include the code at runtime. Will the above code cause a performance impact due to the call being made even when the globally set <code>dbglvl</code> is <code>0</code>? Which alternatives exist?</p>
[]
[ { "body": "<ol>\n<li><p>It's going to take some time for Python to run the test <code>dbglvl &gt;= lvl</code>. You can estimate the amount of time using the <a href=\"http://docs.python.org/3/library/timeit.html\" rel=\"nofollow\"><code>timeit</code></a> module. For example, on my computer,</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; def f1():\n... pass\n... \n&gt;&gt;&gt; def f2():\n... if x &gt; 0:\n... pass\n... \n&gt;&gt;&gt; x = 0\n&gt;&gt;&gt; timeit(f1)\n0.14283514022827148\n&gt;&gt;&gt; timeit(f2)\n0.18653011322021484\n</code></pre>\n\n<p>So the <code>if x &gt; 0:</code> test costs about 40 ns. If this is going to be a problem for you, then Python is probably not a suitable language for your application.</p></li>\n<li><p>You can avoid the test altogether by having a separate name for the logging function at each debug level and then assigning a no-op function to the levels that don't apply.</p>\n\n<pre><code>def debug_message_write(format, *args):\n debug_output.write(format.format(*args))\n\ndef debug_message_ignore(format, *args):\n pass\n\ndebug_message_1 = debug_message_write if debug_level &gt;= 1 else debug_message_ignore\ndebug_message_2 = debug_message_write if debug_level &gt;= 2 else debug_message_ignore\n# etc.\n</code></pre>\n\n<p>(You could avoid the repetition here by writing to the <a href=\"http://docs.python.org/3/library/functions.html#globals\" rel=\"nofollow\"><code>globals()</code></a> dictionary in a loop.)</p>\n\n<p>And then in the code you would call</p>\n\n<pre><code>debug_message_3(\"Opening {}\", filename)\n</code></pre>\n\n<p>or whatever. But this is more complicated than your original approach and I doubt that the minuscule saving in time is worth it.</p></li>\n<li><p>Your code would be easier to read if you wrote <code>debug_message</code> instead of <code>dbgmsg</code> and <code>debug_level</code> instead of <code>dbglvl</code>. There is no need for you to save on vowels: there is no danger of running out.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T15:51:02.420", "Id": "32600", "ParentId": "32554", "Score": "3" } } ]
{ "AcceptedAnswerId": "32600", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T05:43:35.563", "Id": "32554", "Score": "1", "Tags": [ "python" ], "Title": "Debugging based on a debug level without performance impact?" }
32554
<p>Here is a self imposed exercise and solution to learn Scalaz state monad. How can I refactor it to take it to the next level? So far I've only studied the state monad so would welcome suggestions on introducing other Scalaz features of relevance, as well as general Scala style/approach.</p> <p><strong>Exercise</strong></p> <blockquote> <p>Use state monad to simulate the process of drawing 5 coloured balls from a bag of 30x Red, 20x Green, 10x Blue. Rather than representing the bag and sample as collections of balls, use a map to track the number of each colour.</p> </blockquote> <p><strong>Solution</strong></p> <pre><code>import scalaz._ import Scalaz._ object StateExercise extends App{ trait Colour object Red extends Colour { override def toString = "Red"} object Green extends Colour { override def toString = "Green"} object Blue extends Colour { override def toString = "Blue"} type Bag = Map[Colour, Int] val empty: State[Bag, Bag] = state(Map[Colour, Int]()) def drawOne(soFar: Bag): State[Bag, Bag] = for( ball &lt;- State[Bag, Colour]{s =&gt; val (colours, counts) = s.toIndexedSeq.unzip val ballIndex = (math.random * s.values.sum).toInt val selected = colours( counts.tail .view .scanLeft(counts(0))(_ + _) .indexWhere(_ &gt;= ballIndex) ) (s.updated(selected, s(selected) - 1), selected) } ) yield soFar.updated(ball, soFar.getOrElse(ball, 0) + 1) def draw(n: Int): State[Bag, Bag] = for( balls &lt;- get[Bag]; selection &lt;- { assert(balls.values.sum &gt;= n) //Check the bag has enough left (1 to n).foldLeft(empty)((accState, _) =&gt; accState.flatMap(drawOne)) } ) yield selection val full: Bag = Map(Red -&gt; 30, Green -&gt; 20, Blue -&gt; 10) val (remaining, selected) = draw(5)(full) println(" Selected: "+selected) println("Remaining: "+remaining) } </code></pre> <p><strong>Output</strong></p> <blockquote> <p>Selected: Map(Red -> 3, Green -> 2) </p> <p>Remaining: Map(Red -> 27, Green -> 18, Blue -> 10)</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-11T06:18:35.387", "Id": "32555", "Score": "2", "Tags": [ "scala", "monads", "scalaz" ], "Title": "Scalaz state monad exercise to model sampling of coloured balls" }
32555
<p>I have a couple of fields which I am trying to put together into a single <code>ByteBuffer</code> before storing it in a Cassandra database.</p> <p>That byte array which I will be writing into Cassandra is made up of three byte arrays as described below:</p> <pre><code>short employeeId = 32767; long lastModifiedDate = "1379811105109L"; byte[] attributeValue = os.toByteArray(); </code></pre> <p>Now, I will write <code>employeeId</code>, <code>lastModifiedDate</code> and <code>attributeValue</code> together into a single byte array and that resulting byte array will be written into Cassandra. I will then have my C++ program retrieve that byte array data from Cassandra and then deserialize it to extract <code>employeeId</code>, <code>lastModifiedDate</code> and <code>attributeValue</code> from it.</p> <p>To do this, I am using <code>ByyteBuffer</code> with BigEndian byte order format.</p> <p>I have put up this code together: </p> <pre><code>public static void main(String[] args) throws Exception { String text = "Byte Buffer Test"; byte[] attributeValue = text.getBytes(); long lastModifiedDate = 1289811105109L; short employeeId = 32767; int size = 2 + 8 + 4 + attributeValue.length; // short is 2 bytes, long 8 and int 4 ByteBuffer bbuf = ByteBuffer.allocate(size); bbuf.order(ByteOrder.BIG_ENDIAN); bbuf.putShort(employeeId); bbuf.putLong(lastModifiedDate); bbuf.putInt(attributeValue.length); bbuf.put(attributeValue); bbuf.rewind(); // best approach is copy the internal buffer byte[] bytesToStore = new byte[size]; bbuf.get(bytesToStore); // write bytesToStore in Cassandra... // Now retrieve the Byte Array data from Cassandra and deserialize it... byte[] allWrittenBytesTest = bytesToStore;//magicFunctionToRetrieveDataFromCassandra(); ByteBuffer bb = ByteBuffer.wrap(allWrittenBytesTest); bb.order(ByteOrder.BIG_ENDIAN); bb.rewind(); short extractEmployeeId = bb.getShort(); long extractLastModifiedDate = bb.getLong(); int extractAttributeValueLength = bb.getInt(); byte[] extractAttributeValue = new byte[extractAttributeValueLength]; bb.get(extractAttributeValue); // read attributeValue from the remaining buffer System.out.println(extractEmployeeId); System.out.println(extractLastModifiedDate); System.out.println(new String(extractAttributeValue)); } </code></pre> <ol> <li>Is there any better way of doing this?</li> <li>Are there some minor improvements that can be made here?</li> <li>Can anyone take a look and let me know whether this is the right way to use <code>ByteBuffer</code>? This is my first time using it, so I'm having a bit of a problem.</li> </ol>
[]
[ { "body": "<p>I cannot see anything wrong with the way you are using it. The example is a little contrived (given that you are not actually using cassandra), and the only things I can see that look odd are a direct result of that.</p>\n\n<p>Bottom line is that it appears to be a fine piece of code (which is perhaps why there have been no reviews so far).</p>\n\n<p>As for some nit-picky things:</p>\n\n<p>I don't like that you are hard-coding the size of the buffer (on the write-side): <code>int size = 2 + 8 + 4 + attributeValue.length</code> is 'ugly'.</p>\n\n<p>I tend to do th 'overkill' approach and use a buffer that is always too big. I find memory is cheap for the occasional buffer (even up to a couple of megs of memory...). I then make the buffer a thread-local so that I am not always creating new buffers. In your example it is trivial because it is all in the main method.... but for a 'real' program you may want to reconsider. If you know your data will always be less than, say 4K, I would instead do the following on the write side:</p>\n\n<pre><code>// a 'smaprt' implementation will make the buffer a ThreadLocal,\n// and will also make it grow, if needed.\nByteBuffer bbuf = ByteBuffer.allocate(4096);\nbbuf.order(ByteOrder.BIG_ENDIAN);\n</code></pre>\n\n<p>Then, your code should reset the buffer before using it:</p>\n\n<pre><code>bbuf.clear(); // position to 0, limit to capacity\nbbuf.putShort(employeeId);\nbbuf.putLong(lastModifiedDate);\nbbuf.putInt(attributeValue.length);\nbbuf.put(attributeValue);\n</code></pre>\n\n<p>Now, instead of doing a <code>rewind()</code>, do a <code>flip()</code></p>\n\n<pre><code>bbuf.flip(); // limit to position, position to 0\nbyte[] bytesToStore = new byte[bbuf.limit()];\nbbuf.get(bytesToStore);\n</code></pre>\n\n<p>The advantage of the above is that you do not need to manually track the size of your data, and you do not need to keep allocating new ByteBuffers each time,</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T04:48:56.207", "Id": "36265", "ParentId": "32556", "Score": "7" } } ]
{ "AcceptedAnswerId": "36265", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T06:26:50.480", "Id": "32556", "Score": "12", "Tags": [ "java", "database", "integer", "cassandra" ], "Title": "Storing a ByteBuffer into a Cassandra database" }
32556
<p>The code uses SQLAlchemy Core. However, what I want to know is if writing code in this pattern is recommendable.</p> <pre><code>def saveUser(self, user): """ Inserts or updates a user in database. The method first checks if the provided user's id already exists. If no, then the user will be inserted. Otherwise, the stored values are updated. Args: user (User) Returns: User object with inserted id """ result = self._engine.execute(self._userTable.select().where(self._userTable.c.Id == user._id)) if not result.first(): # user doesn't exist in database. result = self._engine.execute(self._userTable.insert(), Email=user.email, PasswordHash=user.passwordHash, DisplayName=user.displayName, Active=user.active) user._id = result.inserted_primary_key[0] else: # user already exists in database. result = self._engine.execute(self._userTable.update().where(self._userTable.c.Id == user._id), Email=user.email, PasswordHash=user.passwordHash, DisplayName=user.displayName, Active=user.active) return user def deleteUser(self, userId=None, email=None): """ Deletes a user. Either userId or email can be passed. If both are passed, then a user containing both userId and email will be deleted. If none of the arguments are provided, then the method call will have not effect. Args: userId (int): If this is None, only email will be used to delete the user. email (str): If this is None, only userId will be used to delete the user. """ if not userId and not email: return # Because an empty and_ clause generated later on will raise OperationalError. idClause = self._userTable.c.Id == userId if userId else None emailClause = self._userTable.c.Email == email if email else None finalClause = and_(idClause, emailClause) deleteQuery = self._userTable.delete().where(finalClause) result = self._engine.execute(deleteQuery) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T13:25:39.150", "Id": "52132", "Score": "1", "body": "You don't need to roll your own insert-or-update logic: SQLAlchemy has a [`merge`](http://docs.sqlalchemy.org/en/rel_0_5/session.html#merging) method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T06:19:51.983", "Id": "52168", "Score": "0", "body": "@GarethRees - Isn't that limited to SQLAlchemy ORM? I am using Core here." } ]
[ { "body": "<p>The only thing I can think of that might make it more Pythonic would be to wrap the body of deleteUser() in a try and catch and handle the OperationalError rather than checking user and email for None before making the attempt.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T03:27:07.403", "Id": "47535", "ParentId": "32559", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T07:11:02.247", "Id": "32559", "Score": "2", "Tags": [ "python", "sqlalchemy" ], "Title": "Insert or update a user in database" }
32559
<p>Here's my first VBA project. I have some very limited Python experience, and this is my first VBA project. I'm sure I could have done it a lot more simply, but I just stuck with what I knew, and googled what I didn't, so feedback is very welcome.</p> <p>The basic purpose is to compare a table from one sheet (OP) with a table from another (Payroll) and print the discrepancies in a third sheet (Results).</p> <p>One last thing I want to do, but can't figure out (without using GoTo, which I read is bad) is to protect the worksheets after I Exit Sub on lines 22, 31, etc. (code for protecting sheets is already written in line 130 - 138.</p> <pre><code>Sub Macro1() Dim counter As Integer Set OPdata = New Dictionary Set Payrolldata = New Dictionary Set HRIDnames = New Dictionary 'Unprotects sheets Worksheets("Results").Unprotect Password:="" Worksheets("OP").Unprotect Password:="" Worksheets("Payroll").Unprotect Password:="" ' Clears Results worksheet Worksheets("Results").Activate Range("A3:L10000").ClearContents ' Looks for missing data in the OP worksheet Worksheets("OP").Activate Range("A2").Select If IsEmpty(ActiveCell) Then MsgBox "There is data missing" Exit Sub End If Worksheets("OP").Activate Range("A1").CurrentRegion.Select For Each C In Selection If C = "" Then C.Select MsgBox "There is data missing" Exit Sub End If Next ' Looks for missing data in the Payroll worksheet Worksheets("Payroll").Activate Range("A2").Select If IsEmpty(ActiveCell) Then MsgBox "There is data missing" Exit Sub End If Worksheets("Payroll").Activate Range("A1").CurrentRegion.Select For Each C In Selection If C = "" Then C.Select MsgBox "There is data missing" Exit Sub End If Next ' Populate OPdata dictionary Worksheets("OP").Activate Range("A2", ActiveCell.End(xlDown)).Select For Each cl In Selection OPdata.Add cl.Value, cl.Offset(0, 2).Value &amp; " " &amp; cl.Offset(0, 3).Value HRIDnames.Add cl.Value, cl.Offset(0, 1).Value Next ' Populate Payrolldata dictionary Worksheets("Payroll").Activate Range("A2", ActiveCell.End(xlDown)).Select For Each cl In Selection Payrolldata.Add cl.Value, cl.Offset(0, 2).Value &amp; " " &amp; cl.Offset(0, 3).Value If HRIDnames.Exists(cl.Value) = False Then HRIDnames.Add cl.Value, cl.Offset(0, 1).Value End If Next ' finds unique values in OPdata and prints them to columns A:C Worksheets("Results").Activate Range("A3").Select For Each i In OPdata If Payrolldata.Exists(i) = False Then ActiveCell = i ActiveCell.Offset(0, 2).Select ActiveCell = OPdata.Item(i) ActiveCell.Offset(1, -2).Select End If Next ' finds unique values in Payrolldata and prints them to columns E:G Worksheets("Results").Activate Range("E3").Select For Each i In Payrolldata If OPdata.Exists(i) = False Then ActiveCell = i ActiveCell.Offset(0, 2).Select ActiveCell = Payrolldata.Item(i) ActiveCell.Offset(1, -2).Select End If Next ' Finds salary discrepencies and prints them to columns I:L Worksheets("Results").Activate Range("I3").Select For Each i In OPdata If Payrolldata.Exists(i) Then If Not OPdata.Item(i) = Payrolldata.Item(i) Then ActiveCell = i ActiveCell.Offset(0, 2).Select ActiveCell = OPdata.Item(i) ActiveCell.Offset(0, 1).Select ActiveCell = Payrolldata.Item(i) ActiveCell.Offset(1, -3).Select End If End If Next ' Prints names Sheets("Results").Range("A3").Select While Not IsEmpty(ActiveCell) ActiveCell.Offset(0, 1) = HRIDnames.Item(ActiveCell.Value) ActiveCell.Offset(1).Select Wend Sheets("Results").Range("E3").Select While Not IsEmpty(ActiveCell) ActiveCell.Offset(0, 1) = HRIDnames.Item(ActiveCell.Value) ActiveCell.Offset(1).Select Wend Sheets("Results").Range("I3").Select While Not IsEmpty(ActiveCell) ActiveCell.Offset(0, 1) = HRIDnames.Item(ActiveCell.Value) ActiveCell.Offset(1).Select Wend ' Reprotect Worksheets Worksheets("Results").Protect Password:="" Worksheets("OP").Protect Password:="" Worksheets("Payroll").Protect Password:="" ' Success message If WorksheetFunction.CountA(Range("A3:L3")) = 0 Then MsgBox ("Congratulations! OurPeople and Payroll reconcile exactly!") End If End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T18:40:05.523", "Id": "52102", "Score": "2", "body": "We don't see line numbers, it's useless to refer to them ;). I suggest you break down this monolith into smaller chunks that do very little, ideally just one thing." } ]
[ { "body": "<ol>\n<li>Always put Option Explicit at the top of your modules (Tools - Options - Editor - Require Variable Declaration).</li>\n<li>Never select or activate something unless it's necessary</li>\n<li>Limit reading and writing to worksheets as it's an expensive operations</li>\n<li>When you have code that looks similar to other code, move it to another procedure</li>\n</ol>\n\n<p>Here's some revised code</p>\n\n<pre><code>Sub Macro2()\n\n Dim dcOp As Scripting.Dictionary, dcPay As Scripting.Dictionary, dcHri As Scripting.Dictionary\n Dim shPay As Worksheet, shOp As Worksheet, shResults As Worksheet\n Dim vaWrite As Variant\n Dim vKey As Variant\n Dim lCnt As Long\n Dim bFail As Boolean\n\n 'The only acceptable use of goto imho\n On Error GoTo ErrHandler\n\n Set dcOp = New Scripting.Dictionary\n Set dcPay = New Scripting.Dictionary\n Set dcHri = New Scripting.Dictionary\n\n 'Set sheet variables so that if a sheet name changes, you only\n 'have to change it in one place. Or better yet, refer to sheets\n 'by their codename\n Set shPay = Worksheets(\"Payroll\")\n Set shOp = Worksheets(\"OP\")\n Set shResults = Worksheets(\"Results\")\n\n shPay.Unprotect \"\"\n shOp.Unprotect \"\"\n shResults.Unprotect \"\"\n\n ' Clears Results worksheet\n 'Don't activate a sheet if you don't need to\n shResults.Range(\"A3:L10000\").ClearContents\n\n ' Looks for missing data in the OP worksheet\n 'Value is the default property of Range, but always use it for clarity\n 'By raising an error, you invoke the error handler where you can do\n 'things like protect sheets\n If IsEmpty(shOp.Range(\"A2\").Value) Or IsEmpty(shPay.Range(\"A2\").Value) Then\n Err.Raise 9999, , \"There is data missing\"\n End If\n\n 'Repeating code should be factored out to a different function or sub\n If DataMissing(shOp.Range(\"A1\").CurrentRegion) Or DataMissing(shPay.Range(\"A1\").CurrentRegion) Then\n Err.Raise 9999, , \"There is data missing\"\n End If\n\n ' Populate OPdata dictionary\n GetData shOp, dcOp, dcHri\n GetData shPay, dcPay, dcHri\n\n vaWrite = GetUnique(dcOp, dcPay, dcHri, bFail)\n shResults.Range(\"A3\").Resize(UBound(vaWrite, 1), UBound(vaWrite, 2)).Value = vaWrite\n\n vaWrite = GetUnique(dcPay, dcOp, dcHri, bFail)\n shResults.Range(\"E3\").Resize(UBound(vaWrite, 1), UBound(vaWrite, 2)).Value = vaWrite\n\n 'Find salary discrepencies.\n 'If you're going to fill cells one-by-one, don't activate them, just offset\n For Each vKey In dcOp.Keys\n If dcPay.Exists(vKey) Then\n If dcOp.Item(vKey) &lt;&gt; dcPay.Item(vKey) Then\n bFail = True\n With shResults.Range(\"I3\")\n .Offset(lCnt, 0).Value = vKey\n If dcHri.Exists(vKey) Then\n .Offset(lCnt, 1).Value = dcHri.Item(vKey)\n End If\n .Offset(lCnt, 2).Value = dcPay.Item(vKey)\n .Offset(lCnt, 3).Value = dcOp.Item(vKey)\n End With\n lCnt = lCnt + 1\n End If\n End If\n Next vKey\n\n If Not bFail Then MsgBox \"Congratulations! OurPeople and Payroll reconcile exactly!\"\n\nErrExit:\n 'If no errors, this executes. If there are errors, ErrHandler resumes execution here\n 'so the sheets get protected no matter what\n shOp.Protect\n shPay.Protect\n shResults.Protect\n Exit Sub 'single point of exit from the sub\n\nErrHandler:\n 'Err.Raise comes here\n MsgBox Err.Description\n Resume ErrExit\n\nEnd Sub\n\nPrivate Function DataMissing(rRng As Range) As Boolean\n\n Dim rBlanks As Range\n\n On Error Resume Next\n Set rBlanks = rRng.SpecialCells(xlCellTypeBlanks)\n On Error GoTo 0\n\n DataMissing = Not rBlanks Is Nothing\n\nEnd Function\n\nPrivate Sub GetData(sh As Worksheet, ByRef dcData As Scripting.Dictionary, ByRef dcExcept As Scripting.Dictionary)\n 'ByRef means that whatever changed you make to the variable will still be there\n 'when you get back to the calling procedure\n\n Dim vaData As Variant\n Dim i As Long 'VB converts all integers to Long anyway, so just use Long\n\n 'Read data once in a big chunk rather than cell-by-cell\n vaData = sh.Range(\"A2\", sh.Range(\"A2\").End(xlDown)).Resize(, 3).Value\n\n For i = LBound(vaData, 1) To UBound(vaData, 1)\n dcData.Add vaData(i, 1), vaData(i, 3) &amp; Space(1) &amp; vaData(i, 4)\n If Not dcExcept.Exists(vaData(i, 1)) Then\n dcExcept.Add vaData(i, 1), vaData(i, 2)\n End If\n Next i\n\nEnd Sub\n\nPrivate Function GetUnique(dcFirst As Scripting.Dictionary, dcLast As Scripting.Dictionary, dcNames As Scripting.Dictionary, ByRef bFail As Boolean) As Variant\n\n Dim aReturn() As Variant\n Dim lCnt As Long\n Dim vKey As Variant\n\n ReDim aReturn(1 To dcFirst.Count, 1 To 3)\n\n For Each vKey In dcFirst.Keys\n If Not dcLast.Exists(vKey) Then\n bFail = True\n lCnt = lCnt + 1\n aReturn(lCnt, 1) = vKey\n If dcNames.Exists(vKey) Then aReturn(lCnt, 2) = dcNames.Item(vKey)\n aReturn(lCnt, 3) = dcFirst.Item(vKey)\n End If\n Next vKey\n\n GetUnique = aReturn\n\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T18:27:15.277", "Id": "52143", "Score": "1", "body": "This is extremely clear and helpful, thank you! When @retailcoder mentioned to break this down into smaller chunks, was he referring to using private functions, as you taught? At first I thought he meant this too much code to use as a macro in Excel? But the code I originally posted runs with 1000+ lines in < 1 second, which seems fine to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T02:28:46.277", "Id": "52234", "Score": "4", "body": "This is precisely what I was referring to - it isn't a matter of performance, but one of readability and maintainability. By identifying what a function does, you tell your future self \"see, that's where it's done\" - it's important for a function to not only say what it does, but also to do what it says. I've written Excel VBA code with thousands of lines of code, broken down into classes and modules, themselves broken down into procedures, functions, methods and properties. Clear code is easier to maintain/modify :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T14:09:59.797", "Id": "32599", "ParentId": "32564", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T10:31:27.923", "Id": "32564", "Score": "7", "Tags": [ "vba", "excel" ], "Title": "Comparing tables and printing discrepancies" }
32564
<p>I would like to know your opinion about my simple JS/jQquery switcher. Is it a good idea to use <code>toggle()</code>?</p> <pre><code>var s = $('.slider'), i = 0; setInterval(function(){ var o = $([]); o = o.add(s[i]); if(i === s.length - 1) { i = -1; } i++; o = o.add(s[i]); o.toggle(); }, 1000); </code></pre> <p><a href="http://jsfiddle.net/skowron_line/ch4g8/1/" rel="nofollow">jsFiddle</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T11:05:04.880", "Id": "52077", "Score": "1", "body": "Why are you saving the options in the DOM and not in a JavaScript array? http://jsfiddle.net/D37qR/" } ]
[ { "body": "<p>I would strongly advise you to modularize your code to make it testable an reusable.</p>\n\n<p>Since you are using jQuery, you could use the <a href=\"http://learn.jquery.com/jquery-ui/widget-factory/how-to-use-the-widget-factory/\" rel=\"nofollow\">widget factory</a>.</p>\n\n<p>I have created an example for you, perhaps it will look overkill and it might be, however it's just an example. Also, I strongly advise you to read how to write <a href=\"http://alistapart.com/article/writing-testable-javascript\" rel=\"nofollow\">testable javascript</a>.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;div id=\"slider\"&gt;&lt;/div&gt;\n\n&lt;input id=\"items-input\" type=\"text\" value=\"abcdef\"&gt;\n\n&lt;button id=\"state-btn\"&gt;Stop&lt;/button&gt;\n</code></pre>\n\n<p><strong>WIDGET</strong></p>\n\n<pre><code>!function ($) {\n $.widget('mylib.layerSlider', {\n options: {\n interval: 1000,\n autoSlide: true, \n createItemUI: function (item) {\n return $('&lt;div&gt;').html(item);\n }\n },\n\n _create: function () {\n this.element.addClass('mylib-layer-slider');\n this._layout();\n this.options.autoSlide &amp;&amp; this.startSliding();\n },\n\n _setOptions: function (options) {\n this._super(options);\n this._layout();\n },\n\n _layout: function () {\n\n var wasSliding = this.isSliding(),\n createItemUI = this.options.createItemUI,\n $items = this._$items = $($.map(this.options.items, function (item) {\n return createItemUI(item).addClass('item').get();\n }));\n\n this.stopSliding();\n\n this.element.empty().append($items);\n\n this._index = 0;\n\n wasSliding &amp;&amp; this.startSliding();\n },\n\n _showNext: function () {\n var i = this._index,\n $items = this._$items;\n\n $items.eq(i).hide();\n $items.eq(this._index = ++i % $items.length).show();\n },\n\n _destroy: function () {\n this.stopSliding();\n this.element.removeClass('mylib-layer-slider').empty();\n },\n\n startSliding: function () {\n if (this.slideTimerId) return;\n\n this.slideTimerId = setInterval($.proxy(this._showNext, this), this.options.interval);\n },\n\n stopSliding: function () {\n clearInterval(this.slideTimerId);\n this.slideTimerId = null;\n },\n\n isSliding: function () {\n return !!this.slideTimerId;\n }\n });\n}(jQuery);\n</code></pre>\n\n<p><strong>DOM READY</strong></p>\n\n<pre><code>$(function ($) {\n var operations = ['Start', 'Stop'],\n $itemsInput = $('#items-input').keyup(function () {\n $slider.layerSlider('option', 'items', $itemsInput.val().split(''));\n }),\n $slider = $('#slider').layerSlider({\n items: $itemsInput.val().split('')\n });\n\n $('#state-btn').click(function (e) {\n var i = +$slider.layerSlider('isSliding');\n\n $slider.layerSlider(operations[i].toLowerCase() + 'Sliding');\n\n $(this).text(operations[++i % 2]);\n });\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/ch4g8/3/\" rel=\"nofollow\"><strong>DEMO</strong></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T17:41:11.447", "Id": "32603", "ParentId": "32565", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T10:51:33.527", "Id": "32565", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "JS/jQuery switcher" }
32565
<p>I'm working on a program that handles UTF-8 characters. I've made the following macros to detect UTF-8. I've tested them with a few thousand words and they seem to work.</p> <p>I'll add another one to do error-checking later, but for now I would like to know what mistakes I've made and how these macros can be improved. </p> <pre><code>//check if value is in range of leading byte #define IS_UTF8_LEADING_BYTE(b) (((unsigned char)(b) &gt;= 192) &amp;&amp; (unsigned char)(b) &lt; 248) //check if value is in range of sequence byte #define IS_UTF8_SEQUENCE_BYTE(b) ((unsigned char)(b) &gt;= 128 &amp;&amp; (unsigned char)(b) &lt; 192) //can be any utf8 byte, first, last... #define IS_UTF8_BYTE(b) (IS_UTF8_LEADING_BYTE(b) || IS_UTF8_SEQUENCE_BYTE(b)) //no error checking, it must be used only on leading byte #define HOW_MANY_UTF8_SEQUENCE_BYTES(b) ((((unsigned char)(b) &amp; 64) == 64) + (((unsigned char)(b) &amp; 32) == 32) + (((unsigned char)(b) &amp; 16) == 16)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T08:45:43.200", "Id": "52173", "Score": "1", "body": "I'd make the brackets consistent: add some extra brackets to the first two macros to make all comparisons match the first one. The first has the form `((b) >= 192)` whereas the rest are `(b) < 248`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T20:48:28.273", "Id": "52285", "Score": "0", "body": "@WilliamMorris thanks. Not sure how I missed that." } ]
[ { "body": "<p>If you are sure that you have only valid encoded UTF8, you can simplify</p>\n\n<pre><code>#define IS_UTF8_BYTE(b) (IS_UTF8_LEADING_BYTE(b) || IS_UTF8_SEQUENCE_BYTE(b))\n</code></pre>\n\n<p>to</p>\n\n<pre><code>#define IS_UTF8_BYTE(b) ((unsigned char)(b) &gt;= 128)\n</code></pre>\n\n<p>because every byte that is not ASCII must be an UTF8-byte.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T18:49:59.337", "Id": "82192", "Score": "1", "body": "… but every byte that is not ASCII is not necessarily a _valid_ UTF-8 byte." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T07:33:50.227", "Id": "82398", "Score": "0", "body": "As I wrote: *'If you are sure, that you have only valid encoded UTF8'*" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T11:29:01.300", "Id": "32569", "ParentId": "32567", "Score": "1" } }, { "body": "<p>There are a lot of magic numbers. They are numbers that would be familiar to any good programmer, but magic numbers nonetheless. Furthermore, it's more useful to think of the problem using bitwise operations, since they are more closely related to the conceptual design behind UTF-8.</p>\n\n<p>You only accept two-, three-, and four-byte sequences, i.e., only code points U+0080 to U+1FFFFF, i.e., the Basic Multilingual Plane (minus the ASCII set) plus the Supplementary Multilingual Plane. That should be made clear in comments.</p>\n\n<p>I suggest renaming <code>IS_UTF8_BYTE()</code> to <code>IS_UTF8_MULTIBYTE()</code>, since ASCII characters ≤ 127 are valid UTF-8 bytes too — just not members of a multibyte sequence.</p>\n\n<pre><code>//check if value is in range of leading byte (0b11?????? but not 0b11111???)\n#define IS_UTF8_LEADING_BYTE(b) (((b) &amp; 0xc0) &amp;&amp; !((b) &amp; 0xf8))\n\n//check if value is in range of sequence byte (0b10??????)\n#define IS_UTF8_SEQUENCE_BYTE(b) (((b) &amp; 0x80) &amp;&amp; !((b) &amp; 0xc0))\n\n//can be any byte within a UTF-8 multibyte sequence\n#define IS_UTF8_MULTIBYTE(b) (IS_UTF8_LEADING_BYTE(b) || IS_UTF8_SEQUENCE_BYTE(b))\n\n//no error checking; it must be used only on leading byte\n#define HOW_MANY_UTF8_SEQUENCE_BYTES(b) (((b) &amp; 0x40 == 0x40) + ((b) &amp; 0x20 == 0x20) + ((b) &amp; 0x10 == 0x10))\n</code></pre>\n\n<p><code>IS_UTF8_SEQUENCE_BYTE()</code> could be more clever.</p>\n\n<pre><code>//check if value is in range of sequence byte (0b10??????)\n#define IS_UTF8_SEQUENCE_BYTE(b) ((b) &amp; 0xc0 == 0x80)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T18:03:46.393", "Id": "46948", "ParentId": "32567", "Score": "3" } } ]
{ "AcceptedAnswerId": "32569", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T11:15:53.327", "Id": "32567", "Score": "4", "Tags": [ "c", "macros", "utf-8" ], "Title": "Macros to detect UTF-8" }
32567
<p>I'm trying to write Jasmine tests and I need a review and some advice on spying on events and their behavior.</p> <pre><code>// my example source code ;(function () { var app = { exampleModuleName: { navigateTo: function () { /* do something */ } }, navigation: { init: function () { this.routeHandler = this.handleRouteTo.bind(this); // bind all events this.bind(); }, bind: function () { $(document).on('click', '.js-route-to', this.routeHandler); }, teardown: function () { $(document).off('click', this.routeHandler); }, handleRouteTo: function (event) { event.preventDefault(); this.routeTo($(event.currentTarget).data('target')); }, routeTo: function (target) { var module = app[target]; if (module &amp;&amp; $.isFunction(module.navigateTo)) { module.navigateTo(); } }, } }; }()); </code></pre> <p>And that is my uncompleted spec file.</p> <pre><code>// my test code describe('App Navigation', function () { describe('initiation the navigation module', function() { it ('spy on behavior', function () { var spy = spyOn(app.navigation, 'init'); app.navigation.init(); expect(spy).toHaveBeenCalled(); }); // which tests are missing to be sure about well tested properties and methodes? }); describe('test routeTo handler', function() { var nav = app.navigation; beforeEach(function () { this.routeHandler = nav.handleRouteTo.bind(this); }); it ('should be defined', function () { expect(this.routeHandler).toBeDefined(); }); it ('click at a link', function () { var node = $('&lt;a href="" class="js-route-to" data-target="exampleModuleName"&gt;some text&lt;/a&gt;'); expect(node.length).toBe(1); spyOn(nav, 'handleRouteTo'); node.click(); // why is it failed? expect(nav.handleRouteTo).toHaveBeenCalled(); }); }); }); </code></pre> <p>Please take a look and let us talk about this example. I want to learn more about testing.</p>
[]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p>I would drop this test, you are testing Jasmine and/or the test, but not the results of calling <code>app.navigation.init()</code></p>\n\n<pre><code>it ('spy on behavior', function () {\n var spy = spyOn(app.navigation, 'init');\n app.navigation.init();\n expect(spy).toHaveBeenCalled();\n});\n</code></pre></li>\n<li>Be aware that <code>Function.bind()</code> which you use in <code>navigation.init()</code> creates a brand new function, so <code>this.routeHandler</code> never calls <code>this.hanldeRouteTo</code></li>\n<li>Also be aware that you are not calling <code>app.navigation.bind()</code> as far as I can tell, so the binding of the event is not happening</li>\n<li>Perhaps you are not a native English native speaker, but your <code>describe</code> calls are not up to snuff. It hampers my reading flow of the code. Example: <code>'initiation the navigation module'</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-03T20:35:24.373", "Id": "71572", "ParentId": "32573", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T14:21:11.977", "Id": "32573", "Score": "5", "Tags": [ "javascript", "jquery", "jasmine" ], "Title": "spyOn click events and check call function" }
32573