body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I've decided a while ago to make my own voxel engine. To start, I coded my own basic 3D engine in Java using minimal OpenGL bindings for things such as SRGB ect. I set up my own VBA and VBOS and had it working with .obj files. I already have transformations and Quaternions set up.</p> <p>I've recently started to implement my attempt at a voxel engine. Last night I set up a very crude jury-rigged attempt that actually worked well enough with perlin noise to draw random 1x1x1 blocks on the screen that resembled a world.</p> <p>The issue is that I've used immediate mode and block-by block-rendering with no chunks. So today I've decided to start writing my chunk class, and was hoping someone could tell me if it seems correctly set up.</p> <p>Edit: I forgot to mention that I currently am trying to figure out how to handle vertices, so that's why there is no code.</p> <pre><code>package cam.base.engine; public class Chunk { public static final int X_CHUNK_SIZE = 16; public static final int Y_CHUNK_SIZE = 128; public static final int Z_CHUNK_SIZE = 16; public int chunkXNumber; public int chunkZNumber; private Block [][][] blocks = new Block[X_CHUNK_SIZE][Y_CHUNK_SIZE][Z_CHUNK_SIZE]; public Chunk(int chunkXNumber, int chunkZNumber) { this.chunkXNumber = chunkXNumber; this.chunkZNumber = chunkZNumber; createBlocks(chunkXNumber, chunkZNumber); Vertex [][][] vertices = createVertices(getActiveBlocks(), chunkXNumber, chunkZNumber); int[] = createIndices(vertices); } private void createBlocks(int chunkXNum, int chunkZNum) { for(int i = 1; i &lt;= X_CHUNK_SIZE; i++) { for(int j = 1; j &lt;= Y_CHUNK_SIZE; j++) { for(int k = 1; k &lt;= Z_CHUNK_SIZE; k++) { float density = getDensity(new Vector3(i,j,k), chunkXNum, chunkZNum); byte material = getMaterial(density,j); boolean isActive = checkBlockActive(material); blocks[i - 1][j - 1][k - 1] = new Block(material, isActive); } } } } private boolean[][][] getActiveBlocks() { boolean [][][] activeBlocks = new boolean[X_CHUNK_SIZE][Y_CHUNK_SIZE][Z_CHUNK_SIZE]; for(int i = 0; i &lt; X_CHUNK_SIZE; i++) { for(int j = 0; j &lt; Y_CHUNK_SIZE; j++) { for(int k = 0; k &lt; Z_CHUNK_SIZE; k++) { activeBlocks[i][j][k] = blocks[i][j][k].isBlockEnabled(); } } } return activeBlocks; } private float getDensity(Vector3 chunkPos, int chunkXNum, int chunkZNum) { float density = 0; int x = chunkPos.getX() * chunkXNum; int y = chunkPos.getY() * chunkZNum; int z = chunkPos.getZ() * chunkZNum; //TODO check to see if double is necessary for(double i = 1; i &lt;= Game.octaveLimit; i *= 2) { density += (1/i) * (Noise.noise((x / 160.0f) * i, (y / 160.0f) * i,( z / 160.0f) * i)); density = Math.abs(density); } return density; } private byte getMaterial(float density, int yVal) { byte material; if(density &gt; .2) { if(yVal &gt;= 80) { material = 0; } else { material = 1; } } else { if(yVal &gt;= 64) { material = 0; } else { material = 2; } } return material; } private boolean checkBlockActive(byte material) { if(material == 0) { return false; } else { return true; } } private Vertex[][][] createVertices(boolean[][][] activeBlocks, int chunkXNum, int chunkZNum) { boolean[][][] verticesActive = new boolean[X_CHUNK_SIZE][Y_CHUNK_SIZE][Z_CHUNK_SIZE]; Vertex[][][] vertices = new Vertex[X_CHUNK_SIZE][Y_CHUNK_SIZE][Z_CHUNK_SIZE]; for(int i = 1; i &lt;= X_CHUNK_SIZE; i++) { for(int j = 1; j &lt;= Y_CHUNK_SIZE; j++) { for(int k = 1; k &lt;= Z_CHUNK_SIZE; k++) { if(activeBlocks[i - 1][j - 1][k - 1]) { if(verticesActive[i - 1][j - 1][k - 1] == false) { vertices[i - 1][j - 1][k - 1] = new Vertex(new Vector3(i * chunkXNum, j , k * chunkZNum)); } continue; } continue; } } } return vertices; } private int[] createIndices(Vertex[][][] vertices) { } } </code></pre>
[]
[ { "body": "<ol>\n<li><p><code>createBlocks</code> actually fills the blocks array, creation happens before that, so this name is a little bit misleading. I'd move the array creation inside the method and use it as a return value:</p>\n\n<pre><code>private Block[][][] blocks;\n\npublic Chunk(int chunkXNumber, int chunkZNumber) {\n ..\n blocks = createBlocks(chunkXNumber, chunkZNumber);\n}\n\nprivate Block[][][] createBlocks(int chunkXNum, int chunkZNum) {\n final Block[][][] blocks = new Block[X_CHUNK_SIZE][Y_CHUNK_SIZE][Z_CHUNK_SIZE];\n // loops here\n return blocks;\n}\n</code></pre></li>\n<li><pre><code>private boolean checkBlockActive(byte material) {\n if (material == 0) {\n return false;\n }\n\n else {\n return true;\n }\n}\n</code></pre>\n\n<p>It could be simply</p>\n\n<pre><code>private boolean checkBlockActive(byte material) {\n return material != 0;\n}\n</code></pre></li>\n<li><p>In the <code>getMaterial</code> method you could use multiple returns and get rid of the <code>result</code> variable:</p>\n\n<pre><code>private byte getMaterial(final float density, final int yVal) {\n if (density &gt; .2) {\n if (yVal &gt;= 80) {\n return 0;\n } else {\n return 1;\n }\n } else {\n if (yVal &gt;= 64) {\n return 0;\n } else {\n return 2;\n }\n }\n}\n</code></pre></li>\n<li><p><code>160.0f</code> is used multiple times and it's a magic number. It would deserve a named constant.</p></li>\n<li><p>The code should follow the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\">Code Conventions for the Java Programming Language</a>.</p></li>\n<li><p>Some of the loops runs from <code>1</code> to <code>&lt;= X_CHUNK_SIZE</code>, some of them <code>0</code> to <code>&lt; X_CHUNK_SIZE</code>. It should be consistent.</p></li>\n<li><p>The two continue is unnecessary here:</p>\n\n<pre><code>for (int k = 1; k &lt;= Z_CHUNK_SIZE; k++) {\n if (activeBlocks[i - 1][j - 1][k - 1]) {\n if (verticesActive[i - 1][j - 1][k - 1] == false) {\n vertices[i - 1][j - 1][k - 1] = new Vertex(new Vector3(i * chunkXNum, j, k * chunkZNum));\n }\n continue;\n }\n continue;\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T05:11:59.627", "Id": "74216", "Score": "1", "body": "Hahaha thanks for the reply. I actually made this a while ago and have since become less bad. My entire engine is in c++ now and actually lets you choose between using a Sparsevoxel octree, linear memory or hashing. Looking back a lot of the crap I was doing was bad :(. Here's a couple semi recent pics.http://imgur.com/JWkX6Va,MXj3mN8,9miaW8Z" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:50:37.643", "Id": "74244", "Score": "0", "body": "@RylandGoldstein: Nice pictures, thanks! :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-22T16:01:34.033", "Id": "42515", "ParentId": "33812", "Score": "5" } } ]
{ "AcceptedAnswerId": "42515", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T00:41:15.057", "Id": "33812", "Score": "6", "Tags": [ "java", "opengl" ], "Title": "Making a voxel engine" }
33812
<p>I wrote a PHP function that generates JSON data to populate a line graph. Through jQuery, my code uses a GET request to the PHP script to fetch the JSON data. An example of the JSON data is as follows:</p> <pre><code>{"labels":[{"x":"2013-10-30","a":"1","b":"8"},{"x":"2013-10-31","a":"2","b":"14"},{"x":"2013-11-01","a":"5","b":"12"}]} </code></pre> <p>The data is used to generate a time graph showing two values per date:</p> <p><strong>x:</strong> date <strong>a:</strong> value1 <strong>b:</strong> value2</p> <p>I'm still a beginner programmer and want to have some peer review on the code I wrote. Please give me some feedback on how I can improve it, and fix any errors or inefficient methods if present.</p> <p><strong>Function</strong></p> <pre><code>function generateGraphData($start, $end, $format, $api, $server, $pdo) { //Fetch unique entries between the given dates $query = "SELECT DISTINCT DATE(traffic_date) FROM traffic WHERE traffic_date BETWEEN ? AND ? AND traffic_api = ? AND traffic_server = ? ORDER BY traffic_date DESC"; $dbc = $pdo-&gt;prepare($query); $dbc-&gt;execute(array($start, $end, $api, $server)); $results = $dbc-&gt;fetchAll(PDO::FETCH_ASSOC); //Count unique and total views for each result foreach ($results as $key =&gt; $value) { $date = "%".$value['DATE(traffic_date)']."%"; $dbc = $pdo-&gt;prepare("SELECT count(*) FROM traffic WHERE traffic_date LIKE ? AND traffic_api = ? AND traffic_server = ?"); $dbc-&gt;execute(array($date, $api, $server)); $total = $dbc-&gt;fetchColumn(); $dbc = null; $dbc = $pdo-&gt;prepare("SELECT count(*) FROM traffic WHERE traffic_date LIKE ? AND traffic_api = ? AND traffic_server = ? GROUP BY traffic_ip"); $dbc-&gt;execute(array($date, $api, $server)); $unique = $dbc-&gt;fetchColumn(); $dbc = null; $data[$key]["x"] = $value['DATE(traffic_date)']; $data[$key]["a"] = $unique; $data[$key]["b"] = $total; } //Create filler dates $fillerDates = new DatePeriod(new DateTime($start), new DateInterval('P1D'), new DateTime($end)); foreach($fillerDates as $date) { $filler_date_array[] = array('x' =&gt; $date-&gt;format("Y-m-d"), 'a' =&gt; '0', 'b' =&gt; '0'); } $data = array_merge($data, $filler_date_array); //Remove filler dates if real date exists $filter_unique_array = array(); $keysArray = array(); foreach ($data as $innerArray) { if (!in_array($innerArray["x"], $keysArray)) { $keysArray[] = $innerArray["x"]; $filter_unique_array[] = $innerArray; } } //Sort by date array_sort_by_date($filter_unique_array, "date"); //Format JSON $json = json_encode($filter_unique_array); $jsonlabel = '{"labels":'.$json.'}'; echo $jsonlabel; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T04:54:51.630", "Id": "54193", "Score": "0", "body": "you are executing three different sql. Here you should execute a query only once and fetch all records. It will improve your code execution time. When you have all records, you could just iterate through the result and compute \"total\" and \"unique\" values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:58:25.290", "Id": "54276", "Score": "0", "body": "I was thinking this too, but how would I approach this? I just started using PDO, and \"beginner/intermediate\" SQL queries is still hard for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:31:25.773", "Id": "54302", "Score": "0", "body": "Would this be be correct?\n\n SELECT DISTINCT DATE(traffic_date), count(traffic_ip), count(distinct traffic_ip) FROM traffic WHERE traffic_date BETWEEN ? AND ? AND traffic_api = ? AND traffic_server = ? GROUP BY DATE(traffic_date)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:45:22.840", "Id": "54306", "Score": "0", "body": "you could try this select traffic_date, count(1) from traffic where traffic_date BETWEEN ? AND ? and traffic_api = ? and traffic_server = ? group by traffic_date, traffic_ip; this will give all result and required counts, then you can iterate the result set in php" } ]
[ { "body": "<p>The first problem is what @Kinjal identified in your comment. You should only run your query once (in this particular case. You can do this because your querys basically return the same result). </p>\n\n<p>So you run your query and load it into a table, and then you can iterate and work with that table. This will be much faster than running your query 3 times. Even so because 2 of your queries runs in a loop.</p>\n\n<p>The second problem are your JSON members. using \"a\" and \"b\" as member names are a bad idea - name these what they should represent. I'd suggest substituting them for \"unique\" and \"total\". So your final JSON should looke like</p>\n\n<p>{\"date\": \"yyyy-mm-dd\", \"unique\": 0, \"total\": 0 }</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:01:16.447", "Id": "54278", "Score": "0", "body": "Thanks for the feedback. As I commented above to @Kinjal, I'm wondering how I should approach this the correct way. SQL queries are still quite new too me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T07:55:58.663", "Id": "33825", "ParentId": "33813", "Score": "1" } } ]
{ "AcceptedAnswerId": "33825", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T01:48:01.473", "Id": "33813", "Score": "1", "Tags": [ "php", "beginner", "json" ], "Title": "Feedback on a small PHP function that generates JSON data" }
33813
<p>If the prefix/suffix does not match the beginning or the end of a string, then, depending on how I call these functions, they should either raise an exception or return the original text unmodified.</p> <p>I am using these inside of a simple script for now, so there was no need to make these member functions of some class. I am hoping to find a way to simplify the logic, extract any common code into private function(s), improve the code style (although I think there are several different standards).</p> <pre><code>def remove_prefix(text, prefix, raise_if_no_match=True): exc_msg = 'Text "{}" does not start with a prefix "{}".'.format(text, prefix) if not prefix or not text: if not raise_if_no_match: return text if len(prefix) == len(text): return '' raise ValueError(exc_msg) if text.startswith(prefix): return text[len(prefix):] if raise_if_no_match: raise ValueError(exc_msg) return text def remove_suffix(text, suffix, raise_if_no_match=True): exc_msg = 'Text "{}" does not end with a suffix "{}".'.format(text, suffix) if not suffix or not text: if not raise_if_no_match: return text if len(suffix) == len(text): return '' raise ValueError(exc_msg) if text.endswith(suffix): return text[:-len(suffix):] if raise_if_no_match: raise ValueError(exc_msg) return text print remove_prefix('Hello, World', 'Hello, ') # ValueError: Text "Hello, World" does not start with a prefix "Hello, Hello". #print remove_prefix('Hello, World', 'Hello, Hello') print remove_prefix('Hello, World', 'Hello, Hello', raise_if_no_match=False) print remove_suffix('I am singing in the rain', ' in the rain') # ValueError: Text "I am singing in the rain" does not end with a suffix "swinging in the rain". #print remove_suffix('I am singing in the rain', 'swinging in the rain') print remove_suffix('I am singing in the rain', 'swinging in the rain', raise_if_no_match=False) </code></pre> <p>Output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>World Hello, World I am singing I am singing in the rain </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:36:17.970", "Id": "54363", "Score": "0", "body": "It seems to me that you could just delete code from first `if` to first `raise`. The rest is ok." } ]
[ { "body": "<p>Firstly I would say turn your print statements into a test. That way you can change the implementation with confidence that you have not broken anything.</p>\n\n<p>Here is what those debug prints are as a test:</p>\n\n<pre><code>class TestRemove(unittest.TestCase):\n\n def test_remove_prefix(self):\n hello = 'Hello, World'\n value = remove_prefix(hello, 'Hello, ')\n self.assertEqual(value, 'World')\n value = remove_prefix(hello, 'Hello, Hello', raise_if_no_match=False)\n self.assertEqual(value, hello)\n self.assertRaises(ValueError, remove_prefix, hello, 'Hello, Hello')\n\n def test_remove_suffix(self):\n singing = 'I am singing in the rain'\n value = remove_suffix(singing, ' in the rain')\n self.assertEqual(value, 'I am singing')\n value = remove_suffix(singing, 'swinging in the rain', raise_if_no_match=False)\n self.assertEqual(value, singing)\n self.assertRaises(ValueError, remove_suffix, singing, 'swinging in the rain')\n</code></pre>\n\n<p>I think you should be using the the built in string operations which can be found <a href=\"http://docs.python.org/2/library/stdtypes.html#string-methods\" rel=\"nofollow\">here</a>. Namely <code>startswith()</code>, <code>endswith()</code>, <code>spilt()</code> and <code>rsplit()</code>.</p>\n\n<p>You can also reassign variable names to give a more clear flow through the function. Here is my version of <code>remove_prefix()</code>.</p>\n\n<pre><code>def remove_prefix(text, prefix, raise_if_no_match=True):\n if (text.startswith(prefix)):\n text = text.split(prefix, 1)[1]\n else:\n if (raise_if_no_match):\n msg_fmt = 'Text \"{}\" does not end with a prefix \"{}\".'\n raise ValueError(msg_fmt.format(text, prefix))\n return text\n</code></pre>\n\n<p>From that I'm sure you can change <code>remove_suffix()</code>.</p>\n\n<p>Also I would add docstrings to the functions so the arguments and exceptions raised are documented.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T23:45:55.860", "Id": "54375", "Score": "1", "body": "I'd omit the `()`s around the conditions; this is Python, not a C-decendent language ... I use them sometimes to spread a more complex condition over several lines, though, and thus avoid backslashes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T00:50:50.650", "Id": "54379", "Score": "0", "body": "Looks good, thanks. One thing - I would rename the following variable to `msg_fmt` instead because that is what it is now: `exc_msg = 'Text \"{}\" does not end with a prefix \"{}\".'`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T09:33:56.620", "Id": "54409", "Score": "0", "body": "@Tobias I like the consistency of always having the brackets whether they are needed for multi-line conditions or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T09:35:27.487", "Id": "54410", "Score": "0", "body": "@Leonid I agree, that is a better name, changed." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:30:41.293", "Id": "33845", "ParentId": "33817", "Score": "1" } } ]
{ "AcceptedAnswerId": "33845", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:16:55.493", "Id": "33817", "Score": "0", "Tags": [ "python", "strings", "helper" ], "Title": "remove_prefix and remove_suffix functions" }
33817
<p>I've just completed the Calculator Kata in the Kata Gem and I was hoping for some feedback. Here's the Kata:</p> <pre><code>Calculator Kata Create a calculator that is initialized with a string expression - detail: The expression is of the form digits separated by commas: "1,2" - detail: The expression is accessed by a method named expr - detail: The expression can be reset for evaluation at any time without re-initializing - example: Calculator.new "1,2" completed (Y|n): y Add Method Create an add method that sums the string expression - detail: The method will return the sum of the digits - detail: The expression can contain 0, 1 or 2 numbers - detail: Then empty string will return 0 - example: "" computes to 0 - example: "1" computes to 1 - example: "1,2" computes to 3 completed (Y|n): Allow the expression to contain an unknown amount of numbers - example: "1,2,3" computes to 6 - example: "1,2,5,8" computes to 16 completed (Y|n): Diff Method Create a diff method that computes the consecutive differences - detail: The expression must contain at least 2 digits - example: "1,0" compues to 1 - example: "3,2,1" computes to 0 - example: "5,4,3,2,1" computes to -5 - detail: Expressions with less than 2 digits raise an exception - example: "" or "5" completed (Y|n): Prod Method Create a prod method that computes the multiples in the expression - detail: The method will return the product of the numbers - example: "0" computes to 0 - example: "2,1" computes to 2 - example: "3,2,1" computes to 6 completed (Y|n): Div Method Create a div method that computes the consecutive divisions in the expression - detail: The method will return the final quotient of the numbers - detail: it will raise an exception if the expression contains the number 0 - example: "2,1" computes to 2 - example: "3,2,1" computes to 1 - example: "1,2,3" computes to 0 completed (Y|n): Congratulations! - Create a calculator that is initialized with a string expression 01:15:02 - Create an add method that sums the string expression 14:34:41 - Allow the expression to contain an unknown amount of numbers 00:04:33 - Create a diff method that computes the consecutive differences 00:06:14 - Create a prod method that computes the multiples in the expression 00:20:07 - Create a div method that computes the consecutive divisions in the exp 00:11:54 ---------------------------------------------------------------------- -------- Total Time taking Calculator kata: 16:32:31 </code></pre> <p>And, here is my solution (specs and the Calculator class are in the same file):</p> <pre><code>class Calculator def initialize(expression="") @expression = expression.split(",").map(&amp;:to_i) || 0 if !@expression.any? @expression = [0] end end def expr @expression end def sum @expression.inject(&amp;:+) || 0 end def diff if @expression.compact.count &lt; 2 raise "expect 2 or more elements but recieved #{@expression.compact.count}" end @expression.inject(&amp;:-) end def prod @expression.inject(&amp;:*) end def div if @expression.find { |element| element == 0 } raise "divide by zero" end @expression.inject(&amp;:/) end end describe "Calculator" do subject(:calculator) { Calculator.new(expression) } shared_examples "methods" do specify { expect { calculator }.to_not raise_exception } it { should respond_to(:expr) } it { should respond_to(:sum) } it { should respond_to(:diff) } it { should respond_to(:prod) } it { should respond_to(:div) } end shared_examples "too few elements" do specify { expect { calculator.diff }.to raise_exception } end shared_examples "divide by zero" do specify { expect { calculator.div }.to raise_exception } end context "with argument ''" do let(:expression) { "" } it_behaves_like "methods" it_behaves_like "too few elements" it_behaves_like "divide by zero" its(:expr) { should eq([0]) } its(:sum) { should eq(0) } its(:prod) { should eq(0) } end context "with argument '1'" do let(:expression) { "1" } it_behaves_like "methods" it_behaves_like "too few elements" its(:expr) { should eq([1]) } its(:sum) { should eq(1) } its(:prod) { should eq(1) } end context "with argument '1,2'" do let(:expression) { "1,2" } it_behaves_like "methods" its(:expr) { should eq([1,2]) } its(:sum) { should eq(3) } its(:diff) { should eq(-1) } its(:prod) { should eq(2) } end context "with argument '1,2,3," do let(:expression) { "1,2,3" } it_behaves_like "methods" its(:expr) { should eq([1,2,3]) } its(:sum) { should eq(6) } its(:diff) { should eq(-4) } its(:prod) { should eq(6) } its(:div) { should eq(0) } end context "with argument '1,2,5,8'" do let(:expression) { "1,2,5,8" } it_behaves_like "methods" its(:expr) { should eq([1,2,5,8]) } its(:sum) { should eq(16) } its(:diff) { should eq(-14) } its(:prod) { should eq(80) } end context "with argument '1,0'" do let(:expression) { "1,0" } it_behaves_like "divide by zero" its(:diff) { should eq(1) } its(:prod) { should eq(0) } end context "with argument '3,2,1'" do let(:expression) { "3,2,1" } its(:diff) { should eq(0) } its(:prod) { should eq(6) } its(:div) { should eq(1) } end context "with argument '5,4,3,2,1,'" do let(:expression) { "5,4,3,2,1" } its(:diff) { should eq(-5) } its(:prod) { should eq(120) } end context "with arguments '2,1'" do let(:expression) { "2,1" } its(:div) { should eq(2) } end end </code></pre>
[]
[ { "body": "<p>Looks good! Most importantly, you're using <code>inject</code> properly. The specs seem nice too (although running all the <code>\"methods\"</code> expectations every time is maybe a little redundant).</p>\n\n<p>But I don't see support for this requirement:</p>\n\n<blockquote>\n <p>The expression can be reset for evaluation at any time without re-initializing</p>\n</blockquote>\n\n<p>Right now, you only have a reader method for <code>expr</code>.<br>\nAlso, that reader returns an array - not the original string. While it's not stated directly, I think it's implied that you should get a string back. <code>calculator.expr = calculator.expr</code> should be idempotent.</p>\n\n<p>There's also something weird going on in your current <code>initialize</code> method:</p>\n\n<pre><code>@expression = expression.split(\",\").map(&amp;:to_i) || 0\n</code></pre>\n\n<p>I don't see how it would ever get to the <code>OR</code> (<code>split</code> will either give you an empty array or raise an exception), but even if it did, it'd just raise an exception in the next line:</p>\n\n<pre><code>if !@expression.any?\n</code></pre>\n\n<p>since Fixnum doesn't respond to <code>any?</code>.</p>\n\n<p>But it wouldn't take much to fix all of this. Something like this should be OK</p>\n\n<pre><code>class Calculator\n attr_reader :expr\n\n def expr=(string='')\n @expr = string\n @expression = @expr.split(\",\").map(&amp;:to_i)\n @expression = [0] if @expression.none?\n end\n\n alias_method :initialize, :expr=\n\n #...\nend\n</code></pre>\n\n<p>But I'd probably rename <code>@expression</code> to <code>@values</code> or something, just to make the separation clearer (and to give the array a pluralized name).</p>\n\n<p>The <code>div</code> method can be made simpler, as this</p>\n\n<pre><code> if @expression.find { |element| element == 0 }\n</code></pre>\n\n<p>can be expressed as just:</p>\n\n<pre><code> if @expression.include?(0)\n</code></pre>\n\n<p>And lastly, you may want to raise the built-in <code>ZeroDivisionError</code> instead of a custom one:</p>\n\n<pre><code> raise ZeroDivisionError if @expression.include?(0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:16:16.310", "Id": "54311", "Score": "0", "body": "Thank you so much for your feedback. This is really very helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:34:55.087", "Id": "54316", "Score": "0", "body": "@user341493 No prob. Don't forget to click the checkmark to mark your question as answered (no rush though)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:12:54.450", "Id": "33842", "ParentId": "33818", "Score": "1" } } ]
{ "AcceptedAnswerId": "33842", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:54:26.987", "Id": "33818", "Score": "1", "Tags": [ "ruby", "calculator" ], "Title": "Ruby Kata Gem: Calculator" }
33818
<p>I wrote a program for a college assignment, and I'd like to receive some pointers on making my code a little more efficient.</p> <blockquote> <p>The program should ask the end user to enter an integer. Use the <code>isPalidrome</code> method to invoke the reverse method, and report whether the integer is a palindrome. Any one-digit integer or negative integer should be rejected with the specific error message (negative or one digit), and then the program should ask the user to re-enter the integer. Hint: To reverse the digits of a number, try this routine:</p> <pre><code>int result = 0; while (number != 0) { // e.g. number = 123 // Iteration 1 Iteration 2 Iteration 3 int remainder = number % 10; // remainder = 3 remainder = 2 remainder = 1 result = result * 10 + remainder; // result = 3 result = 32 result = 321 number = number / 10; // number = 12 number = 1 number = 0 } // result contains the reverse of number </code></pre> </blockquote> <p>My solution:</p> <pre><code>package lab07; import java.util.Scanner; public class Lab07 { public static int reverse(int number){ int result = 0; while (number !=0){ int remainder = number % 10; result = result * 10 + remainder; number = number / 10; } return result; } public static boolean isPalindrome(int input){ int Palindrome = reverse(input); if (Palindrome == input){ return true; } else return false; } public static void main(String[] args) { int integer = 0; Scanner input = new Scanner(System.in); System.out.print("Enter a positive, multi-digit integer: "); integer = input.nextInt(); while (integer &lt;= 9 &amp;&amp; integer &gt; 0) { System.out.println(integer + " is a single digit. Please re-enter another integer: "); integer = input.nextInt(); if (isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is a palindrome"); return; } else if (!isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is not a palindrome"); return; } } while (integer &lt; 0) { System.out.println(integer + " is negative. Please re-enter another integer: "); integer = input.nextInt(); if (isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is a palindrome"); return; } else if (!isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is not a palindrome"); return; } while (integer &lt;= 9 &amp;&amp; integer &gt; 0) { System.out.println(integer + " is a single digit. Please re-enter another integer: "); integer = input.nextInt(); if (isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is a palindrome"); return; } else if (!isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is not a palindrome"); return; } } } while (integer &gt; 9){ if (isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is a palindrome"); return; } else if (!isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9)) { System.out.println(integer + " is not a palindrome"); return; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-26T15:10:27.577", "Id": "148692", "Score": "0", "body": "Am I going to be the one who says that all single digit numbers are palindromes? A special case I'll grant but if ABA is a palindrome what is wrong with B as a palindrome? I think the empty string is a palindrome. But don't listen to me." } ]
[ { "body": "<pre><code>if (isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9))\n {\n System.out.println(integer + \" is a palindrome\");\n return;\n }\n</code></pre>\n\n<p>This piece should be moved to a separed method, for example:</p>\n\n<pre><code>private void checkInt(int value){\n if(value &gt; 0 &amp;&amp; value &gt; 9){\n if (isPalindrome(value))\n {\n System.out.println(value + \" is a palindrome\");\n }\n else if (!isPalindrome(value) &amp;&amp; (value &gt; 0 &amp;&amp; value &gt; 9))\n {\n System.out.println(value + \" is not a palindrome\");\n }\n return;\n }\n</code></pre>\n\n<hr>\n\n<pre><code>if (Palindrome == input){\n return true;} \nelse{\n return false;}\n</code></pre>\n\n<p>This could be reduced to \"return Palindrome == input\"</p>\n\n<hr>\n\n<p>Do not ever give variables such name as \"integer\",\"string\" or any\n other class name.</p>\n\n<hr>\n\n<p>Do not ever capitalize variable name: \"int Palindrome\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T05:51:17.493", "Id": "62213", "Score": "0", "body": "Your code is longer than necessary. The condition `value > 0 && value > 9` can be simplified to `value > 9`, you should not call `isPalindrome` twice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T07:42:50.767", "Id": "33823", "ParentId": "33822", "Score": "3" } }, { "body": "<p>Apart from the other comments about how to calculate the input, I would also suggest that your main method is buggy, and not very 'pretty'. One the the tricks in programming that Java programmers seem to forget, is the do-while loop (note, C programmers use this all the time, and Java programmers do all sorts of crazy things to avoid it ...! ).</p>\n\n<p>Consider the an altered main method</p>\n\n<ul>\n<li>renamed Scanner to be <code>scanner</code></li>\n<li>renamed integer to be <code>input</code>.</li>\n<li>use do-while for input validation</li>\n<li>use 'simpler' printf for output</li>\n</ul>\n\n\n\n<pre><code>public static void main(String[] args) {\n\n int input = 0;\n Scanner scanner = new Scanner(System.in); \n boolean ok = false;\n do {\n System.out.print(\"Enter a positive, multi-digit integer: \");\n input = scanner.nextInt();\n if (input &lt; 0) {\n System.out.println(input + \" is negative. Please re-enter another integer: \");\n } else if (input &lt;= 9) {\n System.out.println(input + \" is a single digit. Please re-enter another integer: \");\n } else {\n ok = true;\n }\n } while (!ok);\n\n System.out.printf(\"%d %s a palindrome\\n\", input, isPalindrome(input) ? \"is\" : \"is not\");\n scanner.close();\n\n}\n</code></pre>\n\n<p>I should add that having 'return' in a main method is unconventional.... not 'wrong' but it probably means you are doing something weird...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:56:34.540", "Id": "54241", "Score": "0", "body": "How do you code `isPalindrom(Integer)` method? - Why are you transforming the input in a `int`? keep it as `String` : `(s==null || s.startwith('-') || s.length <2 ) --> false;` is also a good test to protect StringBuilder method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T13:05:16.643", "Id": "54243", "Score": "0", "body": "Other people have already suggested answers for those questions. My notes are purely on the main method. As for your specific questions, I have used the OP's `isPalindome()` method and I think it is a better method than using String (since it's easier to validate the int). Also, I have just copy/pasted the OP's code and moved it, keeping as much of his 'style' as I can. It is not my intention to criticize or compete against other answers here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T07:16:03.343", "Id": "62218", "Score": "1", "body": "I wouldn't suggest using do-while here. Not that do-while is bad as such, but having an `ok` flag isn't any better. To me the approach by @raistlinthewizard (using continue) is way more elegant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T10:50:44.350", "Id": "62246", "Score": "0", "body": "The initial prompt belongs before the loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:39:37.443", "Id": "33846", "ParentId": "33822", "Score": "5" } }, { "body": "<p>First: There is a wrong template in your code:</p>\n\n<pre><code> if (isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9))\n {\n System.out.println(integer + \" is a palindrome\");\n return;\n }\n else if (!isPalindrome(integer) &amp;&amp; (integer &gt; 0 &amp;&amp; integer &gt; 9))\n {\n System.out.println(integer + \" is not a palindrome\");\n return;\n }\n</code></pre>\n\n<ol>\n<li>(integer > 0 &amp;&amp; integer > 9) is equals to integer > 9</li>\n<li>The isPalindrome(integer) function used 2 times, but only need to invoke it 1 times per iteration.</li>\n</ol>\n\n<p>Modified code:</p>\n\n<pre><code> final boolean inputIsPalindrome = isPalindrome(integer);\n if (inputIsPalindrome &amp;&amp; integer &gt; 9))\n {\n System.out.println(integer + \" is a palindrome\");\n return;\n }\n else if (!inputIsPalindrome &amp;&amp; integer &gt; 9)\n {\n System.out.println(integer + \" is not a palindrome\");\n return;\n }\n</code></pre>\n\n<p>Here 2 problemes still there:</p>\n\n<ol>\n<li>checking double times the integer's value.</li>\n<li>Here you need only \"if {} else {}\" construct, because if the first true, the second is false.</li>\n</ol>\n\n<p>So the re-modified code:</p>\n\n<pre><code> if (integer &gt; 9) {\n if (isPalindrome(integer)) {\n System.out.println(integer + \" is a palindrome\");\n // don't need \"else\" if returning here\n return;\n }\n\n System.out.println(integer + \" is not a palindrome\");\n return;\n }\n</code></pre>\n\n<p>More:</p>\n\n<ol>\n<li>You have a lot of loops to get the user input, but you only need one.</li>\n<li>In Java variables use CamelCase beginning with lower case character.</li>\n<li>The variable names have to tell more about itself.</li>\n<li>Handling input with wrong type is necessary.</li>\n<li>In this case I prefer reverse string instead of compute the reverse of the integer.</li>\n</ol>\n\n<p>I've wrote your program here:</p>\n\n<pre><code>package lab07;\n\nimport java.util.Scanner;\n\npublic class Lab07 {\n\npublic static void main(String[] args) {\n\n System.out.print(\"Enter a positive, multi-digit integer: \");\n final String inputIntegerAsString = readInputIntegerAsString();\n\n if (isPalindrome(inputIntegerAsString)) {\n System.out.println(inputIntegerAsString + \" is a palindrome\");\n return;\n }\n\n System.out.println(inputIntegerAsString + \" is not a palindrome\");\n}\n\nprivate static String readInputIntegerAsString() {\n try (final Scanner scanner = new Scanner(System.in)) {\n // Instead of \"true\" you can use an exit condition, but in\n // this simple case I don't think to care about that.\n while (true) {\n final String line = scanner.nextLine();\n\n int inputInteger = 0;\n try {\n inputInteger = Integer.parseInt(line);\n } catch (final NumberFormatException e) {\n System.out.println(\"Invalid input. Please re-enter another integer: \");\n continue;\n }\n\n if (inputInteger &lt; 10) {\n if (inputInteger &lt; 0) {\n System.out.println(inputInteger + \" is negative. Please re-enter another integer: \");\n continue;\n }\n\n System.out.println(inputInteger + \" is a single digit. Please re-enter another integer: \");\n continue;\n }\n return line;\n }\n }\n}\n\nprivate static boolean isPalindrome(final String originalInputAsString) {\n final String reversedString = reverseString(originalInputAsString);\n\n return reversedString.equals(originalInputAsString);\n}\n\nprivate static String reverseString(final String originalString) {\n final StringBuilder stringBuilder = new StringBuilder(originalString);\n final String reversedString = stringBuilder.reverse().toString();\n\n return reversedString;\n}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T07:25:21.620", "Id": "62219", "Score": "0", "body": "Make `inputInteger` final and do not initialize it before `try` clause." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:23:08.600", "Id": "33849", "ParentId": "33822", "Score": "5" } }, { "body": "<p>Adding a second answer here because this answer is directly targetting your actual question: \"How to make the palindrome program more efficient\". ince the fastest answer I tested has not been mentioned yet in this review, I figure it is worth outlining here...</p>\n\n<p>Personally I feel that the int approach to dealing with it is more intuitive, but I set out to prove this, and I was suprised, so, here is my test program....</p>\n\n<p>First, it generates a million integer values stored as Strings in a char[] array. It then repeatedly 'scans' those values and checks each value to see whether it is a palindrome. In the spirit of the initial program, the test here is really whether converting the value to an int and then doing numberical manipulation is better than keeping the value as a String, and doing String comparisons..... I chose two different mechanisms for String compares....</p>\n\n<p>Bottom line is that keeping the values as Strings is about 50% faster... huh. Half the time.</p>\n\n<p>The most efficient method is:</p>\n\n<pre><code>public static boolean isPalindromeChar(final String input){\n int front = 0;\n int rear = input.length() - 1;\n while (front &lt; rear) {\n if (input.charAt(front++) != input.charAt(rear--)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>which is (on my machine) about 15% faster than:</p>\n\n<pre><code>public static boolean isPalindromeSBuilder(final String input){\n return input.equals(new StringBuilder(input).reverse().toString());\n}\n</code></pre>\n\n<p>Doing Integer-based processing is significantly slower, probably because there's a lot of overhead in the Scanner.nextInt() method.</p>\n\n<p>Here is my full code, but my sunmmary output is:</p>\n\n<pre><code>Average integer took 1.0457 seconds,\naverage string took 0.7060 seconds,\naverage char took 0.6139 seconds\n</code></pre>\n\n<p>Obviously, to benchmark this process I had to take some liberties, and the code is not a great solution to the original problem, but, as for the most efficient way to calculate palindromes from a Scanner, it is clearly to keep the valeus as Strings, and to do char-based comparisons.....</p>\n\n<pre><code>import java.io.CharArrayReader;\nimport java.io.CharArrayWriter;\nimport java.io.IOException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class Lab07 {\n\n public static int reverse(int number){\n\n int result = 0;\n while (number !=0){\n int remainder = number % 10;\n result = result * 10 + remainder;\n number = number / 10;\n }\n return result;\n }\n public static boolean isPalindromeInt(final int input){\n return input == reverse(input);\n }\n\n public static boolean isPalindromeSBuilder(final String input){\n return input.equals(new StringBuilder(input).reverse().toString());\n }\n\n public static boolean isPalindromeChar(final String input){\n int front = 0; int rear = input.length() - 1;\n while (front &lt; rear) {\n if (input.charAt(front++) != input.charAt(rear--)) {\n return false;\n }\n }\n return true;\n }\n\n private static final void palindromeInteger(char[] data, int count) {\n CharArrayReader reader = new CharArrayReader(data);\n int palcount = 0;\n Scanner scanner = new Scanner(reader);\n while (count &gt; 0) {\n int input = 0;\n boolean ok = false;\n do {\n //System.out.print(\"Enter a positive, multi-digit integer: \");\n input = scanner.nextInt();\n count--;\n if (input &lt; 0) {\n System.out.println(input + \" is negative. Please re-enter another integer: \");\n } else if (input &lt;= 9) {\n System.out.println(input + \" is a single digit. Please re-enter another integer: \");\n } else {\n ok = true;\n }\n } while (!ok);\n\n if (isPalindromeInt(input)) {\n palcount++;\n }\n }\n System.out.printf(\"%d palindromes\\n\", palcount);\n scanner.close();\n }\n\n private static final void palindromeString(char[] data, int count) {\n CharArrayReader reader = new CharArrayReader(data);\n int palcount = 0;\n Scanner scanner = new Scanner(reader);\n while (count &gt; 0) {\n String input = null;\n boolean ok = false;\n do {\n //System.out.print(\"Enter a positive, multi-digit integer: \");\n input = scanner.next();\n count--;\n if (input.startsWith(\"-\")) {\n System.out.println(input + \" is negative. Please re-enter another integer: \");\n } else if (input.length() &lt; 2) {\n System.out.println(input + \" is a single digit. Please re-enter another integer: \");\n } else {\n ok = true;\n }\n } while (!ok);\n\n if (isPalindromeSBuilder(input)) {\n palcount++;\n }\n }\n System.out.printf(\"%d palindromes\\n\", palcount);\n scanner.close();\n }\n\n private static final void palindromeChar(char[] data, int count) {\n CharArrayReader reader = new CharArrayReader(data);\n int palcount = 0;\n Scanner scanner = new Scanner(reader);\n while (count &gt; 0) {\n String input = null;\n boolean ok = false;\n do {\n //System.out.print(\"Enter a positive, multi-digit integer: \");\n input = scanner.next();\n count--;\n if (input.startsWith(\"-\")) {\n System.out.println(input + \" is negative. Please re-enter another integer: \");\n } else if (input.length() &lt; 2) {\n System.out.println(input + \" is a single digit. Please re-enter another integer: \");\n } else {\n ok = true;\n }\n } while (!ok);\n\n if (isPalindromeChar(input)) {\n palcount++;\n }\n }\n System.out.printf(\"%d palindromes\\n\", palcount);\n scanner.close();\n }\n\n public static void main(String[] args) throws IOException {\n\n System.out.println(\"Generating values\");\n\n CharArrayWriter caw = new CharArrayWriter();\n Random rand = new Random();\n final int numbers = 1000000;\n for (int i = 0; i &lt; numbers; i++) {\n caw.write(rand.nextInt(numbers) + \"\\n\");\n }\n caw.close();\n final char[] data = caw.toCharArray();\n\n System.out.println(\"Generated \" + numbers + \" values\");\n\n long inttimes = 0L;\n long strtimes = 0L;\n long chrtimes = 0L;\n for (int loop = 0; loop &lt; 11; loop++) {\n long intstart = System.nanoTime();\n palindromeInteger(data, numbers);\n if (loop &gt; 0) {\n inttimes += System.nanoTime() - intstart;\n }\n long strstart = System.nanoTime();\n palindromeString(data, numbers);\n if (loop &gt; 0) {\n strtimes += System.nanoTime() - strstart;\n }\n long chrstart = System.nanoTime();\n palindromeChar(data, numbers);\n if (loop &gt; 0) {\n chrtimes += System.nanoTime() - chrstart;\n }\n }\n\n System.out.printf(\"Average %s took %.4f seconds, average %s took %.4f seconds, average %s took %.4f seconds\\n\",\n \"integer\", (inttimes / 10) / 1000000000.0,\n \"string\", (strtimes / 10) / 1000000000.0,\n \"char\", (chrtimes/ 10) / 1000000000.0);\n\n\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:59:35.897", "Id": "33864", "ParentId": "33822", "Score": "5" } } ]
{ "AcceptedAnswerId": "33846", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T07:23:53.890", "Id": "33822", "Score": "6", "Tags": [ "java", "beginner", "homework", "palindrome" ], "Title": "Palindrome program with reverse method" }
33822
<p>I'll start by saying I've just started with programming, and Ruby is my first language. I've made a little soccer shoot-out game. I'm having problems with the end of the code looping back to where I want it.</p> <p>If there's a tie, I want it to keep the same score and players, but add another round of shooting. Should I do this by creating an array to store the points?</p> <p>If there's anything else I can simplify, I'd really appreciate your input.</p> <pre><code>class Shoot def initialize shoot end def shoot @kick = 1 + rand(6) end def kick @kick end end response = '' until response == 'N' play = "Have another shoot-out? Put Y or N." puts "Player 1's name is:" player_1_name = gets.chomp puts "Player 2's name is?" player_2_name = gets.chomp puts "#{player_1_name} and #{player_2_name}, are you ready to play sudden death (ENTER)?!" gets.chomp p1_score = 0 p2_score = 0 result_1 = 0 result_2 = 0 until result_1 &gt;= 1 || result_2 &gt;= 1 puts "#{player_1_name}, please take your kick (ENTER)." gets.chomp! shot_1 = Shoot.new.kick result_1 = shot_1*0.2 puts "#{player_1_name} takes the shot, and it's looking good..." puts "(ENTER)" gets.chomp if result_1 &gt;= 1 puts "...And it's a goal!!!" p1_score += 1 else puts "...Oh! So close, but it's no good!!!" end puts "#{player_2_name}, please take your kick (ENTER)." gets.chomp! shot_2 = Shoot.new.kick result_2 = shot_2*0.2 puts "#{player_2_name} takes the shot, and it's looking good..." puts "(ENTER)" gets.chomp if result_2 &gt;= 1 puts "...And it's a goal!!!" p2_score += 1 else puts "...Oh! So close, but it's no good!!!" end puts "#{player_1_name}: #{p1_score}" puts "#{player_2_name}: #{p2_score}" if p1_score &gt; p2_score puts "#{player_1_name}, you're the winner! Congratulations!" elsif p1_score &lt; p2_score puts "#{player_2_name}, you're the winner! Congratulations!" else puts "Looks like we've gotta go another round!" return end end puts play response = gets.chomp end </code></pre>
[]
[ { "body": "<p>Not a bad start. However here's a few things that immediately pops out when I look at the code.</p>\n\n<ol>\n<li><strong>Avoid duplication:</strong> The code for both players to kick is exactly the same. You should try to move that into a function instead of writing it out twice.</li>\n<li><strong>Make a player class:</strong> By moving all the code for a player into a class, you avoid having to keep each variable twice. Instead of <code>shot_1</code>/<code>shot_2</code>, <code>result_1</code>/<code>result_2</code> etc, you could have <code>player[0].shot</code>, <code>player[0].result</code> etc.</li>\n<li><strong>Make a game class:</strong> While you're at it, why not also turn the game itself into a class. I think this would solve your looping problem all by itself.</li>\n</ol>\n\n<p>Something like this:</p>\n\n<pre><code>class Game\n def initialize\n # set up for a new game\n end\n\n def play_round\n # play one round of the game\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:31:20.320", "Id": "33830", "ParentId": "33828", "Score": "4" } }, { "body": "<p>You could also move some stuff into the <code>Shoot</code> class you already have,</p>\n\n<pre><code>class Shoot\n def initialize\n @kick = 1 + rand(6)\n end\n\n def result\n @kick * 0.2\n end\n\n def goal?\n result &gt;= 1\n end\nend\n</code></pre>\n\n<p>So then you can write</p>\n\n<pre><code>if Shoot.new.goal?\n puts \"...And it's a goal!!!\"\n p2_score += 1\nelse\n puts \"...Oh! So close, but it's no good!!!\"\nend\n</code></pre>\n\n<p>The general rule here is that if you are pulling data out of an object, and then using it to do more work, it might make more sense to have that logic inside the object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T08:32:10.863", "Id": "33905", "ParentId": "33828", "Score": "2" } }, { "body": "<p>You asked if you should set up an array to keep track of things. I find math is sometimes much easier to keep a count of things. I do so in the code below.</p>\n\n<p>I have set this up with the following (somewhat standard) folder structure:</p>\n\n<pre><code>.\n|-- bin\n| `-- sudden_death\n|-- lib\n| |-- player.rb\n| `-- referee.rb\n`-- test\n |-- player_spec.rb\n |-- referee_spec.rb\n `-- spec_helper.rb\n\n3 directories, 7 files\n</code></pre>\n\n<p>What is in bin is a Ruby file that is marked as executable, and holds this code:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>#!/usr/bin/env ruby\n$:.unshift 'lib/'\n%w[referee player].each do |r|\n require r\nend\ninclude Referee\n\nplayer_1 = Player.new 'Ford Prefect'\nplayer_2 = Player.new 'Zaphod Beeblebrox'\n\nputs \"Are you ready to Rumble?\"\nuntil Referee::winner?(player_1, player_2)\n [player_1, player_2].each do |player|\n puts \"#{player.name} kicks and... \"\n rand(6) * 0.2 == 1 &amp;&amp; player + 1\n puts \"#{player.name} #{player.score == 1 ? 'scores!' : 'misses'}\"\n end\nend\nwinner = Referee::winner?(player_1, player_2).name\nputs \"\\n\\nAnd the winner is: #{winner}!\"\n</code></pre>\n\n<p>And a sample run:</p>\n\n<pre><code>Are you ready to Rumble? \nZaphod Beeblebrox kicks and...· \nZaphod Beeblebrox scores! \nFord Prefect kicks and...· \nFord Prefect misses \n\nAnd the winner is: Zaphod Beeblebrox!\n</code></pre>\n\n<p>This is made possible by Player and Referee</p>\n\n<p>They are not both classes, as you can see in the code above.</p>\n\n<p>Here is <code>lib/player.rb</code></p>\n\n<pre><code>class Player\n attr_reader :score, :name\n def initialize name, handicap = 0\n @name = name\n @score = handicap\n end\n\n def +(other)\n @score += other\n end\n\n def -(other)\n @score -= other\n end\nend\n</code></pre>\n\n<p>And here is <code>lib/referee.rb</code></p>\n\n<pre><code>module Referee\n\n def winner?(player_1, player_2)\n case (player_1.score &lt;=&gt; player_2.score)\n when 0\n nil\n when 1\n player_1\n when -1\n player_2\n end\n end\n\nend\n</code></pre>\n\n<p>As you move other things out of the <code>bin/sudden_death.rb</code> more of the game mechanics may be managed by the Referee module. There is still a lot of work to do in these files, and you will rearrange things as they make sense to you.</p>\n\n<p>I spent just a few minutes on it this afternoon, but I hope it helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T05:46:29.063", "Id": "35154", "ParentId": "33828", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:05:44.900", "Id": "33828", "Score": "4", "Tags": [ "ruby", "beginner", "game" ], "Title": "Cleaning up code and making better loops for soccer shoot-out game" }
33828
<p>I working with a lot of Strings which I get from a web-form:</p> <pre><code>final String user = request.getParameter("user"); final String pw = request.getParameter("password"); final String name = request.getParameter("name"); final String shortname = request.getParameter("shortname"); final String appl_name = request.getParameter("appl_name"); final String db_size_str = request.getParameter("db_size"); final String was_admin_string = request.getParameter("was_admin"); final String sap_nr = request.getParameter("sap_nr"); final String etl_string = request.getParameter("etl"); final String mq_string = request.getParameter("mq"); final String msg_broker_string = request.getParameter("msgbroker"); final String java_batch = request.getParameter("javab"); final String server = request.getParameter("server"); final String apverantw1 = request.getParameter("appliverantw1"); final String apverantw2 = request.getParameter("appliverantw2"); final String psp = request.getParameter("psp"); final String version = request.getParameter("version"); final String applialias = request.getParameter("applialias"); final String applityp = request.getParameter("applityp"); final String data = request.getParameter("data"); final String yesdata = request.getParameter("yesdata"); final String moreoptions = request.getParameter("moreoptions"); </code></pre> <p>If only one of them is empty, the program should be stopped. At this time I check that with an ugly if-statement if no one of the strings is empty: </p> <pre><code>if (user != null &amp;&amp; name != null &amp;&amp; shortname != null &amp;&amp; appl_name != null &amp;&amp; db_size_str != null &amp;&amp; was_admin_string != null &amp;&amp; sap_nr != null &amp;&amp; etl_string != null &amp;&amp; mq_string != null &amp;&amp; msg_broker_string != null &amp;&amp; java_batch != null &amp;&amp; server != null &amp;&amp; apverantw1 != null &amp;&amp; apverantw2 != null &amp;&amp; psp != null &amp;&amp; version != null &amp;&amp; applialias != null &amp;&amp; applityp != null &amp;&amp; data != null &amp;&amp; yesdata != null &amp;&amp; moreoptions != null) </code></pre> <p>This was produced over the time when I added one string after one.<br> How can I improve this? I mean, it is a really big, ugly if-statement. But I don't have a clue how can I write this even better.</p>
[]
[ { "body": "<p>You can build a method which pulls a String from request and check if it is empty:</p>\n\n<pre><code>private static String getString(Request request, String parameter){\n\n String result = request.getParameter(parameter);\n if(result==null||result.isEmpty()){\n System.exit(0);\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:14:20.507", "Id": "54233", "Score": "0", "body": "Looks very good and simple. Will give it a try." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:43:49.450", "Id": "54269", "Score": "0", "body": "So when there are more than 20 parameters(as in @dTDesign's code), you will end up calling the method the same number of times." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T10:41:54.843", "Id": "33838", "ParentId": "33837", "Score": "2" } }, { "body": "<p>You may (beside <a href=\"https://codereview.stackexchange.com/a/33838/31651\">PKopachevsky's suggestion</a>) as well create a new class for this with <code>Request request</code> being a member, and a <code>getParameter</code> method with the same signature as the one of <code>Request</code>, so you spare repeating the same <code>request</code> parameter again and again:</p>\n\n<pre><code>class RequestAdapter {\n\nprivate Request request;\npublic RequestAdapter(Request request) {\n this.request = request;\n}\npublic String getParameter(String parameterName) {\n String result = request.getParameter(parameterName);\n if (result==null) {\n System.exit(0);\n }\n return result;\n}\n</code></pre>\n\n<p>Your may use it like this:</p>\n\n<pre><code>RequestAdapter request = new RequestAdapter(originalRequest);\nfinal String user = request.getParameter(\"user\");\nfinal String pw = request.getParameter(\"password\");\nfinal String name = request.getParameter(\"name\");\n// and so on...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:46:59.243", "Id": "54226", "Score": "1", "body": "@tintinmj: Many thanks for your corrections :) you see, I'm from the C++ planet ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:51:46.273", "Id": "54229", "Score": "0", "body": "yes i can see ;) and correct the indentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:13:39.990", "Id": "54232", "Score": "0", "body": "I don't think so this will reduce my code when I add a new class for such a simple task..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:26:51.340", "Id": "54234", "Score": "0", "body": "@dTDesign: I add classes when I get rid of error-prone code duplications. I think you fundamental problem is to do each future edit twice for not breaking the implementation. Imagine the request provides another parameter after a while..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:35:58.257", "Id": "54236", "Score": "0", "body": "@WolfP.: You're right, but I think in this case a method is the better way. But I'll take your solution also in my presentation (it's not the source code of my own program. I should improve this program). So `+1` for an other way." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:00:48.933", "Id": "33839", "ParentId": "33837", "Score": "1" } }, { "body": "<p>i assume that you don't want to proceed the request, and send error message about missing string to the user, and also you are not using any MVC framework.</p>\n\n<p>First you need to define a list of parameter names. Then define the below method,</p>\n\n<pre><code> List&lt;String&gt; paramNames = ... // you prepared a list of parameter names\n\nList&lt;String&gt; validate(HttpServletRequest req ) {\n List&lt;String&gt; emptyParams = new ArrayList&lt;&gt;();\n\n for(String name : paramNames ){\n if(StringUtils.isBlank( req.getParameter(name))){\n emptyParams.add(param);\n }\n }\n\n return emptyParams; \n }\n</code></pre>\n\n<p>Note: StringUtils class comes from the apache common library. </p>\n\n<p>now the above method can tell you what parameters are empty. you can decide what to do based on the result. </p>\n\n<p>if you use any mvc framework, it is better to use form binding logic and validation provided by the framework. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:11:40.730", "Id": "54231", "Score": "0", "body": "This version looks good. With some changes it is perfect for me. And yes, i'm using the mvc framework but i'm not very familiar with it. I'll take a look to some documentations. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:54:19.800", "Id": "54273", "Score": "0", "body": "you are preparing a list of parameters of type String. This is only going to work when all your parameters are String which is fine as per current code of @dTDesign. However as soon as you start getting values other than String, it would be a problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:07:53.860", "Id": "54280", "Score": "0", "body": "@Kinjal: Thats true, but in my application, I always will get Strings. So for me the best answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:17:38.217", "Id": "54282", "Score": "0", "body": "the drawback would be you need to maintain that paramNames list every time there is a new request parameter" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:17:48.207", "Id": "33843", "ParentId": "33837", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/33843/26200\">nvseenu's answer</a> is good but I like varargs. In your <code>getParameter</code> method</p>\n\n<pre><code>{\n String user = .... // all the parameters\n .\n .\n .\n // then\n validate(user, pwd, ...) // and all this may look big but with auto-completion \n // it's not a big headache\n}\n\nprivate void validate(String... parameters) {\n for(String parameter : parameters) {\n if(parameter == null || \"\".equals(parameter)) {\n System.exit(0); // but it's bad IMO\n }\n }\n return;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:42:04.453", "Id": "33847", "ParentId": "33837", "Score": "0" } }, { "body": "<p>Let me assume your class name is SomeRequestBuilder. With the following solution I will try to validate and get the request value of a specific parameter at the same time. So you do not have to fetch same value twice - one for validation and other one to process the value. I have used reflection to do this. I see you have declared all parameters as <code>final</code>, so I had to use <code>setAccessible</code> as <code>true</code>. In case you do not need those as <code>final</code> then <code>setAccessible</code> can be removed. This code can be improved further with better exception handing. Here I wanted to show you how to do validation with less code.</p>\n\n<pre><code>class SomeRequestBuilder { \n private final String user = \"\";\n private final String password = \"\"; \n private final String name = \"\";\n private final String shortname = \"\"; \n private final String applName = \"\"; \n private final String dbSize = \"\"; \n private final String wasAdmin = \"\";\n private final String sapNr = \"\"; \n private final String etl = \"\"; \n private final String mq = \"\";\n private final String msgbroker = \"\"; \n private final String javab = \"\"; \n private final String server = \"\"; \n private final String appliverantw1 = \"\"; \n private final String appliverantw2 = \"\"; \n private final String psp = \"\"; \n private final String version = \"\"; \n private final String applialias = \"\"; \n private final String applityp = \"\";\n private final String data = \"\"; \n private final String yesdata = \"\"; \n private final String moreoptions = \"\"; \n\n public void validateAndSetValues(SomeRequest request) {\n String input = \"\"; \n Field[] fields = getClass().getDeclaredFields();\n for (Field field : fields) { \n try {\n input = request.getParameter(field.getName()); \n if (null == input) { \n // return here...\n } \n field.setAccessible(true);\n field.set(this, input);\n } catch(IllegalArgumentException e) { \n throw new IllegalArgumentException(\"caught : \" + e); \n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T13:09:53.893", "Id": "33850", "ParentId": "33837", "Score": "0" } } ]
{ "AcceptedAnswerId": "33843", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T10:24:41.243", "Id": "33837", "Score": "2", "Tags": [ "java", "strings" ], "Title": "Improve if-statement for multiple strings" }
33837
<p>I am currently learning JavaScript and wanted to fellow coders to review a function that I had written. I am looking for feedback particularly on:</p> <ul> <li>Whether I have followed best practice and JavaScript conventions</li> <li>Any suggestion on doing it better.</li> </ul> <p>Things I know I need to implement but don't know how:</p> <ul> <li>Validate if array values are numbers</li> </ul> <p>Purpose of function: Return all scores above a certain threshold. Function accepts two arguments. First is an array of scores and second argument is the threshold.</p> <p>My code:</p> <p><strong>UPDATED code after putting it through JS lint - I have ignored some erros like moving vars in the loops to the top or not declaring vars in the for loop etc (before JSLint code is here <a href="http://jsbin.com/UtOMAyU/1/" rel="nofollow">http://jsbin.com/UtOMAyU/1/</a>)</strong></p> <pre><code>function scoresAbove(scoresArg, thresholdArg) { "use strict"; var output = [], nums = scoresArg, threshold = thresholdArg; //check if scores Arg provided is an array if (typeof nums !== "object" || !nums.hasOwnProperty('length')) { return "Error: Number(s) not in the expected format. Please provid number(s) in an array format"; }else if (typeof threshold !== "number") { //check if threshold Arg provided is an array return "Error: Threshold number not in the expected format. Please provid a threshold"; } for (var i = 0, len = nums.length; i &lt; len; i++) { var currentNum = nums[i]; if (currentNum &gt; threshold) { output.push(currentNum); } } //What to return from func if (output == "") { return "No scores were above the " + " threshold you set as " + threshold; } return "The following scores were above the threshold: " + output.join(", "); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T17:33:41.133", "Id": "54479", "Score": "0", "body": "JavaScript is weakly typed. The convention is to do [duck typing](http://en.wikipedia.org/wiki/Duck_typing): do what you want to do without checking `typeof`. If it works, great! If it causes an exception to be thrown, well, it was destined to fail anyway. There's usually not much sense in manually trying to turn it into a strongly typed language. Therefore, I'd skip your precondition checks." } ]
[ { "body": "<p>The only criticism I can think to make of this is that you could/should maybe return a success parameter to identify if an error occurred or not.</p>\n\n<p>maybe:</p>\n\n<pre><code>var result = {\n success=true,\n message=\"The following scores were above the threshold: \" + output.join(\", \")\n};\n</code></pre>\n\n<p>or </p>\n\n<pre><code>var result = {\n success=false,\n message=\"Error: Number(s) not in the expected format. Please provid number(s) in an array format\"\n};\n</code></pre>\n\n<p>then <code>return result;</code>. Allowing you to then do something like </p>\n\n<pre><code>var result = scoresAbove (scoresArg, thresholdArg);\nif (result.success)\n{\n\n}\netc...\n</code></pre>\n\n<p>You could even then extend this object to include other information, maybe even build the string in the calling method. But this depends on your use case.</p>\n\n<p>Apart form that I can't see any issues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:53:07.580", "Id": "33848", "ParentId": "33844", "Score": "2" } }, { "body": "<p>My 2 cents:</p>\n\n<ul>\n<li><p><code>var output</code> should probably be <code>highScores</code> or some such, since it never contains what is returned, nor does it get outputted</p></li>\n<li><p><code>nums = scoresArg, threshold = thresholdArg;</code> makes little sense, just use the arguments</p></li>\n<li><p><code>function scoresAbove(scoresArg, thresholdArg)</code> , I am not sure what the value is of postpending 'Arg' to the argument names, I would go for simply <code>function scoresAbove(scores, threshold)</code></p></li>\n<li><p>The check for Array should really be a separate function, it is completely re-usable</p></li>\n<li><p>Ditto for Number</p></li>\n<li><p>For the actual filtering , I would use the built-in <code>filter</code> : </p>\n\n<p><code>highScores = scores.filter( function(v){ return v &gt; threshold });</code></p></li>\n<li><p>Since output is an array, I would not compare with \"\"</p></li>\n<li><p>Why the double concatenation here: <code>return \"No scores were above the \" + \" threshold you set as \" + threshold;</code></p></li>\n<li><p>Arguments of the wrong type should be rare enough that you can throw an exception since something is clearly wrong with the program.</p></li>\n</ul>\n\n<p>You could try</p>\n\n<pre><code>function scoresAbove( scores, threshold ) \n{\n \"use strict\";\n var highScores;\n\n if( notArray( scores ) )\n throw \"scores is not an array\";\n if( notNumber( treshold ) )\n throw \"treshold is not a number\"\n\n highScores = scores.filter( function(v){ return v &gt; threshold });\n\n if( !highScores || !highScores.length )\n return \"No scores were above the threshold you set as \" + threshold;\n\n return \"The following scores were above the threshold: \" + output.join(\", \");\n}\n</code></pre>\n\n<p>You would have to write the notNumber and notArray function of course.\nJSLint migh complain about missing curly braces, to each his own ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:14:58.197", "Id": "54556", "Score": "0", "body": "Thanks very much, a lot of actionable feedback and learnt couple of tricks such how to check any empty array (test if it returns the FALSE value, instead of checking for an empty string) and the whole idea of \"throwing an exception\" as it's something I need to read on and kind of avoided." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:59:28.853", "Id": "33889", "ParentId": "33844", "Score": "3" } }, { "body": "<p>In addition to what has been said, I suggest:</p>\n\n<p>1) Separation of concerns.\nYou have two concerns. a) checking if any number at all is above the treshold; and if so, return a message and b) to do the acual calculation.\nI would recommend for that using two functions.</p>\n\n<p>If you separate your concerns, there is no need for a <code>success</code> variable from the filtering: the result is clearly saying either you have an empty array or not.\nAn \"errorstate\" is given by the exception.</p>\n\n<p>2) Instead of returning \"Error\"-Messages you should use Exceptions. E.g.:</p>\n\n<pre><code>if(!Array.isArray(numbers)) throw new TypeError(\"numbers is not an Array\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:18:54.613", "Id": "54557", "Score": "0", "body": "Thanks. Going to read on the use of exceptions. It's not something am familiar with yet but from your feedback I will look into it. Also, I understand your point about \"separation of concerns\" and will review my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T16:26:00.280", "Id": "33942", "ParentId": "33844", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:27:10.380", "Id": "33844", "Score": "2", "Tags": [ "javascript" ], "Title": "Refactoring a function to return all scores above a certain threshold" }
33844
<p>The environment I'm working in requires that all allocation is done through a special set of <code>malloc</code>/<code>calloc</code> functions and that a user ID is provided when allocating. The environment has no implementation of exceptions, so errors are signaled by returning <code>NULL</code>.</p> <p>For this reason, I have tried to write a couple of C++ functions which make it easier to create and destroy C++ objects:</p> <pre><code>namespace details { template&lt;typename T&gt; typename enable_if&lt;is_pod&lt;T&gt;::value, T&gt;::type * create(uint32_t module_id) { // use module_id return (T *)calloc(1, sizeof(T)); } template&lt;typename T, typename ...Args&gt; typename enable_if&lt;!is_pod&lt;T&gt;::value, T&gt;::type * create(uint32_t module_id, Args&amp;&amp;... args) { // use module_id T *p = (T *)calloc(1, sizeof(T)); if (p) new (p) T(forward&lt;Args&gt;(args)...); return p; } template&lt;typename T&gt; void destroy(typename enable_if&lt;is_pod&lt;T&gt;::value, T&gt;::type *t) { if (t) free(t); } template&lt;typename T&gt; void destroy(typename enable_if&lt;!is_pod&lt;T&gt;::value, T&gt;::type *t) { if (!t) return; t-&gt;~T(); free(t); } }; template&lt;typename T, typename ...Args&gt; T *create(uint32_t module_id, Args&amp;&amp;... args) { return details::create&lt;T&gt;(module_id, forward&lt;Args&gt;(args)...); } template&lt;typename T&gt; void destroy(T *t) { details::destroy&lt;T&gt;(t); } </code></pre> <p>Can this be done smarter? And are there any cases where my <code>create</code>/<code>destroy</code> functions are not handling as one would expect?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T19:12:23.797", "Id": "54333", "Score": "1", "body": "Why not use new/delete?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T09:00:23.587", "Id": "54405", "Score": "0", "body": "Can you provide an example on how to do that where the actually allocation is done with calloc, and where I can pass a module_id/user_id as an argument?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T18:26:41.693", "Id": "54483", "Score": "0", "body": "No point in reviewing. It does exactly what it says it does. Nothing wrong with some very simple code. There is not enough context to understand if it is the correct thing to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T08:00:21.043", "Id": "54545", "Score": "0", "body": "@Loki Astari: I found one bug in the code which is discussed at: http://stackoverflow.com/questions/19808448/how-to-find-the-allocation-address-of-inherited-classes#19815444 I will update this post with the conclusion from this question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T22:00:08.890", "Id": "59786", "Score": "1", "body": "You are aware that you could define your own `operator new`, `operator delete`, and their array counterparts right? The advantage of that would be that they also work when objects are created outside of code you directly contril, such as standard containers." } ]
[ { "body": "<p>After some research, I'm convinced Christopher Creutzig is right. If you want all your allocations to go through customized functions, you're much better off <a href=\"https://stackoverflow.com/questions/8186018/how-to-properly-replace-global-new-delete-operators\">replacing the global operator new</a>. This will catch all calls to <code>new</code> for the translation unit, whether you replace them with <code>create</code> or not. That means when you create a <code>std::vector&lt;T&gt; myvec(3)</code>, it will use your <code>operator new</code> for any heap allocations it needs to do, instead of sidestepping your global policy.</p>\n\n<p>If you need to pass a module id, <code>operator new</code> can handle that as well by accepting extra parameters. I'm unclear how that mixes with examples such as the <code>std::vector&lt;T&gt;</code> heap allocations; it may require using a custom allocator for each STL container. Setting that aside, here's an example like yours following the lead on <a href=\"http://en.cppreference.com/w/cpp/memory/new/operator_new#Example\" rel=\"nofollow noreferrer\">cppreference.com</a>:</p>\n\n<pre><code>void* operator new(std::size_t cb, uint32_t module_id)\n{\n // use module_id\n return calloc(1, cb);\n}\nvoid operator delete(void* ptr)\n{\n free(ptr); // I'm unsure if this requires a null check\n}\n\ntype *p = new(module_id) type;\n</code></pre>\n\n<p>As an aside, if you're particularly tied to calling functions, I'd be tempted to remove the SFINAE specialization via <code>is_pod&lt;T&gt;</code> and just make it an inline check via <a href=\"http://en.cppreference.com/w/cpp/types/is_constructible\" rel=\"nofollow noreferrer\"><code>is_trivially_constructible&lt;T&gt;</code></a> and <a href=\"http://en.cppreference.com/w/cpp/types/is_destructible\" rel=\"nofollow noreferrer\"><code>is_trivially_destructible&lt;T&gt;</code></a>...that is <a href=\"https://stackoverflow.com/questions/17187975/how-can-i-make-is-podt-tests-be-performed-during-compilation-and-not-execution\">if checking is necessary at all</a>.</p>\n\n<pre><code>template&lt;typename T&gt;\nT* create(uint32_t module_id)\n{\n // use module_id\n T* p = calloc(1, sizeof(T));\n if (!is_trivially_constructable&lt;T&gt;::value &amp;&amp; p)\n {\n new (p) T(forward&lt;Args&gt;(args)...);\n }\n return p;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T02:58:46.333", "Id": "36834", "ParentId": "33858", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T13:44:06.000", "Id": "33858", "Score": "4", "Tags": [ "c++", "c++11", "memory-management" ], "Title": "Implementing `create` and `destroy` functions to replace `new` and `delete` operators" }
33858
<p>I want to parse some reports from multiple devices, reports looks like this:</p> <blockquote> <pre><code>VR Destination Mac Age Static VLAN VID Port VR-Default 192.168.11.13 90:e2:ba:3c:95:c0 2 NO intra1 350 49 VR-Default 192.168.1.1 00:0e:a6:f7:b6:b5 0 NO main 602 1 VR-Default 192.168.1.2 00:0d:88:63:bf:d1 3 NO main 602 1 VR-Default 192.168.1.14 00:1c:f0:c7:d2:52 4 NO main 602 1 etc... Dynamic Entries : 19 Static Entries : 0 Pending Entries : 1 In Request : 3888802 In Response : 4531 and some more data... Rx Error : 0 Dup IP Addr : 0.0.0.0 and some more... </code></pre> </blockquote> <p>I need only vr, destination, mac, age, static, vlan, vid and port fields. I can parse it using <code>split</code> function and regexes, but split fails if one field (e.g. Age) is empty. perldoc says I can use <code>unpack</code>:</p> <pre><code>my $template = 'A13xA16xA18xA4xA7xA13xA5xA*'; for my $line ( split /\n/, $data ) { chomp $line; my ($vr, $destination, $mac, $age, $static, $vlan, $vid, $port) = unpack $template, $line; ... } </code></pre> <p>But it dies on lines with length &lt; 84. And I got to check string length every time (Or maybe using <code>eval</code> on unpack? Is it better?). And again I got to use regexes or <code>index</code> to find the end of main table and skip headers. The code will looks like:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; my $arp = &lt;&lt;'ARP'; VR Destination Mac Age Static VLAN VID Port VR-Default 192.168.11.13 90:e2:ba:3c:95:c0 2 NO intra1 350 49 VR-Default 192.168.1.1 00:0e:a6:f7:b6:b5 0 NO main 602 1 VR-Default 192.168.1.2 00:0d:88:63:bf:d1 3 NO main 602 1 VR-Default 192.168.1.14 00:1c:f0:c7:d2:52 4 NO main 602 1 Dynamic Entries : 19 Static Entries : 0 Pending Entries : 1 In Request : 3888802 In Response : 4531 Rx Error : 0 Dup IP Addr : 0.0.0.0 ARP my $template = 'A13xA16xA18xA4xA7xA13xA5xA*'; for my $line ( split /\n/, $arp ) { last if index( $line, 'Dynamic E' ) == 0; next if length $line &lt; 84; chomp $line; my ($vr, $destination, $mac, $age, $static, $vlan, $vid, $port) = unpack $template, $line; next if $mac eq 'Mac'; print "$mac - $destination\n"; } </code></pre> <p><strong>My question is:</strong> how would you parse this data? split, regexes, unpack, substr or something else?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:57:27.777", "Id": "54274", "Score": "0", "body": "This question does not deserve to be closed — the second program works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:28:46.347", "Id": "54301", "Score": "0", "body": "perhaps CSV module?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:44:18.417", "Id": "54305", "Score": "0", "body": "@mpapec I thought CSV module will fails when some fields will be empty" } ]
[ { "body": "<p>If a problem has been encountered before by someone else, chances are that there is a CPAN module for that <a href=\"http://search.cpan.org/dist/DataExtract-FixedWidth/\" rel=\"nofollow\">(<code>DataExtract::FixedWidth</code>)</a>.</p>\n\n<p>If you don't want to use a CPAN module, then my next choice would be to use regular expressions.</p>\n\n<pre><code>use strict;\n\n# Strips leading and trailing whitespace from all parameters\nsub strip {\n for (@_) { s/^\\s+//; s/\\s+$//; }\n @_;\n}\n\n# Extracts data from lines of text in tabular format.\n#\n# First parameter is a regular expression for capturing fixed-width fields.\n#\n# Subsequent parameters are the lines of tabular data, the first of which holds\n# the column headings. Any line that does not match the regular expression,\n# as well as subsequent lines, are discarded.\n#\n# Returns a list (one element per input line) of hashes (keyed by column names).\nsub extract_table {\n my ($fmt, $first_line) = (shift, shift);\n\n my (@headers) = strip($first_line =~ $fmt);\n\n my @table;\n for my $line (@_) {\n my (@fields) = $line =~ $fmt;\n last unless @fields;\n\n my %data;\n @data{@headers} = strip(@fields);\n push @table, \\%data;\n }\n return @table;\n}\n\nmy $fmt = qr/^(.{14})(.{17})(.{19})(.{5})(.{8})(.{14})(.{6})(.*)/;\n\n# Take lines of input from a reasonable source (STDIN or a filename\n# argument on the command line)\nmy @table = extract_table($fmt, &lt;&gt;);\n\nuse Data::Dumper;\nprint Dumper(\\@table);\n</code></pre>\n\n<p>Note that <code>chomp()</code> is unnecessary since we're stripping whitespace characters anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T06:22:47.900", "Id": "54390", "Score": "0", "body": "It might be worthwhile mentioning that `strip(@fields);` also alters `@fields` array." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T02:09:09.350", "Id": "33894", "ParentId": "33859", "Score": "2" } } ]
{ "AcceptedAnswerId": "33894", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:03:43.307", "Id": "33859", "Score": "3", "Tags": [ "parsing", "perl" ], "Title": "Parsing text from reports" }
33859
<p>I'm just getting started with Python -- completing a simple exercise from a practice website. My code works -- just looking for feedback on better ways to achieve the goal.</p> <p>Goal:</p> <blockquote> <p>Find the original (unscrambled) words, which were randomly taken from a wordlist. Send a comma separated list of the original words, in the same order as in the list below.</p> </blockquote> <p>I stored the scrambled words in <code>words.txt</code> and the wordlist in <code>wordlist.txt</code></p> <pre><code>#!/usr/bin/env python3 # open word files wordlist = open("wordlist.txt", "r").read().split() words = open("words.txt", "r").read().split() s = list() # loop through scrambled words for word in words: # break scrambled word into characters chars = list(word) # loop through comparison list for compare in wordlist: # break compare word into characters compare_chars = list(compare) # make copy of scrambled characters char_list = chars[:] # loop through scrambled word characters for char in chars: # if character not in compare word go to next compare word if not char in compare_chars: break # if character found remove it (in case character exists more than once) compare_chars.remove(char) char_list.remove(char) # if all compare characters exhausted we *may* have found the word if not compare_chars: # if all scrambled characters are utilized then we have the right word if not char_list: s.append(compare) else: s.append('???') break # create comma separated list of words print(",".join(s)) </code></pre>
[]
[ { "body": "<p>I'm not a Python programmer but I would take this approach, as if I understand the problem correctly, it seems like an easy solution. Along side that I believe it makes us of the language features also.</p>\n\n<pre><code>#!/usr/bin/env python3\n\n# open word files\nwordlist = open(\"wordlist.txt\", \"r\").read().split()\nwords = open(\"words.txt\", \"r\").read().split() \n\ns = list()\n\n# loop through scrambled words\nfor word in words:\n # break scrambled word into characters\n chars = sorted(list(word))\n # loop through comparison list\n for compare in wordlist:\n if sorted(list(compare)) == chars:\n s.append(compare)\n\n# create comma separated list of words\nprint(\",\".join(s))\n</code></pre>\n\n<p>This works on the bases that we do not care for order, so an ordered list of each will be a good check.</p>\n\n<p>I have not broken out of the inner loop, as it is unclear weather multiple words could match and all of those words should be returned or not.</p>\n\n<p>This is untested, as stated, I'm not a Python programmer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:18:09.377", "Id": "54283", "Score": "0", "body": "This makes a lot of sense. Essentially all we need to know is that the scrambled word and the compare word have the same characters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:30:51.310", "Id": "54284", "Score": "0", "body": "This worked well. `list(foo).sort()` didn't seem to work, changed to `sorted(list(foo)` and works great!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:06:10.930", "Id": "54291", "Score": "0", "body": "@jwalton512 Sorry `.sort()` is Python 2 syntax. I have updated my answer to be `sorted(list(x))` so it matches the Python 3 request." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:42:28.160", "Id": "33862", "ParentId": "33861", "Score": "1" } }, { "body": "<p>Welcome to CodeReview! First, congratulations on writing a working Python program that is clean, straightforward, and easy to understand.</p>\n\n<p>Now let's see if we can make it better!</p>\n\n<h1>Style</h1>\n\n<p>There are two things I think you could improve stylistically. First, your comments are a little too much. I know people encourage you to write comments. But you need to be careful of the kind of comments you write.</p>\n\n<p>Comments should be used to provide <em>extra</em> information. When you have code like this:</p>\n\n<pre><code># open word files\nwordlist = open(\"wordlist.txt\", \"r\").read().split()\nwords = open(\"words.txt\", \"r\").read().split() \n</code></pre>\n\n<p>Is the comment really adding value? A comment that states in English what your code states in Python is a wasted comment. You want to explain <em>what you are doing</em> rather than focus on <em>how you do it.</em> And you should only explain things that don't already have a set of names explaining it. If you're calling an <code>open</code> function, you don't need to explain that you are opening something. If you're storing data into a variable called <code>wordlist</code>, you probably don't need to explain that you are reading a word list. Use a light touch with your commentary.</p>\n\n<p>Second, it's very much preferred in Python 3 to use the context manager features of file objects. If you are going to read in the entire contents of a file, use a <code>with</code> block to open, read, and close the file safely.</p>\n\n<pre><code>with open(\"wordlist.txt\", 'r') as wlist:\n wordlist = wlist.read().split()\n</code></pre>\n\n<p>Since you do this twice, you might write a function to do it for you. (You say you're a beginner, so I'm not sure if you've learned functions yet.)</p>\n\n<h1>Performance</h1>\n\n<p>Looking at the \"skeleton\" of your code:</p>\n\n<pre><code>for word in words:\n for compare in wordlist:\n for char in word:\n</code></pre>\n\n<p>Your performance is going to be <span class=\"math-container\">\\$O(m \\times n \\times o)\\$</span> where <code>m</code> is the number of scrambled words, <code>n</code> is the number of words in the master wordlist, and <code>o</code> is the average word length.</p>\n\n<p>The phrasing of the problem statements suggests that the scrambled words are a small subset of the inputs. But the worst case is that the scrambled words are the entire wordlist, making your worst-case performance <span class=\"math-container\">\\$O(n^2)\\$</span> which will really hurt for large values of <code>n</code>.</p>\n\n<p>You can improve this performance by converting <span class=\"math-container\">\\$m \\times n\\$</span> into <span class=\"math-container\">\\$m + n\\$</span>. Make a pass through one list computing a \"signature\" for each word. Store the signatures in a Python <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=dict#mapping-types-dict\" rel=\"nofollow noreferrer\"><code>dict</code></a> (dictionary) object mapping the signature to the original word(s) with that signature. Then make a pass through the second list, computing a \"signature\" for those words that can compare with the first signature. Check each word in the second list to see if its signature is in the dictionary, and store the results if so.</p>\n\n<p>This process, <strong>if you can find the right signature,</strong> will work for a large number of problems.</p>\n\n<p>You want a signature that does not depend on the ordering of the letters, since by definition one set of letters is scrambled. One easy mechanism would be to sort the letters into ASCII order, so that \"banana\" -> \"aaabnn\" for example. </p>\n\n<p>Your code would then look like this:</p>\n\n<pre><code>signatures = dict()\n\nfor word in wordlist:\n sig = ''.join(sorted(word))\n signatures[sig] = word\n\nfound_words = []\n\nfor dwro in scrambled_words:\n sig = ''.join(sorted(dwro))\n if sig in signatures:\n found_words.append(signatures[sig])\n</code></pre>\n\n<p><strong>Note:</strong> There's a potential issue, in that words like \"keep\" and \"peek\" are going to have the same signature, since they have all the same letters. You will have to decide how to handle that, but if you decide to maintain a list of all possible words for a signature, you should look at <a href=\"https://docs.python.org/3/library/collections.html#defaultdict-objects\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T16:12:09.467", "Id": "219709", "ParentId": "33861", "Score": "0" } } ]
{ "AcceptedAnswerId": "33862", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:29:15.703", "Id": "33861", "Score": "3", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Find scrambled words within word list" }
33861
<p>Just thought I'd share this and see what kind of improvements could be made that I'm not aware of and taking advantage of.</p> <p>The situation is this: I have a list of items on a page that have a button that opens a menu. I need a click away event as well as close others when a new menu is opened. Also some of the menu actions will replace items in the list which means I have new dynamic menu buttons on the page. </p> <p>To do this efficiently (as far as I can tell) you need to use event delegation and it ends up looking like this:</p> <pre><code>$(document).delegate( '.button', 'click', function(e){ var $button = $(this); var $menu = $button.closest('.menu'); e.stopPropagation(); // Close others $('.button').each(function(){ $(this).closest('.menu').removeClass('open'); }); // Toggle target open/close if( $menu.hasClass('open') ){ $menu.removeClass('open'); } else{ $menu.addClass('open'); } $(document).on('click', function(e){ var $target = $(e.target); if( !$target.is( $( $menu.find('button') ) ) ){ if( $menu.hasClass('open') ){ $menu.removeClass('open'); } } }); }); </code></pre> <p>Maybe there's a better way?</p>
[]
[ { "body": "<p>I believe there is no better way. Regardless, we can shorten the code a little. Also note that <a href=\"http://api.jquery.com/delegate/\" rel=\"nofollow\">.delegate()</a> has been superceded by <a href=\"http://api.jquery.com/on/\" rel=\"nofollow\">.on()</a> since jQuery 1.7, so I replaced your delegate with on.</p>\n\n<pre><code>$(document).on( 'click', '.button', function(e){\n var $button = $(this);\n var $menu = $button.closest('.menu');\n e.stopPropagation();\n\n // Close others-assumed you want all menus closed\n $('.menu').not($menu).removeClass('open'); \n\n // Toggle target open/close\n $menu.toggleClass('open');\n\n $(document).on('click', function(e){\n //This function will only run when e.target isn't a button\n //Your $target.is($menu.find('button')) will always be false\n\n if( $menu.hasClass('open') ){\n $menu.removeClass('open');\n }\n });\n});\n</code></pre>\n\n<p>If this does not do the same thing, you really need to share your html structure so we can get a better idea of your mark-up.</p>\n\n<p><strong>Edit</strong>\nTo work around the fact that the document click event is assigned every time you click on a button, you could do something like the following:</p>\n\n<pre><code>$(document).ready(function() {\n var $menu;\n $(document).on( 'click', '.button', function(e){\n var $button = $(this);\n $menu = $button.closest('.menu');\n e.stopPropagation();\n $('.menu').not($menu).removeClass('open'); \n $menu.toggleClass('open');\n });\n $(document).on('click', function(e){\n if($menu &amp;&amp; $menu.hasClass('open') ){\n $menu.removeClass('open');\n }\n });\n)}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T18:28:28.863", "Id": "54330", "Score": "0", "body": "I forgot to add that your first call to $(document) should be using a more precise selector. From the event performance section of the doc for .on() \"For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.\" So instead of using `$(document)` you should use `$(sharedParentSelector)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T01:34:54.480", "Id": "54381", "Score": "2", "body": "This code (and the original) will keep adding document click event handlers every time you click a `.button`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T17:18:26.747", "Id": "54621", "Score": "0", "body": "You're exactly right Flambino, which is part of what I was looking to fix. My first inclination would be to namespace the event on document and somehow add the event when the button is clicked and remove it when the document is clicked. Not sure how that would work here though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T17:40:01.587", "Id": "54624", "Score": "0", "body": "I'd suggest moving the second event declaration to outside the first. Wrapping both in a function like `$(function() {`. Then move $menu to be scoped within this outer function and use it in both inner functions. This way the `$(document).on('click', function(e){` will only trigger once. I'll update my answer to show what I mean." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T18:08:45.333", "Id": "33875", "ParentId": "33863", "Score": "1" } }, { "body": "<p>Slight variation of @DanielCook's answer, just the 'on click outside, close menu' part :</p>\n\n<pre><code>$(document).on('click', function(e){\n // ensure this is only applied if the element is not contained in a menu\n if ($(e.target).is(':not(.menu, .menu *)')){\n // no need to check if element has class .open, \n // removeClass does nothing if it is not the case\n $('.menu').removeClass('open'); \n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T17:11:43.670", "Id": "54620", "Score": "0", "body": "Missed a ) in the if statement. Otherwise this is perfect." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T10:36:45.043", "Id": "33913", "ParentId": "33863", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:43:41.610", "Id": "33863", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "jQuery delegate events on dynamic elements with a click away handler" }
33863
<p>This <a href="http://codility.com/demo/take-sample-test/triangle" rel="nofollow">Codility challenge</a> is to take an array of integers representing lengths of line segments, and determine whether or not it is possible to choose three distinct segments to form a triangle. (The sum of the lengths of any two sides must exceed the length of the remaining side.) Assume that <code>A</code> contains at most one million <code>int</code>s.</p> <p>Complexity requirements:</p> <ul> <li>Expected worst-case time complexity is O(n log(n));</li> <li>Expected worst-case space complexity is O(n), not counting the input array <code>A</code> itself.</li> </ul> <p>This is my solution:</p> <pre><code>import java.util.Arrays; class Solution { public int solution(int[] A) { // write your code in Java SE 6 int n = A.length; if (n&gt;1000000000) return -1; Arrays.sort(A); int p=0; int q=p+1; int r=q+1; for (;r&lt;n;p++,q++,r++){ if(A[p]+A[q]&gt;A[r] &amp;&amp; A[q]+A[r]&gt;A[p] &amp;&amp; A[r]+A[p]&gt;A[q]) return 1; } return 0; } } </code></pre> <p>I don't how to achieve 100% correctness. I get only 93%.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:26:39.760", "Id": "54313", "Score": "2", "body": "please include the basics of the problem from the link. i clicked the link, and it wanted me to do the test, this could be considered spam by some, trying to lure people to a site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:34:39.820", "Id": "54315", "Score": "0", "body": "@Malachi: Since it's not a blatant intent to spam, it shouldn't apply here. However, it would be useful to have a better reference to this problem (which the OP may have to provide)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:36:25.013", "Id": "54317", "Score": "0", "body": "@Malachi: You may also suggest the tag wiki for this new tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:42:20.333", "Id": "54318", "Score": "0", "body": "@Jamal I suggested a tag wiki for that, I wasn't sure what it was at first, I had to go to the main site first, I have never heard of that site until today, but I can see it becoming a thing here on code review. similar to other sites where you compete by writing code, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:43:08.327", "Id": "54319", "Score": "1", "body": "@Malachi: It is on SO, so it should be okay." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:45:31.713", "Id": "54321", "Score": "0", "body": "@Malachi: On that note, you could also refer to SO's tag wiki. I skipped one of the suggestions because I wasn't sure if it was best to use here as it sounded a tad promotional." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T19:26:55.360", "Id": "54338", "Score": "0", "body": "Is this a code review or an algorithm review? Are they the same here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T19:28:11.490", "Id": "54340", "Score": "0", "body": "Hint: you are not examining all possible triples, which is implied in your question. How can you check all possible triples in n log n time? Can you think of ways to incorporate a binary search into your algorithm?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:56:55.317", "Id": "54369", "Score": "0", "body": "I have run code against this codility, and I believe their system has a bug. I get 93% as well, and I have manually checked my code and the item it tells me I get wrong is not, in fact wrong when I run it myself. The result they get in their environment is different to the one I get." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T22:28:08.437", "Id": "54371", "Score": "0", "body": "Huh, OK, I got 100%, using a different approach. I think there's a problem with Codility's Arrays.binarySearch()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T10:19:06.713", "Id": "54414", "Score": "0", "body": "Thank you to all! Have I to move to stackedoverflow?" } ]
[ { "body": "<p>Funny things that we(human) know that 2,147,483,647 + 1 = 2,147,483,648 but computer thinks <a href=\"http://ideone.com/QX7N6z\" rel=\"nofollow noreferrer\">otherwise</a>. <em>Ahhh! see</em>, so now what to do?</p>\n\n<p>You know <code>4 + 5 &gt; 7</code> is same as <code>5 &gt; (7 - 3)</code>. Yes I know you are grinning ;)</p>\n\n<p>And also as <a href=\"https://codereview.stackexchange.com/a/33874/26200\">200_success suggested</a> you are considering consecutive elements but problem definition say otherwise.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T18:16:42.087", "Id": "33876", "ParentId": "33868", "Score": "2" } }, { "body": "<p>As has been pointed out, you must do several things to ensure you get the maximum marks.</p>\n\n<ol>\n<li>Ensure that negative numbers are checked for.</li>\n<li><p>Handle the <code>MAX_INT</code> overflow issue which could arise.</p>\n\n<blockquote>\n <p>You know <code>4 + 5 &gt; 7</code> is same as <code>5 &gt; (7 - 4)</code>. Yes I know you are grinning ;)</p>\n</blockquote>\n\n<p>This suggested solution is correct for this.</p></li>\n</ol>\n\n<p>These two individual points should allow you to achieve the maximum score. Now I would just like to quickly go over some theory behind why this solution works. </p>\n\n<p><strong>Time complexities</strong></p>\n\n<p>It seems people keep asking you to address the \"consecutive elements\". You have already done this through the use of <code>Arrays.sort()</code>. This Java sort algorithm is referred to as a \"tuned Quicksort\" ( See <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5B%5D%29\" rel=\"nofollow\">http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(int[])</a> ). </p>\n\n<blockquote>\n <p>The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's \"Engineering a Sort Function\", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.\n Quicksort is well known for its <code>O( n log n )</code> time complexity (excluding extreme cases).</p>\n</blockquote>\n\n<p>After this you do a single iteration over the array, which is considered <code>O(n)</code>. When we add the two time complexities together we are given <code>O( 2n log n)</code> where constants are considered insignificant for Big-O notation. So to clarify this simplifies down to <code>O(n log n)</code> which was the upper bound of the problem.</p>\n\n<p><strong>How sorting solves non-consecutive elements</strong></p>\n\n<p>Once the array is sorted it is true that only consecutive triples need to be considered. </p>\n\n<p>Consider the following array: <code>{1,2,6,6,8}</code></p>\n\n<p>Whilst it may be true that <code>(1, 6, 6)</code> is triangular, and is non-consecutive. It can also be proven that if that value is triangular then any number which lies between the initial 1, and 6 will also be triangular. </p>\n\n<p>From this we can see that in the sort array, for each non-consecutive triangular triples which exists there also exists an consecutive triple.</p>\n\n<p><strong>Simplification from sorting</strong></p>\n\n<p>The sort operation allows you to simplify you checks later, and decrease execution time. When checking for negative number, you only need check the lowest number in the triple, as if this is <code>&gt;= 0</code> it is given the follow values must be <code>&gt;=</code> that initial value.</p>\n\n<p>This mean you only need check one value for negativity, not three.</p>\n\n<p>This can be extended further into the actual triangular checks. If it is true that the smallest two numbers in the triple are larger than the largest number when summed, then all three statements are true.</p>\n\n<blockquote>\n <p>1) A[P] + A[Q] > A[R]</p>\n \n <p>2) A[Q] + A[R] > A[P]</p>\n \n <p>3) A[R] + A[P] > A[Q]</p>\n</blockquote>\n\n<p>Remembering the algorithm change to this, so these would be evaluated as</p>\n\n<pre><code>A[P] &gt; (A[R] - A[Q])\n</code></pre>\n\n<p>Because we can guarantee that <code>A[P] &lt; A[Q] &lt; A[R]</code> due to A being sorted, we only need perform the one check above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:21:56.513", "Id": "54348", "Score": "0", "body": "cool. But I didn't know about the _\"It can also be proven [......] be triangular\"_ part, can you provide a link?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:25:29.960", "Id": "54349", "Score": "0", "body": "I said can be proven ;), I haven't found a link which in fact proves this as of yet. But if you consider a large set of numbers, and try extreme cases, you will see it holds. Unfortunately I never continued my Maths further, so I do not have the knowledge required to draw up a full Mathematical proof for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T10:22:29.103", "Id": "54415", "Score": "0", "body": "Thank you! So I have to change the if with A[P]>(A[R]-A[Q]) in case the first number of triangle is negative!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T10:42:27.210", "Id": "54418", "Score": "0", "body": "@user31565 `A[P]>(A[R]-A[Q])` is to prevent the problem of an overflow exception if `A[P] + A[Q] > MAX_INT`, for this problem you are required to ignore negative numbers as they are invalid. Which is why you first do a check of `A[P] >= 0`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T12:32:31.587", "Id": "54432", "Score": "0", "body": "If you could show me the code I will understand better :) I misunderstood!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T19:15:22.640", "Id": "54485", "Score": "0", "body": "`if( (A[P] > 0) && (A[P] > (A[R]-A[Q]) ) { // triangular }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T22:07:18.150", "Id": "58017", "Score": "0", "body": "Perfect 100% :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-16T17:35:16.087", "Id": "108966", "Score": "1", "body": "Suppose there are some values `P`, `Q`, and `R` such that `P < Q`, `Q < R`, and `A[P] > A[R] - A[Q]`. Since `R - 2 >= P` and `R - 2 >= Q`, and since the array is sorted, it follows that `A[R - 2] >= A[P]` and `A[R - 1] >= A[Q]`. From that it follows that `A[R - 2] > A[R] - A[R - 1]`. In other words, if there are three entries _anywhere_ in the array that can form a triangle, then there are three consecutive entries that can form a triangle. That's why it's sufficient to check only consecutive entries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-15T19:49:37.910", "Id": "191713", "Score": "0", "body": "It is not O(2n log n) but it is O(n + n log n), and because n log n is worst time complexity it is treated just like O(n log n). Please update your answer" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T19:44:33.350", "Id": "33881", "ParentId": "33868", "Score": "3" } } ]
{ "AcceptedAnswerId": "33881", "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:19:20.980", "Id": "33868", "Score": "3", "Tags": [ "java", "interview-questions", "programming-challenge" ], "Title": "Determining possible triangle from lengths of line segments" }
33868
<p>Code golfing is the challenge of accomplishing a given task with the shortest source code. The name comes from the sport of golf, where players try to hit the ball into the hole using the fewest number of strokes. When code golfing, all usual considerations, such as clarity and performance, are considered secondary to brevity.</p> <p>The <a href="http://codegolf.stackexchange.com/">Programming Puzzles &amp; Code Golf Stack Exchange</a> site specializes in these exercises. <strong>According to the rules of this site, code golfing is <a href="http://meta.codereview.stackexchange.com/help/on-topic">off-topic</a>.</strong></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:27:32.443", "Id": "33869", "Score": "0", "Tags": null, "Title": null }
33869
Code golfing is the challenge of accomplishing a given task with the shortest source code. NOTE: Code golfing is **off-topic** for this site.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:27:32.443", "Id": "33870", "Score": "0", "Tags": null, "Title": null }
33870
<p>The tests consist of relatively simple programming tasks (Fibonacci sequence, equilibrium index, etc.) and aim to evaluate the applicant's ability to write working, error-free code that is also good performance-wise. Solutions must be produced within a set time limit. It's possible to create and run test cases while solving the test.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:41:19.937", "Id": "33871", "Score": "0", "Tags": null, "Title": null }
33871
Codility offers browser-based tests to verify programming skills of job applicants. The platform supports 14 programming languages, including Java, C#, Ruby, Python, Objective-C, JavaScript and more.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:41:19.937", "Id": "33872", "Score": "0", "Tags": null, "Title": null }
33872
<p>I'm making a server in C that needs to parse JSON that follows oBIX protocol and I'm using the <a href="https://jansson.readthedocs.org/en/2.5/" rel="nofollow">Jansson library</a> for this. I've been programming in high level languages such as Java and C# for my entire career and the last time I touched C was way back in 7-8 years ago, so I'm mostly looking for guidance on writing C-style code.</p> <p>Here's a sample JSON input from client to server:</p> <pre><code>{"obix":"obj","is":"obix:Request","rid":"1","children":[{"obix":"op","name":"add","is":"obix:Watch","children":[{"obix":"obj","is":"obix:WatchIn","children":[{"obix":"list","names":"hrefs","children":[{"obix":"uri","val":"/device/"}]}]}]}]} </code></pre> <p>So a function I have just needs to validate what kind of request the client is making. First, I write the following defines:</p> <pre><code>#define OBIX_REQUEST_INVALID -1 #define OBIX_REQUEST_WATCH 0 #define OBIX_REQUEST_UPDATE 1 .... </code></pre> <p>Then in my callback function. I first validate whether it's a valid JSON input.</p> <pre><code>int callback_web_socket(struct libwebsocket_context * this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { .... json_t *root; json_error_t error; root = json_loads(buf,0,&amp;error); if (!root) { printf("\nInvalid JSON data.\n"); break; } .... </code></pre> <p>If it's valid JSON, I call my parse function to determine request type</p> <pre><code>int request_type = obix_parse_request(root); printf("\nRequest Type: %d\n", request_type); </code></pre> <p>And here's how my parse function looks like:</p> <pre><code>int obix_parse_request(const json_t *obix_root_obj) { json_t *obix_obj = json_object_get(obix_root_obj,"obix"); if (!json_is_string(obix_obj) || strcmp(json_string_value(obix_obj),"obj") != 0) { return OBIX_REQUEST_INVALID; } json_t *first_child = json_object_get(obix_root_obj, "children"); if (!first_child || !json_is_array(first_child)) { return OBIX_REQUEST_INVALID; } json_t *first_child_obj = json_array_get(first_child, 0); if (!first_child_obj || !json_is_object(first_child_obj)) { return OBIX_REQUEST_INVALID; } json_t *first_child_is_str = json_object_get(first_child_obj, "is"); if (!first_child_is_str || !json_is_string(first_child_is_str)) { return OBIX_REQUEST_INVALID; } const unsigned char *request_type = json_string_value(first_child_is_str); if (strcmp(request_type, "obix:Watch") == 0) { return OBIX_REQUEST_WATCH; } ... } </code></pre> <p>If I were coding in C#, this function would raise a huge red flag for lots of code duplication. But this is C, and I'm readily assuming the code duplication is part of my incompetency in C language.</p> <p>How would you elegantly write this function? Aside from cleaning up the function, I'd like to hear some comments on my coding style.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T19:23:41.347", "Id": "54487", "Score": "0", "body": "It is better to use const and enums than #define, because #define's are I scoped and unchecked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T19:26:27.577", "Id": "54488", "Score": "0", "body": "Also, at compile time the preprocessor macros get replaced by their numerical value in the code, so it will be difficult to determine what a number is all about when debugging." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T17:15:48.503", "Id": "55813", "Score": "0", "body": "I would Lex and yacc it makes it very simple." } ]
[ { "body": "<p>A few notes:</p>\n\n<ul>\n<li><p>My first concern with your program is the use of the Jansson library. <a href=\"http://chadaustin.me/2013/01/json-parser-benchmarking/\" rel=\"nofollow noreferrer\">Looking at some benchmarks</a> shows me that it is less than stellar. (The Y-axis is parses-per-second. Thus, higher is faster.)</p>\n\n<p><img src=\"https://i.stack.imgur.com/dU2G3.png\" alt=\"\"></p>\n\n<p>So a new library choice may be in order. I would highly recommend looking a <a href=\"http://zserge.com/jsmn.html\" rel=\"nofollow noreferrer\">jsmn</a>. I have yet to find a faster (and more portable!) option out there. Here is a benchmark for jsmn compared to Jansson (jsmn is 19.28 times faster).</p>\n\n<p>\\$ \n\\newcommand\\T{\\Rule{0pt}{1em}{.5em}}\n\\begin{array}{|c|c|c|c|c|c|}\n\\hline \\textbf{Project} &amp; \\textbf{License} &amp; \\textbf{API} &amp; \\textbf{Neg. tests} &amp; \\textbf{Followers} &amp; \\textbf{Benchmark} \\T \\\\\\hline\n \\text{Jansson} \\T &amp; \\text{MIT} &amp; \\text{DOM} &amp; \\text{yes} &amp; \\dfrac{234}{59} &amp; 25 \\text{MB/s}, 52 \\text{s} \\\\\\hline\n \\text{jsmn} \\T &amp; \\text{MIT} &amp; \\text{custom} &amp; \\text{yes} &amp; \\dfrac{65}{4} &amp; 482 \\text{MB/s}, 2.3 \\text{s} \\\\\\hline\n\\end{array}\n\\$</p></li>\n<li><p>You have used the preprocessor to define some oBIX request values.</p>\n\n<blockquote>\n<pre><code>#define OBIX_REQUEST_INVALID -1\n#define OBIX_REQUEST_WATCH 0\n#define OBIX_REQUEST_UPDATE 1\n</code></pre>\n</blockquote>\n\n<p>You could use an <code>enum</code> here instead.</p>\n\n<pre><code>typedef enum \n{\n INVALID = -1,\n WATCH = 0,\n UPDATE = 1\n} ObixRequest;\n</code></pre></li>\n<li><p>You can remove any <code>!= 0</code> tests from your <code>if</code> conditions for maximum C-ness.</p></li>\n<li><p>You sometimes use <code>printf()</code> when you don't have to.</p>\n\n<blockquote>\n<pre><code>printf(\"\\nInvalid JSON data.\\n\");\n</code></pre>\n</blockquote>\n\n<p>Use <code>puts()</code> for statements like this when you aren't formatting the string. As a plus, you don't have to include the <code>\\n</code> characters.</p>\n\n<pre><code>puts(\"Invalid JSON data.\");\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:06:20.170", "Id": "40821", "ParentId": "33873", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T17:50:42.927", "Id": "33873", "Score": "7", "Tags": [ "c", "json" ], "Title": "Parsing function for a server, using the Jansson library" }
33873
<p>I'm looking for some feedback on Python best practices, general code quality, and bonus points if you have knowledge of CANOpen that you can leverage to find anything I missed functionality-wise, but isn't necessary! I'm hoping that this isn't too technical.</p> <p><strong>PDOMapping.py:</strong></p> <pre><code>import CANOpen import csv, StringIO, binascii """@package PDOMapping This package defines a PDOMapping, which is the PDO interpretation of the DictionaryEntry, but instead does the heavy lifting for PDOs. It defines the methods for sending and retrieving PDOs from CANSock. """ class PDOMapping(object): """Provides an easy to use method for sending and recieving PDOs for a specific device.""" def __init__(self, CANBus, deviceID): """Constructor for the PDOMapping. Takes in a CANBus to communicate over and a deviceID, and calculates the 8 possible PDO identifiers from there.""" self.CANBus = CANBus self.deviceID = deviceID self.transmitPDOBases = {} self.recievePDOs = {} for i in range(1, 5): self.transmitPDOBases[str(i)] = 0x80 + (0x100 * i) + self.deviceID msg = CANOpen.PDO((0x100 + (0x100 * i) + self.deviceID), [0x00]*8) self.recievePDOs[str(i)] = msg for i in range(5, 9): self.transmitPDOBases[str(i)] = 0xC0 + (0x100 * (i - 4)) + self.deviceID msg = CANOpen.PDO((0x140 + (0x100 * (i - 4)) + self.deviceID), [0x00]*8) self.recievePDOs[str(i)] = msg def send(self, mappingList, value): """Takes in a list of different positions and a value. It breaks the value down into the appropriate number of bytes (The least amount possible) and then distributes the bytes to their different positions. This allows for one value to be spread over any number of different PDOs in any order. The mapping list must be ordered highest byte to lowest byte and specifies a tuple containing the PDO number and byte number for that bytes position. It then sends out all the PDOs needed to complete the message. Raises an exception if the value is too large for the provided list of positions, and returns false if the communication with CANSock failed, or true if everything went well.""" stringValue = hex(value) stringValue = stringValue.replace('0x', '') if len(stringValue) &gt; (len(mappingList) * 2): raise Exception('Value is too large to fit into the PDO!') # String needs to have an even number of characters if (len(stringValue) % 2) == 1: stringValue = '0' + stringValue while (len(mappingList) * 2) &gt; len(stringValue): stringValue = "00" + stringValue valueStringList = [] while len(stringValue) &gt; 0: valueStringList.append(stringValue[-2:]) stringValue = stringValue[:-2] valueList = [] for v in valueStringList: valueList.append(int(v, 16)) PDOsToSend = [] for messageLocation in mappingList: self.recievePDOs[str(messageLocation[0])].payload[messageLocation[1]-1] = valueList.pop() if not self.recievePDOs[str(messageLocation[0])] in PDOsToSend: PDOsToSend.append(self.recievePDOs[str(messageLocation[0])]) for pdo in PDOsToSend: worked = self.CANBus.send(pdo.toString()) if worked == False: print "Got a bad response on a send!" return False return True def retrieve(self, mappingList): """Does the opposite of the send. Takes in a mapping list formatted in the same way as the send mapping, and then figures out which PDOs it needs to retrieve to construct the value, then does the appropriate bit shifting to create the value and returns that as an integer.""" PDOsToRetrieve = [] for messageLocation in mappingList: if not (messageLocation[0] in PDOsToRetrieve): PDOsToRetrieve.append(messageLocation[0]) PDOS = {} for pdo in PDOsToRetrieve: PDOS[str(pdo)] = self.fetchPDO(pdo) value = ''; for messageLocation in mappingList: value += PDOS[str(messageLocation[0])][messageLocation[1]] return int(value.replace('0x', ''), 16) def fetchPDO(self, pdoNumber): """Private method used to retrieve a PDO. This ensures that the whole PDO is grabbed at once as opposed to fetching the same PDO 4 times to get 4 different data bytes out of it.""" PDOCOB = self.transmitPDOBases[str(pdoNumber)] response = self.CANBus.send(hex(PDOCOB)) f = StringIO.StringIO(response) reader = csv.reader(f, delimiter= ',', skipinitialspace=True) message = reader.next() if message[-1] == 'T': print 'This is the dead message: ', print message raise Exception('PDO retrieve shows dead PDO!') return message </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:20:55.987", "Id": "54358", "Score": "0", "body": "Could you give a pointer to the context? What is a PDO, etc?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:37:46.420", "Id": "54364", "Score": "0", "body": "A PDO is a type of CAN message (http://en.wikipedia.org/wiki/CANopen#Process_Data_Object_.28PDO.29_protocol). Long story short, its a little class that defines 8 data bytes and an identifier. You can check the link above to get a full rundown of the CANOpen protocol :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:21:30.543", "Id": "54558", "Score": "0", "body": "You may also be interested in the code formatting and naming style checker https://pypi.python.org/pypi/pep8" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-26T22:18:50.413", "Id": "186707", "Score": "0", "body": "Forgive me for straying off-topic... but what CANopen library are you importing there and how has it worked for you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-27T00:46:04.007", "Id": "186715", "Score": "0", "body": "@altendky it's my own self made one - it's really just a python wrapper that talks to a C based service running on the same box which lets python talk to a CAN bus via a socket connection." } ]
[ { "body": "<p>Well, here are a few points that I noticed:</p>\n\n<ul>\n<li>The docstrings are all a long single line, which is hard to read on StackExchange, and in most editors as well. I would suggest to wrap the docstrings to a reasonable line length.</li>\n<li>Spelling error -- \"recieve\" (in <code>recievePDOs</code>) should be \"receive\"</li>\n<li>Lots of hardcoded numbers (5, 9, 0x80, ...). Consider using named constants</li>\n<li>The trailing semicolon on some lines (e.g. <code>value = '';</code>) is unnecessary and uncommon, remove it.</li>\n<li>Using <code>csv</code> to parse the response in <code>fetchPDO</code> is quite \"creative\", but is this really the right tool for the job? Or is this overkill? Is a response really CSV?\n<ul>\n<li>Error handling appears to be inconsistent. Sometimes you return <code>True</code>/ <code>False</code>to indicate success/error, sometimes you use exceptions. I'd suggest to use exceptions throughout.</li>\n</ul></li>\n<li>Don't raise <code>Exception</code> directly. Instead, create a <code>PDOError</code>class derived from <code>Exception</code>, and raise that. This allows clients of your class to catch specifically only PDO errors.</li>\n<li>Avoid <code>print</code> statements in library code. For example, instead of printing error details, include them in your custom exception class. </li>\n<li>Some of your functions are quite long. To conform to the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a>, you might want to factor out the building and parsing of messages into separate functions, preferably in a separate module. This would also be easier to unit-test </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:41:47.063", "Id": "54365", "Score": "0", "body": "This is exactly the sort of stuff I was looking for! Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:27:42.853", "Id": "33888", "ParentId": "33878", "Score": "7" } }, { "body": "<p>In <code>send</code> you do a lot of work to convert a number to a zero-padded hex string. You could use string formatting instead:</p>\n\n<pre><code>stringValue = '{:0{}x}'.format(value, len(mappingList) * 2)\n</code></pre>\n\n<p>Then you reverse the order of bytes and convert to a list of ints which you eventually consume by popping from the end. Thus you are reversing the order twice. Instead of popping inside a loop, the idiomatic way of working with two list in parallel is to use <code>zip</code>. Note also that the <code>bytearray</code> class is very convenient for you because it gives you ints when you iterate over it.</p>\n\n<pre><code>valueList = bytearray.fromhex(stringValue)\nfor messageLocation, byte in zip(mappingList, valueList):\n</code></pre>\n\n<p>I noticed also that you always index the <code>transmitPDOBases</code> and <code>recievePDOs</code> by stringified ints. Perhaps you are not aware that you can just as well use int keys directly. You just have to be consistent because <code>1 != '1'</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:15:16.890", "Id": "33991", "ParentId": "33878", "Score": "2" } } ]
{ "AcceptedAnswerId": "33888", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T19:25:57.167", "Id": "33878", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "PDOMapping: a CAN Open Process Data Object Management Class" }
33878
<p>I'm porting some AVR code from <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html"><code>PROGMEM</code>/<code>PGM_P</code></a> to <a href="http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Named-Address-Spaces.html"><code>__flash</code></a>, and I want to reduce the amount of conditional compilation I need to do in the code.</p> <p>Here's all the code (but keep in mind that only the parts in the conditionals should need changing):</p> <pre><code>#define F_CPU 12000000 #include &lt;avr/io.h&gt; //#undef __FLASH #ifndef __FLASH #include &lt;avr/pgmspace.h&gt; #define FLASH(x) const x PROGMEM #else #define FLASH(x) const __flash x #endif #include &lt;avr/interrupt.h&gt; #include &lt;avr/sleep.h&gt; #define M_CPORT PORTC #define M_CDIR DDRC #define M_C1 PC7 #define M_C2 PC6 #define M_C3 PC5 #define M_C4 PC4 #define M_C5 PC3 #define numCols 5 #define M_RPORT PORTA #define M_RDIR DDRA #define M_R1 PA0 #define M_R2 PA1 #define M_R3 PA2 #define M_R4 PA3 #define M_R5 PA4 #define M_R6 PA5 #define M_R7 PA6 #define numRows 7 // bit values for each row FLASH(unsigned char) rows[] = {_BV(M_R1), _BV(M_R2), _BV(M_R3), _BV(M_R4), _BV(M_R5), _BV(M_R6), _BV(M_R7)}; // byte values for each row of each frame FLASH(unsigned char) letterI[7] = {0x1f, 0x4, 0x4, 0x4, 0x4, 0x4, 0x1f}; ... #ifdef __FLASH const __flash unsigned char const * const __flash sequence[] = { #else unsigned PGM_P const PROGMEM sequence[] = { #endif letterI, ... }; // how long to sustain each row fow, based on the number of dots in the row const unsigned int rowDur[6] = {0, 140, 160, 180, 200, 220}; unsigned char currFrame, currSlice; unsigned char frameBuffer[7]; // optimized routine to count number of 1s in a frame row unsigned char count5Bits(unsigned char v) { asm volatile("clr __tmp_reg__\n\t" "ror %[val]\n\t" "adc __tmp_reg__,__zero_reg__\n\t" "ror %[val]\n\t" "adc __tmp_reg__,__zero_reg__\n\t" "ror %[val]\n\t" "adc __tmp_reg__,__zero_reg__\n\t" "ror %[val]\n\t" "adc __tmp_reg__,__zero_reg__\n\t" "ror %[val]\n\t" "adc __tmp_reg__,__zero_reg__\n\t" "mov %[val], __tmp_reg__" : [val] "=&amp;r" (v) :); return v; } // advance the frame, oring the dots from the next image frame in turn ISR(TIMER1_COMPA_vect) { int r; ++currSlice; #ifdef __FLASH const __flash unsigned char *fPtr = sequence[currFrame]; #else PGM_P fPtr = (PGM_P)pgm_read_word(&amp;(sequence[currFrame])); #endif for (r = numRows; r &gt; -1; --r) { frameBuffer[r] = ((frameBuffer[r] &lt;&lt; 1) | #ifdef __FLASH fPtr[r] #else pgm_read_byte(&amp;(fPtr[r])) #endif &gt;&gt; ((numCols + 1) - currSlice)); } currSlice %= (numCols + 1); if (!currSlice) { ++currFrame; currFrame %= sizeof(sequence) / sizeof(sequence[0]); } } unsigned char currRow; unsigned char rowByte; unsigned char frameRow; // turn on the dots for the current row ISR(TIMER0_OVF_vect) { #ifdef __FLASH rowByte = rows[currRow]; #else rowByte = pgm_read_byte(&amp;(rows[currRow])); #endif frameRow = frameBuffer[currRow]; M_CPORT |= ~(frameRow &lt;&lt; 3); M_RPORT |= rowByte; ++currRow; currRow %= numRows; OCR0A = rowDur[count5Bits(frameBuffer[currRow])]; } // turn off the dots for the current row ISR(TIMER0_COMPA_vect) { M_RPORT = 0; M_CPORT = 0; } int main() { register unsigned char newMCUCR = MCUCR | _BV(JTD); MCUCR = newMCUCR; MCUCR = newMCUCR; // timer 1 for frame advance, CTC mode // OCRA for advance TCCR1A = 0; TCCR1B = (_BV(WGM12) | _BV(CS12) | _BV(CS10)); TIMSK1 = _BV(OCIE1A); OCR1AH = 0x3; OCR1AL = 0x0; //timer 0 for row advance, PWM mode // OVF for advance, OCRA for shutoff TCCR0A = (_BV(WGM01) | _BV(WGM00)); TCCR0B = _BV(CS01); TIMSK0 = (_BV(OCIE0A) | _BV(TOIE0)); OCR0A = 200; M_CDIR |= (_BV(M_C1) | _BV(M_C2) | _BV(M_C3) | _BV(M_C4) | _BV(M_C5)); M_RDIR |= (_BV(M_R1) | _BV(M_R2) | _BV(M_R3) | _BV(M_R4) | _BV(M_R5) | _BV(M_R6) | _BV(M_R7)); set_sleep_mode(SLEEP_MODE_IDLE); sei(); while (1) { sleep_enable(); sleep_cpu(); sleep_disable(); } } </code></pre> <p>Both code paths currently work perfectly, but having a single code path would likely reduce maintenance. I can replace <code>pgm_read_byte</code> with <code>*</code>, but I'm befuddled by both the declaration and access of <code>sequence</code> and the declaration of <code>fPtr</code>, and don't know where I should start with them.</p> <p><strong>EDIT:</strong></p> <p>After a bit of mucking around, here's what I came up with:</p> <pre><code>#ifndef __FLASH #include &lt;avr/pgmspace.h&gt; #define FLASH(x) const x PROGMEM #define FLASH_P(x) const x * const PROGMEM #define FLASH_PR(x, y) (x *)pgm_read_word(&amp;(y)) #else #define FLASH(x) const __flash x #define FLASH_P(x) const __flash x * const __flash #define FLASH_PR(x, y) (y) #define pgm_read_byte(x) *(x) #endif ... FLASH_P(unsigned char) sequence[] = { ... FLASH(unsigned char *) fPtr = FLASH_PR(unsigned char, sequence[currFrame]); </code></pre> <p>Wouldn't mind a sanity check on this though, in case I missed anything.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:08:28.727", "Id": "54353", "Score": "0", "body": "The known alternative to #conditionals is to make a variable and use normal control flow statements. So, I don't understand what you are asking here? The advantage of #conditionals is your code is smaller (important in embedded stuff) - but the disadvantage is that your #conditionals create \"versions\" of your program and you may have unexpected combinations. In this particular case, using normal control flow is going to cause both memory and code size to increase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:15:13.257", "Id": "54356", "Score": "0", "body": "@Jasmine: I'm not looking for an alternative to the conditionals, I'm looking for a way to unify the code in the lower conditionals by using a few macros in the first conditional." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:25:17.807", "Id": "54360", "Score": "1", "body": "Really hard to say much about that, given so much of the code is missing. You could reduce some of this by #define things instead of creating actual types, but that would be super tricky with these alternatives. I do not envy your situation :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:32:53.480", "Id": "54361", "Score": "0", "body": "I agree with Jasmine: you haven't given us enough context to be able to help you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:43:42.887", "Id": "54366", "Score": "1", "body": "@GarethRees: Enjoy." } ]
[ { "body": "<p>A few notes:</p>\n\n<ul>\n<li><p>Your included libraries and definitions at the beginning of your code is not very organized.</p>\n\n<blockquote>\n<pre><code>#include &lt;avr/io.h&gt;\n//#undef __FLASH\n#ifndef __FLASH\n#include &lt;avr/pgmspace.h&gt;\n#define FLASH(x) const x PROGMEM\n#define FLASH_P(x) const x * const PROGMEM\n#define FLASH_PR(x, y) (x *)pgm_read_word(&amp;(y))\n#else\n#define FLASH(x) const __flash x\n#define FLASH_P(x) const __flash x * const __flash\n#define FLASH_PR(x, y) (y)\n#define pgm_read_byte(x) *(x)\n#endif\n#include &lt;avr/interrupt.h&gt;\n#include &lt;avr/sleep.h&gt;\n</code></pre>\n</blockquote>\n\n<p>I would sort it where all of the <code>#include</code>s are at the beginning, then a space, and then all of your preprocessor definitions. Also, I don't like to <code>#include</code> stuff in an <code>#ifndef</code>, just include it. Your compiler will make the proper optimizations if it's not used anyways.</p>\n\n<pre><code>#include &lt;avr/io.h&gt;\n#include &lt;avr/interrupt.h&gt;\n#include &lt;avr/sleep.h&gt;\n#include &lt;avr/pgmspace.h&gt;\n\n#ifndef __FLASH\n#define FLASH(x) const x PROGMEM\n#define FLASH_P(x) const x * const PROGMEM\n#define FLASH_PR(x, y) (x *)pgm_read_word(&amp;(y))\n#else\n#define FLASH(x) const __flash x\n#define FLASH_P(x) const __flash x * const __flash\n#define FLASH_PR(x, y) (y)\n#define pgm_read_byte(x) *(x)\n#endif\n</code></pre></li>\n<li><p>You have a lot of preprocessor conditionals spread throughout your program.</p>\n\n<blockquote>\n<pre><code>#ifdef __FLASH\nconst __flash unsigned char const * const __flash sequence[] = {\n#else\nunsigned PGM_P const PROGMEM sequence[] = {\n#endif\n</code></pre>\n</blockquote>\n\n<p>Another option to this is to have two separate files for the different implementations. This would mean having version-specific implementations of some classes, and switch entire implementations rather than just a few lines here and there. It would clean up your code of all these preprocessor conditionals.</p></li>\n<li><p>You have some preprocessor definitions that aren't capitalized.</p>\n\n<blockquote>\n<pre><code>#define numRows 7\n</code></pre>\n</blockquote>\n\n<p>You should always capitalize <em>all</em> preprocessor definitions.</p>\n\n<pre><code>#define NUMROWS 7\n</code></pre></li>\n<li><p>You use some magic numbers here and there.</p>\n\n<blockquote>\n<pre><code>const unsigned int rowDur[6] = {0, 140, 160, 180, 200, 220};\n</code></pre>\n</blockquote>\n\n<p>You already defined <code>NUMROWS</code>, so you should use it here.</p>\n\n<pre><code>const unsigned int rowDur[NUMROWS - 1] = {0, 140, 160, 180, 200, 220};\n</code></pre></li>\n<li><p>Define variables in your <code>for</code> loops.<sup>(C99)</sup></p>\n\n<pre><code>for (int r = numRows; r &gt; -1; --r)\n</code></pre></li>\n<li><p>Use more comments. If another developer was to take a look at your code, they would have to use a lot of reason and logic to derive what you are trying to do in some places. For longer explanations, put your comments above the tricky statement.</p>\n\n<pre><code>M_CPORT |= ~(frameRow &lt;&lt; 3); // &lt;insert comment here&gt;\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-19T19:34:02.217", "Id": "178167", "Score": "0", "body": "The spread conditionals will fortunately all disappear; that was the point of the exercise in the first place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:12:38.857", "Id": "40852", "ParentId": "33883", "Score": "11" } } ]
{ "AcceptedAnswerId": "40852", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:37:23.400", "Id": "33883", "Score": "8", "Tags": [ "c", "assembly", "type-safety", "embedded" ], "Title": "Embedded conditional code compaction" }
33883
<p>That's an easy one. I just want to calculate the Hamming distance between two strings.</p> <pre><code>function hamming(str1,str2) local distance = 0 -- cannot calculate Hamming distance if strings have different sizes if #str1 ~= #str2 then return false end for i = 1, #str1 do if str1:sub(i,i) ~= str2:sub(i,i) then distance = distance + 1 end end return distance end </code></pre> <p>Maybe the for-loop isn't the most efficient one. I'm not sure. Any improvements?</p>
[]
[ { "body": "<p>There is nothing inefficient about your loop. You are simply counting from <code>1</code> to <code>#str1</code>. Both bounds are known in advance. This is as good as it gets with loops in Lua.</p>\n\n<p>The only improvement I could think of was using <code>string.byte</code> instead of <code>string.sub</code>, avoiding the interning of 1-character substrings. Even then, the difference is negligible, because the overhead of calling a C function (<code>sub</code> or <code>byte</code>) from the interpreter takes most of the CPU time.</p>\n\n<p>Unless you run it under LuaJIT that is. Under LuaJIT, <code>byte</code> will be inlined into the body of the loop (where is consists only of a bounds check + array access) and the string interning (which requires an allocation + hash table lookup) dominates the CPU time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T12:40:56.740", "Id": "33924", "ParentId": "33896", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T02:42:56.790", "Id": "33896", "Score": "2", "Tags": [ "strings", "lua" ], "Title": "Calculating the Hamming distance" }
33896
<p>I am, primarily for learning purposes, working on creating an editor component in C++ with Qt. As a first step, to begin getting familiar with editing a document via <code>QTextCursor</code>, I wrote this function on my subclass of <code>QPlainTextEdit</code> to indent multiple selected lines:</p> <pre><code>void MyEditor::increaseSelectionIndent() { QTextCursor curs = textCursor(); // Do nothing if we don't have a selection. if(!curs.hasSelection()) return; // Get the first and count of lines to indent. int spos = curs.anchor(), epos = curs.position(); if(spos &gt; epos) { int hold = spos; spos = epos; epos = hold; } curs.setPosition(spos, QTextCursor::MoveAnchor); int sblock = curs.block().blockNumber(); curs.setPosition(epos, QTextCursor::MoveAnchor); int eblock = curs.block().blockNumber(); // Do the indent. curs.setPosition(spos, QTextCursor::MoveAnchor); curs.beginEditBlock(); for(int i = 0; i &lt;= (eblock - sblock); ++i) { curs.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); curs.insertText("\t"); curs.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); } curs.endEditBlock(); // Set our cursor's selection to span all of the involved lines. curs.setPosition(spos, QTextCursor::MoveAnchor); curs.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); while(curs.block().blockNumber() &lt; eblock) { curs.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor); } curs.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); // Done! setTextCursor(curs); } </code></pre> <p>I'm interested in any feedback on whether or not I'm following "best practices" with <code>QTextCursor</code> - am I doing anything weird, or that can be simplified or improved?</p>
[]
[ { "body": "<ul>\n<li><p>Some of these comments can be removed:</p>\n\n<p>Too obvious:</p>\n\n<pre><code>// Do nothing if we don't have a selection.\n</code></pre>\n\n<p>Noisy:</p>\n\n<pre><code>// Done!\n</code></pre></li>\n<li><p>These initialized variables:</p>\n\n<pre><code>int spos = curs.anchor(), epos = curs.position();\n</code></pre>\n\n<p>should be on separate lines for better maintenance:</p>\n\n<pre><code>int spos = curs.anchor();\nint epos = curs.position();\n</code></pre></li>\n<li><p>No need to do a manual swap:</p>\n\n<pre><code>if(spos &gt; epos)\n{\n int hold = spos;\n spos = epos;\n epos = hold;\n}\n</code></pre>\n\n<p>Just use <a href=\"http://en.cppreference.com/w/cpp/algorithm/swap\" rel=\"noreferrer\"><code>std::swap</code></a> to keep it idiomatic:</p>\n\n<pre><code>if (spos &gt; epos)\n{\n std::swap(spos, epos);\n}\n</code></pre></li>\n<li><p>No need calculate the difference each time:</p>\n\n<pre><code>for(int i = 0; i &lt;= (eblock - sblock); ++i)\n</code></pre>\n\n<p>Define a constant before the loop and use it instead:</p>\n\n<pre><code>const int blockDifference = eblock - sblock;\n\nfor (int i = 0; i &lt;= blockDifference; ++i)\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-24T16:23:33.463", "Id": "89201", "Score": "0", "body": "Sorry it took me so long to get back to this. This is all great advice. Thanks! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-15T22:49:18.697", "Id": "49893", "ParentId": "33899", "Score": "5" } } ]
{ "AcceptedAnswerId": "49893", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T04:49:58.417", "Id": "33899", "Score": "7", "Tags": [ "c++", "qt" ], "Title": "QPlainTextEdit subclass function to indent lines in selection" }
33899
<p>I have the following constructor</p> <pre><code> /** * @param codePath path to player's code. If ends in '/' it assumes the code is in .class'es in * a directory; otherwise assumes a jar * @throws PlayerException if there is a problem loading the code */ public Player(File codePath) throws PlayerException { if (!codePath.exists() || !codePath.canRead()) { throw new IllegalArgumentException("Path is invalid: " + codePath + ". It can't be read or it doesn't exist"); } if (Thread.currentThread().getPriority() &lt; ROBOTS_MAX_PRIORITY) { throw new PlayerException("Robot priority cannot be greater than game's"); } try { loader = new URLClassLoader(new URL[] { codePath.toURI().toURL() }); InputStream stream = loader.getResourceAsStream(PLAYER_PROPERTIES_FILE); if (stream == null) { throw new PlayerException("Player Specification File not found: " + codePath + "!" + PLAYER_PROPERTIES_FILE); } else { Properties playerInfo = new Properties(); playerInfo.load(stream); // read parameters author = playerInfo.getProperty("Author", "Unknown programmer"); teamName = playerInfo.getProperty("Team", "Unknown team"); robotsThreads = new ThreadGroup(PLAYERS_GROUP, teamName + " Threads"); robotsThreads.setMaxPriority(ROBOTS_MAX_PRIORITY); String banksList = playerInfo.getProperty("Banks"); if (banksList == null) { throw new PlayerException("Error loading configuration property: No banks definition found"); } String[] banksClasses = banksList.split(","); teamId = getNextTeamId(); teamIds.add(teamId); banks = loadBanks(loader, banksClasses); log.info("[Player] Successfully loaded Player: {}. Banks found = {}", this, banksClasses.length); } } catch (ClassCastException | IOException | ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException exc) { closeClassLoader(); throw new PlayerException("Error loading player's code", exc); } catch (PlayerException exc) { closeClassLoader(); throw exc; } } </code></pre> <p>The problem is that the fact that it takes a File makes it hard to test, i don't want to create dummy files. My usual technique is to find what the logic does with the File and then create a constructor that takes that actual object and use that constructor in the unit tests with the original constructor calling the new one. In this case it can be seen that what's needed from the File is the <code>loader</code> so I tried creating a package-protected constructor </p> <pre><code>Player(URLClassLoader pLoader, String codePath) throws PlayerException { .. } //the second parameter is just used for logging </code></pre> <p>However, the problem is that I obviously can't do something like this</p> <pre><code>public Player(File codePath) throws PlayerException, MalformedURLException { if (!codePath.exists() || !codePath.canRead()) { throw new IllegalArgumentException("Path is invalid: " + codePath + ". It can't be read or it doesn't exist"); } this(new URLClassLoader(new URL[] { codePath.toURI().toURL() }), "test"); } </code></pre> <p>i.e. first validate the File and then invoke the other constructor, because <code>this()</code> calls need to be the first in the method. I also tried extracting the initialization code into a separate method that then maybe i could test by itself, but the variables to initialize (<code>author</code>, <code>teamName</code>, etc) are final, so the compiler again complains. I'm trying to leave those variables as final.</p> <p>Can anyone suggest another way to refactor this so that i can test the logic that populates the player's data at least. For the full class <a href="https://github.com/theHilikus/JRoboCom/blob/master/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/Player.java" rel="nofollow">see here</a></p>
[]
[ { "body": "<p>I think you are putting way too much logic in your constructor. The other problem is that you do not want to create dummy files, if so, are there are real files you can make a copy of and test on? If there are no real files either you might actually have to create some real/dummy files.</p>\n\n<p>And if I understand your question you want to test \"the logic\" of the Player class, which is basically invoking and creating a new URLClassLoader, but since this class takes a File as argument you can't invoke it. In that case you could change the argument from a File to a String so the invoke would look something like</p>\n\n<pre><code>public Player(String filePath) {\n this(new URLClassLoader(new URL[] { filePath }), \"test\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:38:01.293", "Id": "54456", "Score": "0", "body": "The reason why i need all that logic in the constructor is because of the stupid rule that you can't initialize final variables outside of the constructor, not even in a _private final_ method.\nAnd no, i don't want to create dummy files, i don't like my unit tests to depend on filesystem stuff, it should all be in memory" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T09:18:36.923", "Id": "33909", "ParentId": "33900", "Score": "1" } }, { "body": "<p>I'm just going to focus on one of your statements:</p>\n\n<blockquote>\n <p>However, the problem is that I obviously can't do something like this:</p>\n</blockquote>\n\n<pre><code>public Player(File codePath) throws PlayerException, MalformedURLException {\n if (!codePath.exists() || !codePath.canRead()) {\n throw new IllegalArgumentException(\"Path is invalid: \" + codePath\n + \". It can't be read or it doesn't exist\");\n }\n this(new URLClassLoader(new URL[] { codePath.toURI().toURL() }), \"test\"); \n}\n</code></pre>\n\n<p>You are right, that's not legal in Java, but there is a relatively common trick to doing this sort of thing (and this trick can sometimes make complicated constructors really quite simple):</p>\n\n<pre><code>private static final URLClassLoader[] fileArgumentHandler(File arg) {\n if (!codePath.exists() || !codePath.canRead()) {\n throw new IllegalArgumentException(\"Path is invalid: \" + codePath\n + \". It can't be read or it doesn't exist\");\n }\n return new URLClassLoader(new URL[]{arg.toURI().toURL()});\n}\n\npublic Player(File codePath) {\n this(fileArgumentHandler(codePath), \"test\");\n}\n</code></pre>\n\n<p>Often in larger projects this type of handling becomes quite regular, and it is common to centralize some of these validation processes in to a 'Utility' class that is reused. This is especially true with unit-testing, and I commonly see something like:</p>\n\n<pre><code>@Test\npublic void testSomeFunction() {\n Player p = newPlayer(UnitTestUtils.fileArgumentHandler(new File(...)));\n} \n</code></pre>\n\n<p>Note that in this case the utility method has moved outside the constructor and is now part of the invocation... but the concept is similar.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:48:03.507", "Id": "54506", "Score": "0", "body": "that's a very nice trick! i will try that tonight" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:11:42.687", "Id": "33958", "ParentId": "33900", "Score": "1" } } ]
{ "AcceptedAnswerId": "33958", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T06:20:21.817", "Id": "33900", "Score": "2", "Tags": [ "java", "unit-testing", "constructor" ], "Title": "Improve testability of constructor" }
33900
<p>I've creating a small library of JavaScript functions that I will be using. Some are for UI functions others are to return something.</p> <p>I am wondering if this method is ok and not a bad move before going any further with this library. Also, please do not mention jQuery as this is all JavaScript!</p> <pre><code>HTMLElement.prototype.drag = function(bool) { var self = this; self.classList.add('draggable'); event.stopPropagation(); event.preventDefault(); var origLeft= parseInt(self.offsetLeft,10); var origTop = parseInt(self.offsetTop,10); var mdX = event.clientX; var mdY = event.clientY; var elements = []; if(bool === true){ var j = window.localStorage.getItem('userSettings'); if(j){ self.style.left= j.left; self.style.top = j.top; } } function drag(bool) { self.style.position="absolute"; self.style.zIndex=999; self.style.left = origLeft + event.clientX - mdX + "px"; self.style.top = origTop + event.clientY - mdY + "px"; event.stopPropagation(); } function stop(bool){ self.classList.remove('draggable'); self.style.zIndex=0; document.removeEventListener('mousemove',drag,true); document.removeEventListener('mouseup',stop,true); if(bool === true){ var settings = { left: self.style.left, top: self.style.top }; var b = JSON.stringify(settings); window.localStorage.setItem('userSettings',b); console.log(b); } event.stopPropagation(); } document.addEventListener('mousemove',drag,true); document.addEventListener('mouseup',stop,true); }; </code></pre> <p>The above code is of course for a <code>draggable</code> function. Here is a <code>getClientRects()</code> sort of function but better:</p> <pre><code>HTMLElement.prototype.getRect = function(){ var a = this.offsetLeft; var b = this.offsetTop; var c = this.offsetHeight + b; var d = this.offsetWidth + a; var f = this.offsetHeight; var g = this.offsetWidth; var obj = { }; obj.left = a; obj.right=d; obj.top=b; obj.bottom=c; obj.width = g; obj.height=f; return obj; }; </code></pre> <p>The purpose of showing you all this is to get your thoughts and maybe advise about prototype or should I not do it this way. I just like the method execution like this:</p> <pre><code>document.getElementById('div').getRect(); </code></pre> <p>instead of doing it with a function <code>getRect('div');</code>.</p> <p>The problem is for one not sure what enumerable is as I've self taught everything, and never really read on the terminology. I know what one of the users means when he says iterating them using a for in loop though not sure how to make it non-enumerable. Nor how to go about this any better way as I don't want my users (who use jQuery a lot) though the library is huge and honestly I'd rather them use a vanilla JavaScript library in the sense that is minimized for purposes of what I am doing (making a huge plug-in with a library and other coding options they can have their hands on).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-10T13:02:58.340", "Id": "183549", "Score": "0", "body": "There is no need to make is enumerable...just use `defineProperty` to add functionality." } ]
[ { "body": "<p>I don't have any insight on extending host objects, because I've never done it, and quite frankly this scares me a little bit.</p>\n\n<p>That said, I can shed a bit of light on that \"enumerable\" problem.</p>\n\n<p>Objects in javascript are traversable, much like arrays. This means that when you do :</p>\n\n<pre><code>var o = {foo: \"bar\", baz: \"buzz\"};\nfor(var property in o){\n console.log(o[property]);\n} \n</code></pre>\n\n<p>you get <code>\"bar\"</code> and <code>\"buzz\"</code> in the console. </p>\n\n<p>Now in a for-in loop, the only properties that you get are those who are enumerable. What does this mean ? Basicly, this means that you only get properties for which <code>o.propertyIsEnumerable('propertyName')</code> is true (and by extension, for which <code>o.hasOwnProperty('propertyName')</code> is true). </p>\n\n<p>When you create a property on an object, by default it is enumerable, and <code>hasOwnProperty</code> returns true for it. But it is possible to define properties with modifiers :</p>\n\n<pre><code> o = {};\n Object.defineProperty(o, 'foo', {\n value: function(){ console.log('foo'); },\n enumerable: false\n });\n\n o.foo(); // \"foo\" \n o.propertyIsEnumerable('foo') // false\n o.hasOwnProperty('foo') // false \n for(property in o){\n console.log(property); // this will never be reached - o has no enumerable property yet\n }\n</code></pre>\n\n<p>One reason to mark certain properties as not enumerable is that when extending an object, one usually copies all enumerable properties from a source object using a for-in loop. When writing a lib, you have to care about this, because if you don't your users will have to deal with properties they probably are not aware of or don't care about.</p>\n\n<p>Also note that every fresh object already has non enumerable properties : <code>prototype</code>, <code>hasOwnProperty</code>, etc...</p>\n\n<p>Hope this helps. For more info, see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow\">Object.defineProperty</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T16:14:20.320", "Id": "54466", "Score": "0", "body": "Ok so I have to use `Object.defineProperty(o` being the object, `foo` being the property of `o` and `value` is the properties value and then `enumerable` `false` makes it non-enumerable. Do I have to do this to each property, hence `defineProperty` and not `defineProperties`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T18:20:50.420", "Id": "54482", "Score": "0", "body": "no, see... [Object.defineProperties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:34:49.183", "Id": "54504", "Score": "0", "body": "Ok thank you, I'll read on it. If all is well then I'll mark this as the accepted answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T04:14:23.600", "Id": "54539", "Score": "0", "body": "I understand now. Though I am now getting in FF something about `property only has a getter` or something like that" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T09:05:42.197", "Id": "33906", "ParentId": "33901", "Score": "1" } }, { "body": "<p>My suggestions on whether to extend native objects or not:</p>\n\n<p>I would not do it. Here are some reasons based on your specific code:</p>\n\n<ul>\n<li><p>Lets say browsers decide to implement their own \"drag\" method in the future. If this happens and your drag function doesn't match theirs, then you'll have the confusing case where your code differs from the standard Javascript interface any other developers know and use. Your code would also be hiding the functionality of the browser's new \"drag\" method, which may be completely different. </p></li>\n<li><p>A problem specific to how you are extending DOM elements: different browsers have different interfaces to the DOM and certain DOM prototypes may not be available in certain browsers. This is described in this article: <a href=\"http://perfectionkills.com/whats-wrong-with-extending-the-dom/\" rel=\"nofollow\">http://perfectionkills.com/whats-wrong-with-extending-the-dom/</a>. For instance, Internet Explorer 7 does not expose DOM elements like Node or Element. Although you are not touching Node or Element, it would be easy to make this mistake if you being extending DOM elements.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-10T13:05:31.343", "Id": "183550", "Score": "1", "body": "your first argument is not an issue since you can check if such functionality is previously declared, then do not proceed with your custom one. Your second argument had more weight in the past, but nowadays things are much more stable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T04:25:49.750", "Id": "34037", "ParentId": "33901", "Score": "1" } } ]
{ "AcceptedAnswerId": "33906", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T06:35:25.703", "Id": "33901", "Score": "0", "Tags": [ "javascript" ], "Title": "Extending DOM elements with prototype for easier function execution" }
33901
<p>I thought to do away with getters and setters behind the real world objects such as <i>Person</i>, <i>Company</i> or <i>Address</i>, i.e. <code>getName</code> and <code>setName</code>.</p> <p>Each of these have <code>public enum Attrib</code> of <a href="https://docs.oracle.com/javase/tutorial/java/concepts/object.html" rel="nofollow">states</a>.</p> <p>And the state is actually a pure <code>Object</code> mapped to a private <code>HashMap</code>.</p> <pre><code>package model; import java.util.HashMap; import java.util.Map; public class Person { public enum Attrib { NAME, //String EMAIL, //String PHONE; //int @Override public String toString() { return name().toLowerCase(); } } private final Map&lt;Person.Attrib, Object&gt; attribs; public Person(String name, String email, int phone) { attribs = new HashMap&lt;&gt;(); attribs.put(Person.Attrib.NAME, name); attribs.put(Person.Attrib.EMAIL, email); attribs.put(Person.Attrib.PHONE, phone); } public Object getAttrib(Person.Attrib attribute) { return attribs.get(attribute); } public boolean setAttrib(Person.Attrib attribute, Object value) { if (attribute == Person.Attrib.PHONE &amp;&amp; !(value instanceof Integer)) { return false; } attribs.put(attribute, value); return true; } @Override public boolean equals(Object o) { if (o instanceof Person) { Person person = (Person) o; String _this = (String) this.getAttrib(Person.Attrib.NAME); String _that = (String) person.getAttrib(Person.Attrib.NAME); return _this.equalsIgnoreCase(_that); } return false; } @Override public int hashCode() { return attribs.get(Person.Attrib.NAME).hashCode(); } @Override public String toString() { return (String) attribs.get(Person.Attrib.NAME); } } </code></pre> <p>I did saved some getters and setters but I guess it can't justify that all attributes are objects. To check what <code>instanceof</code> the <code>getAttrib(Person.Attrib attribute)</code> is, i.e. skim the class source to know whether you deal with a <code>String</code> or an <code>Integer</code> or <code>Whatever</code>, type cast it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T14:28:18.290", "Id": "54444", "Score": "10", "body": "`public int phone;` is, IMO, a Very Bad Thing. If you're not doing math with it, use a string, Full Stop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:13:21.367", "Id": "54450", "Score": "5", "body": "Sometimes you will need a leading 0 or sometimes double 0 (00) to dial some numbers, which will be lost with an integer representation. In some (rarer) case you may need \",\" to temporize between some numbers, too. And an integer will be less human-readable (and there are several ways to group numbers, depending on the country and if it's a local or inter-country call, so you can't 'guess' it from the integer value). Finally, as pointed out by 200_success, the numbers would be limited to the integer range, and this could be not enough. All good reasons that you can't use integer representation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:20:32.393", "Id": "54452", "Score": "2", "body": "@olivier a leading 0 also gets turned into octal, so you've got that to deal with as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T17:12:00.787", "Id": "54478", "Score": "0", "body": "@mikeTheLiar: yes, another (of possibly many more) reason not to use integer ^^" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T13:25:53.740", "Id": "54587", "Score": "0", "body": "what's bugging me more than anything else is `name.toLowerCase()` for the `enum Attrib` `toString()` method. Horribly inefficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:47:37.510", "Id": "54648", "Score": "0", "body": "You'll have to live with that :) this is the way it's usually done in java, although everybody knows it's verbose and not really necessary. For alternatives you may consider Groovy or syntactic sugar libraries such as Lombok" } ]
[ { "body": "<p>You are right, this is not recommended practice. In your case, you need to know how the internals of the Person class works in order to use it effectively. As much as getters and setters appear to be clutter, they actually create a protocol, standard, and convenient system that you can take for granted. It is helps for everything from code readability (not necessarily this Person class, but the code that uses the Person class), to code maintainability, and even code generation.</p>\n\n<p>Because getters and setters are such a common, simple, and reliable pattern the Java IDE's often make things really simple. For example, if I code your class in Eclipse, I would do the following:</p>\n\n<pre><code>public class Person {\n private String name;\n private String email;\n private int phone;\n // I create an empty line here....\n}\n</code></pre>\n\n<p>Then I would type <kbd>Alt</kbd>-<kbd>Shift</kbd>-<kbd>S</kbd> and select 'Create Constructor Using Fields...' and hit <kbd>enter</kbd>, then I would type <kbd>Ctrl</kbd>-<kbd>Shift</kbd>-<kbd>S</kbd> again and select 'Generate Getters and Setters...' and I would hit 'Select All' and then enter. This is the result:</p>\n\n<pre><code>public class Person {\n private String name;\n private String email;\n private int phone;\n public Person(String name, String email, int phone) {\n super();\n this.name = name;\n this.email = email;\n this.phone = phone;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getEmail() {\n return email;\n }\n public void setEmail(String email) {\n this.email = email;\n }\n public int getPhone() {\n return phone;\n }\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\n}\n</code></pre>\n\n<p>It took 20 seconds or less.</p>\n\n<p>Saving time and convenience is not an excuse.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:38:41.613", "Id": "33920", "ParentId": "33914", "Score": "13" } }, { "body": "<p>As you observed, casting within your implementation of <code>setAttribute()</code> is ugly. Worse than that, returning <code>Object</code> from <code>getAttribute()</code> is horrible — you've given up all type safety. In a loosely typed language, that would just be business as usual. However, in Java, the caller would have to cast the result (cumbersome and a potential source of bugs) or just treat it as an opaque <code>Object</code> (spreading the nastiness throughout the program).</p>\n\n<p>Are you sure that you want to represent phone numbers as integers? You would only get 9 digits reliably. That's not enough to hold, say, an American phone number including the area code, which would be 10 digits. Not to mention, you may need country codes, extension numbers, and spaces or punctuation for readability. A string may be more appropriate after all.</p>\n\n<p>Now, suppose that you just store all three attributes as strings, which eliminates the type safety issue. What if you want to implement validation within <code>setAttribute()</code>? You would end up putting in a <code>switch</code>, which would defeat any code savings you have achieved by doing this instead of implementing a separate setter for each attribute.</p>\n\n<p>In summary, this is a bad idea, unless you had a requirement to associate many obscure or arbitrary attributes with a person (e.g. pet, priest, etc.). In that case, you would implement something more elaborate, such as</p>\n\n<pre><code>public abstract class ModelEntity {\n public String getAttribute(String attrname);\n public void setAttribute(String attrname, String value) throws ValidationException;\n public ModelEntity getRelationship(String relname);\n public void setRelationship(String relname, ModelEntity obj) throws ValidationException;\n}\n\npublic class Person extends ModelEntity {\n ...\n}\n\npublic class Pet extends ModelEntity {\n ...\n}\n</code></pre>\n\n<p>… but you would be doing that out of necessity, not out of laziness. If you really wanted to be sloppy and lazy, you might as well publicly expose the <code>Person</code>'s instance variables (not that I'm recommending that at all!).</p>\n\n<hr>\n\n<p>Returning <code>false</code> to indicate validation failure is poor design. I would throw an exception to force the caller to deal with it.</p>\n\n<p>Your <code>hashCode()</code> and <code>equals()</code> methods need to be consistent. If your <code>equals()</code> compares names case insensitively, then your <code>hashCode()</code> should also squash the name to lowercase.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:11:13.187", "Id": "54449", "Score": "1", "body": "@paveljurca: as 200_success points out, integer to represent numbers is bad. Sometimes you will need a leading 0 or sometimes double 0 (00) to dial some numbers, which will be lost with an integer representation..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T20:43:12.217", "Id": "54492", "Score": "2", "body": "@OlivierDulac I do hope you mean **phone**numbers. \"Integer to represent numbers is bad\" is a bit overkill. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:47:14.690", "Id": "54534", "Score": "0", "body": "Good answer. I would add that this approach makes unit testing extremely difficult as setAttribute and getAttribute will have potentially hundreds of code paths that cannot be broken down." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T08:12:16.693", "Id": "54546", "Score": "2", "body": "@SimonAndréForsberg: you did made me laugh ^^ ... However the context (answer + my following sentence stating \"to dial some numbers\" made it clear ;) I also didn't precise \"in your program\" \"at the current technology level and on this planet\", etc... So many things could change the whole thing! It's mind boggling. In any sentence we *have* to accept that there always will be assumtions about a \"common context\" that goes uncited ^^ [that's what makes citations so different depending on who uses them and where they cut the sentences ^^]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:01:30.470", "Id": "54776", "Score": "0", "body": "Good answer. Apart from all point mentioned; Regular getters/setters will be understandable by other developers looking at the code, whereas the code of the OP will be confusing and take time to understand, which will make the code confusing and may lead to bugs." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:58:27.907", "Id": "33922", "ParentId": "33914", "Score": "19" } }, { "body": "<p>I think, <strong>you don't save any work</strong> to users of your class <code>Person</code>: The <code>setAttrib</code> method needs a further literal argument, which is only a pseudo-argument, and each time calling the <code>getAttrib</code> method, a cast is needed with all its downsides.</p>\n\n<p>Obviously, you also don't save any work for maintainers of this class, because its structure is much more complicated than the every-day getter and setter approach. </p>\n\n<p>Maybe the following would be an option (this is how I always imagined POJOs):</p>\n\n<pre><code>public class Person {\n public String name;\n public String email;\n public int phone;\n public Person() {}\n}\n</code></pre>\n\n<p>maybe not:</p>\n\n<blockquote>\n <p><a href=\"https://stackoverflow.com/q/7455630/2932052\">Is it necessary to have getters and setters in POJO's</a></p>\n</blockquote>\n\n<p>I'm no java programmer (but I'd discourage such \"mutli-methods\" even from a C/C++ POV) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:46:48.503", "Id": "54581", "Score": "0", "body": "Making all fields public is **very bad idea**. You can't make any validation when someone is changing the value of any field. Actually setters-getters are not only for encapsulation but for also data-safety. [Further reading](http://stackoverflow.com/questions/565095/are-getters-and-setters-poor-design) and get over it C/C++ != Java" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T12:48:05.250", "Id": "33926", "ParentId": "33914", "Score": "3" } }, { "body": "<p>As other people have pointed out, this is probably a bad idea. There are some instances where attribute specifiers have a legitimate role, and in such cases, you can get type-checked attributes using generics like this:</p>\n\n<pre><code>public class Person {\n\n public static class Attrib&lt;U&gt;{\n private Attrib() {}\n }\n public static final Attrib&lt;String&gt; NAME = new Attrib&lt;&gt;();\n public static final Attrib&lt;String&gt; EMAIL = new Attrib&lt;&gt;();\n public static final Attrib&lt;Integer&gt; PHONE = new Attrib&lt;&gt;();\n\n private final Map&lt;Attrib, Object&gt; attribs;\n\n public Person(String name, String email, int phone) {\n attribs = new HashMap&lt;&gt;();\n attribs.put(NAME, name);\n attribs.put(EMAIL, email);\n attribs.put(PHONE, phone);\n }\n\n public &lt;U&gt; U getAttrib(Attrib&lt;U&gt; attribute) {\n return (U) attribs.get(attribute);\n }\n\n public &lt;U&gt; void setAttrib(Attrib&lt;U&gt; attribute, U value) {\n attribs.put(attribute, value);\n }\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:57:03.440", "Id": "33960", "ParentId": "33914", "Score": "2" } }, { "body": "<p>Let's take your idea to the extreme. You want to get rid of specific getters and setters? Heck, why not get rid of specific classes too? Everything generic.</p>\n\n<p>So instead of </p>\n\n<pre><code>Person person = new Person();\nperson.setAttribute(Person.Attribute.EMAIL, \"john.doe@test.com\");\n</code></pre>\n\n<p>why not have</p>\n\n<pre><code>Thing thing = new Thing(Thing.Type.PERSON);\nthing.setAttribute(Person.Attribute.EMAIL, \"john.doe@test.com\");\n</code></pre>\n\n<p>Hey look I just got rid of all those useless classes and replaced them with one generic class, Thing. WOW! Why didn't anyone think of this before? Maybe I can replace ALL of my classes like this!!!</p>\n\n<p>Obviously this is ridiculous. At some point, someone has to declare that certain things that have certain behavior, can only have certain attributes, and that the attributes conform to certain rules. That is how we define the system in code. </p>\n\n<p>The way we do this is by defining classes for the different things and properties for the attributes. And when we do that, we benefit from things like inheritance, composition, type safety, etc.</p>\n\n<p>If you get rid of all that, you... well... get rid of all that. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:45:42.793", "Id": "33967", "ParentId": "33914", "Score": "2" } } ]
{ "AcceptedAnswerId": "33922", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T10:53:31.107", "Id": "33914", "Score": "8", "Tags": [ "java", "beginner" ], "Title": "Getters and setters in a Person class" }
33914
<p>GPGPU is the use of graphics processing units for general-purpose computing, usually to exploit the GPU's ability to perform parallel computations on multiple data inputs.</p> <p>Related tag: <a href="/questions/tagged/simd" class="post-tag" title="show questions tagged &#39;simd&#39;" rel="tag">simd</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:01:42.517", "Id": "33915", "Score": "0", "Tags": null, "Title": null }
33915
General-purpose computing on graphics processing units
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:01:42.517", "Id": "33916", "Score": "0", "Tags": null, "Title": null }
33916
<p>I'm creating a Python API client, after thinking and checking some open source Python clients I created this class, and I'm looking for any feedback (design, best practices...), this is an example URL of the API:</p> <blockquote> <pre><code>https://www.api.com/collection/resource.json?userid=id&amp;key=apikey&amp;command=value </code></pre> </blockquote> <p>Here's my class using the <a href="http://www.python-requests.org/" rel="nofollow">requests library</a>:</p> <pre><code>import requests class APIClient(object): """Creates an API client object :param userid: the API userid found in the control panel :param api_key: the API key found in the control panel Settings &gt; API """ def __init__(self, userid=None, api_key=None): # userid and api key sent with every request self.userid = userid self.key = api_key # the base production api url self.base_url = None # the sandbox api url self.test_url = None # boolean value to indicate which url to use self.testing = False # the error description if it occured self.error = None def request(self, method='GET', path=None, params=None): """Makes a request to the API with the given parameters :param method: the HTTP method to use :param path: the api path to request :param params: the parameters to be sent """ # if we're testing use the sandbox url api_url = self.test_url if self.testing else self.base_url # add the authentication parameters (sent with every request) params.update({ 'userid': self.userid, 'key': self.key }) # the api request result result = None try: # send a request to the api server r = requests.request( method = method, url = api_url + path + '.json', params = params, headers = {'User-Agent': 'Python API Client'} ) # raise an exception if status code is not 200 if r.status_code is not 200: raise Exception else: result = r.json() except requests.ConnectionError: self.error = 'API connection error.' except requests.HTTPError: self.error = 'An HTTP error occurred.' except requests.Timeout: self.error = 'Request timed out.' except Exception: self.error = 'An unexpected error occurred.' return result </code></pre> <p>And here's a usage example:</p> <pre><code>from api import APIClient # create the client api = APIClient() # authentication api.userid = '123456' api.key = '0tKk8fAyHTlUv' # api urls api.base_url = 'https://api.com/' api.test_url = 'https://test.api.com/' # api in testing mode api.testing = True # create a request r = api.request( method = 'GET', # this will be appended to the base or test url and add .json at the end path = 'collection/resource', params = { 'string-command': 'string', 'list-command': ['a', 'b', 'c'], 'boolean-command': False } ) # how can I improve the way I get the API result and the error checking ? # I currently use: if api.error: print api.error else: print r # what about using something like ?: if api.request.ok: print api.request.result else: print api.request.error </code></pre> <p>My questions are:</p> <ul> <li>Is this a good design for use in a website, and is it safe for multiple requests?</li> <li>Should I store the API result in a property <code>api.result</code> instead of returning it when calling <code>api.request()</code>?</li> <li>How can I improve the way I get the API result? Is the second example better?</li> <li>How can I improve my code?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T22:23:12.400", "Id": "56892", "Score": "0", "body": "Look at this package: https://github.com/olegpidsadnyi/restart" } ]
[ { "body": "<ol>\n<li><p>Python has a mechanism for handling exceptional situations, but you go to great lengths to suppress it: you catch all the exceptions that might result from your <code>request</code> method and replace them with a string in the <code>.error</code> property of the <code>APIClient</code> object.</p>\n\n<p>This has several problems.</p>\n\n<p>First, it needlessly complicates every API call. A caller can't just write:</p>\n\n<pre><code>r = api.request(...) # might raise an exception\ndo_something_with(r)\n</code></pre>\n\n<p>allowing exceptions to pass up the call stack and so eventually appear on the console or in the log. Instead, they have to write:</p>\n\n<pre><code>api.error = None # clear the old error, if any\nr = api.request(...) # might set api.error\nif api.error:\n # handle the error somehow\nelse:\n do_something_with(r)\n</code></pre>\n\n<p>This means that <em>every call to your API</em> needs to consider how to handle errors. What are programmers going to do? Well, mostly likely they will <em>raise</em> these errors:</p>\n\n<pre><code>api.error = None # clear the old error, if any\nr = api.request(...) # might set api.error\nif api.error:\n raise MyError(\"API error: {}\".format(api.error))\nelse:\n do_something_with(r)\n</code></pre>\n\n<p>So why bother suppressing these errors in your API in the first place?</p>\n\n<p>Second, you replace all exceptions that you don't recognize with <code>An unexpected error occurred.</code> So this makes it impossible to distinguish a <code>ProxyError</code> from a <code>TooManyRedirects</code> from an <code>SSLError</code>.</p>\n\n<p>Third, you lose information that was present in the exception objects. For example, an <code>SSLError</code> comes with a description of the problem, for example if the certificate doesn't match the domain, you'll get an error like this:</p>\n\n<pre><code>requests.exceptions.SSLError: hostname 'foo.com' doesn't match 'bar.com'\n</code></pre>\n\n<p>This kind of information is vital in tracking down the cause of problems. But you replace this with <code>An unexpected error occurred</code> which is, frankly, useless.</p></li>\n<li><p>If the status code is not 200, you:</p>\n\n<pre><code>raise Exception\n</code></pre>\n\n<p>Which has three problems: (i) you should raise an <em>instance</em> of an exception class, not the class itself; (ii) you should initialize the exception object with data that describes the exception; and (iii) the class <a href=\"http://docs.python.org/3/library/exceptions.html#Exception\"><code>Exception</code></a> is supposed to be the <em>root of the class hierarchy</em> for \"built-in, non-system-exiting exceptions\" and user exceptions. You shouldn't raise <code>Exception</code> itself, but instead derive a specific exception class and raise an instance of that. So here you would need something like:</p>\n\n<pre><code>class HTTPError(Exception): pass\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>raise HTTPError('Status code {}'.format(r.status_code))\n</code></pre>\n\n<p>But in fact the <code>requests</code> module <a href=\"http://www.python-requests.org/en/latest/user/quickstart/#response-status-codes\">already has a function</a> for doing this, so all you need to do is:</p>\n\n<pre><code>r.raise_for_status()\n</code></pre></li>\n<li><p>Your interface for setting API parameters is to set them directly as properties of the API object:</p>\n\n<pre><code>api = APIClient()\napi.userid = '123456'\napi.key = '0tKk8fAyHTlUv'\napi.base_url = 'https://api.com/'\napi.test_url = 'https://test.api.com/'\napi.testing = True\n</code></pre>\n\n<p>It would be better for the constructor to take these as keyword arguments: (i) this allows the constructor to check that all required parameters have been set; (ii) parameter values can be checked (if possible); and (iii) the keyword argument mechanism is more flexible than object properties since you can pass a sets of keywords around in the form of a dictionary. So I would expect to write:</p>\n\n<pre><code>api = APIClient(userid = '123456',\n key = '0tKk8fAyHTlUv',\n base_url = 'https://api.com/',\n test_url = 'https://test.api.com/',\n testing = True)\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T11:27:16.390", "Id": "54806", "Score": "0", "body": "Thank you very much for the details, but about the exceptions, I'm suppressing the errors because I wanted to show these messages only to the users of the website, I don't want to print all the errors although I want to log all of them, so should I keep suppressing the exceptions or call `api.request()` in a try/except block ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T11:46:48.527", "Id": "54809", "Score": "1", "body": "Deciding how to handle exceptions should be up to the *caller* of the API, not up to the API itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-31T19:15:01.753", "Id": "291548", "Score": "0", "body": "Nice explanation, but i did't completely understood error handling part. Do you mean he should have only used one `raise HTTPError('Status code {}'.format(r.status_code))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-31T19:16:09.763", "Id": "291549", "Score": "0", "body": "And what is the good way to deal with validation errors" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:24:11.943", "Id": "34071", "ParentId": "33919", "Score": "8" } } ]
{ "AcceptedAnswerId": "34071", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:32:40.693", "Id": "33919", "Score": "5", "Tags": [ "python", "http" ], "Title": "Python API client" }
33919
<p>I have written this Pseudo-Code for the following program, I'm wondering if this might be descriptive enough for anyone to follow up and perform more or less the same program. The program reads and analyzes a set of data in a text file, then displays the information in a filtered way. Any improvements/ revision would be immensely appreciated.</p> <p>PseudoCode:</p> <ol> <li>Module main ()</li> <li>//Set up format for text reading.</li> <li>Declare String content</li> <li>//Open and read file</li> <li>Open “Data.txt”</li> <li>Set contents = opened “Data.txt”</li> <li> <ol> <li>//Declare an array to store and split data</li> </ol></li> <li>Declare string rows[] = contents split to lines</li> <li>Declare string table [][] = length of rows[]</li> <li> <ol> <li>//Set loop to iterate through all values</li> </ol></li> <li>For i is 0 less than length of rows</li> <li>Table[] increments by 1</li> <li>End for</li> <li>//Declare arras to select and parse info</li> <li>[]districts integer = integer [length of rows]</li> <li>[] ages integer = integer [length of rows]</li> <li>For i is 0, i is less than length of rows</li> <li>i increments by 1</li> <li>Set i of districts to integer parsing with position [i] in table[]</li> <li>Set i of ages to integer parsing with position [i] in table[]</li> <li>End for</li> <li>// Analyze and pass data</li> <li>Foreach integer in district</li> <li>Display “district {0} has {1} resident”, district, countofdistrict.</li> <li>Display “ Agegroup1 has {0} residents”, count of ages (restriction)</li> <li>Display “Agegroup2 has {0} residents”, count of ages (restriction)</li> <li>Display “ Agegroup3 has {0} residents”, count of ages (restriction)</li> <li>Display “ Agegroup4 has {0} residents”, count of ages (restriction)</li> <li>Display “ Agegroup5 has {0} residents”, count of ages (restriction)</li> <li>End foreach</li> </ol> <p>Program:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Project_2_practice { class Program { static void Main(string[] args) { //Parsing data into memory string content; using (StreamReader reader = new StreamReader(File.Open("Data.txt", FileMode.Open))) { content = reader.ReadToEnd(); } string[] rows = content.Split('\n'); //Each row is on a new line string[][] table = new string[rows.Length][]; for (int i = 0; i &lt; rows.Length; table[i] = rows[i].Split(','), i++) ; //selecting information int[] districts = new int[rows.Length]; int[] ages = new int[rows.Length]; for (int i = 0; i &lt; rows.Length; i++) { districts[i] = int.Parse(table[i][3]); ages[i] = int.Parse(table[i][0]); } //Analyzing selected information foreach (int district in districts.Distinct().OrderBy(x =&gt; x)) Console.WriteLine("District {0} has {1} resident(s)", district, districts.Count(x =&gt; x == district)); Console.WriteLine("Ages 0-18 : {0} resident(s)", ages.Count(x =&gt; x &lt; 18)); Console.WriteLine("Ages 18-30 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 18 &amp;&amp; x &lt;= 30)); Console.WriteLine("Ages 31-45 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 31 &amp;&amp; x &lt;= 45)); Console.WriteLine("Ages 46-64 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 46 &amp;&amp; x &lt;= 64)); Console.WriteLine("Ages &gt;=65 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 65)); } } } </code></pre>
[]
[ { "body": "<p>When it comes to pseudo-code there are different standards depending on your organization, target group, etc, but here is my input:</p>\n\n<p>The comments in your pseudo-code are redundant.</p>\n\n<p>17 and 18 should be merged.</p>\n\n<p>Variable declaration (such as <em>3. Declare String content</em>) are not needed.</p>\n\n<p>Not sure if every Console.WriteLine() is needed. This could be replaced with something like \"Display data regarding Agegroup\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:33:36.967", "Id": "54643", "Score": "2", "body": "+1 for \"comments ... redundant\". The whole point of pseudo code is to maximize communication/understanding necessarily by sacrificing <your language here> correct syntax, language-driven structure and idioms, and compile-ability." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T12:43:24.237", "Id": "33925", "ParentId": "33923", "Score": "1" } }, { "body": "<p>I have a suggestion for the program itself: why are you iterating over the data twice?</p>\n\n<pre><code>for (int i = 0; i &lt; rows.Length; table[i] = rows[i].Split(','), i++) ;\n</code></pre>\n\n<p>And</p>\n\n<pre><code>for (int i = 0; i &lt; rows.Length; i++)\n {\n districts[i] = int.Parse(table[i][3]);\n ages[i] = int.Parse(table[i][0]);\n } \n</code></pre>\n\n<p>Why bother with having table be a two dimensional array when it is just a stop-gap collection to get you to ages and districts? Why not just do something like this:</p>\n\n<pre><code>string[] rows = content.Split('\\n'); //Each row is on a new line\nint[] districts = new int[rows.Length];\nint[] ages = new int[rows.Length];\nstring[] currentRow;\n\nfor (int i = 0; i &lt; rows.Length; i++)\n{\n currentRow = rows[i].Split(',');\n districts[i] = int.Parse(currentRow[3]);\n ages[i] = int.Parse(currentRow[0]);\n}\n</code></pre>\n\n<p>Additionally, depending on the size of your data set, why do five different Count() executions on ages when you could just group that data before hand like this:</p>\n\n<pre><code>var ageRanges = new []{17, 30, 45, 64};\n\nvar groupedAges = ages.GroupBy(a =&gt; ageRanges.FirstOrDefault(r =&gt; r &gt;= a));\n\nfor (var i = 0; i &lt; ageRanges.Length; i++)\n{\n var grp = groupedAges.FirstOrDefault (a =&gt; a.Key == ageRanges[i]);\n var count = grp == null ? 0 : grp.Count();\n Console.WriteLine(string.Format(\"Ages {0}-{1} : {2} residents\", i == 0 ? 0 : ageRanges[i-1]+1, i == 0 ? ageRanges[i] + 1 : ageRanges[i], count));\n}\nConsole.WriteLine(string.Format(\"Ages &gt;= 65 : {0} residents\", groupedAges.Count(g =&gt; g.Key == 0)));\n</code></pre>\n\n<p>Admittedly, the logic inside the loop for display purposes is a little hairy since you have different criteria (less than as opposed to less/greater than or equal) for the first age range, but that cuts down on the operations you need to do on the set of data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T15:56:54.843", "Id": "34006", "ParentId": "33923", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T12:09:37.960", "Id": "33923", "Score": "0", "Tags": [ "c#" ], "Title": "C# Pseudo-Code improvement/peer revision" }
33923
<p>I am fairly new to programming and I am having difficulty modulating the following code.</p> <p>The program reads a file, selects certain requirements, and displays them. I have tried to use passing arrays as arguments or functions as indicated in my textbook. I have been using examples such as <code>int getAges(int array[], integer)</code>. </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Project_2_practice { class Program { static void Main(string[] args) { //Parsing data into memory string content; using (StreamReader reader = new StreamReader(File.Open("Data.txt", FileMode.Open))) { content = reader.ReadToEnd(); } string[] rows = content.Split('\n'); //Each row is on a new line string[][] table = new string[rows.Length][]; for (int i = 0; i &lt; rows.Length; table[i] = rows[i].Split(','), i++) ; //selecting information int[] districts = new int[rows.Length]; int[] ages = new int[rows.Length]; for (int i = 0; i &lt; rows.Length; i++) { districts[i] = int.Parse(table[i][3]); ages[i] = int.Parse(table[i][0]); } //Analyzing selected information foreach (int district in districts.Distinct().OrderBy(x =&gt; x)) Console.WriteLine("District {0} has {1} resident(s)", district, districts.Count(x =&gt; x == district)); Console.WriteLine("Ages 0-18 : {0} resident(s)", ages.Count(x =&gt; x &lt; 18)); Console.WriteLine("Ages 18-30 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 18 &amp;&amp; x &lt;= 30)); Console.WriteLine("Ages 31-45 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 31 &amp;&amp; x &lt;= 45)); Console.WriteLine("Ages 46-64 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 46 &amp;&amp; x &lt;= 64)); Console.WriteLine("Ages &gt;=65 : {0} resident(s)", ages.Count(x =&gt; x &gt;= 65)); } } } </code></pre>
[]
[ { "body": "<p>Here's how I would do it. </p>\n\n<p>Update: I included a description of my code this time based on comments. </p>\n\n<p>First, reading a file into a variable so that each line of the file is its own element in an array is super easy with File.ReadAllLines(...). But I don't feel like using a variable for that is necessary here, so I immediately start using the array by using the Select(...) method. I'm using Select here to create an anonymous type (That's the <strong>return new { ... }</strong> part). </p>\n\n<pre><code>var data = File.ReadAllLines(@\"c:\\temp\\data.txt\").Select (f =&gt; \n{\n var split = f.Split(',');\n return new { \n Age = int.Parse(split[0]),\n District = split[3]\n };\n});\n</code></pre>\n\n<p>At this point, I've got a type-safe collection of \"data\" that I can work with. That's important, and very useful. For example.. </p>\n\n<pre><code>var byDistrict = data.GroupBy (d =&gt; d.District);\n</code></pre>\n\n<p>In the line above, I've grouped the data by District. Grouping is, in my opinion, almost always better than using Distinct. </p>\n\n<p>The rest of the code is very similar to your original code, except my code avoids the need to have the age reports within a loop. </p>\n\n<pre><code>foreach (var district in byDistrict)\n{\n Console.WriteLine(\"District {0} has {1} resident(s)\", district.Key, district.Count());\n\n}\n\nConsole.WriteLine(\"Ages 0-18 : {0} resident(s)\", data.Count(x =&gt; x.Age &lt; 18));\nConsole.WriteLine(\"Ages 18-30 : {0} resident(s)\", data.Count(x =&gt; x.Age &gt;= 18 &amp;&amp; x.Age &lt;= 30));\nConsole.WriteLine(\"Ages 31-45 : {0} resident(s)\", data.Count(x =&gt; x.Age &gt;= 31 &amp;&amp; x.Age &lt;= 45));\nConsole.WriteLine(\"Ages 46-64 : {0} resident(s)\", data.Count(x =&gt; x.Age &gt;= 46 &amp;&amp; x.Age &lt;= 64));\nConsole.WriteLine(\"Ages &gt;=65 : {0} resident(s)\", data.Count(x =&gt; x.Age &gt;= 65));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:55:44.453", "Id": "54461", "Score": "0", "body": "would you please explain your code? Code Only answers are frowned upon on Code Review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T16:06:04.980", "Id": "54465", "Score": "0", "body": "Sorry. Fairly new to Code Review. But I really love this site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T16:32:45.310", "Id": "54470", "Score": "0", "body": "it's all good, thank you for editing your answer. +1" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T13:40:24.103", "Id": "33931", "ParentId": "33928", "Score": "3" } }, { "body": "<p>I feel as though you are looking at how to really understand the code and how to separate it out into functions and still have all the variables working and all that.\nI rewrote it a bit to show how to use different functions with and without return values, with variables passed in, using global variables, and passing in variables by reference.\nTake a look.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\n\nnamespace Project_2_practice\n{\n class Program\n {\n static string[][] table;\n static void Main(string[] args)\n {\n\n //Parsing data into memory\n string[] rows = ReadLines(\"Data.txt\");\n table = new string[rows.Length][];\n PopulateTable(rows);\n\n //selecting information\n int[] districts = new int[rows.Length];\n int[] ages = new int[rows.Length];\n PopulateArrays(ref districts, ref ages, rows.Length);\n\n\n //Analyzing selected information\n DisplayResults(districts, ages);\n }\n /// &lt;summary&gt;\n /// Read file into memory\n /// &lt;/summary&gt;\n /// &lt;param name=\"file\"&gt;string filepath&lt;/param&gt;\n /// &lt;returns&gt;array of lines in file&lt;/returns&gt;\n private static string[] ReadLines(string file)\n {\n return File.ReadAllLines(file);\n }\n /// &lt;summary&gt;\n /// Populates a table with split values from the string\n /// &lt;/summary&gt;\n /// &lt;param name=\"rows\"&gt;array of strings to split&lt;/param&gt;\n private static void PopulateTable(string[] rows)\n {\n for (int i = 0; i &lt; rows.Length; table[i] = rows[i].Split(','), i++) ;\n }\n /// &lt;summary&gt;\n /// Populates 2 arrays by reference with values from the table variable\n /// &lt;/summary&gt;\n /// &lt;param name=\"districts\"&gt;int array&lt;/param&gt;\n /// &lt;param name=\"ages\"&gt;int array&lt;/param&gt;\n /// &lt;param name=\"length\"&gt;int length of table&lt;/param&gt;\n private static void PopulateArrays(ref int[] districts, ref int[] ages, int length)\n {\n for (int i = 0; i &lt; length; i++)\n {\n districts[i] = int.Parse(table[i][3]);\n ages[i] = int.Parse(table[i][0]);\n }\n }\n /// &lt;summary&gt;\n /// Writes values to console for displaying results\n /// &lt;/summary&gt;\n /// &lt;param name=\"districts\"&gt;int array of districts&lt;/param&gt;\n /// &lt;param name=\"ages\"&gt;int array of ages&lt;/param&gt;\n private static void DisplayResults(int[] districts, int[] ages)\n {\n foreach (int district in districts.Distinct().OrderBy(x =&gt; x))\n {\n Console.WriteLine(\"District {0} has {1} resident(s)\", district, districts.Count(x =&gt; x == district));\n }\n Console.WriteLine(\"Ages 0-18 : {0} resident(s)\", ages.Count(x =&gt; x &lt; 18));\n Console.WriteLine(\"Ages 18-30 : {0} resident(s)\", ages.Count(x =&gt; x &gt;= 18 &amp;&amp; x &lt;= 30));\n Console.WriteLine(\"Ages 31-45 : {0} resident(s)\", ages.Count(x =&gt; x &gt;= 31 &amp;&amp; x &lt;= 45));\n Console.WriteLine(\"Ages 46-64 : {0} resident(s)\", ages.Count(x =&gt; x &gt;= 46 &amp;&amp; x &lt;= 64));\n Console.WriteLine(\"Ages &gt;=65 : {0} resident(s)\", ages.Count(x =&gt; x &gt;= 65));\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:15:48.260", "Id": "54451", "Score": "0", "body": "thank you very much for this insight! this is exactly what I wanted to see if it was possible, however your code doesn't compile, it seems that the errors marked in visual studio are that static string[] contentLines;\n static string[][] table; are not used" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:24:04.733", "Id": "54453", "Score": "0", "body": "You are right, I am going to edit my answer to fix those.\nI erroneously created a local variable named table as well as the global one so that caused the code to fail.\nAlso, I just removed the contentLines var as it's not needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:47:57.020", "Id": "54458", "Score": "1", "body": "thank you I see how everything comes together, this is pretty interesting. Thanks for making me understand Kemo Sabe!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:48:37.520", "Id": "54459", "Score": "1", "body": "Glad to help :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T14:50:44.690", "Id": "33937", "ParentId": "33928", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T13:14:26.720", "Id": "33928", "Score": "2", "Tags": [ "c#", "array", "beginner", "modules" ], "Title": "Finding correct format? Arrays and Modulation" }
33928
<p>Am I making good use of a 2-D array? Is this code inefficient? I am supposed to receive input from 6 departments for 4 quarterly periods in Java.</p> <p>My assignment asks:</p> <blockquote> <p><strong>Quarterly Sales Statistics</strong></p> <p>Write a program that lets the user enter four quarterly sales figures for six divisions of a company. The figures should be stored in a two- dimensional array.</p> </blockquote> <pre><code>public static void main(String[] args) { double test1; double test2; double test3; double test4; /* These are just test variable that will show output, to assure that my methods are summing my 2-D array */ Scanner keyboard = new Scanner(System.in); test1 = Quarterly1(); System.out.println(" Test 1 = " + test1); test2 = Quarterly2(); System.out.println(" Test 2 = " + test2); test3 = Quarterly3(); System.out.println(" Test 3 = " + test3); test4 = Quarterly4(); System.out.println(" Test 4 = " + test4 " /n "); } </code></pre> <p>This is a method that will receive input for my first quarterly report and sum it up.</p> <pre><code>public static double Quarterly1() { Scanner keyboard = new Scanner(System.in); double [][] sales = new double [6][4]; int num = 1; double total = 0; // this for statement will assign a row to every department for (int row = 0; row &lt; 6; row++) { // This for statement is taking one column from the array in order to fill with input for (int col = 0; col &lt; 4 - 3; col++) { // This will receive sale numbers from the six departments System.out.print("Enter a The First Quarterly Sales For Department [ "+num+" ]. . . . . $ "); sales[row][col] = keyboard.nextDouble(); num++; // This for statement will sum each department's input for (int i = 0; i &lt; sales.length; i++); total += sales[row][col]; } } return total; } </code></pre> <p>This is a method that will receive input for my second quarterly report and sum it up.</p> <pre><code>public static double Quarterly2() { Scanner keyboard = new Scanner(System.in); double [][] sales = new double [6][4]; int num = 1; double total = 0; for (int row = 0; row &lt; 6; row++) { // This for statement is taking one column from the array in order to fill with input for (int col = 0; col &lt; 4 - 3; col++) { // This will receive sale numbers from the six departments System.out.print("Enter a The Second Quarterly Sales For Department [ "+num+" ]. . . . . $ "); sales[row][col] = keyboard.nextDouble(); num++; // This for statement will sum each department's input for (int i = 0; i &lt; sales.length; i++); total += sales[row][col]; } } return total; } </code></pre> <p>This is a method that will receive input for my third quarterly report and sum it up.</p> <pre><code>public static double Quarterly3() { Scanner keyboard = new Scanner(System.in); double [][] sales = new double [6][4]; int num = 1; double total = 0; for (int row = 0; row &lt; 6; row++) { // This for statement is taking one column from the array in order to fill with input for (int col = 0; col &lt; 4 - 3; col++) { // This will receive sale numbers from the six departments System.out.print("Enter a The Third Quarterly Sales For Department [ "+num+" ]. . . . . $ "); sales[row][col] = keyboard.nextDouble(); num++; // This for statement will sum each department's input for (int i = 0; i &lt; sales.length; i++); total += sales[row][col]; } } return total; } </code></pre> <p>This is a method that will receive input for my fourth quarterly report and sum it up.</p> <pre><code>public static double Quarterly4() { Scanner keyboard = new Scanner(System.in); double [][] sales = new double [6][4]; int num = 1; double total = 0; // this for statement will assign a row to every department for (int row = 0; row &lt; 6; row++) { // This for statement is taking one column from the array in order to fill with input for (int col = 0; col &lt; 4 - 3; col++) { // This will receive sale numbers from the six departments System.out.print("Enter a The Forth Quarterly Sales For Department [ "+num+" ]. . . . . $ "); sales[row][col] = keyboard.nextDouble(); num++; // This for statement will sum each department's input for (int i = 0; i &lt; sales.length; i++); total = total + sales[row][col]; } } return total; } </code></pre>
[]
[ { "body": "<p>I'm not really sure why you have 4 functions that are doing the exact same thing!?</p>\n\n<p>The only difference seems to be the prompt text</p>\n\n<p>I'm also not a big fan of the second for statement</p>\n\n<p>// This for statement will sum each department's input</p>\n\n<pre><code>for (int i = 0; i &lt; sales.length; i++);\ntotal += sales[row][col];\n</code></pre>\n\n<p>what does that mean? My guess is:</p>\n\n<pre><code>// This for statement will sum each department's input\nfor (int i = 0; i &lt; sales.length; i++){\ntotal += sales[row][col];\n}\n</code></pre>\n\n<p>but it still doesn't make sense here</p>\n\n<p>I always suggest using {}'s it makes your code cleaner, easier to read and less error prone.</p>\n\n<p>also why are you doing the 4-3? can't you just put 1?</p>\n\n<p>Now my JAVA is a bit rusty but the point is still valid</p>\n\n<pre><code>public Enum Quarter{\n First,\n Second,\n Third,\n Forth\n}\n\npublic class Quarterly{\n\n private final const ROW = 6;\n private final const COL = 4;\n private Scanner _scanner;\n\n public Quarterly(Scanner scanner){\n this._scanner = scanner;\n }\n private string GetMessage(Quarter quarter, int departmentNumber){\n switch(quarter){\n case First:\n return \"Enter a The Third Quarterly Sales For Department [ \" + departmentNumber+\" ]. . . . . $ \"\n case Second:\n ...\n\n }\n //May even want to use a template string\n //const string QuartlyTemplate = \"Enter a The {0} Quarterly Sales for Department [{1}]. . . . . .$ \"\n //then do a string format on the template to populate it\n }\n\n\n public double GetTotalForDepartments(Quarter quarter){\n double [][] sales = new double [ROW][COL];\n int num = 1;\n double total = 0;\n for (int row = 0; row &lt; ROW ; row++)\n {\n // This for statement is taking one column from the array in order to fill with input\n for (int col = 0; col &lt; 4 - 3; col++)\n {\n // This will receive sale numbers from the six departments\n System.out.print(message + \"[\" + num + \" ]. . . . . $ \");\n sales[row][col] = _scanner.nextDouble();\n num++;\n // This for statement will sum each department's input\n for (int i = 0; i &lt; sales.length; i++);\n total += sales[row][col];\n }\n }\n\n return total;\n}\n }\n</code></pre>\n\n<p>Now I know this may not compile right off the bat, because I don't have a java compiler handy, but it will be easier to read than having 4 functions doing the same exact work.</p>\n\n<p>then your main will be </p>\n\n<pre><code> public static void main(String[] args)\n {\n double test1;\n double test2;\n double test3;\n double test4;\n\n Scanner keyboard = new Scanner(System.in);\n Quarterly helper = new Quarterly(keyboard);\n\n test1 = helper.GetTotalForDepartments(Quarter.First);\n System.out.println(\" Test 1 = \" + test1);\n\n test2 = helper.GetTotalForDepartments(Quarter.Second);\n System.out.println(\" Test 2 = \" + test2);\n\n test3 = helper.GetTotalForDepartments(Quarter.Third);\n System.out.println(\" Test 3 = \" + test3);\n\n test4 = helper.GetTotalForDepartments(Quarter.Fourth);\n System.out.println(\" Test 4 = \" + test4 \" /n \");\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T16:59:48.413", "Id": "54619", "Score": "0", "body": "Awesome!!! I just have just reviewed you code and I will compile it to check for any syntax and logical errors. I will post the corrected version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:55:52.143", "Id": "54728", "Score": "0", "body": "I can't seem to get this code complied!!! I am having trouble with the case statement communicating with the enum class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T03:23:47.947", "Id": "56904", "Score": "0", "body": "@eruano57 hmm guess enums are different in java you don't have to qualify it with the enum name(Just remove the Quarter prefix in the case statement)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T20:28:42.300", "Id": "58004", "Score": "1", "body": "`public Enum Quarter` should be `public enum Quarter` and a Java coding convention is to use start method names with a lowercase letter (not like C#)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T18:26:07.910", "Id": "33949", "ParentId": "33930", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T13:37:12.513", "Id": "33930", "Score": "5", "Tags": [ "java", "optimization", "array", "homework", "statistics" ], "Title": "How is my quarterly sales statistics program?" }
33930
<p>I'm writing a laser connection game. This is my first game on Windows Phone, and I've never used C# and XNA before.</p> <p>The part of my code that could be improved is <code>Update()</code> (where I make my sprites move).</p> <pre><code>public void Update(GameTime gameTime) { TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities(); if (touchCap.IsConnected) { TouchCollection touches = TouchPanel.GetState(); if (touches.Count &gt;= 1) { Vector2 PositionTouch = touches[0].Position; for (int i = 0; i &lt; ListDragObj.Count(); i++) { if (ListDragObj[i].Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y)) { //Permit to avoid several Obj to moove in the same time if (!OnlyOneSelected(ListDragObj)) { ListDragObj[i].selected = true; TamponPosition = ListDragObj[i].Position; } } else { ListDragObj[i].selected = false; } if (touches[touches.Count - 1].State == TouchLocationState.Released) { if (gm.Check_Tile((int)(PositionTouch.X / 10), (int)(PositionTouch.Y / 10))) { ListDragObj[i].Update(PositionTouch); } else { ListDragObj[i].Update(TamponPosition); } } } } } } </code></pre> <p>I'm looking for the selected Sprite (in the List <code>ListDragobj</code>), and then I move it. The last couple <code>if/else</code> is where I check collisions.</p> <p>I was wondering how I could improve that position <code>Update()</code> method.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:26:16.703", "Id": "54454", "Score": "0", "body": "touches.Count will give you the number of items, but the last item would be touches.Count - 1, hence the crashing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:37:42.710", "Id": "54455", "Score": "0", "body": "if the code doesn't work you should post this question on StackOverflow or [Game Development](http://gamedev.stackexchange.com/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:43:43.580", "Id": "54457", "Score": "1", "body": "Code is working." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T16:40:45.560", "Id": "54471", "Score": "1", "body": "`The last couple if/else is where I check collisions (it actually doesn't work fine, but that's another point)` this could lead down a bunny trail to other issues in your code. get it functioning and then bring it back for review, or limit your review question to the parts of your code that work, if the code you want reviewed links {in any way} to the code that doesn't work, then this question is off-topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:03:44.110", "Id": "54553", "Score": "0", "body": "@Malachi It wasn't working but now its fine since SimonV told me how to correct it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:32:23.160", "Id": "54595", "Score": "0", "body": "I retracted my Close Vote and up voted the question" } ]
[ { "body": "<ol>\n<li><p>You can reduce some of the indent by checking for the negative condition and bailing out early. E.g.:</p>\n\n<pre><code>TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities();\nif (!touchCap.IsConnected) { return; }\n\nTouchCollection touches = TouchPanel.GetState();\nif (touches.Count == 0) { return; }\n\n... your other code goes here ...\n</code></pre></li>\n<li><p><code>PositionTouch</code>: Standard naming convention for local variables is <code>camelCase</code>. Also the names reads slightly weird - <code>touchPosition</code> would be better.</p></li>\n<li><p>On every iteration through your <code>ListDragObj</code> method you check <code>if (touches[touches.Count - 1].State == TouchLocationState.Released)</code>. You can store that in a local variable before the loop:</p>\n\n<pre><code>var touchReleased = touches[touches.Count - 1].State == TouchLocationState.Released;\n\nfor (...)\n{\n ...\n if (touchReleased)\n</code></pre></li>\n<li><p>You don't actually use the index in this loop: <code>for (int i = 0; i &lt; ListDragObj.Count(); i++)</code>. A more idiomatic C# way would be to use a <code>foreach</code> in this case:</p>\n\n<pre><code>foreach (var dragObject in ListDragObj)\n{\n ...\n}\n</code></pre>\n\n<p>And replace all uses of <code>ListDragObj[i]</code> with <code>dragObject</code>.</p></li>\n<li><p>This:</p>\n\n<pre><code>for (int i = 0; i &lt; ListDragObj.Count(); i++)\n{\n if (ListDragObj[i].Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y))\n {\n //Permit to avoid several Obj to moove in the same time\n if (!OnlyOneSelected(ListDragObj))\n</code></pre>\n\n<p>looks suspiciously like an <code>O(n^2)</code> algorithm - assuming that <code>OnlyOneSelected</code> iterates over the list and counts how many are selected. You should consider keeping track of how many items are selected in your class. This could be achieved by adding two methods:</p>\n\n<pre><code>void SelectedObject(DragObj dragObject) { ... }\nvoid DeselectObject(DragObj dragObject) { ... }\n</code></pre>\n\n<p>which modify the <code>selected</code> property and adjust the selected count.</p></li>\n<li><p>This</p>\n\n<pre><code>if (gm.Check_Tile((int)(PositionTouch.X / 10), (int)(PositionTouch.Y / 10))) \n</code></pre>\n\n<p>looks like it computes a tile index from the position - assuming tiles are 10x10. If this assumption is correct then you should change <code>Check_Tile</code> to accept a position. It should then calculate the appropriate tile index by itself. Otherwise what happens if you ever want to change your tile size from 10x10 to something else? You would need to find every place in your code where you make this implicit assumption.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T11:00:42.103", "Id": "59845", "Score": "0", "body": "Thanks man, Since 1 month i have done some of these optimisation, i'm taking the overs too now :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T12:58:38.660", "Id": "59852", "Score": "1", "body": "+1 Great job, you really seem to take time to provide detailed answers for older unanswered questions (I guess it has to do with that [recent meta discussion](http://meta.codereview.stackexchange.com/questions/991/how-is-code-review-doing-right-now?cb=1))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:53:08.627", "Id": "36496", "ParentId": "33938", "Score": "3" } } ]
{ "AcceptedAnswerId": "36496", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:08:40.003", "Id": "33938", "Score": "3", "Tags": [ "c#", "xna" ], "Title": "Position update loop and checking collision" }
33938
<p>I have the following SQL query that computes for every date the week it falls in (a week begins on Sunday and ends on Saturday):</p> <pre><code>SELECT EntryDate ,CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE) AS 'SundayDate' ,CAST(DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE) AS 'SaturdayDate' ,CONVERT(VARCHAR, DATEADD(DAY ,1-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) + ' - ' + CONVERT(VARCHAR, DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) AS 'Week' FROM MyTable WHERE CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE) &lt;= CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) AS DATE) ORDER BY CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE) </code></pre> <p>It works fine, but I don't like the repeated function calls because they cluster the query and make it less readable.</p> <p>How can I make the query cleaner and more readable? (I'm using SQL Server 2008.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T16:02:38.113", "Id": "54464", "Score": "0", "body": "I am not sure that you can make this \"cleaner\" or more readable. it looks pretty straight forward." } ]
[ { "body": "<p>You can lose the <code>CAST</code> that surrounds the <code>DATEADD</code> function.</p>\n\n<p>The <code>DATEADD</code> function should spit out a <code>DATETIME</code> datatype.</p>\n\n<p>It should look like this:</p>\n\n<pre><code>SELECT EntryDate\n ,DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS 'SundayDate'\n ,DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS 'SaturdayDate'\n ,CONVERT(VARCHAR, DATEADD(DAY ,1-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) + ' - ' +\n CONVERT(VARCHAR, DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) AS 'Week'\nFROM MyTable\nWHERE DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) &lt;=\n DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) \nORDER BY DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate)\n</code></pre>\n\n<p>In the <code>ORDER BY</code> statement you might be able to use the Alias from your <code>SELECT</code> Statement, which would really speed this up.</p>\n\n<pre><code>SELECT EntryDate\n ,DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS 'SundayDate'\n ,DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS 'SaturdayDate'\n ,CONVERT(VARCHAR, DATEADD(DAY ,1-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) + ' - ' +\n CONVERT(VARCHAR, DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) AS 'Week'\nFROM MyTable\nWHERE DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) &lt;=\n DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) \nORDER BY 'Sunday_Date`\n</code></pre>\n\n<p>I would put <code>DESC</code> on that order by because I would want the newest dates to show up first, <strong>if you are grabbing dates from the past</strong></p>\n\n<p><strong>If you are grabbing from the future</strong>, then you would want 'ASC' in there, but that is default. </p>\n\n<p>I Can't remember who said it but</p>\n\n<blockquote>\n <p>it is as simple as it can be when there is nothing left that can be taken away</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:34:04.650", "Id": "57975", "Score": "0", "body": "OUCH!! MY EYES BLEED!! (that's just me I guess)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:40:46.467", "Id": "57977", "Score": "0", "body": "@retailcoder, unfortunately, when you use a function in the `SELECT` and give it an alias, you can't just use the alias in the `WHERE` clause, you have to calculate it again. the `ORDER BY` the OP Might be able to use the alias..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:52:09.680", "Id": "57981", "Score": "1", "body": "I meant all these caps aren't making it an easy read imho :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:53:12.450", "Id": "57982", "Score": "4", "body": "that is the coding syntax of SQL, most of the SQL engines are not case sensitive on these keywords though. but it makes it easier to pick them out when the code gets bigger, @retailcoder" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T16:34:47.993", "Id": "59088", "Score": "0", "body": "Thanks! But unfortunately `CAST` is necessary here because only the date part is needed; the time part should be omitted. But I did use an alias in the `ORDER BY` clause, I didn't notice it was possible to do it (unlike in the `WHERE` clause)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T16:58:03.007", "Id": "59100", "Score": "1", "body": "@kodkod, if you need the date without the time part for reporting purposes, that should be done on the report side not on the database side. that should speed things up a little bit, because that is less functions running in the query. the reporting software would be able to do it easier I think." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:18:02.210", "Id": "35708", "ParentId": "33939", "Score": "2" } }, { "body": "<pre><code>WITH Dates AS (\n SELECT EntryDate\n , DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SundayDate\n , DATEADD(DAY, 7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SaturdayDate\n FROM MyTable\n), Coming AS (\n SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) AS Sunday\n)\nSELECT EntryDate\n , SundayDate\n , SaturdayDate\n , CONVERT(VARCHAR, SundayDate, 103) + ' - ' + CONVERT(VARCHAR, SaturdayDate, 103) AS Week\n FROM Dates, Coming\n WHERE SundayDate &lt;= Coming.Sunday\n ORDER BY 2;\n</code></pre>\n\n<p>The simplifications I've made are:</p>\n\n<ul>\n<li>Extracted most of the query into a Common Table Expression named <code>Dates</code> to reduce redundancy.</li>\n<li>Removed the pointless <code>CAST(... AS DATE)</code>, since <code>DATEADD()</code> already produces dates.</li>\n<li>Used a column number for <code>ORDER BY</code>. With the Common Table Expression, though, we could just as easily <code>ORDER BY SundayDate</code>.</li>\n<li>Extracted <code>DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE())</code> into a Common Table Expression named <code>Coming</code>. This doesn't reduce the complexity of the query, but helps make the WHERE-clause read more like English.</li>\n</ul>\n\n<p><a href=\"http://sqlfiddle.com/#!3/cf783/8\" rel=\"nofollow\">SQLFiddle</a></p>\n\n<hr>\n\n<h3>Edit</h3>\n\n<p>Since the benefits of the last two suggestions are debatable, you may prefer a milder approach that incorporates just the first two suggestions:</p>\n\n<pre><code>WITH Dates AS (\n SELECT EntryDate\n , DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SundayDate\n , DATEADD(DAY, 7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS SaturdayDate\n FROM MyTable\n)\nSELECT EntryDate\n , SundayDate\n , SaturdayDate\n , CONVERT(VARCHAR, SundayDate, 103) + ' - ' + CONVERT(VARCHAR, SaturdayDate, 103) AS Week\n FROM Dates\n WHERE SundayDate &lt;= DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE())\n ORDER BY SundayDate;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T00:05:36.093", "Id": "59172", "Score": "0", "body": "what are you doing? can you elaborate on this answer? I am a little lost myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T05:42:04.647", "Id": "59191", "Score": "0", "body": "@Malachi Sorry, the previous revision didn't actually work with SQL Server. I've edited it into a proper answer now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T06:23:06.197", "Id": "59196", "Score": "0", "body": "I don't like it, but it is functional. personally I like my query better than this one. your Query and mine have the exact same Execution plan. :) http://sqlfiddle.com/#!3/cf783/11" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T07:13:29.007", "Id": "59201", "Score": "1", "body": "@Malachi The `Coming` CTE might be a bit excessive; you can easily undo that part if you prefer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T14:28:37.463", "Id": "59260", "Score": "0", "body": "you would have to change the Query completely. I think that with out that `Coming` CTE you might have to do it the other way....not positive though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T17:25:27.807", "Id": "59331", "Score": "1", "body": "@Malachi It's not that hard to remove the `Coming` CTE." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T17:55:55.613", "Id": "59339", "Score": "0", "body": "oh I see now. I was skimming, I really have to learn not to do that." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T23:38:12.383", "Id": "36168", "ParentId": "33939", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:40:16.350", "Id": "33939", "Score": "3", "Tags": [ "sql", "datetime", "sql-server", "t-sql" ], "Title": "Computing the week for a certain date" }
33939
<p>Can anyone optimize this code? I am new to jQuery.</p> <p>I want add class on next and previous button click. I wrote this code that works for me, but could anyone optimize it using jQuery predefined methods? That would be helpful. </p> <pre><code>$(document).ready(function () { var length = $('#slides li').size() - 1; var curren = 0; console.log(length); $('.next').on('click', function () { if (curren &gt;= 0 &amp;&amp; curren &lt; length) { curren++; $('.selected').removeClass('selected'); $('#slides li:eq(' + curren + ')').addClass('selected'); } }); $('.prev').on('click', function () { if (curren &gt;= 1) { curren--; $('.selected').removeClass('selected'); $('#slides li:eq(' + curren + ')').addClass('selected'); } }); }); </code></pre> <p>My HTML code:</p> <pre><code>&lt;ul id="slides"&gt; &lt;li class="selected"&gt;first&lt;/li&gt; &lt;li&gt;second&lt;/li&gt; &lt;li&gt;third&lt;/li&gt; &lt;li&gt;fourth&lt;/li&gt; &lt;li&gt;five&lt;/li&gt; &lt;li&gt;six&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS code:</p> <pre><code>.selected{ color:red; } </code></pre>
[]
[ { "body": "<p>There's not much in the way of predefined jQuery methods to add. Here's what I came up with though...</p>\n\n<pre><code>$(document).ready(function () {\n var $slides = $('#slides li'); //Save repeated selector result. \n var length = $slides.length - 1; //size is deprecated\n var curren = 0;\n console.log(length);\n // used .click due to personal preference .on('click', does the same thing\n $('.next').click(function () {\n if (curren &lt; length) { //Removed check that will always be true\n curren++;\n changeSelected(curren); //Moved repeated code to function\n }\n });\n $('.prev').click(function () {\n if (curren &gt;= 1) {\n curren--;\n changeSelected(curren);\n }\n });\n\n function changeSelected(index) {\n $('.selected').removeClass('selected');\n $slides.eq(index).addClass('selected'); //Use previously selected object\n }\n});\n</code></pre>\n\n<p>Here's a link to the <a href=\"http://api.jquery.com/size/\" rel=\"nofollow\">doc for .size()</a> where you can find it is deprecated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:36:59.373", "Id": "54596", "Score": "0", "body": "FYI, I didn't know about .next() and .prev(), [Flambino's answer](http://codereview.stackexchange.com/a/33961/14909) better suits your requirements and is niftier." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T17:28:25.587", "Id": "33946", "ParentId": "33943", "Score": "1" } }, { "body": "<p>See <a href=\"https://codereview.stackexchange.com/q/33590/14370\">this very similar question</a> and its answers (it's slightly different in that it loops if you keep clicking next or previous, but otherwise it's the same idea).</p>\n\n<p>Here's my take on a (non-looping) version</p>\n\n<pre><code>$(function () { // same as (document).ready(function () {..})\n var slides = $(\"#slides li\"); // find the slides once\n\n // common next/prev function\n function changeSlide(direction) {\n var target,\n current = slides.filter(\".selected\"); // find the current slide\n target = current[direction](); // call either .next() or .prev()\n if(target.length) { // if there is a next/prev slide switch to it\n current.removeClass();\n target.addClass(\"selected\");\n }\n }\n\n // add the handlers\n $(\".next\").on(\"click\", function () { changeSlide('next') });\n $(\".prev\").on(\"click\", function () { changeSlide('prev') });\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/JfY9X/\" rel=\"nofollow noreferrer\">Here's a demo</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T13:56:44.810", "Id": "54589", "Score": "0", "body": "Very nice. Unfortunately, the buttons don't do anything in my browser, IE 9.0. I wonder why..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:15:42.340", "Id": "54590", "Score": "1", "body": "@DanielCook Ugh... I'd love to say I'm surprised, but _nothing_ about IE can really surprise me anymore. I have no idea what might cause it (and I don't have a Windows machine handy to check). But it works fine in Chrome/FF/Safari/Opera and on my phone..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:37:38.047", "Id": "54598", "Score": "0", "body": "Naturally, I'm tempted to ask on SO. It certainly looks like it should work. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:49:21.750", "Id": "54602", "Score": "0", "body": "Thought you'd like to know that this DOES work on IE 9.0. It just that your demo doesn't work on IE 9.0. I copied this independently outside of jsfiddle and it worked just fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T15:52:09.890", "Id": "54610", "Score": "0", "body": "@DanielCook Well that's a relief. Still pretty weird, though. Thanks for testing it!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:07:03.743", "Id": "33961", "ParentId": "33943", "Score": "1" } } ]
{ "AcceptedAnswerId": "33946", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T16:31:50.463", "Id": "33943", "Score": "2", "Tags": [ "javascript", "jquery", "optimization", "html5" ], "Title": "Menu traversing on next and prev button click up and down" }
33943
<p>I believe this is considered value noise or possibly gradient noise in that I simply interpolate between random values (always returning the same values per coordinate).</p> <p>I am using this currently to generate a basic heightmap in a 3D game that expands outward as the player moves (being nearly infinite, only restricted by variable limitations).</p> <p>I contain my game's map within chunks, 32x32 (1024) data points per chunk representing height. I call the function <code>GetNoise2D()</code> with the X and Z values of every data point.</p> <p>This is currently my largest bottleneck. I could probably just do the 4 corners per chunk and interpolate between them to get reasonable looking terrain, but to put it simply, I'd rather not. </p> <p>Does anyone see any noticeable performance issues with the algorithm or the concept after initialization? I call on the algorithm using the function <code>GetHeight()</code> which combines two calls to the algorithm.</p> <pre><code>private float GetHeight(int X, int Z) { float fNoise = Noise.GetNoise2D(X * .02f, Z * .02f) * .5f; fNoise += Noise.GetNoise2D(X * .04f, Z * .04f) * .5f; //Scale noise from 0-1 to 0-20 return fNoise * 20f; } public class clsNoise2D { readonly byte[] Permutations = new byte[512]; readonly float[] Values = new float[256]; float xLerpAmount, yLerpAmount, v00, v10, v01, v11; //pX, pXa, dX, and dY are helper values to reduce operations int pX, pXa; int dX, dY; public Random random; public clsNoise2D(int iSeed) { random = new Random(iSeed); //Randomize permutations array with values 0-255 List&lt;byte&gt; listByte = new List&lt;byte&gt;(); for (int i = 0; i &lt; 256; i++) listByte.Add((byte)i); for (int i = 256; i &gt; 0; i--) { Permutations[256 - i] = listByte[random.Next(i)]; listByte.Remove(Permutations[256 - i]); } //Take permutations array up to 512 elements to reduce wrapping needs in GetNoise2D call for (int i = 256; i &lt; 512; i++) { Permutations[i] = Permutations[i - 256]; } //Set values to be between 0 and 1 incrementally from 0/255 through 255/255. for (int i = 0; i &lt; 256; i++) { Values[i] = (i / 255f); } } public float GetNoise2D(float CoordX, float CoordY) { //Get floor value of inputs dX = (int)Math.Floor(CoordX); dY = (int)Math.Floor(CoordY); //Get fractional value of inputs xLerpAmount = CoordX - dX; yLerpAmount = CoordY - dY; //Wrap floored values to byte values dX = dX &amp; 255; dY = dY &amp; 255; //Start permutation/value pulling pX = Permutations[dX]; pXa = Permutations[dX + 1]; v00 = Values[Permutations[(dY + pX)]]; v10 = Values[Permutations[(dY + pXa)]]; v01 = Values[Permutations[(dY + 1 + pX)]]; v11 = Values[Permutations[(dY + 1 + pXa)]]; //Smooth lerp amounts by cosine function xLerpAmount = (1f - (float)Math.Cos(xLerpAmount * Math.PI)) * .5f; yLerpAmount = (1f - (float)Math.Cos(yLerpAmount * Math.PI)) * .5f; //Return 2D interpolation for v00, v01, v10, and v11 return (v00 * (1 - xLerpAmount) * (1 - yLerpAmount) + v10 * xLerpAmount * (1 - yLerpAmount) + v01 * (1 - xLerpAmount) * yLerpAmount + v11 * xLerpAmount * yLerpAmount); } } </code></pre> <p>Edit: To clarify the question itself, is there a very noticeable performance mistake currently being made OR is there a completely different way to achieve identical or nearly identical values that SHOULD knock the performance out of the park?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T17:16:52.193", "Id": "57309", "Score": "0", "body": "In what way is this a bottleneck? If I take your sample and run it over a sample set of 1024 values (as I think you are doing) then it takes milliseconds for it to complete, so I think the question is how fast do you expect it to perform and how are you sure this is the slowest part of your program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T19:41:43.683", "Id": "57323", "Score": "0", "body": "This is being ran over 1024 values per chunk. 17x17 chunks. If the player is moving fast (ie. flying) it is possible to be generating up to 10 chunks per frame. Although I don't like it, I am currently interpolating using only the algorithm above in the corners of each chunk (and it works well enough I believe). I was simply hoping to not have to." } ]
[ { "body": "<p>I'm not sure if Cos and Sin are efficient here, they might be a ferformance killer. Consider making a table of sin/cos values for come range of angles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T09:36:40.740", "Id": "59553", "Score": "0", "body": "It's possible a lookup table would be more performant, but it would be almost insignificant. http://stackoverflow.com/questions/1382322/calculating-vs-lookup-tables-for-sine-value-performance" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T08:46:33.467", "Id": "36342", "ParentId": "33944", "Score": "2" } }, { "body": "<p>According to Visual Studio, the most expensive calls are indeed the lines where you call <code>Math.Cos</code>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/qiFJF.png\" alt=\"Visual Studio performance analysis for &lt;code&gt;GetNoise2D&lt;/code&gt;\"></p>\n\n<p>You could probably shave a couple of cycles by creating a lookup table which would return the result of that whole expression, <code>(1-cos(w * PI))/2</code>, just by indexing an array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:01:13.037", "Id": "36513", "ParentId": "33944", "Score": "1" } } ]
{ "AcceptedAnswerId": "36513", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T17:07:11.537", "Id": "33944", "Score": "5", "Tags": [ "c#", "algorithm", "performance", "game" ], "Title": "Looking for performance suggestions in Noise algorithm" }
33944
<p>I have a <code>Playlist</code> object which contains many <code>PlaylistItem</code> children. If I have 10,000 children then the UI gets blocked from rendering until all 10,000 children have been processed.</p> <p>To avoid this, I've created a recursive function wrapped in a <code>setTimeout</code>. This allows a chunk of the playlist to be rendered, allow the UI to update by pausing for <code>setTimeout</code> and then continue to run until it is empty.</p> <p>Is this a good implementation? Any critiques? I know I still should implement pagination in the long run, but this is for the short term.</p> <pre><code>render: function () { this.$el.html(this.template( _.extend(this.model.toJSON(), { // Mix in chrome to reference internationalize. 'chrome.i18n': chrome.i18n }) )); // Group playlistItems into chunks of 200 to render incrementally to prevent long-running operations. var chunkSize = 200; var playlistItemChunks = _.toArray(this.model.get('items').groupBy(function (playlistItem, index) { return Math.floor(index / chunkSize); })); var self = this; this.incrementalRender(playlistItemChunks, function () { self.$el.find('img.lazy').lazyload({ container: self.$el, event: 'scroll manualShow' }); }); return this; }, incrementalRender: function (playlistItemChunks, onRenderComplete) { // Render a chunk: if (playlistItemChunks.length &gt; 0) { var playlistItemChunk = playlistItemChunks.shift(); // Build up the views for each playlistItem. var items = _.map(playlistItemChunk, function(playlistItem) { var playlistItemView = new PlaylistItemView({ model: playlistItem }); return playlistItemView.render().el; }); // Do this all in one DOM insertion to prevent lag in large playlists. this.$el.append(items); var self = this; setTimeout(function() { self.incrementalRender(playlistItemChunks, onRenderComplete); }); } else { onRenderComplete(); } }, </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-13T10:57:10.403", "Id": "196887", "Score": "0", "body": "I'm not entirely convinced that `setTimeout` to control the amount you render is the right way to go here. Your problem is that you're trying to render 10,000 elements at once.. thats way too much information for a human to process. Instead, why not try using paging and / or infinite scrolling?" } ]
[ { "body": "<p>You code looks good, I only can give a few suggestions:</p>\n\n<ul>\n<li>I find it more convenient to use <code>...bind(this)</code> instead of <code>var self = this;</code> - in this case the extra variable is not necessary the code looks better.</li>\n<li>Maybe it is better to use an index within the array - in this way the array will not be copied several times. Of course, the JS is highly optimized internally, but it is a good to help it a little.</li>\n<li>Rendering 10.000 items is still very CPU consuming process (especially on mobile devices) so maybe use the similar approach that you have used with images and build the next chunk only when the user scrolled down to the end?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T23:50:41.727", "Id": "54660", "Score": "0", "body": "Thanks for responding! I definitely should be using bind -- I just haven't used it enough to be comfortable with it -- but now is a good time. I'll also strongly consider using an indexer in the array instead of breaking into chunks to prevent copying. This is a valid point. And yes, finally, I do need to support pagination -- the logic is just more complex and I was trying to create a temporary fix until I'm able to fully grasp what I need to do to implement that while reading data from a server. :) Cheers" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T19:34:03.543", "Id": "34017", "ParentId": "33947", "Score": "2" } } ]
{ "AcceptedAnswerId": "34017", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T17:37:14.897", "Id": "33947", "Score": "2", "Tags": [ "javascript", "jquery", "backbone.js", "lodash.js" ], "Title": "Rendering a large collection using BackboneJS and LoDash" }
33947
<p>I am trying to standardize the way I write code. Which is the best way to place the values into a string, method 1 or 2?</p> <pre><code>string myCat = "persian"; // Method 1 Console.WriteLine("I have a wild {0} cat that likes to visit", myCat); // Method 2 Console.WriteLine("I have a wild " + myCat + " cat that likes to visit"); </code></pre> <p>I would like to point out that I am intending this for simple uses, where <code>StringBuilder</code> would be overkill.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T21:16:47.167", "Id": "54496", "Score": "3", "body": "Not too sure about on-topicness of this question. This isn't a code review, it's asking about the *best way to concatenate strings*, which I believe would be a better fit on Programmers.SE." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T03:23:07.103", "Id": "54538", "Score": "1", "body": "What about `string.concat` or `list.join` ... etc. etc. I think the best option is to understand the underlying mechanics of what you are writing and choose the right tool. Check out: http://www.joelonsoftware.com/articles/fog0000000319.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T08:27:00.580", "Id": "54548", "Score": "0", "body": "sometimes we just have to remember - Less is More :-) Choose option that is more readable unless it is much less efficient, but for small inefficiencies it is better to choose readability over efficiency." } ]
[ { "body": "<p>I much prefer method 1. Try adding 3-4 values and you'll quickly see it takes less code. Plus, you can reuse a value elsewhere in the string. Dunno which is more performant though. If you want performance, use StringBuilder. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T21:34:49.560", "Id": "54498", "Score": "5", "body": "Method 1 has the added bonus that you can save your format string to a variable allowing you to write something like `Console.WriteLine(catSentence, myCat);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T08:42:12.380", "Id": "54550", "Score": "2", "body": "Method 1 is better for localization: you can easily move the insertion point." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T20:09:04.360", "Id": "33953", "ParentId": "33952", "Score": "10" } }, { "body": "<p>both methods have their uses, </p>\n\n<p>I usually use the second method, for two reasons</p>\n\n<ol>\n<li><p>when I am writing the code I put in the variable that I want while writing instead of having to figure out which variable I needed when I am done writing it.</p></li>\n<li><p>it is faster to see what I am inserting into the string this way, I see the variable right away and know.</p></li>\n</ol>\n\n<p>but I also Agree with Alex Dresko's Answer, and Daniel Cook's Comment to the answer (if that works I have not tried it myself, but I like the way it looks and works)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T22:59:37.023", "Id": "33957", "ParentId": "33952", "Score": "4" } }, { "body": "<p>Method 1 creates two strings in memory:</p>\n\n<ol>\n<li>\"I have a wild {0} cat that likes to visit\"</li>\n<li>\"I have a wild persian cat that likes to visit\"</li>\n</ol>\n\n<p>Method 2 creates four strings in memory:</p>\n\n<ol>\n<li>\"I have a wild \"</li>\n<li>\" cat that likes to visit\"</li>\n<li>\"I have a wild persian\"</li>\n<li>\"I have a wild persian cat that likes to visit\"</li>\n</ol>\n\n<p>Method 1 is better because it always allocates fewer strings. In this case it allocates half as many.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T03:19:04.553", "Id": "54537", "Score": "2", "body": "Method 2 should have \"Persian\" inserted before point 3. Also it would be good to note that method 1 has to parse the format which I believe is a small overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:37:14.607", "Id": "54597", "Score": "0", "body": "can you post a reference link that this is what happens? I think this kind of answer should show proof." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:46:29.977", "Id": "54601", "Score": "1", "body": "This is incorrect. Method 2 does not create an intermediate string from the two first strings. The compiler makes it a call to `String.Concat` which concatenates all the strings into one." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:05:38.037", "Id": "33965", "ParentId": "33952", "Score": "-1" } }, { "body": "<p>For simple straightforward string concatenation like your <code>\"persian\"</code> cat example, I agree with @Malachi - being slightly memory-inefficient over a few bytes will not hurt anyone, and if there's a gain in readability then it's worth it.</p>\n\n<p><strong>However</strong>, since you're looking to <strong>standardize</strong> the way you're doing string concatenations, you should go with <code>string.Format()</code> all the way, without hesitation*.</p>\n\n<p>Say you're writing a program for some petshop (say, one that only sells cats), you'll potentially want to format/concatenate the cat's breed, birthdate/age and price tag. With <code>string + string</code> your only option is essentially to hard-code the date and currency formats, while this: </p>\n\n<pre><code>string.Format(\"{0} cat, born {1:d} ({2} weeks) | {3:C2}\", cat.Breed, \n cat.BirthDate, \n cat.AgeInWeeks, \n cat.Price)\n</code></pre>\n\n<p>...has an obvious advantage, especially when you consider that</p>\n\n<pre><code>\"{0} cat, born {1:d} ({2} weeks) | {3:C2}\"\n</code></pre>\n\n<p>is a string all by itself (as mentioned by Daniel Cook).</p>\n\n<p>*At the end of the day, <strong>common sense</strong> should prevail. If you end up doing this:</p>\n\n<pre><code>var result = string.Format(\"{0}{1}\", string1, string2);\n</code></pre>\n\n<p>...then you know you've gone overboard.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T02:31:17.483", "Id": "33968", "ParentId": "33952", "Score": "11" } }, { "body": "<p>Well, first lets look at what the two options actually are. This is what the code is doing:</p>\n\n<pre><code>// Method 1 calls String.Format, which makes it functionally equivalent to:\nConsole.WriteLine(String.Format(\"I have a wild {0} cat that likes to visit\", myCat));\n\n// Method 2 is converted to this by the compiler:\nConsole.WriteLine(String.Concat(\"I have a wild \", myCat, \" cat that likes to visit\"));\n</code></pre>\n\n<p>If you are looking at performance, the second option is better, as it will simply concatenate the strings without having to parse a format string to determine what to do. However, the first option performs reasonably well, so in most applications the small performance difference will never be noticable.</p>\n\n<p>If you are looking at readability, it's a matter of taste. A formatting string is easier to read, especially if you have several values, but it also makes it somewhat harder to see which value goes where in the string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:41:01.700", "Id": "34001", "ParentId": "33952", "Score": "2" } }, { "body": "<p>For anyone who is curious, here is the IL for the OP's example.</p>\n\n<pre><code>IL_0001: ldstr \"persian\"\nIL_0006: stloc.0\nIL_0007: ldstr \"I have a wild {0} cat that likes to visit\"\nIL_000c: ldloc.0\nIL_000d: call string [mscorlib]System.String::Format(string, object)\nIL_0012: call void [mscorlib]System.Console::WriteLine(string)\nIL_0017: nop\nIL_0018: ldstr \"I have a wild \"\nIL_001d: ldloc.0\nIL_001e: ldstr \" cat that likes to visit\"\nIL_0023: call string [mscorlib]System.String::Concat(string, string, string)\nIL_0028: call void [mscorlib]System.Console::WriteLine(string)\n</code></pre>\n\n<p>Personally I opt for String.Format() because it does so much for so little.</p>\n\n<p>Consider this example:</p>\n\n<pre><code>Console.WriteLine(\"I have \" + count.ToString() + \" wild cats that like to visit\");\n</code></pre>\n\n<p>Which results with this IL:</p>\n\n<pre><code>IL_0030: ldstr \"I have \"\nIL_0035: ldloca.s count\nIL_0037: call instance string [mscorlib]System.Int32::ToString()\nIL_003c: ldstr \" wild cats that like to visit\"\nIL_0041: call string [mscorlib]System.String::Concat(string, string, string)\nIL_0046: call void [mscorlib]System.Console::WriteLine(string)\n</code></pre>\n\n<p>In comparison, using String.Format</p>\n\n<pre><code>Console.WriteLine(String.Format(\"I have {0} wild cats that like to visit\", count));\n</code></pre>\n\n<p>...is slightly better.</p>\n\n<pre><code>IL_0096: ldstr \"I have {0} wild cats that like to visit\"\nIL_009b: ldloc.1\nIL_009c: box [mscorlib]System.Int32\nIL_00a1: call string [mscorlib]System.String::Format(string, object)\nIL_00a6: call void [mscorlib]System.Console::WriteLine(string)\n</code></pre>\n\n<p>Not convinced? How about this realistic example with two substitution parameters including a date (I'm often inserting a date into log strings, for example).</p>\n\n<p>The bad way:</p>\n\n<pre><code>Console.WriteLine(\"Today is \" + System.DateTime.Now.ToString(\"M/d/yy\") + \" and I have \" + count.ToString() + \" wild cats that like to visit\");\n</code></pre>\n\n<p>Insane block of IL this time:</p>\n\n<pre><code>IL_004c: ldc.i4.5\nIL_004d: newarr [mscorlib]System.String\nIL_0052: stloc.2\nIL_0053: ldloc.2\nIL_0054: ldc.i4.0\nIL_0055: ldstr \"Today is \"\nIL_005a: stelem.ref\nIL_005b: ldloc.2\nIL_005c: ldc.i4.1\nIL_005d: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()\nIL_0062: stloc.3\nIL_0063: ldloca.s CS$0$0001\nIL_0065: ldstr \"M/d/yy\"\nIL_006a: call instance string [mscorlib]System.DateTime::ToString(string)\nIL_006f: stelem.ref\nIL_0070: ldloc.2\nIL_0071: ldc.i4.2\nIL_0072: ldstr \" and I have \"\nIL_0077: stelem.ref\nIL_0078: ldloc.2\nIL_0079: ldc.i4.3\nIL_007a: ldloca.s count\nIL_007c: call instance string [mscorlib]System.Int32::ToString()\nIL_0081: stelem.ref\nIL_0082: ldloc.2\nIL_0083: ldc.i4.4\nIL_0084: ldstr \" wild cats that like to visit\"\nIL_0089: stelem.ref\nIL_008a: ldloc.2\nIL_008b: call string [mscorlib]System.String::Concat(string[])\nIL_0090: call void [mscorlib]System.Console::WriteLine(string)\n</code></pre>\n\n<p>Using String.Format:</p>\n\n<pre><code>Console.WriteLine(String.Format(\"Today is {0:M/d/yy} and I have {1} wild cats that like to visit\", DateTime.Now, count));\n</code></pre>\n\n<p>Much much shorter than the other version:</p>\n\n<pre><code>IL_00ac: ldstr \"Today is {0:M/d/yy} and I have {1} wild cats that like to visit\"\nIL_00b1: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()\nIL_00b6: box [mscorlib]System.DateTime\nIL_00bb: ldloc.1\nIL_00bc: box [mscorlib]System.Int32\nIL_00c1: call string [mscorlib]System.String::Format(string, object, object)\nIL_00c6: call void [mscorlib]System.Console::WriteLine(string)\n</code></pre>\n\n<p>The only thing that bothers me a little bit is the boxing operation, since String.Format only takes objects for the substitution parameters. From every other perspective, it is easier to read and results in more efficient IL.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T06:31:12.357", "Id": "57364", "Score": "0", "body": "Lots of helpful answers here, but I'm afraid I'm going to have to choose this answer as the best. @John thank you for checking the efficiency of the code and mentioning about readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T18:31:10.300", "Id": "59496", "Score": "0", "body": "@block14 don't be affraid, you did the right thing!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-15T15:23:55.740", "Id": "71790", "Score": "0", "body": "Interresting, but the number of lines of IL code isn't really a measure of efficiency or performance..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:14:00.183", "Id": "34027", "ParentId": "33952", "Score": "7" } } ]
{ "AcceptedAnswerId": "34027", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T20:02:56.957", "Id": "33952", "Score": "8", "Tags": [ "c#", "strings" ], "Title": "Cleanest way to place values into strings" }
33952
<p>I'm a beginner at JavaScript and I'm working on building a mini-framework just to become familiar with what good code looks like. In my application I often have the need for the user to enter in a list of things they want to send to the server for querying purposes. So currently I have <a href="http://jsfiddle.net/Zutg2/" rel="nofollow">this</a> fiddle. When I user enters in something into the text box the JS will check to see if that item has already been entered and disallow it if it has, or it will add the text entered into the text box and the user can see what they're going to send to the server (that part is taken out for brevity's sake). I know this isn't quite there, but I would like to do something like <code>$('#control').holder(optionsForHolderControl)</code> and allow the behavior to be as dynamic as possible. While I know that I'm not quite there yet, I would like to know what the experts out there would change about my code as it stands right now (organization, is it OK to have these closures in there, do the functions need to be properties, etc).</p> <pre><code>$(document).ready(function () { $('#textButton').click(function () { var options = { button: '#textButton', textBox: '#textBox', catcher: '#catcher' }; //fxn call stick($(options.textBox), options.catcher); }); //this takes text entered into a text box and makes a div with a strip class //and puts it inside the holder div function stick(textBox) { /***********variables*****************/ var text = $(textBox).val(); var holderArray = []; //gets all of the text elements $('.holder .strip').each(function () { holderArray.push($(this).text()); }); /*************functions***************/ function addStrip() { var $strip = $('&lt;div&gt;').text(text).appendTo(catcher).addClass('strip'); } function clearTextbox() { $(textBox).val(''); $(textBox).focus(); } //duplicates aren't allowed in the holder container if ($.inArray(text, holderArray) != -1) { alert('that item has already been entered'); } else { addStrip(); } clearTextbox(); }; }); </code></pre>
[]
[ { "body": "<p>The starting point in plugin creation is most likely the official documentation here: <a href=\"http://learn.jquery.com/plugins/basic-plugin-creation/\" rel=\"nofollow\">http://learn.jquery.com/plugins/basic-plugin-creation/</a></p>\n\n<p>You can start from the very simple plugin that actually contain the function <code>stick</code> as follows:</p>\n\n<pre><code>$.fn.holder = function (options) { /* ... stick's code goes here ... */ return this; };\n</code></pre>\n\n<p>and this will be the base for your plugin.</p>\n\n<p>Then later you can call</p>\n\n<pre><code>$('#control').holder({ ... some options ... });\n</code></pre>\n\n<p>And the defined method should be called.</p>\n\n<p>This approach will probably change and below is the review of the code you actually posted, assuming that later you will change it anyway.</p>\n\n<p>The coding style of the presented code is good. I only recommend to remove <code>/***********variables*****************/</code> and <code>/*************functions***************/</code> because they are usually become inconsistent with the code blocks below them. Even now the <code>variables</code> are mixed with expressions.</p>\n\n<p>The logic here is unclear:</p>\n\n<pre><code>$('#textButton').click(function () {\n var options = {\n button: '#textButton',\n textBox: '#textBox',\n catcher: '#catcher'\n };\n stick($(options.textBox), options.catcher);\n});\n</code></pre>\n\n<p><code>this</code> in click handler is the clicked object - <code>$(this) === $(options.textBox)</code> so it it makes sense to move options outside of the click handler and use <code>options.button</code> in <code>$('#textButton')</code>.</p>\n\n<p>Also in <code>strip</code> it is not necessary to use <code>$(textBox)</code> because <code>textBox</code> is a jQuery object already.</p>\n\n<p>It is not clear why you have added the functions <code>addStrip</code> and <code>clearTextbox</code> - they are used only once so their code can be just inlined.</p>\n\n<pre><code>$(textBox).val('');\n$(textBox).focus();\n</code></pre>\n\n<p>The power of jQuery allows you to chain the methods (and <code>textBox</code> is already a jQuery object):</p>\n\n<pre><code>textBox.focus().val('');\n</code></pre>\n\n<p>And the main logic issue - currently the code on the halfway between pure jQuery implementation without model at all and model-driven approach (the code recreates model-like construction on every click). So it is better to select one of the ways and make a step:</p>\n\n<ul>\n<li>remove <code>holderArray</code> and just use <code>$(''.holder .strip'').filter(function () { return $(this).text() === text; })</code> instead of the array routines</li>\n<li>or (and what is better) move <code>holderArray</code> and add code that keeps it consistent with the list. You can check my article on JavaScript MVC for more info on this approach: <a href=\"http://alexatnet.com/articles/model-view-controller-mvc-javascript\" rel=\"nofollow\">http://alexatnet.com/articles/model-view-controller-mvc-javascript</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T02:25:16.553", "Id": "54673", "Score": "0", "body": "Thanks for the criticism, this is the kind of thing I was looking for. I've never used any MVC before. I've only been learning JavaScript besides kiddy jQuery stuff for a couple months so I don't know if I'm quite ready for that yet, but might as well get familiar with it. Thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T13:59:13.547", "Id": "54712", "Score": "0", "body": "You are welcome. If you like style of my reviews you can contact me directly for further reviews because I'm not frequent guest on this site. Good luck." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T02:04:17.257", "Id": "34031", "ParentId": "33955", "Score": "3" } } ]
{ "AcceptedAnswerId": "34031", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T22:07:13.400", "Id": "33955", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Building jQuery like controls" }
33955
<p>In a complex library I've been working on, I got pretty tired of all of the individual type functions and operators to determine whether I was working with an object or piece of data of a given type. This was especially true when I was checking for inherited prototypes between classes. In an effort to alleviate, I made this generalized is() function.</p> <pre><code>( function( root ) { var is = function( v, t ) { if ( typeof v !== 'undefined' ) { if ( typeof t === 'string' ) return typeof v === t; else if ( typeof t === 'function' ) { if ( typeof v === 'object' ) return v instanceof t; else if ( typeof v === 'function' ) return t.prototype.isPrototypeOf( v.prototype ); else return false; } } return false; }; root['is'] = is; }( this ) ); </code></pre> <p><strong>Syntax</strong></p> <ul> <li><code>is(variable, type)</code> where type is any return from <code>typeof</code> <ul> <li>returns true if <code>variable</code> typeof === <code>type</code></li> </ul></li> <li><code>is(variable, class)</code> where variable is an object and class is a constructor <ul> <li>returns true if <code>variable</code> is an instanceof <code>class</code></li> </ul></li> <li><code>is(class1, class2)</code> where class is a constructor and class is a constructor <ul> <li>returns true if <code>class1</code>'s prototype is a descendant of <code>class2</code>'s prototype.</li> </ul></li> </ul> <p><strong>Usage</strong></p> <p>I use this function whenever the type of a value is imperative. One common example is when I need different behaviors depending on the type. As an example:</p> <pre><code>// typeof myVar === 'number' if(is(myVar,'number')) { doSomething(); } // myVar instanceof Array elseif (is(myVar,Array)) { doSomethingWithArray(); } // typeof myVar === 'object' elseif (is(myVar,'object')) { doSomethingWithObject(); } </code></pre> <p><strong>Reasons for this function</strong></p> <p>The goal is to reduce the amount of <code>typeof</code>, <code>instanceof</code> and <code>isPrototypeOf</code> statements, as well as the need for individualized type checking methods. This certainly seems to accomplish much of that goal. A nice little beneficial side effect is that it reduces the code of using libraries significantly. I've been utilizing it in some newer libraries (at a minified overhead of 150 bytes) and it has saved me much more than that, as well as an uncountable number of keystrokes. </p> <p><strong>Reason for this Question</strong></p> <p>While I haven't noticed a performance hit, I would like a review with more quantifiable statistics. Additionally, should I have special handling for falsey values? Are there other gotchas that I'm not accounting for?</p> <p>Here is the minified code:</p> <pre><code>(function(c){c['is']=function(a,b){if("undefined"!==typeof a){if("string"===typeof b)return typeof a===b;if("function"===typeof b){if("object"===typeof a)return a instanceof b;if("function"===typeof a)return b.prototype.isPrototypeOf(a.prototype)}}return !1}})(this); </code></pre> <p><strong>Update: Performance</strong></p> <p>After performing some of the suggested changes, since no one addressed performance, I took some time and learned me some jsPerf. The switch/case variant, performed much more slowly than the if/else variant. Further, I made another variant using the ternary (?) operator which performed much better. <a href="http://jsperf.com/is-switch-vs-is-ternary-vs-operators" rel="nofollow" title="Here is the test.">Here is the test.</a> </p> <p>Since type-checking is generally quick and fairly uncommon compared to many other operations, I'm certainly willing to take the hit.</p> <p><strong>Update: Revised Code (using comments and answer)</strong></p> <pre><code>( function( root ) { // To force minifiers to ignore function name root['is'] = function(value, type) { if ('undefined' !== typeof value) { switch (typeof type) { case 'string': return typeof value === type; case 'function': switch (typeof value) { case 'object': return value instanceof type; case 'function': // Account for default behavior return type === Function ? true : type.prototype.isPrototypeOf(value.prototype); } } } // Account for passed undefined values return ('undefined' === t) ? true : false; }; }( this ) ); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:53:41.020", "Id": "54507", "Score": "3", "body": "Could you give an example of how this code would be used in practice? Usually, JavaScript programmers don't encounter the `is(v, t)` problem because [duck-typing](http://en.wikipedia.org/wiki/Duck_typing) is the norm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:49:44.383", "Id": "54535", "Score": "0", "body": "Added in edit above" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T04:35:56.917", "Id": "54541", "Score": "1", "body": "I know this is intentional behavior, but consider whether you want `is(v, Array)` to return `true` when `v` is an array, but `is(v, Function)` to return `false` when `v` is a function and `is(v, Number)` to return `false` when `v` is a primitive number. (`is(v, 'function')` and `is(v, 'number')` work correctly, though.) Also, `is(v, 'undefined')` can never return `true`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:42:45.377", "Id": "54561", "Score": "0", "body": "There is no way to resolve is(v,'undefined') as calling v when it is undefined results in an runtime error. The others, however, I should consider, thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:59:43.887", "Id": "54564", "Score": "0", "body": "@icktoofay is behavior different between 'function' and Function, or between 'number' and Number?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T10:15:59.697", "Id": "54566", "Score": "0", "body": "After checking the various debuggers, a function does validate as an instanceof Function, and [] does validate as an instanceof Array. Since this is default behavior, I shall not change it, as it should be expected. 32 is not a Number, however, and am not sure how/if I will address that, yet. Thanks for bringing it to my attention." } ]
[ { "body": "<h1>Code Review</h1>\n\n<h2>Coding Style</h2>\n\n<p>You coding style is quite uncommon. However, it is fine if it is consistent across\nyour projects.</p>\n\n<p>My personal preference is to use constant ahead of comparison so it looks a\nlittle bit less confusing:</p>\n\n<pre><code>if ('function' === typeof v)\n</code></pre>\n\n<p>Anyway, in this particular case it is sematically better to use <code>switch</code> so it\nemphasises that the variable is immutable within the statement:</p>\n\n<pre><code>switch (typeof t) {\ncase 'string':\n return t === typeof v;\ncase 'function':\n ...\n}\n</code></pre>\n\n<p>Some style guides also recommend to remove redundant <code>else</code> after <code>return</code>. This\nwill decrease indentation and simplify the code statements.</p>\n\n<p>It is better to use a little bit descriptive variable names. For example,\n<code>type</code> instead of <code>t</code> and <code>value</code> instead of <code>v</code>.</p>\n\n<p>You can elliminate the variable <code>is</code> by assigning the function directly to\nroot's property. Or there is a special preference to keep the variable <code>is</code>?</p>\n\n<h2>Logic</h2>\n\n<p>It is doubtful whether this function should return <code>false</code> for\n<code>is(undefined, 'undefined')</code>. It looks like it is a completely valid check that\nwill fail.</p>\n\n<p>If the argument value is not supported, it may be better to throw an exception\ninstead of returning plausible value. For example, <code>is(null, null)</code> will return\nfalse, but <code>null</code> is just not supported value of the parameter <code>t</code>.</p>\n\n<p>I understand that it contradicts a little with an original purpose of the function\nbut it looks like this usage of the function may be quite handy.</p>\n\n<p>Please also be aware of multi-instance environment. If Array object created\nwithin one vm instance (or iframe), <code>instanceof Array</code> will fail. You can find\nmore examples here: <a href=\"http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/\" rel=\"nofollow\">http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/</a></p>\n\n<h2>Revised Code</h2>\n\n<pre><code>(function (root) {\n root.is = function (value, type) {\n if ('undefined' !== typeof value) {\n switch (typeof type) {\n case 'string':\n return type === typeof value;\n case 'function':\n switch (typeof value) {\n case 'object':\n return value instanceof type;\n case 'function':\n return type.prototype.isPrototypeOf(value.prototype);\n }\n }\n }\n return false;\n };\n}(this));\n</code></pre>\n\n<p>BTW, its minified version is 8 bytes shorter (with closure-compiler)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:49:06.267", "Id": "54562", "Score": "0", "body": "Thank you for the comments. Some notes: I never feel uncomfortable looking at other projects. I've been doing this for 20 years, but am new simply to JS. Regarding `undefined, 'undefined'` I shall amend that because it is valid. `null, null`, I do agree, should probably return an exception. What do you mean about your statement on Arrays? could you elaborate or give a use case? Regarding variable names, understood. I often use descriptive unless it is painfully obvious, and when it isn't supportive doc (like above) is always provided. Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:50:31.680", "Id": "54563", "Score": "0", "body": "One note: is it preferrable to use `switch/case` when there are only two cases? I've often leaned toward `if/else` with few cases. I'd like to see if some other pipe in, but this is a handy candidate for an accepted answer if you can elaborate on the Arrays in multi-instance environment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:31:26.110", "Id": "54571", "Score": "0", "body": "I'm sorry for the first statement. Just corrected it. As for Array here is an example: http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ You may do not use the function `is` in this way, of course, so it is fine now, but it is very interesting aspect of the `instanceof`. As for `switch` it is, of course, very subjective, but there is at least one important drawback of `if` in such case: the value should be calculated twice so it is a code duplication. Very small, but here it is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T13:10:34.563", "Id": "54583", "Score": "0", "body": "Thank you very much for that link. I would still prefer that you place it in your answer, but this is certainly good enough for an accepted answer. While your switch does not perform well for this function, your justification regarding usage is sound. I will be providing edits as I gather more information, I encourage you to do the same should you feel the need." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T04:45:37.797", "Id": "33972", "ParentId": "33956", "Score": "4" } } ]
{ "AcceptedAnswerId": "33972", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T22:24:11.977", "Id": "33956", "Score": "5", "Tags": [ "javascript", "classes" ], "Title": "Generalized is() type-checking function for JavaScript" }
33956
<pre><code>fadeTo = function(obj, time, to, cChange ){ if ( typeof( time ) == "undefined" ) time = 1000; if ( typeof( to ) == "undefined" ) to = 1; if ( time &lt;= 0 ) return true; objSt = obj.style; objOpac = parseFloat(objSt.opacity) + 0; if ( typeof( cChange ) == "undefined" ) { cChange = (to - objOpac)/(time/10); } objSt.opacity = objOpac + cChange; setTimeout( function(){ fadeTo( obj, time - 10, to, cChange); }, 10); }; </code></pre> <p>This code was written as a replacement for <code>fadeIn</code> and <code>fadeOut</code>. I made this for learning purposes and it works fine.</p> <p>I'm just not sure if I could write it better, and if it could cause problems in the future. I feel that I should use two functions instead: one as an init function, and one to finish the process without asking all the extra <code>if</code>s and simple variable settings.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:36:25.323", "Id": "54511", "Score": "1", "body": "`typeof` is an operator and not a function, also prefer `===` to `==` for consistency. Why the `+ 0` on `objOpac` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:40:11.667", "Id": "54512", "Score": "0", "body": "For dos, don'ts (especially don'ts) and tips read [_JavaScript: The Good Parts_](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/05965177429) by Douglas Crockford. Can't recommend it enough for anyone leaning JS, and it's only ~150 pages; not some gigantic \"bible\"-type programming book. Also check out [his site](http://crockford.com), and run your code through [jslint](http://www.jslint.com) (incidentally built by Crockford) or [jshint](http://www.jshint.com/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:44:26.203", "Id": "54514", "Score": "0", "body": "@BenjaminGruenbaum Much thanks for the quick response! I'll remember the === comparison operator. I used The + 0 because I read some where that **parseFloat(objSt.opacity)** could return a null or something like that, so add a real to make it a value. I believe it originally looked more like: (parseFloat(objSt.opacity) || 0)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:46:04.680", "Id": "54515", "Score": "0", "body": "@Flambino Thanks for the recommendation! I think this will be a great place for me to start!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:00:49.750", "Id": "54517", "Score": "1", "body": "@Lemony There are things that aren't \"really numbers\" like `NaN` if you add 0 to it you still get `NaN` so that doesn't help." } ]
[ { "body": "<p>Well written animation functions typically use a tweening algorithm that checks the system clock to see how much time is actually remaining in the originally specified time allotment and then adjusts the animation increment to put things back on time, even if the timer events weren't coming in exactly on time or the browser was super busy and you weren't getting all the cycles you might want or the host CPU just isn't very fast. Done well, this can even allow you to adjust the step value for smoother animations on more capable computers and coarser steps on less capable computers.</p>\n\n<p>As you have it, you have a hard coded step function in time of 1/10th the time and thus 1/10th the total opacity change. On capable computers, you can run much, much smoother than this.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>function now() {\n return new Date().getTime(); \n}\n\nfunction fadeTo(obj, time, to, doneFn){\n\n // sanitize optional arguments\n if ( typeof time === \"undefined\" )\n time = 1000;\n if ( typeof to === \"undefined\" )\n to = 1;\n\n if ( time &lt;= 0 )\n return true;\n\n var objSt = obj.style, \n originalOpacity = parseFloat(getComputedStyle(obj, null).getPropertyValue(\"opacity\")),\n deltaOpacity = to - originalOpacity,\n sanitizeOpacity,\n minT = 30,\n startTime = now();\n\n // based on whether we're going up or down, set our santize function\n if (deltaOpacity &gt; 0) {\n sanitizeOpacity = function(x) {\n // not more than 1\n return Math.min(x, 1);\n }\n } else {\n sanitizeOpacity = function(x) {\n // not less than zero\n return Math.max(x, 0);\n }\n }\n\n function step() {\n // calculate how much time has elapsed since start\n // and then calculate what the opacity should be set\n // to for the animation to be perfectly on time\n var elapsed = now() - startTime, completion;\n\n // if all our time has elapsed, then just set to final opacity\n if (elapsed &gt;= time) {\n objSt.opacity = to;\n // we're done, call the completion function\n // with the this pointer set to the object that was animating\n if (doneFn) {\n doneFn.apply(obj);\n }\n } else {\n // still some time remaining\n // calculate ideal opacity value to be \"on time\"\n completion = elapsed/time;\n objSt.opacity = sanitizeOpacity((deltaOpacity * completion) + originalOpacity);\n // schedule next step\n setTimeout(step, minT);\n }\n\n\n }\n // start the animation\n setTimeout(step, minT);\n}\n</code></pre>\n\n<p>Working demo: <a href=\"http://jsfiddle.net/jfriend00/hG3Wj/\" rel=\"nofollow\">http://jsfiddle.net/jfriend00/hG3Wj/</a></p>\n\n<p>In other comments:</p>\n\n<ol>\n<li>You MUST use <code>var</code> in front of variables that should be local variables.</li>\n<li>You need to be getting the original opacity as the computedStyle, not just reading opacity directly because you need to include style sheet opacity, if nothing is set directly on the object.</li>\n<li>If you want to know if an argument is truly undefined, you need to use <code>===</code> to test for it so there can be no automatic type conversions.</li>\n<li>I find it more efficient to define an inner function that is called repeatedly because then all of our argument sanitization and what/not only has to happen once, not on each iteration and we can have state variables in the outer closure.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:15:39.227", "Id": "54521", "Score": "0", "body": "Thanks, that was actually very insightful to my question! I will revise my function to follow a similarity and hopefully it'll run smoothly. Also, I too noticed my hard-coding mistake. It most likely happened because I was in a hurry to write this - I've been struggling with javascript for about a day and now I'm grasping it a bit better. \nI'll do some research on the var-- but I understand what you're saying about it.\nThanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:18:56.023", "Id": "54522", "Score": "0", "body": "@Lemony - code example added to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:25:51.200", "Id": "54526", "Score": "0", "body": "Thanks! It looks great. On a side note, I noticed that if you were to quickly press the \"GO\" button it would flicker until changing to the last wanted opacity.\nSo that means I would have to erase any Timers related to the object fading, right? How show I go about doing this. Saving a variable in the document div called \"fadeTimer\" and erasing it then set it to the new timer each time needed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:29:38.157", "Id": "54528", "Score": "0", "body": "@Lemony - you have to decide what you want the behavior to be if another animation is started while one is currently running. Do you want it to stop the previous one and start the new one, ignore the new one because one is already running, start the new one only when the current one has already finished, etc...? Doing any of these will involve creating a way to safely store some state that an animation of a certain type is running so you can implement one of these behaviors. That's some more code, but it could be leveraged by multiple animation functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:29:58.190", "Id": "54530", "Score": "0", "body": "@Lemony - FYI, things like animation queuing is built into libraries like jQuery." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:36:46.537", "Id": "54531", "Score": "0", "body": "@Lemony - also added a done callback function so you can know when the animation is done" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:44:11.637", "Id": "54532", "Score": "0", "body": "@Lemony - added protection to the demo so it won't start a new animation until the previous one is done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:51:04.523", "Id": "54536", "Score": "0", "body": "Thanks! You helped me quite a bit and gave me a lot more than I could really ask for. Learned quite a bit :). Wish I could keep people in contact because a lot of you that responded are so helpful!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:45:48.577", "Id": "33963", "ParentId": "33962", "Score": "1" } }, { "body": "<p>You can more succinctly express</p>\n\n<pre><code>if ( typeof( time ) == \"undefined\" )\n time = 1000;\n</code></pre>\n\n<p>as</p>\n\n<pre><code>time == null &amp;&amp; (time = 1000);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:02:46.423", "Id": "54518", "Score": "0", "body": "This is a bad suggestion. Readability of code is much more important than it being short. Tools like the closure compiler will convert simple ifs to short circuit for you anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:08:40.517", "Id": "54520", "Score": "0", "body": "If you can't read it that says more about your own familiarity with JavaScript than the code itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:20:20.680", "Id": "54523", "Score": "1", "body": "@QuolonelQuestions Yes, but I am not very familiar with JavaScript yet. -- I do agree with Benjamin a lot; writing readable code is very important. \n\nI do think that overtime the top code would be much easier to read off again if for some reason I took a few months to learn another language and came back to that. But Still, thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:58:48.030", "Id": "33964", "ParentId": "33962", "Score": "-1" } } ]
{ "AcceptedAnswerId": "33963", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:29:56.987", "Id": "33962", "Score": "1", "Tags": [ "javascript" ], "Title": "Should I write my fadeTo function differently?" }
33962
<p>I have a file directory which contains folders for every month, and within those folders are several text files. In this context I would like to copy all of the text files from my <code>January</code> folder into a separate <em>target</em> folder. Then copy all of the text files within the <code>February</code> folder to the <em>target</em> folder, and so on for each month. This needs to happen sequentially and I'm not sure if I'm doing the iteration properly. I need the code to be able to run on several machines, and installing libraries on each is not possible.</p> <p>Am I on the right track with the following? I'm not sure if this is the right approach to take or how to flesh this out. </p> <pre><code>function listdirectory(directory) local i, t, popen = 0, {}, io.popen for filename in popen('dir "'..directory..'" /b /ad'):lines() do i = i + 1 t[i] = filename end return t end os.execute(xcopy folder_month target_folder) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:26:55.713", "Id": "54527", "Score": "0", "body": "There is an extra `end` at the end. It it a function definition?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:29:46.793", "Id": "54529", "Score": "0", "body": "Sorry I forgot to include the function name. That is correct, I've updated the post to reflect that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:46:46.257", "Id": "54576", "Score": "0", "body": "Why do you need to do it file by file? A simple `cp -r path/to/January new/path` would work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T13:21:33.187", "Id": "54585", "Score": "0", "body": "This script is a smaller part of a large process. When the text files are moved into the target folder there is a separate script reading them. When that completes this script will be called again and the next months files will be needed" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:20:10.910", "Id": "33966", "Score": "6", "Tags": [ "lua", "directory" ], "Title": "Copying folder contents from several folders" }
33966
<p><a href="http://en.wikiedia.org/wiki/Computational_complexity_theory" rel="nofollow">Computational complexity</a> is the analysis of how the time and space requirements of an algorithm vary according to the size of the input.</p> <p>A common metric of complexity is <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="nofollow">"Big O" notation</a>, which gives an upper-bound estimate of the running time or required memory. Big O focuses only on the growth behavior, disregarding constant factors, since constant factors would be insignificant for sufficiently large inputs. (An algorithm that requires 7 <em>n</em> + 5 steps and an algorithm that requires 10 <em>n</em> steps are both considered O(<em>n</em>); both of those would be considered less complex than an algorithm requiring 2 <em>n</em><sup>2</sup> steps, which is O(<em>n</em><sup>2</sup>).)</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T04:21:32.130", "Id": "33970", "Score": "0", "Tags": null, "Title": null }
33970
Complexity is the analysis of how the time and space requirements of an algorithm vary according to the size of the input. Use this tag for reviews where the "Big O" is a concern.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T04:21:32.130", "Id": "33971", "Score": "0", "Tags": null, "Title": null }
33971
<p>My application's structure looks like this:</p> <p>Solution: MySolution</p> <p>Projects in MySolution: Host, Business, Server.</p> <p>References between the projects looks like this:</p> <pre><code>Host &lt;-- Business --&gt; Server </code></pre> <p>(Business references Host and Server but Host does not reference Server and vice versa because this causes a circular-)</p> <p>So, I have some Database stuff in Server. I have a property, <code>DBConnectionString</code> - which should contain the connection string. What I want to do is to set this property from the Host but I want to keep all methods that have anything to do with the database in the Server project.</p> <p>Keeping interfaces in mind - so that I can also at a later stage just create an web application.</p> <p>I have some code and it's working but I don't know if this is the right way.</p> <p>I have this interface in Library (connection between the other two projects):</p> <pre><code> public interface IDBUtils { string DBConnectionString { get; set; } bool OpenConnection(); bool CloseConnection(); bool ExecuteSQL(string sql); bool CreateDatabase(string servername, string databaseName, string databaseDataPath); bool CreateDatabaseUser(string servername, string username, string password); } </code></pre> <p>Then the class in Library that has the code for the interface:</p> <pre><code>public string DBConnectionString { get { return DBService.DB.DBUtils.DBConnectionString; } set { DBService.DB.DBUtils.DBConnectionString = value; } } public bool OpenConnection() { return DBService.DB.DBUtils.OpenConnection(); } public bool CloseConnection() { return DBService.DB.DBUtils.CloseConnection(); } public bool ExecuteSQL(string sql) { return DBService.DB.DBUtils.ExecuteSQL(sql); } public bool CreateDatabase(string servername, string databaseName, string databaseDataPath) { return DBService.DB.DBUtils.CreateDatabase(servername, databaseName, databaseDataPath); } public bool CreateDatabaseUser(string servername, string username, string password) { return DBService.DB.DBUtils.CreateDatabaseUser(servername, username, password); } </code></pre> <p>I'm only going to show the property and one method on the server otherwise this is going to get too long.</p> <p>On the Server: Property:</p> <pre><code>public static string DBConnectionString { get; set; } </code></pre> <p>The OpenCOnnection() Method:</p> <pre><code> public static bool OpenConnection() { bool success = false; try { if (DBConnectionString.Length &gt; 0) { conn = new SqlConnection(DBConnectionString); conn.Open(); success = true; } } catch { /* Do nothing... */ } return success; } </code></pre> <p>To set the property from Host on Server:</p> <p>It uses the interface on Library:</p> <pre><code>iDBUtils.DBConnectionString = connectionString.ToString(); </code></pre> <p>To execute a method from Host on Server:</p> <pre><code>iDBUtils.OpenConnection(); </code></pre> <p>So as you can see, Library is the "Middle Man".</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T08:41:54.143", "Id": "54549", "Score": "1", "body": "What about having a Data layer that is your db layer and using a config file for the connection string?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T08:48:20.230", "Id": "54551", "Score": "0", "body": "Yes I understand that, but what about the methods then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T08:49:44.063", "Id": "54552", "Score": "0", "body": "Also, If I put the connection string in the config file, will a company like be able to connect to a central server without going and editing the file? The app is basically on its own and not manual editing is done at the moment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:39:08.597", "Id": "54560", "Score": "0", "body": "That depends on how your db server is setup, network paths etc. But if you have an application that is non-environment dependant (i.e., you can run it from basically any workstation) then it shouldnt be a problem, and keeping your connection string in a config file is preferred." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:22:57.510", "Id": "54568", "Score": "2", "body": "So it's 4 projects then? What's the direction of dependencies between Library and the rest? Imo Business shouldn't depend on anyone, not on the UI, not on the data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:38:36.310", "Id": "54575", "Score": "1", "body": "Is the `Catch { /* do nothing */ }` really swallowing everything that could go wrong with opening a connection? Imo that method should either succeed or blow up with something more meaningful than a `false`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T17:54:58.177", "Id": "54627", "Score": "0", "body": "An aside from the question, but I would refactor DBService.DB.DBUtils to implement the interface with instance methods (since it appears to have all the implementation code anyways) and then optionally create a singleton reference for the DBUtils class if you still really want a static means of accessing it. Then you wouldn't need an instance class wrapper for it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:39:14.593", "Id": "54644", "Score": "0", "body": "WARNING! `string`s can be null. Calling a method on a null reference is, well, `NullReferenceException`" } ]
[ { "body": "<p><strong>Var</strong></p>\n\n<p>Use the <code>var</code> keyword when defining local variables where the right hand side of the definition makes the type obvious. This looks cleaner and saves time when it comes to changing types during refactoring.</p>\n\n<p>e.g.</p>\n\n<pre><code>bool success = false;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>var success = false;\n</code></pre>\n\n<p><strong>Validation</strong></p>\n\n<p>You should validate the arguments to your public methods, any of those strings could be null or empty.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-28T13:16:23.380", "Id": "78870", "ParentId": "33974", "Score": "2" } }, { "body": "<p><strong>Naming</strong> </p>\n\n<p><code>IDBUtils</code> is a name for a namespace, but for an interface representing a database system it is poorly named. Better use something like <code>IDatabase</code>, <code>IDatabaseServer</code> or <code>IDatabaseSystem</code>. </p>\n\n<p><strong>OpenConnection()</strong></p>\n\n<p>This method can be simplified by removing the <code>success</code> variable and also using a guard clause, which reduces horizontal spacing. </p>\n\n<pre><code>public static bool OpenConnection()\n{\n if (String.IsNullOrWhiteSpace(DBConnectionString.Length))\n {\n return false;\n }\n\n try\n {\n conn = new SqlConnection(DBConnectionString);\n conn.Open();\n return true;\n }\n catch { /* Do nothing... */ }\n return false;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-28T13:37:36.983", "Id": "78871", "ParentId": "33974", "Score": "3" } } ]
{ "AcceptedAnswerId": "78871", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T07:42:03.030", "Id": "33974", "Score": "3", "Tags": [ "c#", "interface" ], "Title": "Interfaces and Classes between Projects" }
33974
<p>I am trying to read a large file ~200 MB (~300 million lines of text). I am using a relatively standard way of reading like: </p> <pre><code>for (int i = 1; i &lt;= numProcs; i++) { System.out.println("Parsing " + traceFilePrefix + i + ".prg"); System.out.println("##########################"); try { String line; int instrType; String hexAddr; ArrayList&lt;Trace&gt; traces = new ArrayList&lt;Trace&gt;(); int lineNum = 1; BufferedReader br = new BufferedReader(new FileReader(traceFilePrefix + numProcs + "/" + traceFilePrefix + i + ".PRG")); while ((line = br.readLine()) != null) { line = line.toUpperCase(); // validate line format if (line.matches(regexLineFormat)) { StringTokenizer tokenizer = new StringTokenizer(line); instrType = Integer.parseInt(tokenizer.nextToken()); hexAddr = tokenizer.nextToken(); traces.add(new Trace(instrType, hexAddr)); } else { // line is in invalid format System.err.println("ERR: line " + lineNum + " is invalid \"" + line + "\""); } lineNum++; if (lineNum % 1000 == 0) System.out.println("line " + lineNum); } br.close(); processorsTraces.add(i-1, traces); } catch (Exception e) { e.printStackTrace(); } } </code></pre> <p>I find that reading slows down at about line 20 million... in face it doesnt seem to progress at all ... how can I improve this? Whats the problem in this simple piece of code? </p> <p>A latest run seem to run out of heap space ... I guess I cant store data in an arraylist like that? </p> <p>This is supposed to be a simulator. It first parses trace files containing hexadecimal addresses of memory accesses. Then is supposed to run simulation of these data. This code snipplet only parses and stores the traces in an arraylist. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T18:07:21.060", "Id": "54629", "Score": "0", "body": "Comment the `traces.add` and see if you title is correct. I feel that reading is not a problem at all. It should be a memory, an issue of storing the millions of small objects. Actually, the average size of your lines is 300/200 = 1.5 bytes per item. The overhead will be huge. Since java performance is based on JIT, it does not care about memory efficiency and you will have about 100 bytes overhead per evert 1.5 bytes of real data. You'll need about 30 GB to store all your 300 mln items. Java is not suitable for this task and you have a wrong title." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-31T20:51:12.190", "Id": "63925", "Score": "0", "body": "To be pedantic… a 200 MB file cannot possibly contain 300 million lines of text." } ]
[ { "body": "<p>First thing you should change in the code is avoid reading binary file using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html\" rel=\"nofollow\">FileReader</a>. It is meant for reading streams of character. You can use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html\" rel=\"nofollow\">FileInputStream</a>.</p>\n\n<p>Close <code>io</code> streams in <code>finally</code> block so that they are closed even if an exception is thrown.</p>\n\n<p>Also try increasing the buffer size of the <code>BufferedReader</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:32:57.020", "Id": "54572", "Score": "0", "body": "Oh i put `close()` in try since it also throws an exception. And in this simple program I thought of avoiding the need for so much try catch. Ok but I'll follow ur advice and try changing things" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:35:57.397", "Id": "54573", "Score": "0", "body": "But I am actually reading characters? Its a text file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:37:39.100", "Id": "54574", "Score": "0", "body": "I saw you have extension PRG" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:31:10.807", "Id": "54578", "Score": "0", "body": "for some reason its a \"PRG\" file ... but the data inside is just text" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T10:42:40.153", "Id": "33977", "ParentId": "33976", "Score": "-1" } }, { "body": "<p>I would split this up into a 2-threaded program.</p>\n\n<p>The first thread simply reads into a chunk of the file, say 100.000 (or 1 000.000) first lines, and stores it in an array.</p>\n\n<p>Then the second thread would parse the lines and evaluate them according to your rules.</p>\n\n<p>The first thread would then continue reading the next 100.000 lines, and the second thread does it magic on those lines, and so on until there are no more lines in the file.</p>\n\n<p>What else? Well, you dont actually need your <em>lineNum</em> variable, because <em>i</em> will always have the same value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:31:11.513", "Id": "54570", "Score": "0", "body": "The lecturer advised against using a threaded program because of complexities it introduces. I agree, this is supposed to be a small relatively easy assignment ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T18:16:24.760", "Id": "54630", "Score": "0", "body": "I +1 because your answer corresponds to the (mis)title." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:00:05.747", "Id": "33978", "ParentId": "33976", "Score": "2" } }, { "body": "<p>If the file I/O is really what is slowing you down. Then you should consider how much memory you can afford to use at a given time, and find the trade of between the two.</p>\n\n<p>Decide how much memory you can spare, then read in as much of the file as possible. Then parse out the lines once it is all loaded.</p>\n\n<p>Reading in larger chunks will increase your file I/O speed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:03:06.523", "Id": "54720", "Score": "0", "body": "I was commenting on the file read, as that can help speed it up. Space issues need to be address as a separate thing, which I was not addressing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:16:40.003", "Id": "54743", "Score": "0", "body": "That is why I am telling that you ignored the question. Author clearly says that his problem is dramatically slowed down due to memory limit, which you do not address. Just saying that you have ignored the question does not mean that you responded the real issue." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:11:32.383", "Id": "33989", "ParentId": "33976", "Score": "2" } }, { "body": "<p>The issue is almost certainly in the structure of your <code>Trace</code> class, and it's memory efficiency. You should ensure that the <code>instrType</code> and <code>hexAddress</code> are stored as memory efficient structures. The instrType appears to be an <code>int</code>, which is good, but just make sure that it is declared as an <code>int</code> in the Trace class.</p>\n\n<p>The more likely problem is the size of the hexAddress String. You may not realise it but Strings are notorious for 'leaking' memory. In this case, you have a <code>line</code> and you think you are just getting the hexString from it... but in reality, the hexString contains the entire line.... yeah, really. For example, look at the following code:</p>\n\n<pre><code>public class SToken {\n\n public static void main(String[] args) {\n StringTokenizer tokenizer = new StringTokenizer(\"99 bottles of beer\");\n int instrType = Integer.parseInt(tokenizer.nextToken());\n String hexAddr = tokenizer.nextToken();\n System.out.println(instrType + hexAddr);\n }\n}\n</code></pre>\n\n<p>Now, set a break-point in (I use eclipse) your IDE, and then run it, and you will see that hexAddr contains a char[] array for the entire line, and it has an offset of 3 and a count of 7.</p>\n\n<p>Because of the way that String substring and other constructs work, they can consume huge amounts of memory for short strings... (in theory that memory is shared with other strings though). As a consequence, you are essentially storing the entire file in memory!!!!</p>\n\n<p>At a minimum, you should change your code to:</p>\n\n<pre><code>hexAddr = new String(tokenizer.nextToken().toCharArray());\n</code></pre>\n\n<p>But even better would be:</p>\n\n<pre><code>long hexAddr = parseHexAddress(tokenizer.nextToken());\n</code></pre>\n\n<hr>\n\n<p>EDIT: Request to get help on how to debug the code:</p>\n\n<p>To debug the code, you need to set a break-point in the method. Select the line <code>System.out.println(...);</code> and use the key-board short-cut Ctrl-Shift-B which will toggle a break-point, and you will get the 'dot' marker like the picture below:</p>\n\n<p><img src=\"https://i.stack.imgur.com/EJx7t.jpg\" alt=\"enter image description here\"></p>\n\n<p>Then, with that break-point enabled, you need to debug the program:</p>\n\n<p>Right-click on the 'main' word in the <code>public static void main (String[] ...)</code> and select 'Debug As -> Java Application'</p>\n\n<p>This should prompt you to go to the 'Debug' perspective, and you will have a window with the 'Variables' displayed. One of the variables will be <code>hexAddr</code> and you can expand it to show its contents. Here's a screen-shot:</p>\n\n<p><img src=\"https://i.stack.imgur.com/YU9ec.jpg\" alt=\"enter image description here\"></p>\n\n<p>From the variables section there are a few things of note. At the bottom, the 'value' variable is highlighted, and it's internal value is shown in the area below ( <code>[9, 9, , b, o, ......, r]</code></p>\n\n<p>You can see the <code>count</code> and <code>offset</code> variables for <code>hexAddr</code> too. This means that the <code>hexAddr</code> variable stores the char[] array for the entire line, but also stores an offset and count in that array which it uses for managing the subset of the chars that this String instance is interested in</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:32:27.300", "Id": "54579", "Score": "0", "body": "Ok I will change hex address to int first. Its currently a string" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T13:05:54.947", "Id": "54582", "Score": "0", "body": "When I execute your code, I just get \"99bottles\" how do you get the array and stuff? I am using Eclipse J2EE Kepler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T13:33:15.747", "Id": "54588", "Score": "0", "body": "\"String theory\" is true .... believe it or not. Haters will hate... :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:23:20.753", "Id": "54591", "Score": "1", "body": "Note that the `char[]` sharing is no longer true in recent Oracle/OpenJDK releases (at least in Java 7 and I think even in newer Java 6 releases), it has been modified so that every `String` has its own `char[]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:24:48.450", "Id": "54592", "Score": "0", "body": "@JoachimSauer - huh, did not know that. Thanks. I use IBM's JDK and it's still true there. I presume also true in the OP's environment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:29:57.533", "Id": "54594", "Score": "0", "body": "I checked, and I'm not sure you're right. The copy-the-value constructor here, which is used in substring, etc. See: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/String.java#String.%3Cinit%3E%28int%2Cint%2Cchar[]%29" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T10:11:44.140", "Id": "54702", "Score": "2", "body": "@rolfl: I mis-remembered the exact versions: it's JDK8 since b40 and JDK7 since u6: http://mail.openjdk.java.net/pipermail/core-libs-dev/2012-May/010257.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T11:33:52.220", "Id": "54706", "Score": "0", "body": "@JoachimSauer thanks for the update. This is interesting and it is this type of information that will make a positive difference in my work later (when I discover one of those places where I took advantage of the sharing...)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:14:06.970", "Id": "33990", "ParentId": "33976", "Score": "18" } }, { "body": "<p>First: When memory is an issue, you cannot read the entire data set into memory. You need to follow an algorithm similar to (pseudo code)</p>\n\n<pre><code>while(notDone){\n readFixedAmountOfData();\n processData();\n}\n</code></pre>\n\n<p>Right now, you are doing</p>\n\n<pre><code>readALLData(); // &lt;- everything goes into memory\nprocessData();\n</code></pre>\n\n<p>For specific points in your code:</p>\n\n<ul>\n<li>If you know the data is ASCII text, don't use Reader classes and don't use Strings, use raw InputStream (or some derivative) and use byte[].</li>\n<li>avoid superfluous calls that create excess objects (e.g. <code>line = line.toUpperCase()</code> creates a new String -- do you really need it in upper case?)</li>\n<li>What does the <code>Trace</code> class look like? That will play a significant part of this.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:56:39.070", "Id": "33997", "ParentId": "33976", "Score": "3" } }, { "body": "<p>I see several issues that could impact performance</p>\n\n<pre><code> if (line.matches(regexLineFormat)) {\n</code></pre>\n\n<p>If the file is large, compiling the regular expression would be a performance bottleneck.\nSuggest to put the following block in to a static block:</p>\n\n<pre><code> Pattern regexLineFormatPattern = Pattern.compile(regexLineFormat);\n</code></pre>\n\n<p>And then use </p>\n\n<pre><code>if (regexLineFormatPattern.matcher(line).matches()){\n</code></pre>\n\n<p>References: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\">Java Doc of Pattern class</a></p>\n\n<p>And then since you are already using regular expression, you could try to use regular expression to complete the work done by <code>StringTokenizer</code> to replace the following code:</p>\n\n<pre><code>StringTokenizer tokenizer = new StringTokenizer(line);\ninstrType = Integer.parseInt(tokenizer.nextToken());\nhexAddr = tokenizer.nextToken();\n</code></pre>\n\n<p>The <code>Matcher#group</code> method would be helpful to extract the value from the String.</p>\n\n<p>The code would be like this:</p>\n\n<pre><code>//outside the looop, better in a static block\nString regexLineFormat = \"(\\d+) ([^ ]+) ....\"//define the capture groups here.\n\nPattern regexLineFormatPattern = Pattern.compile(regexLineFormat);\n\n//in the method, inside the loop\n\nMatcher matcher = regexLineFormatPattern.matches(line);\n\nif( matcher.matches()){\n traces.add(new Trace(Integer.parseInt(matcher.group(1)),matcher.group(2)));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T16:05:44.127", "Id": "34007", "ParentId": "33976", "Score": "6" } }, { "body": "<p>Since you have a 300/200 bytes per line, this means that you'll have a lot of identical items in your list. Consider <a href=\"https://en.wikipedia.org/wiki/Flyweight_pattern\" rel=\"nofollow\">flyweight pattern</a> to save your memory requirements. As experiment, add the same item 300 mln times in your list. It is the minumum amount of memory you need. See if you have so much.</p>\n\n<p>I wonder how do you manage to have a type/address with 1.5 bytes/instruction. Since hex address is supposed to be different every time, you cannot use flyweight. Yet, you may use the heap as a cache whereas the program is stored on disk. Yet, <a href=\"http://valjok.blogspot.com/2013/04/java-gc-makes-memory-management.html\" rel=\"nofollow\">java is bad for disk swapping</a> again.</p>\n\n<p>Since you'll have a memory map, it may be cheaper to allocate an array <code>int[max_hex_address]</code> for storing the types. A 300 million of integers is only 1.2 GB.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T18:14:58.550", "Id": "34012", "ParentId": "33976", "Score": "0" } } ]
{ "AcceptedAnswerId": "33990", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T10:21:19.963", "Id": "33976", "Score": "10", "Tags": [ "java", "performance", "io" ], "Title": "Reading Large Files in Java getting really slow" }
33976
Cocoa is Apple's application-development framework for macOS, consisting of Foundation, Application Kit, and Core Data.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-11-07T11:43:10.683", "Id": "33980", "Score": "0", "Tags": null, "Title": null }
33980
Canvas is a drawing element introduced to web development with HTML5.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:45:01.520", "Id": "33982", "Score": "0", "Tags": null, "Title": null }
33982
<p><a href="https://www.mongodb.org/" rel="nofollow">MongoDB</a> is based on NoSQL databases, which means:</p> <blockquote> <p>When compared to relational databases, NoSQL databases are more scalable and provide superior performance, and their data model addresses several issues that the relational model is not designed to address.</p> </blockquote> <p>Data is stored in BSON documents, similar to JSON structures. It may be helpful to think of documents as analogous to rows in a relational database, fields as similar to columns, and collections as similar to tables.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:47:16.860", "Id": "33983", "Score": "0", "Tags": null, "Title": null }
33983
MongoDB is a scalable, high-performance, open source, document-oriented database. It supports a large number of languages and application development platforms.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:47:16.860", "Id": "33984", "Score": "0", "Tags": null, "Title": null }
33984
OCaml is a strict statically-typed functional programming language, focusing on expressivity, correctness and efficiency.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:52:25.353", "Id": "33986", "Score": "0", "Tags": null, "Title": null }
33986
<p>Shuffling is the process by which the order of the elements in a collection is randomized. One effective algorithm for doing so is as follows:</p> <p>For a zero-based collection of <code>n</code> elements:</p> <ol> <li>i = n</li> <li>j = random integer between 0 and i (inclusive)</li> <li>Swap the values of the elements at j and i</li> <li>i = i - 1</li> <li>If (i > 0), go to 2</li> </ol> <p>This is called the <a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow">Fisher-Yates shuffle</a> and has a time complexity of O(n).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:57:48.033", "Id": "33987", "Score": "0", "Tags": null, "Title": null }
33987
Shuffling is the act of randomizing the order of the elements in a collection.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:57:48.033", "Id": "33988", "Score": "0", "Tags": null, "Title": null }
33988
Parsec is a parser library for the Haskell programming language.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:19:46.977", "Id": "33993", "Score": "0", "Tags": null, "Title": null }
33993
<p>I'm working on a simple little one page website for giving a presentation and I have some working code now, but I'm thinking there has to be a more elegant way of doing this. I would describe myself, at best, as a "dabbler" in JavaScript at this point; I'm much more comfortable with statically-typed languages and am doing this as a learning exercise.</p> <p>Here's my <a href="http://jsfiddle.net/ECDZY/3/" rel="nofollow">JSFiddle</a> showing what I am doing.</p> <p>In my "real" site, the <code>PageContent</code> object is coming from an AJAX POST response (via an instance of node.js). I've included all of that code to make it easier to understand what is going on (any suggestions on how to restructure that server-side code would also be appreciated). If I have the time, I'll probably read these "points" from a config file or something else, but for now, a switch statement fits my needs.</p> <p>The segment of this that makes me the most uneasy is this:</p> <pre><code>$('#pageContent').append('&lt;li id="' + i + '"&gt;' + mp.main); if (mp.subPoints.length &gt; 0){ $('li#'+i).append('&lt;ul&gt;'); $.each(mp.subPoints, function(index, sp){ $('li#'+i+' ul').append('&lt;li&gt;' + sp + '&lt;/li&gt;'); }); $('li#'+i).append('&lt;/ul&gt;'); } $('#pageContent').append('&lt;/li&gt;'); </code></pre> <p>I don't like how I am having to add <code>id</code> values to my list items so I can then append my subpoints to the correct parent. Is there a less hacky-feeling way to go about this?</p> <p>In case it isn't obvious from the fiddle, the page should show a list of main points, and, if they exist, subpoints under each main point. I'm basically trying to mimic PowerPoint.</p> <p>Any criticisms of this code would be gladly accepted; I know this probably isn't idiomatic JavaScript.</p>
[]
[ { "body": "<p>You do not need to add the id to the created <code>li</code> if you store it to a variable. </p>\n\n<p>The code below shows the basic concept. Does it make you more comfortable?</p>\n\n<pre><code>$.each(current.contents, function(_, mp){\n var $li = $('&lt;li&gt;' + mp.main + '&lt;/li&gt;'); \n if (mp.subPoints.length){\n var $ul =$('&lt;ul&gt;')\n $.each(mp.subPoints, function(_, sp){\n $ul.append('&lt;li&gt;' + sp + '&lt;/li&gt;');\n });\n $li.append($ul);\n }\n $pageContent.append($li);\n});\n</code></pre>\n\n<p>Here's a <a href=\"http://jsfiddle.net/4Lyu6/4/\" rel=\"nofollow\">fiddle using the different coding</a> I'm sure this could be improved more. I'm also still learning.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T15:59:16.460", "Id": "54612", "Score": "0", "body": "That is a helpful suggestion, thanks. Is it a best practice to have the index variable named the same when doing nested each loops like you have there (_ as the variable name) if you aren't going to use it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T16:22:30.680", "Id": "54615", "Score": "0", "body": "I've been given the impression that using _ for a variable you do not intend to use is considered common practice at least. I got this impression from [this question with answers on SO.](http://stackoverflow.com/questions/11406823/underscore-as-a-jquery-javascript-variable)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T16:28:47.470", "Id": "54616", "Score": "0", "body": "To answer the other part of your question, it hardly matters what the name of the index variable are since they are not used. If they were used, javascript would use the correct ones. Javascript handles scoping of variables on the function level, so even with a [name conflict](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FFunctions_and_function_scope#Name_conflicts) the correct variable would be used. I didn't even think about the same name issue since the indexes aren't used." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T15:54:03.777", "Id": "34005", "ParentId": "34002", "Score": "2" } }, { "body": "<p>This will depend on your content and how you prepare it, but I'd suggest a very generic solution that'll work for any level of nested points. Now, arbitrary nesting doesn't appear to be required in your case, but, hey, nice to have.</p>\n\n<p>Suppose your JSON content is structured like so:</p>\n\n<pre><code>var points = [\n {title: \"Point\", children: [\n {title: \"Point\"},\n {title: \"Point\"},\n {title: \"Point\"},\n {title: \"Point\", children: [\n {title: \"Point\"},\n {title: \"Point\"},\n {title: \"Point\", children: [\n // more...?\n ]}\n ]}\n ]}\n]\n</code></pre>\n\n<p>You'll note that you can just keep nesting the points indefinitely.</p>\n\n<p>To render this as HTML, you can use a recursive function. Like this:</p>\n\n<pre><code>function buildList(parentElement, items) {\n var i, l, list, li;\n if( !items || !items.length ) { return; } // return here if there are no items to render\n list = $(\"&lt;ul&gt;&lt;/ul&gt;\").appendTo(parentElement); // create a list element within the parent element\n for(i = 0, l = items.length ; i &lt; l ; i++) {\n li = $(\"&lt;li&gt;&lt;/li&gt;\").text(items[i].title); // make a list item element\n buildList(li, items[i].children); // add its subpoints\n list.append(li);\n }\n}\n</code></pre>\n\n<p>And call it like so:</p>\n\n<pre><code>buildList($(\"#pageContent\").empty(), points);\n</code></pre>\n\n<p>The point is that since the structure is recursive, it can nest to any depth, but the code is simpler.</p>\n\n<p><a href=\"http://jsfiddle.net/e28r4/\" rel=\"nofollow\">Here's a jsfiddle</a>. This is quite a different approach, and Daniel Cook's answer is probably more immediately applicable to you current code, but I thought it worth to point out.</p>\n\n<p>You could also extend it to add the \"1\", \"1.1\", \"1.2\" (and so on) numbers to the titles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T19:51:21.153", "Id": "54638", "Score": "0", "body": "I don't know why I didn't think of recursive functions, yes, that would work very nicely." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T17:54:59.210", "Id": "34011", "ParentId": "34002", "Score": "3" } } ]
{ "AcceptedAnswerId": "34011", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T14:55:00.540", "Id": "34002", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Creating lists and sublists dynamically" }
34002
<p>This example is simplified down to the bare minimum. No <code>DatabaseAdapter</code> <code>IdentityMap</code> or anything. No <code>fetch()</code> method. Just what is needed to demonstrate this.</p> <p>If all your data mappers have a method:</p> <pre><code>/** * @return EntityType */ public function assign(EntityType $entity, Array $row); </code></pre> <p>You are basically creating a new blank entity each time you want to assign data to it.</p> <p>I have began thinking what if all the data mappers get an entity of the related type injected into its constructor:</p> <pre><code>UserMapper::__construct(User $user) </code></pre> <p>Now the </p> <p><code>UserMapper::assign(User $user, Array $row)</code></p> <p>method could be changed to</p> <pre><code>UserMapper::assign(Array $row); </code></pre> <p>Since the mapper has an instance of a <code>User</code> object which it got when the mapper was constructed and it just assigns the row data to that.</p> <p>There is a slight problem though because if I do something like the following:</p> <pre><code>$user1 = $userMapper-&gt;assign( array('username' =&gt; 'user1') ); $user2 = $userMapper-&gt;assign( array('username' =&gt; 'user2') ); // Now $user1 has the same username as $user2. $user2-&gt;setUsername('user2_something'); </code></pre> <p>Any changes I make to either user instance reflects in the other instance.</p> <p>This can be solved by cloning the single user instance in the mapper when returning it in the assign method:</p> <pre><code>public function assign(Array $row) { $this-&gt;user-&gt;setUsername( $row['username'] ); return clone $this-&gt;user; } </code></pre> <h2>UPDATE: Or Maybe Better...</h2> <pre><code>// Now the user object in the mapper never changes, just gets cloned. public function assign(Array $row) { $user = clone $this-&gt;user; $user-&gt;setUsername( $row['username'] ); return $user; } </code></pre> <p>And now the user instance you get back from the <code>UserMapper::assign(Array $row)</code> method does not point to the user instance inside the mapper.</p> <p>I have never had to use the <code>clone</code> feature before so I am not too sure about it.</p> <p>Is this implementation okay? Could it cause any problems?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:23:46.523", "Id": "54668", "Score": "0", "body": "Which library do you use? There are at least several PHP libraries that claim DataMapper implementation and all of them are different in details." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T09:43:51.613", "Id": "54701", "Score": "0", "body": "I don't use any library for this. I have seen a few implementations of data DataMapper but never really liked any of them. I came up with this idea yesterday and wanted to see if anyone can find any pitfalls in it. It is nicer and easier to just do `$user = $userMapper->assign($userDataArray);` instead of first creating a `User` object and passing it in also. The mapper is for transferring of data between domain objects and that is what it does. I have seen examples where the mapper creates the actual entity. I don't think it is its job to do that. In my example it keeps cloning 1 entity." } ]
[ { "body": "<p>I can't speak to cloning specifically, as I've never used it before, but here are a few basic things to think about.</p>\n\n<p><strong>Is the User class used in any other methods of your UserMapper?</strong></p>\n\n<p>If it is then injecting it in the constructor, or through a setter is ideal as it no longer depends on a user object being passed to it in each method.</p>\n\n<p>This is basic OOP.</p>\n\n<p><strong>Are you perhaps trying to do too much for the scope of this class?</strong></p>\n\n<p>If we follow the Single Responsibility Principle, as we should, then our classes should be responsible for just one thing. According to WikiPedia:</p>\n\n<blockquote>\n <p>A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer).</p>\n</blockquote>\n\n<p>To me, this means that a Data Mapper is essentially a database read/write object. What you have here seems to be a Factory object that builds individual User objects. If what you are trying to accomplish is indeed a Factory and not a Data Mapper, then you should call it what it is to avoid confusion. But for a Data Mapper the <code>assign()</code> method seems to be out of scope. You might consider refactoring your code, perhaps create a new class if necessary. If this is the only violation, then perhaps a better way of doing this would be to simply create the new object out of the class and remove the <code>assign()</code> method.</p>\n\n<p><strong>Is your User class perhaps doing too much?</strong></p>\n\n<p>It seems odd seeing a user object that allows you to change its name on the fly like this. Most user objects, that I'm familiar with, perform these kinds of operations in instantiation. Allowing this kind of change is invisible to the rest of your code. In other words, between one method and the next, the object can change and your code wont know the difference. So it is possible to encounter \"state\" errors, such as information from a previous user not being overwritten by the new user.</p>\n\n<p>Sorry I couldn't be more precise, but with so little to work with its hard to determine what you are trying to accomplish. Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T19:57:29.640", "Id": "35381", "ParentId": "34004", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T15:28:27.657", "Id": "34004", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "Data mapper reuse related domain object for setting data and return a clone of the domain object" }
34004
<p>I'm just wanting feedback on the efficiency, design and layout of this code if possible please. I suspect it's weird having a constructor with nothing in. I'd be grateful if it could be explained how to modify the code to fit in with conventions, especially in this respect, but also in others.</p> <pre><code>package cubes; import java.util.ArrayList; public class Cubes { ArrayList&lt;Integer&gt; sum = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; x = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; y = new ArrayList&lt;Integer&gt;(); boolean found = false; int cSum = 0, a = 0 , b = 0, c = 0, d = 0, k, floor; Integer cubeSum, X, Y, answer; double K, J, cs; int iterations; public static void main(String[] args) { Cubes c = new Cubes(); c.find(); } public Cubes() { } private void find() { int i = 3; K = (double)2; J = (double)1; cs = Math.pow(K,3.0)+Math.pow(J,3.0); cubeSum = new Integer((int) cs); sum.add(cubeSum); x.add(1); y.add(2); i = 4; while(found!=true) { floor = (int)Math.floor(i/2); for(int j = 1; j &lt; floor+1; j++) { k=i-j; K = (double)k; J = (double)j; cs = Math.pow(K,3.0)+Math.pow(J,3.0); cubeSum = new Integer((int) cs); X = new Integer((int) j); Y = new Integer((int) k); for (int l = 0; l &lt; sum.size(); l++) { a = (int)x.get(l); b = (int)y.get(l); if(cubeSum.compareTo(sum.get(l))==0) { if (a != j &amp;&amp; a != k &amp;&amp; b != j &amp;&amp; b != k) { c=j; d=k; System.out.println("The first positive integer " + "expressible as the sum\nof 2 different positive" + " cubes in 2 different ways\nis " + cubeSum + " = " +a+"^3 + "+b+"^3 = " + c+"^3 + "+d+"^3"); found=true; } } } sum.add(cubeSum); x.add(X); y.add(Y); } i++; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T21:28:31.287", "Id": "54652", "Score": "0", "body": "In other words, find the smallest positive integer expressible as a sum of two cubes in two different ways. http://mathworld.wolfram.com/Hardy-RamanujanNumber.html" } ]
[ { "body": "<p>There are a few things I would like to comment on:</p>\n\n<ol>\n<li>Whether you have an empty constructor or not is irrelevant. In your case, there already was a public 'default' (empty) constructor, and you have just made it explicit. This is neither a good thing nor a bad thing. Many classes have an empty constructor. Many IDE's will warn you that you have an empty method though, so I recommend that you put a comment in there to make it happy: <code>// empty constructor does nothing</code>. On the other hand, you will have the identical Java behaviour if you remove the constructor entirely (the default constructor is <code>public Cubes() {}</code> anyway).</li>\n<li>Do you really need to even create an instance of the class? Sometimes it makes things neater, but sometimes it is just redundant. In your case, I would be just as happy to put all the logic in the main method (you do not need to do anything object related, so why bother).</li>\n<li>in general, when doing 'high performance computing' (which is what this problem is), it is best to optimize the algorithms as much as possible. In your case, th regular conversions of values from <code>double</code> to <code>int</code> and to <code>Integer</code> is just wasting CPU time.</li>\n<li>similarly, storing values as <code>Integers</code> in an <code>ArrayList</code> means that you are creating lots of Integer values and you are regularly converting them back to <code>int</code> to do the math.</li>\n<li>finally, sometimes moving the heavy computations (the <code>Math.pow(....)</code> ) out of the loop is a good thing. Is there any reason why you have to continuously repeat the calculation of integer powers?</li>\n</ol>\n\n<p>So, taking the above in to consideration, consider the following method, it has the properies:</p>\n\n<ol>\n<li>it precomputes the powers, saving redundant computation time in the loops.</li>\n<li>it does not do any primitive to Object 'auto-boxing'.</li>\n<li>it uses binary search for fast lookups.</li>\n<li>it uses primitive-based comparisons and arithmetic.</li>\n</ol>\n\n\n\n<pre><code>public static void main(String[] args) {\n\n long[] cubes = new long[8192];\n int ncubes = 0;\n // your code limits the largest sum to Integer.MAX_INT (your code declares 'i' to be 'int')\n // I'll calculate all the way to half of Long.MAX_VALUE instead....\n // pre-calculate the cube value of all cubes less than Integer.MAX_INT.\n for (long i = 0; i &lt; Integer.MAX_VALUE; i++) {\n final long cube = i * i * i;\n if (cube &gt; (Long.MAX_VALUE &gt;&gt;&gt; 1)) {\n break;\n }\n if (ncubes &gt;= cubes.length) {\n cubes = Arrays.copyOf(cubes, cubes.length * 2);\n }\n cubes[ncubes++] = cube;\n }\n cubes = Arrays.copyOf(cubes, ncubes);\n\n System.out.println(\"There are \" + ncubes + \" int values which have cubes less than \" + Long.MAX_VALUE);\n\n // Now, start from the smallest possible sum-of-cubes.\n // we start from 1 and 4 because we know that there needs to be at least 2 cubes between them in order\n // to have another pair that has the same sum.\n for (long sum = cubes[1] + cubes[4]; sum &lt; Long.MAX_VALUE; sum++) {\n // go through all the 'i' cubes which are less than half the sum (because we still need to add a larger value)\n final long halfsum = sum &gt;&gt; 1;\n for (int i = 1; i &lt; cubes.length - 4 &amp;&amp; cubes[i] &lt; halfsum; i++) {\n // find a 'partner' for cube[i] that together will add up to match the target sum\n final int jmatch = Arrays.binarySearch(cubes, i+3, cubes.length - (i + 3), sum - cubes[i]);\n if (jmatch &gt;= 0) {\n // there's one pair that matches the target sum.... let's see if there's another.\n // the other pair will have to be somewhere in between these two values.\n for (int k = i+1; k &lt;= jmatch - 2 &amp;&amp; cubes[k] &lt; halfsum; k++) {\n // start scanning ahead, and look for it....\n final long difference = sum - cubes[k];\n int match = Arrays.binarySearch(cubes, k+1, jmatch, difference);\n if (match &gt;= 0) {\n System.out.printf(\"Both pairs (%d,%d) and (%d,%d) have cube-sums of %d\\n\", i, jmatch, k, match, sum);\n }\n }\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T19:03:00.613", "Id": "54632", "Score": "0", "body": "Looks like a good answer. I haven't taken it all in yet. I must admit that I'm not familiar with the >> or >>> operators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T19:03:58.657", "Id": "54633", "Score": "1", "body": "In all cases (in this code - because all the values are positive) they just mean 'divide by 2'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T19:31:38.453", "Id": "54636", "Score": "0", "body": "Why not just use '/2'? +1 for info. I might have accepted this answer prematurely though. Was your code supposed to be a complete solution? If so, it doesn't seem to be correct, since it doesn't stop when it finds the Hardy-Ramanujan number. Your post does contain useful info though. I'm a fair way from understanding everything you've written, but I have already learnt some useful things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:05:45.430", "Id": "54639", "Score": "1", "body": "If you are really only after the first valid numbers, then simply `return` after the `System.out.println` line. Otherwise it is complete.... but will keep running until it gets to very large combinations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T21:46:04.547", "Id": "54654", "Score": "0", "body": "Good. I like it. Answer reaccepted. +1 for return info. I had thought of doing that, but for some reason I didn't bother and got distracted. In this particular case, searching ahead results in lots of unnecesary computation, but I suppose there are cases where it's worth doing so." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T18:45:52.523", "Id": "34013", "ParentId": "34009", "Score": "4" } }, { "body": "<h3>Discrete Mathematics</h3>\n\n<p>Discrete calculations should not be done using floating-point math. You should be <a href=\"http://falseproofs.blogspot.ca/2006/06/simpsons-and-fermats-last-theorem.html\" rel=\"nofollow noreferrer\">suspicious</a> of any results contaminated by floating-point math. The way to compute the cube of an integer is <code>n * n * n</code>. For larger powers, <a href=\"https://stackoverflow.com/q/101439\">do repeated squaring</a>, or use <code>BigInteger.pow()</code> (which is slower, but immune to overflow).</p>\n\n<h3>Variable Usage</h3>\n\n<p>To be honest, I found your code extremely difficult to read, mainly due to the way you misuse variables.</p>\n\n<ul>\n<li><strong>Scope:</strong> You should declare and define variables as close as possible to the point of use. If a variable only applies within a loop, declare and define it inside the loop. If it's local to a function, define it as a local variable in the function. Instead, you've used a lot of instance variables, which, for all practical purposes, are \"global\" (since you only have one class). As you really only have one function, <em>all</em> of the variables should have been local!</li>\n<li><strong>Proliferation:</strong> You've declared 19 instance variables. Surely fewer variables would suffice? A human brain can keep track of about 7 items at a time. You have <code>cSum</code> (an <code>int</code>), <code>cubeSum</code> (an <code>Integer</code>), and <code>cs</code> (a <code>double</code>) — which raises the question, how are they related? (Answer: <code>cSum</code> is never used, and <code>cs</code> is just a temporary variable that shouldn't have been needed at all.) Also, <code>answer</code> and <code>iterations</code> are never used. You've got so many variables that you couldn't keep track of the dead ones to prune.</li>\n<li><strong>Cryptic naming:</strong> Without studying the code, can you remember what <code>x</code>, <code>y</code>, <code>k</code>, <code>X</code>, <code>Y</code>, <code>K</code>, <code>J</code>, and <code>floor</code> mean? If not, then your variables are named too cryptically.</li>\n<li><strong>Unconventional naming:</strong> By connotation, I would expect <code>x</code> to represent a floating-point number, not a list of <code>Integer</code>s. Then, you've also got <code>X</code>, which is a boxed version of <code>j</code>.</li>\n<li><strong>Misuse for flow control:</strong> To terminate the loop, why do you set a variable and test for <code>found != true</code> elsewhere? Just <code>return</code> after printing the result — you're done!</li>\n</ul>\n\n<h3>Language Disfluency</h3>\n\n<p>If you familiarize yourself with the Java language a bit more, you can express yourself less clumsily.</p>\n\n<ul>\n<li><strong>Prefer primitives:</strong> You should always prefer the primitives (e.g. <code>int</code>) to their boxed counterparts (<code>Integer</code>). Code written using primitives reads better and performs better. The boxed types exist mainly so that you can store them in collections such as <code>ArrayList&lt;Integer&gt;</code>. Even then, the compiler will automatically <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7\" rel=\"nofollow noreferrer\">box</a> and <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.8\" rel=\"nofollow noreferrer\">unbox</a> the values for you, so you don't have to say <code>new Integer(n)</code>.</li>\n<li><strong>Type Promotion:</strong> The compiler will automatically perform <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2\" rel=\"nofollow noreferrer\">widening conversions</a>, such as promoting <code>int</code> to <code>double</code>, so casting is unnecessary in those cases.</li>\n<li><strong>Integer division:</strong> When dividing an integer by an integer, the result will also be integral (<a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.2\" rel=\"nofollow noreferrer\">with truncation towards 0</a>). When you do <code>(int)Math.floor(i/2)</code>, you're just promoting <code>i / 2</code> to a <code>double</code> argument, rounding it to the same <code>double</code>, and casting the result back to an <code>int</code>. It would have been sufficient to just do <code>i / 2</code>.</li>\n</ul>\n\n<hr>\n\n<h3>Time Out… Let's Rewrite!</h3>\n\n<p>Let's rewrite the code using the trivial simplifications mentioned so far.</p>\n\n<pre><code>import java.util.ArrayList;\n\npublic class Cubes {\n\n public static void main(String[] args) {\n new Cubes().find();\n }\n\n private void find()\n {\n ArrayList&lt;Integer&gt; sum = new ArrayList&lt;Integer&gt;();\n ArrayList&lt;Integer&gt; x = new ArrayList&lt;Integer&gt;();\n ArrayList&lt;Integer&gt; y = new ArrayList&lt;Integer&gt;();\n int a, b, c, d;\n\n sum.add((2 * 2 * 2) + (1 * 1 * 1));\n x.add(1);\n y.add(2);\n\n int i = 4;\n\n while(true)\n {\n for(int j = 1; j &lt; i/2 +1; j++)\n {\n int k=i-j;\n int cubeSum = (k * k * k) + (j * j * j);\n\n for (int l = 0; l &lt; sum.size(); l++)\n {\n a = (int)x.get(l);\n b = (int)y.get(l);\n if(cubeSum == sum.get(l))\n {\n if (a != j &amp;&amp; a != k &amp;&amp; b != j &amp;&amp; b != k)\n {\n c=j;\n d=k;\n System.out.println(\"The first positive integer \"\n + \"expressible as the sum\\nof 2 different positive\"\n + \" cubes in 2 different ways\\nis \"\n + cubeSum + \" = \" +a+\"^3 + \"+b+\"^3 = \"\n + c+\"^3 + \"+d+\"^3\");\n return;\n }\n }\n }\n\n sum.add(cubeSum);\n x.add(j);\n y.add(k);\n }\n i++;\n }\n }\n}\n</code></pre>\n\n<p>I find the rewritten version slightly more readable than the original, though I still can't really understand it.</p>\n\n<hr>\n\n<p>Now, back to our regularly scheduled programming…</p>\n\n<h3>Algorithm</h3>\n\n<ul>\n<li><strong>Magic numbers:</strong> You start with <code>x.add(1)</code>, <code>y.add(2)</code>, and <code>i = 4</code>. Where did those magic numbers come from? They're not naturally part of the problem, and you didn't explain.</li>\n<li><strong><code>x</code> vs. <code>y</code>:</strong> What do lists <code>x</code> and <code>y</code> represent? How does a number end up on these lists, why would it appear on <code>x</code> rather than <code>y</code>, or <code>y</code> rather than <code>x</code>?</li>\n<li><strong>Commenting:</strong> What is the strategy of your code? <em>Please</em> outline it in a comment. Mathematical algorithms in general are complicated, and algorithms, more than anything else, need comments!</li>\n<li><strong>False proof:</strong> How do you know that you've found the <em>minimum</em> answer rather than just any answer? I'm not convinced at all. In fact, if you remove the <code>return</code> after <code>System.out.println()</code> and just let it run, you'll see that it prints <code>110808 = 6^3 + 48^3 = 27^3 + 45^3</code> <em>before</em> <code>110656 = 4^3 + 48^3 = 36^3 + 40^3</code>. Therefore, the fact that your program prints 1729 is <em>luck</em>, not <em>skill</em>.</li>\n<li><strong>Separation of concerns:</strong> If you force yourself to separate the code that does input/output from the code that does pure computation, then you will also force yourself to write well organized code.</li>\n</ul>\n\n<h3>Proposed Solution</h3>\n\n<p>Since your algorithm is bogus, we'll have to start from scratch. I propose an algorithm in which we iterate through <em>n</em> = 1, 2, 3, 4, … until we find one that is the sum of two cubes. Then we test if it is also expressible as a sum of another two cubes. Since we're testing <em>n</em> in increasing sequence, we can be sure that the first result is indeed the <em>minimum</em> number meeting the criteria.</p>\n\n<p>To test whether <em>n</em> is a sum of two cubes, we can successively try subtracting 1<sup>3</sup>, 2<sup>3</sup>, 3<sup>3</sup>, 4<sup>3</sup>, … and test whether the difference is also a perfect cube. To test whether the difference is a perfect cube, we could take its cube root (floating point — nope!), or check it against a list of perfect cubes (better — raising integers to the third power is easy). I've written a class called <code>Cubes</code> to help enumerate all perfect cubes.</p>\n\n<p>There's a lot of verbose supporting code. However, if you look at the heart of the solution, which is <code>hardyRamanujanBreakdown(long n)</code>, you'll find it to be very readable.</p>\n\n<p>I've also written it such that you can easily modify the program to find subsequent numbers that are representable as sums of two cubes in two ways. If you let this run infinitely, it's vulnerable to overflow, but you'll have hit <kbd>Ctrl</kbd><kbd>C</kbd> long before that happens. ☺ </p>\n\n<p>It's also slower than your original, but the original strategy is flawed, so it doesn't count.</p>\n\n<pre><code>import java.util.Iterator;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\n\n//////////////////////////////////////////////////////////////////////\n\n/**\n * An iterator of positive perfect cubes, starting from 1, and ignoring\n * overflow.\n */\nclass Cubes implements Iterator&lt;Long&gt; {\n /**\n * An \"infinite\" set of all perfect cubes.\n */\n private static SortedSet&lt;Long&gt; allCubes = new TreeSet&lt;Long&gt;();\n\n /**\n * Helper to generate more members of allCubes as needed.\n */\n private static Cubes allIter = new Cubes();\n static {\n allCubes.add(allIter.next());\n }\n\n public static boolean isCube(long num) {\n while (num &gt; allCubes.last()) {\n allCubes.add(allIter.next());\n }\n return allCubes.contains(num);\n }\n\n public static int cubeRoot(long num) {\n while (num &gt; allCubes.last()) {\n allCubes.add(allIter.next());\n }\n return 1 + allCubes.headSet(num).size();\n }\n\n public static final long cube(int num) {\n return (long)num * num * num;\n }\n\n\n private int i = 1;\n\n @Override\n public boolean hasNext() {\n return true;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public Long next() {\n return cube(this.i++);\n }\n\n public Cubes dup() {\n Cubes moreCubes = new Cubes();\n moreCubes.i = this.i;\n return moreCubes;\n }\n}\n\n//////////////////////////////////////////////////////////////////////\n\npublic class HardyRamanujan implements Iterator&lt;Long&gt; {\n\n private long n;\n private long[] breakdown;\n\n public HardyRamanujan() {\n this.n = 1;\n }\n\n @Override\n public boolean hasNext() {\n // Ignores overflow\n return true;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public Long next() {\n while (null == (this.breakdown = hardyRamanujanBreakdown(this.n))) {\n this.n++;\n }\n return this.n++;\n }\n\n /**\n * Returns the breakdown of the current Hardy-Ramanujan number n as an\n * array of four perfect cubes [a, b, c, d]. n = a + b = c + d.\n * a &lt; c &lt;= n/2 &lt;= d &lt; b. Returns null if next() has never been called.\n */\n public long[] breakdown() {\n return this.breakdown;\n }\n\n private static long[] hardyRamanujanBreakdown(long n) {\n long a, b, c, d;\n\n // Exists n == a + b, where a and b are cubes?\n Cubes cubes = new Cubes();\n while ((a = cubes.next()) &lt; n / 2) {\n if (!Cubes.isCube(b = n - a)) {\n continue;\n }\n\n // If so, exists n == c + d, where c and d are cubes, and c &gt; a ?\n Cubes moreCubes = cubes.dup();\n while ((c = moreCubes.next()) &lt;= n / 2) {\n if (!Cubes.isCube(d = n - c)) {\n continue;\n }\n return new long[] { a, b, c, d };\n }\n }\n return null;\n }\n\n public static void main(String[] args) {\n HardyRamanujan hrIter = new HardyRamanujan();\n do {\n long hrNum = hrIter.next();\n long[] breakdown = hrIter.breakdown();\n System.out.format(\"%d = %d^3 + %d^3 = %d^3 + %d^3\\n\",\n hrNum,\n Cubes.cubeRoot(breakdown[0]),\n Cubes.cubeRoot(breakdown[1]),\n Cubes.cubeRoot(breakdown[2]),\n Cubes.cubeRoot(breakdown[3]));\n } while (false); // Change to true to get more!\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T08:34:54.307", "Id": "54700", "Score": "0", "body": "By the way, the solution proposed here is essentially the same as @rolfl's algorithm, just implemented differently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T15:00:24.217", "Id": "54717", "Score": "0", "body": "Thanks: you've made lots of useful points here, especially that the algorithm I used obtains the result by luck. (+1)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T05:26:55.303", "Id": "34045", "ParentId": "34009", "Score": "6" } } ]
{ "AcceptedAnswerId": "34013", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T17:18:27.737", "Id": "34009", "Score": "4", "Tags": [ "java", "mathematics" ], "Title": "How is my program for computing the Hardy-Ramanujan number?" }
34009
<p>I am asking about the right way to make a component that holds some state. This includes a Jbutton that saves a color in it, or a list item that saves a certain object. So when those GUI components fire an event, I can use the saved states to do something with it.</p> <p>My way is like this:</p> <ol> <li><p>Make a subclass of the required component, like a subclass from Jbutton.</p></li> <li><p>Make a Listener for this new subclass: in the listener check, if the event source is the subclass, convert it and then use the stored data.</p></li> </ol> <p></p> <pre><code>class ColorButton extends JButton { static class Listener implements ActionListener{ @Override public void actionPerformed(ActionEvent actionEvent) { Object source = actionEvent.getSource(); if( source.getClass() == ColorButton.class) { ColorButton t = (ColorButton) source; t.getComponent().setBackground(t.getColor()); } } } //states i want to be saved private Color c; private Component comp; ColorButton(Component comp, Color c) { setColorChanger(comp, c); } /* ...... ...... rest of constructors added with those additions ...... */ private void setColorChanger(Component comp, Color c) { this.comp = comp; this.c = c; } Color getColor() { return c; } Component getComponent() { return comp; } } </code></pre> <p>And I use it this way: </p> <pre><code>JPanel panel = new JPanel(); ColorButton.Listener l = new ColorButton.Listener(); JButton b = new ColorButton("Blue", panel, Color.BLUE); JButton r = new ColorButton("Red", panel, Color.RED); r.addActionListener(l); b.addActionListener(l); panel.add(b); panel.add(r); add(panel); </code></pre> <p>I am wondering: is this way okay? I feel it is very boring to make this for every component that should hold a certain state. Is there a better way?</p>
[]
[ { "body": "<p>Instead of comparing the class with <code>if( source.getClass() == ColorButton.class)</code> you can use <code>if (source instanceof ColorButton)</code>. This is preferable in case you would make a subclass of <code>ColorButton</code>. If it's an instance of a subclass of <code>ColorButton</code> it is still an <code>instanceof</code> but <code>source.getClass() != ColorButton.class</code>.</p>\n\n<p>With the way that you are using the code above, I would save the color in the <strong>listener</strong> instead of in the button. This way you don't need the if statement in your code at all, since you can pass the appropriate type to the Listener. In this case, <code>.setBackground</code> is declared in the <code>JComponent</code> class so all you need to make sure is that it's a <code>JComponent</code> that gets passed to the Listener, which is no problem:</p>\n\n<pre><code>static class Listener implements ActionListener {\n private Color color;\n private JComponent comp;\n public Listener(JComponent comp, Color color) {\n this.color = color;\n this.comp = comp;\n }\n @Override\n public void actionPerformed(ActionEvent actionEvent) {\n comp.setBackground(this.color);\n }\n}\n</code></pre>\n\n<p>By using this, you don't need the <code>ColorButton</code> subclass, instead you create multiple instances of your listener:</p>\n\n<pre><code>JPanel panel = new JPanel();\nJButton b = new JButton(\"Blue\");\nJButton r = new JButton(\"Red\");\nr.addActionListener(new Listener(panel, Color.BLUE));\nb.addActionListener(new Listener(panel, Color.RED));\npanel.add(b);\npanel.add(r);\nadd(panel);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T10:45:07.210", "Id": "54703", "Score": "1", "body": "much better than making contructors for the subclass which saves time and it and less code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T22:48:49.320", "Id": "34021", "ParentId": "34015", "Score": "4" } } ]
{ "AcceptedAnswerId": "34021", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T19:22:29.033", "Id": "34015", "Score": "3", "Tags": [ "java", "swing" ], "Title": "Create GUI components with states" }
34015
<p>The variable <code>result</code> is an integer representing the exit code of a command line process that was run via Groovy code. An exit code of 0 means the process was successful and an exit code from 1-255 means a failure. Then this line is executed:</p> <pre><code>println result ? "The command failed." : "The command succeeded." </code></pre> <p>What's happening here is that <code>result</code> is being coerced to a boolean (nonzero is true, zero is false) and then the ternary operator is used to determine which message to print, telling the user if the command succeeded or failed.</p> <p>Is this fine in the context of the Groovy language, or is this going a bit too far with implicit magic?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:40:46.343", "Id": "54645", "Score": "6", "body": "Nothing about this seems like magic. It is _very_ straightforward especially in light of the [Elvis Operator](http://docs.codehaus.org/display/GROOVY/Operators#Operators-ElvisOperator%28%3F%3A%29)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T05:32:47.910", "Id": "54694", "Score": "0", "body": "anyone who can read code should understand Ternary operations." } ]
[ { "body": "<p>I don't do JS or Groovy stuff, so I'm a bit biased (and possibly completely wrong).</p>\n\n<p>What I would normally expect in such an expression is </p>\n\n<pre><code>{bool expression} ? {true part} : {false part}\n</code></pre>\n\n<p>... and your <em>groovy</em> code has that reversed, which <em>is</em> confusing, if not a bug (I don't know how Groovy implicitly converts integers into Booleans).</p>\n\n<p>If the language allows it, I would cast/convert <code>result</code> into a <code>Boolean</code> to make it more clear, because implicit conversions can cause not only surprises, but also nasty unexpected bugs.</p>\n\n<p>Bottom line, <em>write code as if the next person reading it was a dangerous psychopath that knows where you live</em> - and that person might be your <em>future self</em>!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:29:29.700", "Id": "54642", "Score": "0", "body": "the standard for exit codes is successful=0 (which would coerce to false) and failure >0 (which would coerce to true)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:42:26.213", "Id": "54646", "Score": "0", "body": "If my future self can't understand a ternary expression there's little hope for him." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:43:10.373", "Id": "54647", "Score": "0", "body": "This isn't about the ternary expression (I use them all the time in C#). If `result` were a Boolean, `result ? \"command failed\" : \"command succeeded\"` would look wrong. What I'm saying is that using implicit conversion in this case forces the casual reader to *look twice* before saying \"ah, ok I get it\". OTOH, by making the conversion explicit, you instantly eliminate any ambiguity and find yourself having to reverse the two string values to keep the resulting string correct, hence the readability issue with implicit conversion in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:50:14.403", "Id": "54649", "Score": "3", "body": "I Agree with @retailcoder - but would go further and add a function to do the checking for me: `println successful(result) ? \"the command succeeded.\" : \"The command failed.\"`. This has served me well in the past when dealing with program exit codes, etc. where the 'external' logic is not the same as the natural logic of the language. In C language for example, the `0 == true` is 'normal' and the code above would need to be adapted too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T15:48:38.357", "Id": "54719", "Score": "0", "body": "May I ask *why* this post was downvoted?! Has the downvoter also downvoted the accepted answer, which says the same thing worded differently/better? I'll gladly edit this post if I have to." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:01:45.590", "Id": "34018", "ParentId": "34016", "Score": "2" } }, { "body": "<p>In your original post, you wrote</p>\n<blockquote>\n<p>The variable result is an integer representing the exit code of a command line process that was run via Groovy code. An exit code of 0 means the process was successful and an exit code from 1-255 means a failure. Then this line is executed:</p>\n<p>println result ? &quot;The command failed.&quot; : &quot;The command succeeded.&quot;</p>\n</blockquote>\n<p>I find it interesting you had to explain it so much. I imagine if this were real code you may have to attach a similar code comment.</p>\n<p>Personally I prefer to write code that requires no comments, if possible, and no explanation, by using well-crafted symbols. So for example if you wrote it as</p>\n<pre><code>boolean success = (exitCode == 0);\nprintln success ? &quot;The command succeeded.&quot; : &quot;The command failed.&quot;;\n</code></pre>\n<p>...you wouldn't have to explain that a exit code of 0 indicates success, and it wouldn't require a second glance to figure out the reversed ternary expression.</p>\n<p>Any compiler worth its salt will optimize out the working variable and emit exactly the same executable code, so the increased readability costs you nothing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T14:59:22.060", "Id": "54716", "Score": "0", "body": "that's exactly why I made the question. the code isn't complicated, but the fact that it required an explanation was a bad smell." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:32:23.670", "Id": "34028", "ParentId": "34016", "Score": "5" } }, { "body": "<p>I think it's common knowledge in groovy, and it's idiomatic, to rely on the \"truthiness\" of non-boolean values. The only change that I'd suggest to what you have is to put the explicit parens in for the println, so:</p>\n\n<pre><code>println(result ? \"The command failed.\" : \"The command succeeded.\")\n</code></pre>\n\n<p>At my first glance at what you wrote, I was misunderstanding the precedence and thinking that you were evaluating the truthiness of <code>println result</code> (which is a <code>void</code> method so would always be \"falsy\"). With the parens in place, I think it's obvious that you're coercing the <code>result</code> into it's truthiness value and the rest is self documenting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T11:25:09.900", "Id": "54705", "Score": "0", "body": "This still leaves the ternary expression reversed, which still requires a double-read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:23:33.690", "Id": "54751", "Score": "1", "body": "ah, I see what you're saying now about that. yeah, it is a little confusing that the `true` value is a failure. I think that could be fixed by changing the variable name to something like `failedExitCode`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:53:01.550", "Id": "54753", "Score": "0", "body": "Indeed - but John Wu's `successful` function solution is even better :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T04:15:33.803", "Id": "34036", "ParentId": "34016", "Score": "1" } } ]
{ "AcceptedAnswerId": "34028", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T19:30:22.367", "Id": "34016", "Score": "3", "Tags": [ "error-handling", "groovy", "child-process" ], "Title": "Reporting success or failure of a child process" }
34016
<p>I created a class a while ago that I named a "Recursion Array". It is a way to create dynamically memoized sequences such as the Fibonacci sequence or the factorial numbers sequences. The concept is to create mathematic sequences defined by recursion by only providing the first values and the recursive formula; all the computed results are internally stored into a vector. That allows to create mathematic formula in a recursive way, without having to care about the access time; each result is only computed once. Here is the base class:</p> <pre><code>#include &lt;initializer_list&gt; #include &lt;vector&gt; template&lt;typename T&gt; types_t; template&lt;typename Derived&gt; class RecursionArray { public: using value_type = typename types_t&lt;Derived&gt;::value_type; // A RecursionArray is not copyable RecursionArray(const RecursionArray&amp;) = delete; RecursionArray&amp; operator=(const RecursionArray&amp;) = delete; /** * @brief Calls "function" and applies memoization * @see value_type self(size_t n) */ inline auto operator()(std::size_t n) -&gt; value_type { return self(n); } protected: RecursionArray() = default; /** * @brief Initializer-list constructor * * This should be the one and only way to instance a * RecursionArray. * * @param vals Results of "function" for the first values */ RecursionArray(std::initializer_list&lt;value_type&gt; vals): _values(vals.begin(), vals.end()) {} /** * @brief Calls "function" and applies memoization * * @param n Index of the value to [compute, memoize and] return * @return Value of "function" for n */ auto self(std::size_t n) -&gt; value_type { while (size() &lt;= n) { // Compute and add the values to the vector _values.emplace_back(function(size())); } return _values[n]; } /** * @brief Returns the number of computed elements * @return Number of computed elements in the vector */ constexpr auto size() const -&gt; std::size_t { return _values.size(); } /** * @brief User-defined function whose results are stored * * This is the core of the class. A RecursionArray is just * meant to store the results of "function" are reuse them * instead of computing them another time. That is why a * RecursionArray function can only accept unsigned integers * as parameters. * * @param n Index of the element * @return See user-defined function */ auto function(std::size_t n) -&gt; value_type { return static_cast&lt;Derived&amp;&gt;(*this).function(n); } private: // Member data std::vector&lt;value_type&gt; _values; /**&lt; Computed results of "function" */ }; </code></pre> <p>It is a base class that uses static polymorphism. Here is an example of a user-defined derived class:</p> <pre><code>class MemoizedFibonacci; /* * We need to tell to the RecursionArray which * kind of data it has to store. */ template&lt;&gt; struct types_t&lt;MemoizedFibonacci&gt; { using value_type = unsigned int; }; /** * @brief Fibonacci function class * * A way to implement the Fibonacci function and to force it * to store its results in order to gain some speed with the * following calls to the function. */ struct MemoizedFibonacci: RecursionArray&lt;MemoizedFibonacci&gt; { using super = RecursionArray&lt;MemoizedFibonacci&gt;; using typename super::value_type; /** * @brief Default constructor * * To use a Fibonacci function, we need to know at least * its first two values (for 0 and 1) which are 0 and 1. * We pass those values to the RecursionArray constructor. */ MemoizedFibonacci(): super( { 0, 1 } ) {} /** * @brief Fibonacci function * * Fibonacci function considering that the first values are * already known. Also, "self" will call "function" and * memoize its results. * * @param n Wanted Fibonacci number * @return nth Fibonacci number */ auto function(std::size_t n) -&gt; value_type { return self(n-1) + self(n-2); } }; </code></pre> <p>And finally, here is how we can use the user-defined class:</p> <pre><code>int main() { MemoizedFibonacci fibonacci; // The Fibonacci numbers up to the nth are computed // and stored into the RecursionArray std::cout &lt;&lt; fibonacci(12) &lt;&lt; std::endl; // 144 std::cout &lt;&lt; fibonacci(0) &lt;&lt; std::endl; // 0 std::cout &lt;&lt; fibonacci(1) &lt;&lt; std::endl; // 1 std::cout &lt;&lt; fibonacci(25) &lt;&lt; std::endl; // 75025 } </code></pre> <p>The problem is that I want to keep the user side simple, but also to avoid <code>virtual</code> (hence the static polymorphism). There are three main functions in the class: * <code>function</code>: the recursive formula. * <code>operator()</code>: so that the end user can use the final instances as functions. * <code>self</code>: helper function (same as operator()) so that the recursive formula is easier to write.</p> <p>It would be great if the user did not have to specialize <code>types_t</code> and could just give <code>MemoizedFibonacci</code>, but I can't seem to find a way to do so. Do you whether there would be some way to ease the functor writer work?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T09:12:29.847", "Id": "75873", "Score": "0", "body": "I am not very experienced with C++, but wouldn't it be better to pass in the `value_type` as an argument to the template: `RecursionArray<MemoizedFibonnacci, unsigned int>`? It seems you *really* like templates, and have overused them a little bit ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T12:09:26.370", "Id": "75882", "Score": "0", "body": "@amon Haha, I know what you mean. At first, the reason was since `RecursiveArray` already knows `Derived`, there is no reason to pass to it any other template parameters than can be found in `Derived`. I say `unsigned int` in `types_t` and if I want to change it, I only have to change it in one place. But note that I failed since I wrote `unsigned int` int `MemoizedFibonacci` while I should have written `types_t<MemoizedFibonacci>::value_type`, which is quite dumb since I created `types_t` so that I would have to write `unsigned int` in only one place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T23:06:39.800", "Id": "78415", "Score": "0", "body": "I don't like to do this, but I edited the code I posted to show how `types_t` is useful for DRY." } ]
[ { "body": "<p>There's a (slight) typo in what you've posted - the forward declaration of <code>types_t</code>:</p>\n\n<pre><code> template&lt;typename T&gt;\n types_t;\n// ^^^^^^^^\n// Should be struct types_t;\n</code></pre>\n\n<p>Similarly, you've forward defined <code>class MemoizedFibonacci</code> and then defined it as <code>struct MemoizedFibonacci</code> (this isn't really a problem, but clang will complain about it with warnings enabled).</p>\n\n<p>It'd be nice to not have to specialise a <code>struct</code> with a <code>value_type</code>. Often, <code>decltype</code> can help you get around this, however, in this case, since you're using CRTP and static polymorphism, it's unfortunately not going to work. I actually agree that using another template parameter is potentially a better solution here than to force specialisation of a <code>template</code>.</p>\n\n<p>To me, the largest shortcoming here is that this only works with functions that take a single <code>std::size_t</code> parameter. Perhaps this is fine for your uses (calculating mathematical sequences that depend only on 1 variable). Using variadic templates, you can lift this restriction (at the expense of imposing another). Something like the following (incomplete, but hopefully gives you the idea):</p>\n\n<pre><code>#include &lt;tuple&gt;\n#include &lt;unordered_map&gt;\n\ntemplate&lt;typename Derived, typename... Args&gt;\nclass RecursionArray\n{\n\npublic:\n using argument_type = std::tuple&lt;Args...&gt;;\n\n inline auto operator()(Args&amp;&amp;... args)\n -&gt; value_type\n {\n return self(std::forward&lt;Args&gt;(args)...);\n }\n\n auto self(Args&amp;&amp;... args)\n -&gt; value_type\n {\n auto tup = argument_type(args...);\n auto it = values_.find(tup);\n if(it != values_.end()) {\n return it-&gt;second;\n }\n auto p = values_.emplace(std::make_pair(std::move(tup), function(std::forward&lt;Args&gt;(args)...));\n return p.first-&gt;second;\n }\n\nprivate:\n std::unordered_map&lt;argument_type, value_type&gt; values_;\n\n};\n</code></pre>\n\n<p>This lifts the restriction that you need to have a single <code>std::size_t</code> parameter, at the expense of extra complexity, and the ability to easily enforce computation up to a given size. Whether the trade-off is worth it is up to you, but it is something to think about.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T15:26:17.307", "Id": "76492", "Score": "0", "body": "Well, for a more general memoizer, I already asked [that question](http://codereview.stackexchange.com/q/35180/15094). This structure was dedicated to memoize recursive functions, hence some design choices. As I detailed in the comments under the question, the `types_t` specialization is to write the `value_type` only (which I failed to do...). Concerning the `struct`/`class`, I have to admit that I totally overlooked it. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T02:04:22.977", "Id": "44116", "ParentId": "34022", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T23:34:10.063", "Id": "34022", "Score": "8", "Tags": [ "c++", "c++11", "recursion", "cache", "fibonacci-sequence" ], "Title": "Optimize RecursionArray interface" }
34022
<p>I have an array of a struct containing 5 byte values. I need to sort this array by each value in a different order depending on the situation. These arrays are sometimes quite small (10-30 elements), sometimes quite large (1024-16384). </p> <p>Below is the code I'm using. The reason this has become a bottleneck for me is due to having to make it an array again which reallocates memory for it if I understand correctly (for both the sort and turning it back to an array). My desire is to sort the array the way I want (which can be one of the 3 below situations) without having to do something like ToArray and instead populate the array that exists.</p> <p>I may be entirely wrong about sorting like this or my analysis of the problem, which is why I'm here. If anyone can point me to a better way to do this, please let me know. This program needs to be able to call this routine hundreds (sometimes thousands) of times per second.</p> <pre><code>public enum eCubeType : byte { Air = 0, Dirt = 1 } public struct strCubeFace { public byte X, Y, Z, LightLevel; public eCubeType CubeType; } </code></pre> <p>Function call snippet including array sorting code:</p> <pre><code> if (iSide == 0 || iSide == 1) { Faces = Faces.OrderBy(c =&gt; c.Y).ThenBy(c =&gt; c.CubeType).ThenBy(c =&gt; c.LightLevel).ThenBy(c =&gt; c.X).ThenBy(c =&gt; c.Z).ToArray(); SmartMesh0(); } if (iSide == 2 || iSide == 3) { Faces = Faces.OrderBy(c =&gt; c.Z).ThenBy(c =&gt; c.CubeType).ThenBy(c =&gt; c.LightLevel).ThenBy(c =&gt; c.X).ThenBy(c =&gt; c.Y).ToArray(); //SmartMesh1(); } if (iSide == 4 || iSide == 5) { Faces = Faces.OrderBy(c =&gt; c.X).ThenBy(c =&gt; c.CubeType).ThenBy(c =&gt; c.LightLevel).ThenBy(c =&gt; c.Y).ThenBy(c =&gt; c.Z).ToArray(); //SmartMesh2(); } </code></pre> <p>Edit for @svick or anyone else wanting to know more details:</p> <p>This is in regards to a 3D procedural map generator that expands as the player moves outwards. The terrain is geometrically similar to that of Infiniminer or Minecraft. This lends itself well to combining like faces of the cube based terrain to lower vertices by 50% or higher (usually higher).</p> <p>After generating the points I need to represent each cube, it's light level, and so on; I then iterate over every solid block that is adjacent to transparent/translucent blocks to create the strCubeFace structure I use to represent individual faces.</p> <p>Unless I am simply doing this whole process in a very "bad" way for performance, I need to sort 6 of these arrays per chunk (grouping of 32x256x32 cubes), one for each face. It is indeed always a different array each time it is needed to be sorted. It doesn't necessarily need to be an array, but as I already know the total number of cubes adjacent to transparent/translucent blocks, setting up a simple array of the max size made the most sense to me (once the array is populated, if the number of faces in each specific array is larger than the array's length, I simply re-size the array down prior to the sort). It is my belief that most other collection storage techniques would incur a higher processing penalty or a higher memory storage penalty.</p> <p>The only reason I am sorting these to begin with, which is probably most important to know/understand, is so that I can iterate over the sorted array of faces to very quickly/easily create the vertices necessary to combine like faces.</p> <p>Sorry for rambling so much, but this is a rather big project and I'm not so good at condensing down my reasoning for any of these things without nearly writing a paper on the subject since it's all so intertwined. I'd nearly just post the whole project for review, but that would seem inappropriate (that and my code is borderline illegible at times as I'm currently just a hobbyist).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T00:36:00.953", "Id": "54662", "Score": "0", "body": "Why exactly do you need to sort it so often? Is it always a different array or do you sort the same array over and over to get different views? Also, why does it have to be an array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T03:10:26.750", "Id": "54676", "Score": "0", "body": "@svick If you think you could help me and it'd be better to do so via email or chat, just let me know. As I try to say in my edit, I'm probably not explaining this terribly well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T13:38:31.180", "Id": "54711", "Score": "0", "body": "Have you considered using [octree](https://en.wikipedia.org/wiki/Octree)? It could limit the number of cubes significantly and will also mean you don't have to sort all the time to find cubes that are close." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:44:09.840", "Id": "54745", "Score": "0", "body": "I use a quadtree for storing chunks as they are pillars (they never stack). I'd probably need a better explanation regarding how to use an octree in reference to limiting the number of cubes or to avoid sorting. Feel free to E-Mail me (address is in my profile) if you're up for that." } ]
[ { "body": "<p>If your analysis is correct and the slowdown is really cased by the copying, then you could avoid that by using <a href=\"http://msdn.microsoft.com/en-us/library/System.Array.Sort\"><code>Array.Sort()</code></a>, which directly sorts the array you have.</p>\n\n<p>Though <code>Array.Sort()</code> isn't as convenient as <code>OrderBy()</code> combined with <code>ThenBy()</code>, you will have to create an <code>IComparer</code> or <code>Comparison</code> for each of the possible sort orders. It could look something like this:</p>\n\n<pre><code>Comparison&lt;eCubeType&gt; yFirstComparison = (c1, c2) =&gt;\n{\n int result = c1.Y.CompareTo(c2.Y);\n if (result != 0)\n return result;\n\n // ...\n\n return c1.Z.CompareTo(c2.Z);\n}\n</code></pre>\n\n<p>If you don't like to do this manually you can use <a href=\"http://www.nuget.org/packages/NList/\">NList</a> (the project site seems to be down at the moment):</p>\n\n<pre><code>IComparer&lt;eCubeType&gt; yFirstComparer = KeyComparer&lt;eCubeType&gt;.OrderBy(c =&gt; c.Y)\n .ThenBy(c =&gt; c.CubeType).ThenBy(c =&gt; c.LightLevel).ThenBy(c =&gt; c.X).ThenBy(c =&gt; c.Z);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T21:57:39.950", "Id": "54761", "Score": "0", "body": "Without even changing anything else, using the Comparison method eliminated the whole performance issue. Thank you very much." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T00:49:25.937", "Id": "34025", "ParentId": "34023", "Score": "8" } } ]
{ "AcceptedAnswerId": "34025", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T00:03:01.243", "Id": "34023", "Score": "4", "Tags": [ "c#", "performance", "array", "sorting", "game" ], "Title": "Improving performance when sorting array of structs by multiple fields" }
34023
<blockquote> <p><strong>Question: Simple Calculator</strong></p> <p>Input loaded from file. Instructions can be any binary operators. Ignore math precedence. Last input is apply and a number e.g. "apply 5". Calc is then initialized with that number and previous instructions are applied to it.</p> <p>Also: There is no requirement to cater for invalid input.</p> </blockquote> <p><strong>Example 1:</strong></p> <blockquote> <p>[Input from file]</p> <pre><code>add 2 multiply 3 apply 3 </code></pre> <p>[Output to screen]</p> <pre><code>15 </code></pre> <p>[Explanation]</p> <pre><code>(3 + 2) * 3 = 15 </code></pre> </blockquote> <p><strong>Example 2:</strong></p> <blockquote> <p>[Input from file]</p> <pre><code>multiply 9 apply 5 </code></pre> <p>[Output to screen]</p> <pre><code>45 </code></pre> <p>[Explanation]</p> <pre><code>5 * 9 = 45 </code></pre> </blockquote> <p><strong>Example 3:</strong></p> <blockquote> <p>[Input from file]</p> <pre><code>apply 1 </code></pre> <p>[Output to screen]</p> <pre><code>1 </code></pre> </blockquote> <p>I've submitted the following code (with unit tests). I think the mistakes I made were:</p> <ol> <li><p>I think the design was too complicated because I created a processor interface, which could have multiple implementations. Maybe the command class was a bad idea.</p></li> <li><p>Leaving this method in Operator, but not using it: <code>abstract BigDecimal calculate(BigDecimal x);</code> and not providing a Boolean method in the abstract class to determine which of these methods should be used by a client class. </p></li> <li><p>The <code>getSymbol</code> method in <code>FileCalculationConsumer</code>. If the design was generic, I should not have hard coded that method.</p></li> <li><p>Badly-named files?</p></li> </ol> <p>There may other places where I went wrong. Any feedback is appreciated.</p> <p><strong>class FileCalculationConsumer</strong></p> <pre><code>import java.io.File; import java.io.FileNotFoundException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; /** * Main Class for the File based Calculation Consumer. Calculation instructions * are consumed in batches. * * The FileCalculationConsumer class provides methods to consume Calculation * Instructions from a flat file. Calculation instructions are mapped to * Command objects. Processing of the command objects is delegated to a * processor. * * */ public class FileCalculationConsumer implements CalculationConsumer { private String inputPath=""; private Scanner in; private int batchSize = 100; int batchCount=0; private CommandProcessor processor; private FileCalculationConsumer(String inputPath, CommandProcessor processor) { this.inputPath = inputPath; try { this.in = new Scanner(new File(inputPath)); } catch (FileNotFoundException e) { System.err.println("Input file not found at path: " + inputPath); return; } if(processor == null) { System.err.println("CommandProcessor must not be null"); return; } this.processor = processor; } /** * Initialises the Consumer with the input file path and the processor. * * @param inputPath The path of the input file containing Calculation instructions * @param processor The processor for the calculation command objects * @param batchSize The size of each batch of instructions to consume * @throws IllegalAccessException * @throws BatchSizeInvalidException */ public FileCalculationConsumer(String inputPath, CommandProcessor processor,int batchSize) throws BatchSizeInvalidException { this(inputPath,processor); if(batchSize&lt;1) { throw new BatchSizeInvalidException("Batchsize must be larger than zero"); } this.batchSize = batchSize; } /* (non-Javadoc) * @see CalculationConsumer#consume() */ @Override public void consume() { Queue&lt;Command&gt; commands = readCommandBatch(); processor.process(commands); if(commands.size() == batchSize) { consume(); } else { in.close(); } } /** * * Reads in a batch of Calculation instructions and creates a new * Command object for each one. * * @return A queue of commands, which has the size as configured by * the batchsize variable. */ public LinkedList&lt;Command&gt; readCommandBatch() { LinkedList&lt;Command&gt; result = new LinkedList&lt;&gt;(); int count=0; while(in.hasNext() &amp;&amp; count &lt; batchSize) { String operation = getSymbol(in.next()); BigDecimal operand = in.nextBigDecimal(); Command command = new Command(operation,operand); result.add(command); if(in.hasNextLine()) in.nextLine(); count++; } return result; } private String getSymbol(String operation) { if(operation.equals("add")) return "+"; else if (operation.equals("multiply")) { return "*"; } else if (operation.equals("apply")) { return "="; } else { throw new IllegalArgumentException(operation + "Is an invalid operator"); } } public String getInputPath() { return inputPath; } /** * Main entry point for the File based Calculation Consumer. Calculation instructions * are consumed in batches. * * @param args */ public static void main(String[] args) { if(args.length!=2) { System.err.println("Usage: Java FileCalculationConsumer &lt;filepath&gt; &lt;batchsize&gt;"); return; } int batchSize=0; String inputFile=args[0]; String batchSizeString=args[1]; try{ batchSize = Integer.parseInt(batchSizeString); } catch(NumberFormatException e) { System.err.println("Usage: Batchsize must be numeric"); return; } consume(batchSize, inputFile); } private static void consume(int batchSize, String inputFile) { List&lt;Operator&gt; operators = createOperators(); CommandProcessor processor = new DefaultCommandProcessor(new Calculator(operators)); CalculationConsumer consumer=null; try { consumer = new FileCalculationConsumer(inputFile,processor,batchSize); } catch (BatchSizeInvalidException e) { System.err.println("BatchSize must be greater than zero"); return; } consumer.consume(); } private static List&lt;Operator&gt; createOperators() { List&lt;Operator&gt; operators = new ArrayList&lt;&gt;(); Operator multiply = Operator.createMultiplyOperator(); Operator add = Operator.createAddOperator(); operators.add(multiply); operators.add(add); return operators; } } </code></pre> <p><strong>interface CalculationConsumer</strong></p> <pre><code>/** * A consumer for Calculation Instructions. * */ public interface CalculationConsumer { /** * Consumes Calculation Instructions */ public abstract void consume(); } </code></pre> <p><strong>class DefaultCommandProcessor</strong></p> <pre><code>import java.util.ArrayDeque; import java.util.Deque; import java.util.Queue; /** * The DefaultCommandProcessor class provides the default implementation of the * CommandProcessor. This processor reorders the commands, so that the Apply command * is first in the queue of the commands. Calculation is delegated to the Calculator * class. * */ public class DefaultCommandProcessor implements CommandProcessor { private Calculator calc; private Deque&lt;Command&gt; deque = new ArrayDeque&lt;Command&gt;(); /** * Initialises this processor with a specific calculator. * @param calc */ public DefaultCommandProcessor(Calculator calc) { this.calc = calc; } /** * @param deque */ private void calculate(Deque&lt;Command&gt; deque) { for (Command command : deque) { calc.calculate(command); } } @Override public void process(Command command) { if(command.getOperation().equals("=")) { deque.addFirst(command); calculate(deque); calc.displayResult(); calc.resetState(); deque.clear(); } else { deque.add(command); } } @Override public void process(Queue&lt;Command&gt; commands) { for (Command command : commands) { process(command); } } } </code></pre> <p><strong>interface CommandProcessor</strong></p> <pre><code>import java.util.Queue; public interface CommandProcessor { /** * Processes a single command object * * @param command */ void process(Command command); /** * Processes a queue of command objects * * @param commands */ void process(Queue&lt;Command&gt; commands); } </code></pre> <p><strong>class Command</strong></p> <pre><code>import java.math.BigDecimal; /** * The Command class encapsulates a Calculation request. * This class is immutable. * * Example operation "+" * Example operand 2 * * */ public class Command { private String operation; private BigDecimal operand; /** * Initializes the immutable Command * @param operation The operation to perform * @param operand The associated operand */ public Command(String operation, BigDecimal operand) { this.operation = operation; this.operand = operand; } /** * Accessor of the Operation of a Command * @return a String representation of the operator */ public String getOperation() { return operation; } /** * Accessor for the operand, which is the value that this * operator is applied to. * @return */ public BigDecimal getOperand() { return operand; } } </code></pre> <p><strong>class Calculator</strong></p> <pre><code>import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The Calculator class provides a stateful calculator, with * operators passed in at construction. * * */ public class Calculator { HashMap&lt;String, Operator&gt; operators = new HashMap&lt;&gt;(); private BigDecimal operand1=new BigDecimal(0); /** * Initializes a new Calculator with the operators provided. * * @param operators The operators this Calculator can use to * perform mathematical operations. */ public Calculator(List&lt;Operator&gt; operators) { for (Operator operator : operators) { this.operators.put(operator.getSymbol(),operator); } } /** * Handles a command. If the command is an equals command, * the state of the calculator is updated to reflect this. * Otherwise the corresponding mathematical * operation is performed for this command and then the calculator state is updated * to reflect this operation. * * @param com */ public void calculate(Command com) { if(com.getOperation().equals("=")) { operand1=com.getOperand(); return; } else { String operation = com.getOperation(); Operator op = operators.get(operation); operand1 = op.calculate(operand1,com.getOperand()); } } /** * Accessor for the operators set for this Calculator. * * @return An unmodifiable collection of immutable operators. */ public Map&lt;String, Operator&gt; getOperators() { return Collections.unmodifiableMap(operators); } /** * Displays the current state of the calculator to * the console */ void displayResult() { System.out.println(operand1.toString()); } /** * Displays the current state of the calculator * @return */ public BigDecimal getOperand1() { return operand1; } /** * Resets the state of the calculator */ public void resetState() { operand1= new BigDecimal(0); } } </code></pre> <p><strong>interface CalculationConsumer</strong></p> <pre><code>/** * A consumer for Calculation Instructions. * */ public interface CalculationConsumer { /** * Consumes Calculation Instructions */ public abstract void consume(); } </code></pre> <p><strong>class operator</strong></p> <pre><code>import java.math.BigDecimal; /** * Provides an immutable abstract type for a binary * mathematical operator * * */ public abstract class Operator { private String symbol; public Operator(String symbol) { this.symbol=symbol; } abstract BigDecimal calculate(BigDecimal x, BigDecimal y); abstract BigDecimal calculate(BigDecimal x); public String getSymbol() { return symbol; } static Operator createAddOperator() { Operator add = new Operator("+") { @Override BigDecimal calculate(BigDecimal x, BigDecimal y) { return x.add(y); } @Override BigDecimal calculate(BigDecimal x) { throw new UnsupportedOperationException(); }}; return add; } static Operator createMultiplyOperator() { Operator multiply = new Operator("*") { @Override BigDecimal calculate(BigDecimal x, BigDecimal y) { return x.multiply(y); } @Override BigDecimal calculate(BigDecimal x) { throw new UnsupportedOperationException(); }}; return multiply; } } </code></pre> <p><strong>class FileCalculationConsumerTest</strong></p> <pre><code>package test; import static org.junit.Assert.assertEquals; import BatchSizeInvalidException; import CalculationConsumer; import Command; import FileCalculationConsumer; import java.io.FileNotFoundException; import java.util.Queue; import org.junit.Before; import org.junit.Test; public class FileCalculationConsumerTest extends BaseTest { private static final String UNITTEST_TXT = "UnitTest.txt"; private static final int BATCH_SIZE = 10; FileCalculationConsumer consumer; @Before public void setup() throws FileNotFoundException, BatchSizeInvalidException { consumer = new FileCalculationConsumer(UNITTEST_TXT,processor,BATCH_SIZE); } @Test public void testCreate() throws FileNotFoundException { assertEquals(UNITTEST_TXT,consumer.getInputPath()); } public void testCreateWithInvalidFilePath() throws BatchSizeInvalidException { CalculationConsumer consumer = new FileCalculationConsumer("ex.txt",processor,3); assertEquals("Input file not found at path: ex.txt", out.toString().trim()); } @Test(expected=IllegalArgumentException.class) public void testConsumeInvalidOperator() throws BatchSizeInvalidException { FileCalculationConsumer consumer = new FileCalculationConsumer("InvalidOperatorTest.txt",processor,3); consumer.readCommandBatch(); } @Test public void testProcess() { consumer.consume(); assertEquals("15", out.toString().trim()); } @Test public void testReadCommandBatch() throws FileNotFoundException, BatchSizeInvalidException { consumer = new FileCalculationConsumer(UNITTEST_TXT,processor,2); Queue&lt;Command&gt; batch = consumer.readCommandBatch(); assertEquals(2,batch.size()); batch = consumer.readCommandBatch(); assertEquals(1,batch.size()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-21T10:39:44.867", "Id": "515112", "Score": "0", "body": "Is there a source code in C# for this problem?" } ]
[ { "body": "<p>my 2 cents:</p>\n\n<ul>\n<li>I am not sure why you split the constructor over 2 methods. Looks awkward.</li>\n<li>You store <code>inputPath</code> in <code>FileCalculationConsumer</code>, you even have a getter, but you never do anything with after you create the Scanner</li>\n<li>Why would you initialize batch size to 100 if you get it from a parameter?</li>\n<li>It seems that if there are less than <code>batchSize</code> commands, the program does quietly nothing?</li>\n<li>You have far too many methods called <code>consume</code>, I get lost trying to track how your code works, whereas this should be pretty simple</li>\n</ul>\n\n<p>Note, you should probably reformat your question, to separate the class files and put the filenames in bold on top of your code..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T03:19:02.373", "Id": "54678", "Score": "0", "body": "Thanks for having a look. I have updated the formatting. I was looking for a library to use, instead of writing my own batching, but ended up adding the batching in a hurry. Which is why the two constructors, and yes, thanks for pointing that out, it would indeed fail silently. I have added a test where the getter for the input path is used. Also is it the design thats confusing, or just the naming of the methods? Is the design too complex?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T02:34:04.103", "Id": "34032", "ParentId": "34026", "Score": "3" } }, { "body": "<p>It looks to me like you went all over the place here, both over engineering things, and also inventing some additional requirements that don't seem to be in the problem statement.</p>\n\n<p>The calculator itself is pretty simple - start with an input, apply operations until you run out, emit the answer. I'd probably go to generics right away -- intending to test with Integers or Longs, but if you want to use BigDecimal, that would be fine too. It's a good place to have a discussion about requirements and tradeoffs </p>\n\n<pre><code>interface Operation&lt;T&gt; {\n T calculate(T input);\n}\n\nclass Calculator&lt;T&gt; {\n final List&lt;Operation&lt;T&gt; operations;\n\n Calculator(Operation&lt;T&gt; operations) {\n this.operations = operations;\n }\n\n T calculate(T input) {\n T result = input;\n for(Operation&lt;T&gt; op : operations) {\n result = op.calculate(result);\n }\n return result;\n }\n}\n</code></pre>\n\n<p>From here, the next step is to create the operation List. The input file is a set of instructions, that either tell us to build more, or to output the answer. That sounds to me like an Interpreter</p>\n\n<pre><code>class Interpreter&lt;T&gt; {\n void run(Iterable&lt;String&gt; instructions) {\n List&lt;Operation&lt;T&gt;&gt; operations = Lists.newArrayList();\n\n for(String instruction : instructions) {\n if (instruction.startsWith(\"apply\")) {\n T input = getInput(instruction);\n\n Calculator&lt;T&gt; calc = new Calculator(operations);\n T output = calc.calculate(input);\n\n System.out.println(String.valueOf(output));\n\n break;\n } else {\n operations.add(parse(instruction));\n }\n }\n }\n}\n</code></pre>\n\n<p>I'm not a big fan of branch based behavior, so I might shuffle this up a bit....</p>\n\n<pre><code>class Interpreter&lt;T&gt; {\n void run(Iterable&lt;String&gt; instructions) {\n List&lt;Operation&lt;T&gt;&gt; operations = Lists.newArrayList();\n\n Command parse = new Parser(operations);\n Command execute = new Execute(operations);\n\n for(String instruction : instructions) {\n if (instruction.startsWith(\"apply\")) {\n execute.run(instruction);\n break;\n } else {\n parse.run(instruction);\n }\n }\n }\n}\n</code></pre>\n\n<p>You get a somewhat cleaner design if you realize that you get the right answer if \"apply\" produces an operation that returns its input unchanged.</p>\n\n<pre><code>class Interpreter&lt;T&gt; {\n void run(Iterable&lt;String&gt; instructions) {\n List&lt;Operation&lt;T&gt;&gt; operations = Lists.newArrayList();\n\n Parser parser = new Parser(operations);\n\n for(String instruction : instructions) {\n parser.parse(instruction);\n }\n String lastInstruction = parser.getLastInstruction();\n\n Execute execute = new Execute(operations);\n execute.run(lastInstruction);\n }\n}\n</code></pre>\n\n<p>The Parser's job is to figure out which factory is responsible for creating the operation specified by each instruction.</p>\n\n<pre><code>class Parser&lt;T&gt; {\n // the factories are going to give us something that implements\n // Operation&lt;T&gt;, so extends is right\n private final Iterable&lt;Factory&lt;? extends Operation&lt;T&gt;&gt;&gt; factories ;\n\n // the parser is putting items into the list, so super is the\n // right answer, in case a client hands us a List&lt;Object&gt;\n private final List&lt;? super Operation&lt;T&gt;&gt; operations;\n\n Parser(Iterable&lt;Factory&lt;? extends Operation&lt;T&gt;&gt;&gt; factories, List&lt;Operation&lt;T&gt;&gt; operations) {\n this.factories = factories;\n this.operations = operations;\n }\n\n public void parse(String instruction) {\n setLastInstruction(instruction);\n\n for(Factory&lt;Operation&lt;T&gt;&gt; factory : factories) {\n if (factory.match(instruction)) {\n operations.add(factory.create(instruction));\n break;\n }\n }\n }\n // ...\n}\n\n\nclass MultiplicationFactory&lt;T&gt; implements Factory&lt;MultiplicationOperation&lt;T&gt;&gt; {\n static final String keyword = \"multiply \";\n\n final ConvertStringTo&lt;T&gt; convertor;\n\n // ...\n\n public boolean match(String instruction) {\n return instruction.startsWith(keyword);\n }\n\n public MultiplicationOperation&lt;T&gt; create(String instruction) {\n\n T operand = convertor.convert(instruction.substring(keyword.length());\n\n return new MultiplicationOperation(operand);\n }\n\n //...\n}\n</code></pre>\n\n<p>You could go really overboard on the instruction to operation problem; at the low end, you call a bunch of string operations. You can split the string into tokens, and then use the first token to discover how to interpret the rest. You can use a set of regular expressions. You can build a grammar.....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T07:45:27.793", "Id": "54699", "Score": "2", "body": "This is why I think that sometimes telling an interviewee to do a program in order to get the position might be wrong - either it puts you under unnecessary pressure, or you over-complicate something as simple as a calculator.\n\nThis, of course, do vary from programming challenge and from position..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T06:25:12.900", "Id": "34049", "ParentId": "34026", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:06:41.613", "Id": "34026", "Score": "7", "Tags": [ "java", "unit-testing", "interview-questions", "calculator" ], "Title": "Simple calculator for an interview" }
34026
<p>I have implemented a very basic sandwich (sub) shop which a user can add extra toppings at an additional cost. The cost is calculated and the contents of the sandwich is outputted.</p> <p>I am learning design patterns and the book I am learning from (<em>Head First Design Patterns</em>) is in Java, which I am not too familiar with, so I may be making some errors.</p> <p><strong>Sub.h</strong></p> <pre><code>#ifndef SUB_H #define SUB_H //Class Sub: Abstract Base class. //Following the decorator pattern #include &lt;string&gt; #include &lt;memory&gt; class Sub { public: virtual double getCost() = 0; virtual std::string getToppings() = 0; virtual ~Sub() = 0; }; class Plain: public Sub { public: double getCost() override; std::string getToppings() override; }; class ExtraCheese: public Sub { public: ExtraCheese(std::shared_ptr&lt;Sub&gt; s) : sub(s) {} double getCost() override; std::string getToppings() override; private: std::shared_ptr&lt;Sub&gt; sub; }; class ExtraMeat: public Sub { public: ExtraMeat(std::shared_ptr&lt;Sub&gt; s) : sub(s) {} double getCost() override; std::string getToppings() override; private: std::shared_ptr&lt;Sub&gt; sub; }; class ExtraSauce: public Sub { public: ExtraSauce(std::shared_ptr&lt;Sub&gt; s) : sub(s) {} double getCost() override; std::string getToppings() override; private: std::shared_ptr&lt;Sub&gt; sub; }; #endif </code></pre> <p><strong>Sub.cpp</strong></p> <pre><code>#include "Sub.h" inline Sub::~Sub(){} //class Plain : public Sub double Plain::getCost() { return 3.75; } std::string Plain::getToppings() { return "Basic Sub"; } //class ExtraCheese : public Sub double ExtraCheese::getCost() { return sub-&gt;getCost() + 0.75; } std::string ExtraCheese::getToppings() { return sub-&gt;getToppings() + ", Extra Cheese"; } //class ExtraMeat : public Sub double ExtraMeat::getCost() { return sub-&gt;getCost() + 1.50; } std::string ExtraMeat::getToppings() { return sub-&gt;getToppings() + ", Extra Meat"; } //class ExtraSauce : public Sub double ExtraSauce::getCost() { return sub-&gt;getCost() + 0.15; } std::string ExtraSauce::getToppings() { return sub-&gt;getToppings() + ", Extra Sauce"; } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include "Sub.h" int main() { std::shared_ptr&lt;Sub&gt; s(new Plain()); s = std::make_shared&lt;ExtraCheese&gt;(s); s = std::make_shared&lt;ExtraMeat&gt;(s); s = std::make_shared&lt;ExtraSauce&gt;(s); std::cout&lt;&lt;"COST: "&lt;&lt; s-&gt;getCost() &lt;&lt;std::endl; std::cout&lt;&lt;"Toppings: " &lt;&lt; s-&gt;getToppings() &lt;&lt;std::endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T05:49:02.117", "Id": "54695", "Score": "3", "body": "You should probably use int for monetary units. You don't want to have rounding errors. Use int and make the price in cent (you can put the decimal point in when printing)." } ]
[ { "body": "<p>No:</p>\n\n<p>An object \"Sub\" and a decorator \"Topping\" implement the same interface. \nIn addition a decorator takes an item (of the same interface) that it is decorating.<br>\nThis is not quite what you have done.</p>\n\n<p>What if I want extra cheese and meat?</p>\n\n<p>You need something more like this:</p>\n\n<pre><code>class Price\n{\n public:\n virtual ~Price() = 0;\n virtual int getPrice() = 0;\n};\n\nclass Sub: public Price\n{\n public:\n int getPrice() override {return 375;}\n};\n\nclass ExtraCheese: public Price\n{\n std::unique_ptr&lt;Price&gt; item\n public:\n ExtraCheese(std::unique_ptr&lt;Price&gt;&amp;&amp; item)\n : item(std::move(item))\n {}\n int getPrice() override {return item-&gt;getPrice() + 25;}\n};\n\nint main()\n{\n std::unique_ptr&lt;Price&gt; sub(new Sub);\n std::unique_ptr&lt;Price&gt; subCheese(new ExtraCheese(sub));\n std::unique_ptr&lt;Price&gt; subCheeseMeat(new ExtraMeat(subCheese));\n\n std::cout &lt;&lt; subCheeseMeat-&gt;getPrice();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T05:39:25.207", "Id": "34047", "ParentId": "34035", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T04:12:04.123", "Id": "34035", "Score": "0", "Tags": [ "c++", "design-patterns", "c++11" ], "Title": "Sandwich shop interface using the Decorator pattern" }
34035
<p>I need to check whether a generic type parameter is in a set of valid types and have created extension methods to do a run time check:</p> <pre><code>public static bool Is(this Type type, params Type[] types) { return types.Any(t =&gt; t == type); } public static bool Is&lt;T1&gt;(this Type type) { return type.Is(typeof (T1)); } public static bool Is&lt;T1, T2&gt;(this Type type) { return type.Is(typeof (T1), typeof (T2)); } </code></pre> <p>With additional methods for T3 - T#...</p> <p>Usage (in constructor for the generic class):</p> <pre><code>if(!typeof(T).Is&lt;Int32, String, Boolean, CustomClass, Whatever&gt;()) throw new ArgumentException("T must be a type."); </code></pre> <p>But I would prefer a compile time check (which I don't believe is possible). Failing that, any suggestions on improvements are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:39:08.193", "Id": "54685", "Score": "1", "body": "Part of me wonders if this would be more suited for [codereview.se]..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:41:05.260", "Id": "54686", "Score": "1", "body": "I think you're right. The closest thing to your needs is the [where](http://msdn.microsoft.com/en-us/library/vstudio/bb384067.aspx) keyword, but it seems too limited for your case. BTW: your exception message is not very helpful :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:42:46.690", "Id": "54687", "Score": "0", "body": "possible duplicate of [User-defined compile-time type constraints in C#](http://stackoverflow.com/questions/8663342/user-defined-compile-time-type-constraints-in-c-sharp)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:46:01.327", "Id": "54688", "Score": "1", "body": "Instead of Linq `Any` in the first method you might as well use Linq `Contains` instead. You can get rid of one lambda." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:46:27.087", "Id": "54689", "Score": "0", "body": "If your goal is compile time checking, why does your context allow so many types?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:49:29.037", "Id": "54690", "Score": "0", "body": "JeffBridgman - Thanks, didn't know about that.\nBartoszKP - Yep, where is \"and\", I need \"or\". The real exception message is something better.\nJeppeStigNielsen - Contains is better, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:00:40.430", "Id": "54691", "Score": "5", "body": "If your generic type parameter can only be one of a finite set of types then **your code is not generic in the first place**. Rather than trying to figure out how to more elegantly abuse generics, stop abusing generics." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:16:43.173", "Id": "54692", "Score": "0", "body": "@EricLippert - Yes, perhaps it's abuse, but in one of the scenarios where I use this I have to wrap an old pre-generics API which returns \"object\". This \"object\" is always either one of a predefined set of types. So with this style I can do var myObject = (T)objectParameter;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:29:53.507", "Id": "54693", "Score": "0", "body": "And I should add that all of the T:s have the same method which is what I make use of. But they don't implement the same interface and are sealed. So the Int32, String, Boolean bits are more to illustrate that I need to support structs as well as reference types." } ]
[ { "body": "<p>Would something like this be helpful?</p>\n\n<pre><code>List&lt;Type&gt; acceptedTypes = new List&lt;Type&gt;(){typeof(string), typeof(int), typeof(long)};\nvar stringTypeToCheck = \"this is a string type\";\nvar intTypeToCheck = 123;\nvar guidToCheck = Guid.NewGuid();\n\nif(!acceptedTypes.Contains(typeof(stringTypeToCheck.GetType())))\n throw new ArgumentException(\"incorrect type\");\n</code></pre>\n\n<p>You could have a serialized List of the Types stored in a text file if you wanted this to happen on compile time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:57:35.660", "Id": "34042", "ParentId": "34041", "Score": "0" } }, { "body": "<p>I don't think you should consider this an improvement, but it is an alternative.</p>\n\n<p>After calling <code>Is</code> you can chain calls to <code>Or</code>. Whenever the chain is complete it's implicitly converted to a <code>bool</code> based on whether the given type was found.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n object x = 1;\n\n // prints yep\n if (x.Is&lt;float&gt;().Or&lt;double&gt;().Or&lt;int&gt;())\n Console.WriteLine(\"yep\");\n else\n Console.WriteLine(\"nope\");\n\n // prints nope\n if (x.Is&lt;decimal&gt;().Or&lt;double&gt;().Or&lt;string&gt;())\n Console.WriteLine(\"yep\");\n else\n Console.WriteLine(\"nope\");\n\n Console.ReadKey();\n }\n}\n\nstatic class Extensions\n{\n public static Intermediate Is&lt;T&gt;(this object obj)\n {\n return new Intermediate(obj.GetType().Equals(typeof(T)), obj.GetType());\n }\n}\n\npublic class Intermediate\n{\n public Type ObjType { get; set; }\n public bool Found { get; set; }\n\n public Intermediate(bool result, Type type)\n {\n ObjType = type;\n Found = result;\n }\n\n public static implicit operator bool(Intermediate i)\n {\n return i.Found;\n }\n\n public Intermediate Or&lt;T&gt;()\n {\n if (Found)\n return this;\n else\n return new Intermediate(ObjType.Equals(typeof(T)), ObjType);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:13:54.290", "Id": "34043", "ParentId": "34041", "Score": "0" } }, { "body": "<p>Here is a run-time and a compile-time approach. For the compile-time approach I only show how it works for 3 type parameters and for 20 type parameters to show the concept. You can easily add more methods/classes for the number of type parameters you need.</p>\n\n<p>Scroll down to the bottom to see some usage examples.</p>\n\n<pre><code>public static class RuntimeTypeCheckExtensions\n{\n public static bool IsAssignableToAnyOf(this Type typeOperand, IEnumerable&lt;Type&gt; types)\n {\n return types.Any(type =&gt; type.IsAssignableFrom(typeOperand));\n }\n\n public static bool IsAssignableToAnyOf(this Type typeOperand, params Type[] types)\n {\n return IsAssignableToAnyOf(typeOperand, types.AsEnumerable());\n }\n\n public static bool IsAssignableToAnyOf&lt;T1, T2, T3&gt;(this Type typeOperand)\n {\n return typeOperand.IsAssignableToAnyOf(typeof(T1), typeof(T2), typeof(T3));\n }\n\n public static bool IsAssignableToAnyOf&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20&gt;(this Type typeOperand)\n {\n return typeOperand.IsAssignableToAnyOf(typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12), typeof(T13), typeof(T14), typeof(T15), typeof(T16), typeof(T17), typeof(T18), typeof(T19), typeof(T20));\n }\n}\n\npublic static class CompileTimeTypeCheckUtils\n{\n public static IsAssignableToAnyOfWrapper&lt;T1, T2, T3&gt; IsAssignableToAnyOf&lt;T1, T2, T3&gt;()\n {\n return new IsAssignableToAnyOfWrapper&lt;T1, T2, T3&gt;();\n }\n\n public static IsAssignableToAnyOfWrapper&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20&gt; IsAssignableToAnyOf&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20&gt;()\n {\n return new IsAssignableToAnyOfWrapper&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20&gt;();\n }\n}\n\npublic class IsAssignableToAnyOfWrapper&lt;T1, T2, T3&gt;\n{\n public void OperandToCheck(T1 operand) { }\n public void OperandToCheck(T2 operand) { }\n public void OperandToCheck(T3 operand) { }\n}\n\npublic class IsAssignableToAnyOfWrapper&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20&gt;\n{\n\n public void OperandToCheck(T1 operand) { }\n public void OperandToCheck(T2 operand) { }\n public void OperandToCheck(T3 operand) { }\n public void OperandToCheck(T4 operand) { }\n public void OperandToCheck(T5 operand) { }\n public void OperandToCheck(T6 operand) { }\n public void OperandToCheck(T7 operand) { }\n public void OperandToCheck(T8 operand) { }\n public void OperandToCheck(T9 operand) { }\n public void OperandToCheck(T10 operand) { }\n public void OperandToCheck(T11 operand) { }\n public void OperandToCheck(T12 operand) { }\n public void OperandToCheck(T13 operand) { }\n public void OperandToCheck(T14 operand) { }\n public void OperandToCheck(T15 operand) { }\n public void OperandToCheck(T16 operand) { }\n public void OperandToCheck(T17 operand) { }\n public void OperandToCheck(T18 operand) { }\n public void OperandToCheck(T19 operand) { }\n public void OperandToCheck(T20 operand) { }\n}\n</code></pre>\n\n<p>Usages:</p>\n\n<pre><code>Type someType = ...\n\n// Three example usages of run-time check (using generic types, params and IEnumerable):\nif (someType.IsAssignableToAnyOf&lt;string, int, double&gt;())\n{\n}\n\nif (someType.IsAssignableToAnyOf(typeof(string), typeof(int), typeof(double)))\n{\n}\n\nIEnumerable&lt;Type&gt; enumerableOfAcceptedTypes = new Type[]\n{\n typeof (string),\n typeof (int),\n typeof (double)\n};\n\nif (someType.IsAssignableToAnyOf(enumerableOfAcceptedTypes))\n{\n}\n\n// Two example usages of compile-time check:\nCompileTimeTypeCheckUtils.IsAssignableToAnyOf&lt;string, int, long&gt;().OperandToCheck(5); // &lt;-- No compile-time error\n\nCompileTimeTypeCheckUtils.IsAssignableToAnyOf&lt;string, int, long&gt;().OperandToCheck(5F); // &lt;-- Compile-time error\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T23:10:28.910", "Id": "34044", "ParentId": "34041", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:35:49.423", "Id": "34041", "Score": "10", "Tags": [ "c#" ], "Title": "Check if a type is of any from a list of types?" }
34041
<p>I have heard that some patterns in R code are really anti-patterns and thus I am trying to imitate superior examples of R code.</p> <p>I am confused about control flow.</p> <p>I have been reviewing some R code from openintro.org; the original exercise is explained at:</p> <p><a href="http://www.openintro.org/download.php?file=os2_lab_02A&amp;referrer=/stat/labs.php" rel="nofollow">http://www.openintro.org/download.php?file=os2_lab_02A&amp;referrer=/stat/labs.php</a></p> <p>One of the very early examples deals with counting "hit" or "miss" streaks within a vector of "H" and "M" characters. We consider a winning streak to be at least one H, and each streak ends in M. So H M M H H M counts as a streak of 1, a streak of 0, a streak of 2, etc.</p> <p>So, for example, we start with a sequence like kobe$basket:</p> <pre><code> [1] "H" "M" "M" "H" "H" "M" "M" "M" "M" "H" "H" "H" "M" "H" "H" "M" "M" "H" [19] "H" "H" "M" "M" "H" "M" "H" "H" "H" "M" "M" "M" "M" "M" "M" "H" "M" "H" [37] "M" "M" "H" "H" "H" "H" "M" "H" "M" "M" "H" "M" "M" "H" "M" "M" "H" "M" [55] "H" "H" "M" "M" "H" "M" "H" "H" "M" "H" "M" "M" "M" "H" "M" "M" "M" "M" [73] "H" "M" "H" "M" "M" "H" "M" "M" "H" "H" "M" "M" "M" "M" "H" "H" "H" "M" [91] "M" "H" "M" "M" "H" "M" "H" "H" "M" "H" "M" "M" "H" "M" "M" "M" "H" "M" [109] "H" "H" "H" "M" "H" "H" "H" "M" "H" "M" "H" "M" "M" "M" "M" "M" "M" "H" [127] "M" "H" "M" "M" "M" "M" "H" </code></pre> <p>and if we call calc_streak on that, we get:</p> <pre><code> [1] 1 0 2 0 0 0 3 2 0 3 0 1 3 0 0 0 0 0 1 1 0 4 1 0 1 0 1 0 1 2 0 1 2 1 0 0 1 0 [39] 0 0 1 1 0 1 0 2 0 0 0 3 0 1 0 1 2 1 0 1 0 0 1 3 3 1 1 0 0 0 0 0 1 1 0 0 0 1 </code></pre> <p>The "1 0 2" of the answer indicates the streak of 1, the streak of 0, the streak of 2 mentioned above.</p> <p>The following function is referred to as "calc_streak" but apparently that name doesn't show up in the code listing.</p> <pre><code>function(x){ y &lt;- rep(0,length(x)) y[x == "H"] &lt;- 1 y &lt;- c(0, y, 0) wz &lt;- which(y == 0) streak &lt;- diff(wz) - 1 return(streak) } </code></pre> <p>I think the first line makes a big vector of "0" values, just as long as the input, so in this case it should be 133 entries long.</p> <p>I think the second line goes through that vector and rewrites the "0" value to "1" if the input has an "H." </p> <p>The third line might be putting an extra "0" at the front and back of the vector. I think it's in there to make the "diff" work correctly, so that the first winning streak shows up as a "1" value.</p> <p>I think the object "wz" is a vector of integers. (I suspect this is a short vector, just containing the indices of the entries in x that satisfy the test.)</p> <p>So first and foremost, if I am misunderstanding the way this example code works, please correct me.</p> <p>But my primary question is - Should I regard the example R code as a good example of control flow and imitate it in my other programs?</p> <p>Thanks. </p>
[]
[ { "body": "<p>In my opinion, this function is a nice example of R code. Your interpretation of the code is correct. One unnecessary command is <code>y == 0</code> since the information is redundant given that <code>x == \"H\"</code> is already known. In this case, <code>y == 0</code> is identical to <code>c(TRUE, !(x == \"H\"), TRUE)</code>.</p>\n\n<p>The code can be simplified. The object <code>wz</code> can be created more easily:</p>\n\n<pre><code>calc_streak &lt;- function(x){\n wz &lt;- c(1, which(x == \"M\") + 1, length(x) + 2)\n streak &lt;- diff(wz) - 1\n return(streak)\n}\n</code></pre>\n\n<p>Alternatively and probabily even more efficiently, you can create a logical index indicating the positions of the <code>\"M\"</code>s in the vector and calculate <code>streak</code> more directly:</p>\n\n<pre><code>calc_streak &lt;- function(x){\n idx &lt;- x == \"M\"\n streak &lt;- c(!idx[1], diff(which(idx)) - 1, !tail(idx, 1))\n return(streak)\n}\n</code></pre>\n\n<p>The <code>!</code> sign indicates logical <em>not</em>. If numeric and logical values are combined in one vector, the logical values are cast into numeric values. <code>TRUE</code> becomes <code>1</code>, <code>FALSE</code> becomes <code>0</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T01:14:40.080", "Id": "56901", "Score": "0", "body": "Thank you for the demonstration of the which(idx) syntax. I'm still reading basic R textbooks to find good examples of which and how to extract elements from vectors. I think I need to retype your code in my rstudio environment and observe how it works." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T14:47:49.853", "Id": "34057", "ParentId": "34048", "Score": "4" } }, { "body": "<p>Your interpretation of the code is correct, but I think that it could be written more idiomatically.</p>\n\n<p>But before getting into that, the textual description of the output and the example output don't agree</p>\n\n<blockquote>\n <p>We consider a winning streak to be at least one <code>H</code>, and each streak ends in <code>M</code>. So <code>H M M H H M</code> counts as a streak of 1, a streak of 0, a streak of 2, etc.</p>\n</blockquote>\n\n<p>If a streak must have at least one <code>H</code>, how can you have a streak of 0? The example here (and the following example) are consistent with a definiton of streak of \"the number of consecutive <code>H</code>'s preceding each <code>M</code>.\" I'll continue with this interpretation so that it matches the existing code.</p>\n\n<p>Now to improvements to the code.</p>\n\n<p>The initialization of <code>y</code> can be simplified because <code>0</code> is the default numeric value, so the first line can be re-written as</p>\n\n<pre><code>y &lt;- numeric(length(x))\n</code></pre>\n\n<p>The first two lines together create a 0/1 vector corresponding to whether the value in <code>x</code> was <code>\"H\"</code> (1) or <code>\"M\"</code> (0) (and uses the fact that it must be one or the other of those values). This can be done as one statement, using the fact that <code>TRUE</code> and <code>FALSE</code> become <code>1</code> and <code>0</code> when converted to numbers.</p>\n\n<pre><code>y &lt;- as.numeric(x == \"H\")\n</code></pre>\n\n<p>The <code>y</code> vector has a <code>0</code> added to the beginning and the end which is equivalent to adding a <code>\"M\"</code> to the beginning and end of the baskets. This makes the first streak start at the beginning and the last streak stop at the end.</p>\n\n<p><code>wz</code> is a vector of indexes of where the misses (\"M\" in <code>x</code>, 0 in <code>y</code>) occur. The lengths of the streaks preceding them, then, is just the difference in successive indexes (minus 1, since you want to count the number of spaces between, which is one less than the difference of the positions).</p>\n\n<p>Now, since the intermediate results are just used once on the next statement, they can be rolled up. Here are successive versions of doing that:</p>\n\n<pre><code>calc_streak &lt;- function(x){\n y &lt;- as.numeric(x == \"H\")\n y &lt;- c(0, y, 0)\n wz &lt;- which(y == 0)\n streak &lt;- diff(wz) - 1\n return(streak)\n}\n\ncalc_streak &lt;- function(x){\n y &lt;- c(0, as.numeric(x == \"H\"), 0)\n wz &lt;- which(y == 0)\n streak &lt;- diff(wz) - 1\n return(streak)\n}\n\ncalc_streak &lt;- function(x){\n wz &lt;- which(c(0, as.numeric(x == \"H\"), 0) == 0)\n streak &lt;- diff(wz) - 1\n return(streak)\n}\n\ncalc_streak &lt;- function(x){\n streak &lt;- diff(which(c(0, as.numeric(x == \"H\"), 0) == 0)) - 1\n return(streak)\n}\n\ncalc_streak &lt;- function(x){\n diff(which(c(0, as.numeric(x == \"H\"), 0) == 0)) - 1\n}\n</code></pre>\n\n<p>The last simplification uses the fact that a function returns the last evaluated expression by default.</p>\n\n<p>I don't necessarily recommend doing that because with compactness comes a loss in being able to see what the computations are/mean. (To understand it, you must essentially reverse the steps and break out each transformation separately to see what it does and to figure out why.)</p>\n\n<p>Looking at it again, the conversion to numeric is not a necessary step to determine <code>wz</code>; you can operate from <code>x</code> directly:</p>\n\n<pre><code>calc_streak &lt;- function(x){\n wz &lt;- which(c(\"M\", x, \"M\") == \"M\")\n streak &lt;- diff(wz) - 1\n return(streak)\n}\n</code></pre>\n\n<p>For understandability, I'd use a different name than <code>wz</code></p>\n\n<pre><code>calc_streak &lt;- function(x){\n miss_indexes &lt;- which(c(\"M\", x, \"M\") == \"M\")\n streak &lt;- diff(miss_indexes) - 1\n return(streak)\n}\n</code></pre>\n\n<p>Then applying the default return value</p>\n\n<pre><code>calc_streak &lt;- function(x){\n miss_indexes &lt;- which(c(\"M\", x, \"M\") == \"M\")\n diff(miss_indexes) - 1\n}\n</code></pre>\n\n<p>It could be simplified once further to</p>\n\n<pre><code>calc_streak &lt;- function(x){\n diff(which(c(\"M\", x, \"M\") == \"M\")) - 1\n}\n</code></pre>\n\n<p>but the loss in clarity (for you and someone else later) is (in my opinion) not worth it.</p>\n\n<hr>\n\n<p>If length 0 streaks are not allowed, the approach I would use would be</p>\n\n<pre><code>calc_streak &lt;- function(x) {\n r &lt;- rle(x)\n r$lengths[r$values == \"H\"]\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T01:16:41.573", "Id": "56902", "Score": "0", "body": "I may have been confused about whether streaks of zero length are well-defined in the original problem. Thanks for your code examples. I like the idea of avoiding the conversion to numeric values." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:52:43.413", "Id": "34069", "ParentId": "34048", "Score": "2" } } ]
{ "AcceptedAnswerId": "34069", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T05:46:08.230", "Id": "34048", "Score": "1", "Tags": [ "r" ], "Title": "Should I be trying to imitate the control flow in this example R code?" }
34048
<p>I've just written a palindrome generator and would like to know what you think about it.</p> <p>Especially:</p> <ul> <li>code style </li> <li>Is it possible to get the same result without making a special case for 1-digit palindromes?</li> <li>efficiency</li> </ul> <p></p> <pre><code>#!/usr/bin/env python def getPalindrome(): """ Generator for palindromes. Generates palindromes, starting with 0. A palindrome is a number which reads the same in both directions. """ # First print all one-digit palindromes for i in range(10): yield i length = 2 while True: # Do the symmetric part for i in range(10**(length//2-1), 10**(length//2)): a = str(i) r = a + a[::-1] yield int(r) length += 1 # Do the unsymmetric part exponent = (length-1)//2 for prefix in range(10**(exponent-1), 10**exponent): prefix = str(prefix) for i in range(10): result = prefix + str(i) + prefix[::-1] yield int(result) length += 1 if __name__ == "__main__": palindromGenerator = getPalindrome() for i, palindromeNumber in enumerate(palindromGenerator): print("%i-th palindrome: %i" % (i, palindromeNumber)) if i &gt;= 500: break </code></pre>
[]
[ { "body": "<ol>\n<li><p>I'd implement this function like this:</p>\n\n<pre><code>from itertools import count\n\ndef palindromes():\n \"\"\"Generate numbers that are palindromes in base 10.\"\"\"\n yield 0\n for digits in count(1):\n first = 10 ** ((digits - 1) // 2)\n for s in map(str, range(first, 10 * first)):\n yield int(s + s[-(digits % 2)-1::-1])\n</code></pre>\n\n<p>(In Python 2, you should replace <code>range</code> with <a href=\"http://docs.python.org/2/library/functions.html#xrange\" rel=\"nofollow\"><code>xrange</code></a> and <code>map</code> with <a href=\"http://docs.python.org/2/library/itertools.html#itertools.imap\" rel=\"nofollow\"><code>itertools.imap</code></a>.)</p>\n\n<p>The insight is that instead of building an odd-length palindrome from the parts prefix + middle + xiferp, we can build it as prefix + iferp: that is, with the middle digit being supplied by the last digit of the prefix.</p></li>\n<li><p>In your main loop, you arrange to generate the first 501 palindromes:</p>\n\n<pre><code>for i, palindromeNumber in enumerate(palindromGenerator):\n ...\n if i &gt;= 500:\n break\n</code></pre>\n\n<p>but it would be simpler to use <a href=\"http://docs.python.org/2/library/itertools.html#itertools.islice\" rel=\"nofollow\"><code>itertools.islice</code></a>:</p>\n\n<pre><code>for i, palindrome in islice(enumerate(palindromeGenerator), 501):\n ...\n</code></pre></li>\n<li><p>As for your question about efficiency, it is impossible to answer without knowing the purpose of this code. If all you are going to do is to print the first 501 palindromes, then your code is fine: the runtime will be dominated by printing the output.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:14:31.577", "Id": "34059", "ParentId": "34052", "Score": "4" } } ]
{ "AcceptedAnswerId": "34059", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T10:16:21.937", "Id": "34052", "Score": "3", "Tags": [ "python", "optimization", "palindrome" ], "Title": "Python Palindrome Generator" }
34052
<p>I'm quite new to C, and I'm looking for feedback on this (doubly) linked list code.</p> <p>Once I get to the add and remove methods, I feel like the code goes downhill. I'm looking for any potential errors I haven't spotted, and improvements that could be made for efficiency/tidiness.</p> <pre><code>struct node { int data; struct node *next; struct node *previous; }; struct listset { struct node *head; struct node *tail; int current_elements; }; struct listset * new_listset(){ struct listset *new_list = malloc(sizeof(struct listset)); new_list -&gt;head = NULL; new_list -&gt;tail = NULL; return new_list; }; struct node *listset_lookup(struct listset *this, int item){ struct node *curr_elem = this-&gt;head; if(!curr_elem) return NULL; while(item != curr_elem-&gt;data){ if(curr_elem-&gt;next==NULL)return NULL; curr_elem = curr_elem-&gt;next; } return curr_elem; } void listset_add(struct listset *this, int item){ struct node *new_node = malloc(sizeof(struct node)); new_node -&gt; data = item; new_node -&gt;next = NULL; if(!this-&gt;head) { new_node-&gt;previous = NULL; this-&gt;head = this-&gt;tail = new_node; } else{ this-&gt;tail-&gt;next = new_node; } this-&gt;current_elements++; } void listset_remove(struct listset *this, int item){ struct node *elem_remove = listset_lookup(this, item); if(!elem_remove) return; if(elem_remove-&gt;next &amp;&amp; elem_remove-&gt;previous) elem_remove-&gt;previous-&gt;next = elem_remove-&gt;next; else if (elem_remove-&gt;previous &amp;&amp; !elem_remove-&gt;previous){ elem_remove-&gt;previous-&gt;next=NULL; this-&gt;tail = elem_remove-&gt;previous; } else{ this-&gt;tail = NULL; this-&gt;head = NULL; } free(elem_remove); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T13:10:10.480", "Id": "54710", "Score": "0", "body": "In the listset_add you do not change the tail in the `else` block: `this->tail = new_node`" } ]
[ { "body": "<p>The code of the list looks correct but the coding style is not neat yet. There are some suggestions:</p>\n\n<ul>\n<li>There are different recommendations on how to format the type of the pointers, but probably all agree that the character <code>*</code> is the part of the type. So it is better to always keep it near the type.</li>\n<li>The code is unreasonably compacted. It is good if you want to have a whole algorithm on one screen but most likely you will spend most of the time focusing on its particular aspects so the readability of the individual fragments prevails.</li>\n<li>develop a good habit of putting constants at the first place in logical expressions.</li>\n<li>it is cool that you know this trick <code>a = b = NULL</code> but you do not use it consistently in the code - anyway, it is better to not use it.</li>\n<li>prefer positive constructions in <code>if</code>s because it is very easy to overlook just the single <code>!</code> in the boolean expression.</li>\n<li><code>current_elements</code> is not a quite right name for the variable that contains the size of the list. <code>size</code> is much better :)</li>\n<li>avoid unnecessary shorten variable names: is there a strong reason to use <code>curr_elem</code> instead of just <code>current</code> or <code>element</code>?</li>\n</ul>\n\n<h2>Logic</h2>\n\n<ul>\n<li>consider <code>calloc</code> - it clears the memory so you do not need to null all the structure variables - they will be set to zeroes.</li>\n<li><code>listset_add</code> should be revised - it does not set <code>this-&gt;tail</code> and <code>new_node-&gt;previous</code> if <code>NULL != this-&gt;head</code></li>\n<li><code>listset_remove</code> should be revised - it does not set <code>elem_remove-&gt;next-&gt;previous</code> correctly, <code>elem_remove-&gt;previous &amp;&amp; !elem_remove-&gt;previous</code> is never true.</li>\n<li><code>list_free</code> that releases all the elements and list itself in one operation will be very handy.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:05:33.240", "Id": "54721", "Score": "1", "body": "I don't agree that '*' is part of the type. If I define `int *a, b;` and `int* a, b;`, the second (which would be logical if the * is part of the type) gives the impression that `b` is a pointer to int, which it clearly isn't. Defining two variables in this way would be unwise, but is legal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:19:42.517", "Id": "54725", "Score": "0", "body": "Thank you for writing this up. By putting constants first do you mean for example: if(NULL == x) rather than if(x == NULL)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:39:15.173", "Id": "54726", "Score": "0", "body": "The `if (NULL == x)` is better because the compiler will warn you if you forget one `=` and write `if (NULL = x)`. The `if (x = NULL)` is valid construction that can be easy overlooked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:47:55.193", "Id": "54727", "Score": "0", "body": "@WilliamMorris I understand you point but it is about C syntax which is clumsy sometimes, not about the concept. The code review is all about helping other to avoid what is legal and syntactically correct but unwise, isn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:18:54.847", "Id": "54729", "Score": "0", "body": "@AlexAtNet Compilers can and do check for that already. Yoda conditions haven't been useful for a long time (or arguably ever)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:32:52.713", "Id": "54731", "Score": "0", "body": "@Corbin, so could you please go one step forward and provide user31885 with instructions on how to configure his or her compiler correctly because this check is not enabled by default in most of the compilers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:10:08.547", "Id": "54740", "Score": "1", "body": "Depends on the compiler. The short answer though is to just crank up warnings as high as they'll go and it will surely be included." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T15:41:30.973", "Id": "34058", "ParentId": "34053", "Score": "0" } }, { "body": "<p>I will try not to repeat what was said in the comments and in Alex' answer.</p>\n\n<p>In <code>new_listset()</code> you forgot to initialize <code>current_elements</code> to zero. If you replace <code>malloc</code> with <code>calloc</code>, you will not need to do that. In that case, you can also remove initializations of <code>head</code> and <code>tail</code>, since <code>NULL == (void*)0</code>.</p>\n\n<p>I find your lookup a bit counter-intuitive. I'd do it like this:</p>\n\n<pre><code>struct node *listset_lookup(struct listset *this, int item){\n struct node *curr_elem = this-&gt;head;\n while (curr_elem) {\n if (curr_elem-&gt;data == item) return curr_elem;\n curr_elem = curr_elem-&gt;next;\n }\n return NULL;\n}\n</code></pre>\n\n<p>or, even more intuitive (for me, at least):</p>\n\n<pre><code>struct node *listset_lookup(struct listset *this, int item){\n struct node *curr_elem;\n for (curr_elem = this-&gt;head; curr_elem; curr_elem = curr_elem-&gt;next)\n if (curr_elem-&gt;data == item) return curr_elem;\n return NULL;\n}\n</code></pre>\n\n<p>There are several reasons I like it this way better.</p>\n\n<ol>\n<li><p>This is a standard \"go through the whole list and do something\" loop, instead of your \"do something special (loop until the element is found)\".</p></li>\n<li><p>My code doesn't have check for <code>NULL</code> on two places.</p></li>\n<li><p>Each step is dealing with the \"current\" element. In your code, you have <code>if</code> checking the <em>next</em> element, which is an approach I prefer to avoid if it is reasonably possible.</p></li>\n</ol>\n\n<p>Mind you, this is not a big deal, and it is alright if you want to keep your version.</p>\n\n<p>Maybe a bit more important remark is regarding the <code>listset_remove()</code> function. I'd make it return <code>int</code>, which would be the count of the elements removed. This way, wherever you've called it, you would know if it has removed anything. You could also add a third parameter which would say how many items can be removed at most (zero for all of them), so that more than one item can be removed if some are equal among themselves.</p>\n\n<p>By the way, you forgot to decrease <code>this-&gt;current_elements</code> in that function.</p>\n\n<p>Lastly, I suggest adding checks if your <code>malloc</code>/<code>calloc</code> calls were successful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:08:54.403", "Id": "34067", "ParentId": "34053", "Score": "0" } }, { "body": "<p>Your code is actually \"off-topic\" because it doesn't work. You should really\ninclude a short <code>main</code> that illustrates its use and allows it to be tested. All the same, here are some comments.</p>\n\n<p>Be consistent with spacing. My preference is for no spaces around <code>-&gt;</code> and\nfor a space after keywords (<code>if</code>, <code>while</code> etc).</p>\n\n<p>Variable naming. Your names are not to my taste, often too long:</p>\n\n<ul>\n<li>Rename <code>previous</code> as <code>prev</code>, <code>current_elements</code> as <code>n_elements</code></li>\n<li>Rename <code>this</code> globally as <code>list</code> - <code>this</code> means nothing whereas <code>list</code> is\nclearly a list.</li>\n<li>Rename <code>item</code> as <code>data</code>. It is called <code>data</code> within the <code>node</code> structure so\nwhy not be consistent?</li>\n<li><code>new_listset</code> would perhaps be more consistent with the other functions if\nnamed <code>listset_new</code>. It also needs a <code>void</code> parameter list.</li>\n</ul>\n\n<p>Function <code>listset_lookup</code> tests the wrong condition in the loop. Better to\ntest for the end of the list:</p>\n\n<pre><code>struct node *listset_lookup(const struct listset *list, int data)\n{\n struct node *n = list-&gt;head;\n while (n) {\n if (data == n-&gt;data) {\n break;\n }\n n = n-&gt;next;\n }\n return n;\n}\n</code></pre>\n\n<p>Notice also that the parameter <code>list</code> is <code>const</code> (as you don't alter it). Also\nnote that writing this with a short variable name makes it much more readable\ncompared to the dense text that results from a longer name. In a ten line\nfunction with only 3 variables there is really nothing wrong (and a lot right)\nwith using such a short name.</p>\n\n<p>Your <code>listset_add</code> is missing two terms in the <code>else</code> clause and should test\nfor <code>malloc</code> failure (and return something to show whether it failed). I\nwould also rename <code>new_node</code> as simple <code>n</code> - again, it is a short function (as\nmost should be) and so this is ok.</p>\n\n<pre><code>static struct node* listset_add(struct listset *list, int data)\n{\n struct node *n = malloc(sizeof(struct node));\n if (n) {\n n-&gt;data = data;\n n-&gt;next = NULL;\n if (!list-&gt;head) {\n n-&gt;prev = NULL;\n list-&gt;head = list-&gt;tail = n;\n } else {\n n-&gt;prev = list-&gt;tail; // new\n list-&gt;tail-&gt;next = n;\n list-&gt;tail = n; // new\n }\n list-&gt;n_elements++;\n }\n return n;\n}\n</code></pre>\n\n<p>Your <code>listset_remove</code> is hard to read and wrong. Again, a shorter variable\nname would help. You should also avoid long lines such as:</p>\n\n<pre><code>if(elem_remove-&gt;next &amp;&amp; elem_remove-&gt;previous) elem_remove-&gt;previous-&gt;next = elem_remove-&gt;next;\n</code></pre>\n\n<p>This is much clearer as:</p>\n\n<pre><code>if (n-&gt;next &amp;&amp; n-&gt;previous) {\n n-&gt;previous-&gt;next = n-&gt;next;\n}\n</code></pre>\n\n<p>All the same, it is perhaps wrong. And this:</p>\n\n<pre><code>else if (elem_remove-&gt;previous &amp;&amp; !elem_remove-&gt;previous){\n</code></pre>\n\n<p>is quite clearly not sensible. You also don't decrement the element count.\nThe correct function is:</p>\n\n<pre><code>static void listset_remove(struct listset *list, int data)\n{\n struct node *n = listset_lookup(list, data);\n if (!n) return;\n\n if (n-&gt;prev) {\n n-&gt;prev-&gt;next = n-&gt;next;\n } else {\n list-&gt;head = n-&gt;next;\n }\n if (n-&gt;next) {\n n-&gt;next-&gt;prev = n-&gt;prev;\n } else {\n list-&gt;tail = n-&gt;prev;\n }\n list-&gt;n_elements--;\n free(n);\n}\n</code></pre>\n\n<p>Here's what I used to test it:</p>\n\n<pre><code>static void listset_print(const struct listset *list)\n{\n struct node *n = list-&gt;head;\n while (n) {\n printf(\"%d \", n-&gt;data);\n n = n-&gt;next;\n }\n printf(\" : \");\n\n n = list-&gt;tail;\n while (n) {\n printf(\"%d \", n-&gt;data);\n n = n-&gt;previous;\n }\n printf(\"\\n\");\n}\n\nint main(void)\n{\n struct listset *list = new_listset();\n listset_add(list, 1);\n listset_add(list, 2);\n listset_add(list, 3);\n listset_add(list, 4);\n listset_add(list, 5);\n listset_print(list);\n listset_remove(list, 6);\n listset_print(list);\n listset_remove(list, 1);\n listset_print(list);\n listset_remove(list, 5);\n listset_print(list);\n listset_remove(list, 3);\n listset_print(list);\n listset_remove(list, 2);\n listset_print(list);\n listset_remove(list, 4);\n listset_print(list);\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:46:48.363", "Id": "34068", "ParentId": "34053", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T11:36:35.080", "Id": "34053", "Score": "2", "Tags": [ "c", "beginner", "linked-list" ], "Title": "Doubly linked list implementation in C" }
34053
<p>The program assignment:</p> <blockquote> <p>A drunkard in a grid of streets randomly picks one of four directions and stumbles to the next intersection, then again randomly picks one of four directions, and so on. You might think that on average the drunkard doesn't move very far because the choices cancel each other out, but that is not the case. Represent locations as integer pairs (x,y). Implement the drunkard's walk over 100 intersections, starting at (0,0) and print the ending location.</p> </blockquote> <p>I created this <code>Drunkard</code> class:</p> <pre><code>import java.util.*; class Drunkard { int x, y; Drunkard(int x, int y) { this.x = x; this.y = y; } void moveNorth() { this.y -= 1; } void moveSouth() { this.y += 1; } void moveEast() { this.x += 1; } void moveWest() { this.x -= 1; } void report() { System.out.println("Location: " + x + ", " + y); } } </code></pre> <p>And this <code>DrunkardTester</code> class to test the above class</p> <pre><code>import java.util.Random; public class DrunkardTester { public static void main(String[] args) { Random generator = new Random(); Drunkard drunkard = new Drunkard(0, 0); int direction; for (int i = 0; i &lt; 100; i++) { direction = Math.abs(generator.nextInt()) % 4; if (direction == 0) { // N drunkard.moveNorth(); } else if (direction == 1) { // E drunkard.moveEast(); } else if (direction == 2) { // S drunkard.moveSouth(); } else if (direction == 3) { // W drunkard.moveWest(); } else { System.out.println("Impossible!"); } } drunkard.report(); } } </code></pre> <p>It complies and runs fine, and it prints a different coordinate location each time I run it, but I just wanted to get a few other pairs of eyes on it to see if there are any glaring errors.</p> <p>Also, on my <code>DrunkardTester</code> class is there anyway to eliminate the "Impossible!" <code>else</code> statement? I wasn't really sure if that was necessary or what else could be put there.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:54:49.487", "Id": "54707", "Score": "3", "body": "Simplify your random call to `generator.nextInt(MAX_DIRECTION)` where MAX_DIRECTION is an int constant and == 4." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:58:05.117", "Id": "54708", "Score": "3", "body": "Your code is correct, easy to follow, and neatly formatted. It's standard practice to indent the statements in each of the `if` branches, but you might consider replacing the multi-part `if` with `switch`." } ]
[ { "body": "<p>Why don't you indent inner statements?</p>\n\n<p>The constants 0, 1, 2, 3 could be declared as constants like</p>\n\n<pre><code>private static final short NORTH = 0;\nprivate static final short EAST = 1;\netc...\n</code></pre>\n\n<p>Also, the \"Impossible!\" is an unreachable statement so it would be fine to remove it in your case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T06:23:54.030", "Id": "56837", "Score": "2", "body": "No sure who down-voted this without a comment, but extracting a magic number to a constant is always a good idea. As stated above, a Enum is a better choice here, but if you go with the current approach extracting the constant make your code easier to handle." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:57:28.283", "Id": "34055", "ParentId": "34054", "Score": "2" } }, { "body": "<p>There is absolutely no need to call <code>Math.abs</code> for <code>generator.nextInt()</code> since nextInt will never produce a negative number. Also, your last else-statement is impossible to happen so you can erase that one.</p>\n\n<p>There is also no need to use the modulo (<code>%</code>) operator to fix your <code>direction</code> variable to the correct range when you instead can supply an integer value to the <code>nextInt</code> method. <code>generator.nextInt(4);</code> will give you a value from 0 to 3 (inclusive).</p>\n\n<p>It is a Java coding convention to indent your code properly, after each <code>{</code> the next line should have one more indentation step, like this:</p>\n\n<pre><code>void moveSouth() {\n this.y += 1; \n}\n</code></pre>\n\n<hr>\n\n<p>The below might be a little bit over your level, but it is a really nice solution and is very useful to learn. When you are dealing with four directions, I would create an <code>enum</code> to help with the different direction possibilities.</p>\n\n<pre><code>public enum Direction4 {\n NORTH(0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);\n\n private final int dx;\n private final int dy;\n\n private Direction4(int dx, int dy) {\n this.dx = dx;\n this.dy = dy;\n }\n public int getX() { return dx; }\n public int getY() { return dy; }\n}\n</code></pre>\n\n<p>Using this enum, you can simplify several things of your other code. For starters, you can replace your move-methods with one single move method:</p>\n\n<pre><code>void move(Direction4 direction) {\n this.x += direction.getX();\n this.y += direction.getY();\n}\n</code></pre>\n\n<p>And when generating the direction to move at, you can use the <code>Direction4</code> enum:</p>\n\n<pre><code>// Get an index number and input the \"size\" of the enum to `nextInt`\nint directionIndex = generator.nextInt(Direction4.values().length);\n\n// Get the direction from the index generated above\nDirection4 dir = Direction4.values()[directionIndex];\n\n// Make the move:\ndrunkard.move(dir);\n</code></pre>\n\n<p>It might be subjective whether four different <code>moveNorth</code>, <code>moveSouth</code> etc. methods are preferable instead of using a single <code>move</code>-method that takes the direction as an argument. I myself find that using an <code>enum</code> redures the amount of code and it makes the code flexible and scalable (if you want to add or modify existing directions you can do so, for example adding <code>MEGA_NORTH</code> that moves 10 steps north just for fun).</p>\n\n<p>If you don't perform the <code>enum</code> approach, then at least use a <code>switch</code></p>\n\n<pre><code>direction = generator.nextInt(4);\nswitch (direction) {\n case 0:\n drunkard.moveNorth();\n break;\n case 1:\n drunkard.moveEast();\n break;\n case 2:\n drunkard.moveSouth();\n break;\n case 3:\n drunkard.moveWest();\n break;\n}\n</code></pre>\n\n<p>Although I must say: There's not much that beat a nice little enum :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:14:56.187", "Id": "54723", "Score": "0", "body": "I would probably add one more abstraction around choosing a direction. Enum.values() returns an array, so I would want to have an interface with a signature like\n\n<T> T choose(T[] choices);\none of the implementations of which uses an instance of Random to pick from the array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T16:18:34.117", "Id": "54724", "Score": "0", "body": "@VoiceOfUnreason I don't see the reason for making it an interface, but it surely could be a static utility method." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T14:22:08.553", "Id": "34056", "ParentId": "34054", "Score": "9" } }, { "body": "<p>It's functional.</p>\n\n<p><strong>A suggestion:</strong> It's good java practice to only import the classes you need. So I suggest not using the <em>*</em> notation to import all of the java.util package, actually you don't even use anything from the java.util package so you might as well remove unused imports.</p>\n\n<p>Remove this:</p>\n\n<pre><code>import java.util.*;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T16:17:13.687", "Id": "34097", "ParentId": "34054", "Score": "2" } }, { "body": "<p>First, please <strong>indent</strong> your code.</p>\n\n<p>Your sequence of if-elses would be better as a <code>switch</code> — it's more efficient and more readable. However, in general, a big <code>switch</code> statement in Java can usually be replaced with something better. In this case, an <strong><code>enum</code></strong> for the four cardinal directions would really help.</p>\n\n<pre><code>enum Direction {\n NORTH(0, 1),\n EAST(1, 0),\n SOUTH(0, -1),\n WEST(-1, 0);\n\n public final int x, y;\n\n private Direction(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n private static Random generator = new Random();\n\n public static Direction random() {\n return values()[generator.nextInt(4)];\n }\n}\n</code></pre>\n\n<p>Notice the following benefits from using an <code>enum</code>:</p>\n\n<ul>\n<li>No more <code>switch</code> statement.</li>\n<li>In the <code>Drunkard</code> class, four methods can be replaced with <code>void move(Direction d)</code>.</li>\n<li>A lot of code (i.e., machine instructions) has been replaced with data. Data is usually easier to manage than code.</li>\n<li>The assumption of four cardinal directions is centralized, rather than divided between <code>Drunkard</code> and <code>DrunkardTester</code>. If, for example, you wanted to allow diagonal moves, you would only need to modify the <code>Direction</code> enum.</li>\n</ul>\n\n<blockquote>\n <p>You asked, what to do about the impossible case. To assert that a situation is impossible, use an <strong><code>assert</code></strong>. Alternatively, throw a <code>RuntimeException</code>. Printing a message to <code>System.out</code> just clutters the output and lets your faulty program continue, when the right thing to do is to abort. (By the way, if you must print diagnostics, print to <code>System.err</code> instead, to avoid contaminating the output on <code>System.out</code>.)</p>\n</blockquote>\n\n<p>Also note that a more proper way to uniformly pick a number from [0, 1, 2, 3] is <code>random.nextInt(4)</code>. In general, doing <code>random.nextInt() % n</code> <em>might</em> be slightly biased. (Consider a hypothetical case where n = 1 billion. Since <code>.nextInt()</code> picks uniformly from integers between 0 and 2 147 483 647, the lowest 147 483 647 numbers are 50% more likely to be picked with <code>random.nextInt() % 1000000000</code>. When n = 4, there happens to be no bias, but you might as well call the right code out of habit.)</p>\n\n<p>A few more tips:</p>\n\n<ul>\n<li>In <code>Drunkard</code>, instead of <code>void report() { System.out.println(...); }</code>, <strong>prefer <code>String toString() { ... }</code></strong>. This gives the caller flexibility to display the result, for example, in a graphical UI.</li>\n<li>In <code>Drunkard</code>, also offer a <strong>no-argument constructor</strong> that places the drunkard at the origin.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T17:01:06.787", "Id": "34101", "ParentId": "34054", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T01:52:45.830", "Id": "34054", "Score": "7", "Tags": [ "java", "beginner", "random" ], "Title": "Random walk on a 2D grid" }
34054
<p>I've recently try to brush up my javascript skills, so I have a friend who gives me puzzles from time to time to solve. Yesterday I got this :</p> <pre><code>function testFun() { f = {}; for( var i=0 ; i&lt;3 : i++ ) { f[i] = function() { alert("sum='+i+f.length); } } return f; } Expected Results: testFun()[0]() should alert “sum=0” testFun()[1]() should alert “sum=2” testFun()[2]() should alert “sum=4” </code></pre> <p>I did this which does like requested above:</p> <pre><code>function testFun() { var i, f = {}; for (i = 0; i &lt; 3; i++) { f[i] = (function(number) { return function() { alert("sum=" + (number * 2)); } }(i)); } return f; } </code></pre> <p>Could my answer be written better and what can be improved if so?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:25:02.227", "Id": "54730", "Score": "0", "body": "@downvoter care to explain why" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:49:41.630", "Id": "54732", "Score": "1", "body": "I did not down-vote you but I think that your question was down-voted becase: 1) you ask several question in one post 2) you ask to help you with your own homework, which is not welcomed 3) you are asking for solution for second task without demonstrating you own effort 4) your second question better matches stackoverflow.com, not codereviews. Consider it \"code reviewing\" your post so you get what this site is for :) I would recommend to delete this one and repost trying to follow the rules. Good luck." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:54:14.803", "Id": "54733", "Score": "0", "body": "@AlexAtNet, if you reference the [\"Rules\"](http://codereview.stackexchange.com/help) please post a link to them. on Point **3** the OP has shown that they know enough about Javascript to solve the first challenge. on point **2** this doesn't look like homework to me and is not phrased as such IMO. OP please remove the part about asking for code to be written. we can review the code that you have written and it might help you to write the code for today's challenge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:57:34.240", "Id": "54734", "Score": "1", "body": "@Malachi, thank you for the link, will keep it in mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:58:43.220", "Id": "54735", "Score": "1", "body": "@AlexAtNet, BTW, it is on the top of the page along with the [ABOUT](http://codereview.stackexchange.com/about) page" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:58:53.567", "Id": "54736", "Score": "1", "body": "ok I edited my question to fit the rules, thanks for your comments" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:03:28.857", "Id": "54737", "Score": "0", "body": "@Malachi Thanks, got it. Sorry for my phrasing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:05:55.157", "Id": "54738", "Score": "1", "body": "it's all good, it is hard to see `<voicetone>` tags on the internet. so I read everything in a pleasant and helpful tone so that if I do take it the wrong way I still don't take offense." } ]
[ { "body": "<p>The style of you code is good. Here is not much of it but it looks like you understand the concept of closures well.</p>\n\n<p>The logic of the original task is changed so even if you code returns the right values, they are calculated differently. The original task calculates it as <code>i + f.length</code>. It is questionable how to calculate length of an object. There are some ways but we can simply guess that the initialization of <code>f</code> is incorrect and <code>f</code> should be an array.</p>\n\n<p>Another question is how to capture the current state of the array in the closure. Because it is object the closure will get the reference to it so it should be copied. The simplest way of copying an array it to call <code>f.slice()</code>.</p>\n\n<p>The last issue (reported by jshint) is that the function created in the loop is always the same. So you can move it outside of the loop and just call in the loop.</p>\n\n<p><strong>Update:</strong> Some notes on capturing objects in closures.</p>\n\n<p>The closure captures variable by reference. If you have a loop with an index variable and capture this variable and then invoke the closure you will have not the value of the variable on the corresponding loop iteration. What you will get is the final value on the last loop iteration.</p>\n\n<p>To capture the value the variable should be copied to some temporary context. In the languages with statement scope it is enough to declare local variable, but in JS with function scope you need to capture the variable by running the function. That is why in your code you have this <code>function(number) {</code> - it copies the index variable <code>i</code> to the function parameter <code>number</code> and when value of <code>i</code> is changed, value of <code>number</code> remains.</p>\n\n<p>But when you capturing objects the situation is different, because objects are passed into function scope by reference too. So if the state of the object is changed, it will be changed in both parent and function scope. So in your example later, while invoking, the function will add the final length of the array to the variable, not the length of the array from the corresponding loop iteration.</p>\n\n<p>So the length somehow should be preserved in the closure. It can be passed as number but it will be too boring - you already know how to deal with them. So it is better to think how to pass the copy of the array itself.</p>\n\n<pre><code> f[i] = (function(number, array) {\n return function() {\n alert(\"sum=\" + number + array.length);\n }\n }(i, f.slice()));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:45:12.387", "Id": "54746", "Score": "0", "body": "Thanks for the comments that was really useful, I changed f to be an array and put the function outside the for loop. Could you further explain the capturing array in the closure? what you mean by that. thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T19:32:56.810", "Id": "54748", "Score": "0", "body": "I've added the nodes on objects." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:19:42.070", "Id": "34063", "ParentId": "34060", "Score": "6" } } ]
{ "AcceptedAnswerId": "34063", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:21:01.060", "Id": "34060", "Score": "2", "Tags": [ "javascript" ], "Title": "Solving the puzzle in javascript" }
34060
<p>I'm hoping someone could look through this code for my <code>Chunk</code>, <code>Mesh</code> and <code>ChunkManager</code> classes and tell me what I need to do to improve.</p> <p>For some reason, when I wrote it in NetBeans and transferred it to Eclipse it deleted all my comments.</p> <p>I especially don't understand the buffer system. Can I use backbuffers in OpenGL?</p> <p><strong><code>Chunk</code> class:</strong></p> <pre><code>public class Chunk { public static final int X_CHUNK_SIZE = 16; public static final int Y_CHUNK_SIZE = 64; public static final int Z_CHUNK_SIZE = 16; public int chunkXNumber; public int chunkZNumber; private Mesh mesh; private Shader shader; private Material material; private Texture texture; private Transform transform; private boolean chunkUpdateNeeded; private ArrayList&lt;Integer&gt; indiceList = new ArrayList&lt;Integer&gt;(); private Block [][][] blocks = new Block[X_CHUNK_SIZE][Y_CHUNK_SIZE][Z_CHUNK_SIZE]; public Chunk(int chunkXNumber, int chunkZNumber) { this.chunkXNumber = chunkXNumber; this.chunkZNumber = chunkZNumber; createBlocks(chunkXNumber, chunkZNumber); boolean[][][] blocksActive = getActiveBlocks(); texture = new Texture("terrain.png"); material = new Material(texture, new Vector3f(1.0f, 1.0f, 1.0f)); transform = new Transform(); //shader = BasicShader.getInstance(); shader = BasicShader.getInstance(); generateChunk(blocksActive); } private void generateChunk(boolean[][][] blocksActive) { Vertex[] allVertices = createVertices(blocksActive); int[] indices = new int[indiceList.size()]; for(int i = 0; i &lt; indices.length; i++) { indices[i] = indiceList.get(i); } indiceList.clear(); mesh = new Mesh(allVertices, indices, false); transform.setTranslation(chunkXNumber * X_CHUNK_SIZE, -64, chunkZNumber * Z_CHUNK_SIZE); // transform.setScale(new Vector3f(1, 1, 1)); } private void createBlocks(int chunkXNum, int chunkZNum) { float density ; for(int i = 0; i &lt; X_CHUNK_SIZE; i++) { for(int j = 0; j &lt; Y_CHUNK_SIZE; j++) { for(int k = 0; k &lt; Z_CHUNK_SIZE; k++) { density = getDensity(new Vector3f(i ,j ,k ), chunkXNum, chunkZNum); int material = getMaterial(density,j); boolean isActive = setMaterialRules(material); blocks[i][j][k] = new Block(material, isActive); } } } } public void update() { boolean[][][] blocksActive = getActiveBlocks(); Vertex[] allChangedVertices = createVertices(blocksActive); int[] indices = new int[indiceList.size()]; for(int h = 0; h &lt; indices.length; h++) { indices[h] = indiceList.get(h); } mesh = new Mesh(allChangedVertices, indices, false); setChunkUpdateNeeded(false); } } public void render() { shader.bind(); shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), material); mesh.draw(); } private boolean[][][] getActiveBlocks() { boolean [][][] activeBlocks = new boolean[X_CHUNK_SIZE][Y_CHUNK_SIZE][Z_CHUNK_SIZE]; for(int i = 0; i &lt; X_CHUNK_SIZE; i++) { for(int j = 0; j &lt; Y_CHUNK_SIZE; j++) { for(int k = 0; k &lt; Z_CHUNK_SIZE; k++) { activeBlocks[i][j][k] = blocks[i][j][k].isBlockEnabled(); } } } return activeBlocks; } private float getDensity(Vector3f chunkPos, int chunkXNum, int chunkZNum) { float density = 0; //TODO check to see if double is necessary for(float i = 1; i &lt;= Game.octaveLimit; i *= 8) { density += (1/i) * (Noise. noise(((chunkPos.getX() + (chunkXNum * X_CHUNK_SIZE) + .001) / 190.0f) * i, ((chunkPos.getY() + .001) /27.0f) * i,( (chunkPos.getZ() + (chunkZNum * Z_CHUNK_SIZE) + .001) / 190.0f) * i)); density = (density); } // density += (1/i) * (Noise.noise((x / 790.0f) * i, (y / 590.0f) * i,( z / 790.0f) * i)); // density = Math.abs(density); return density; } private int getMaterial(float density, int yVal) { int material; if(density &gt; .52) { if(yVal &gt;= 38) { material = 0; } else { material = 1; } } else { if(yVal &gt;= 8) { material = 0; } else if(yVal &gt; -12 &amp;&amp; yVal &lt; 8) { material = 2; } else { material = 0; } } return material; } private boolean setMaterialRules(int material) { if(material == 1) { return true; } else if(material == 2) { return true; } else { return false; } } private Vertex[] createVertices(boolean[][][] blockActive) { ArrayList&lt;Vertex&gt; vertexList = new ArrayList&lt;Vertex&gt; (); int v1 = X_CHUNK_SIZE; int v2 = Y_CHUNK_SIZE; int v3 = Z_CHUNK_SIZE; for(int i = 0; i &lt; v1; i++) { for(int j = 0; j &lt; v2; j++) { for(int k = 0; k &lt; v3; k++) { if(blockActive[i][j][k]) { Vertex[] blockVerts = createBlock(i, j, k); for(int h = 0; h &lt; blockVerts.length; h++) { vertexList.add(blockVerts[h]); indiceList.add(h); } } } } } Vertex[] finalVertices = new Vertex[vertexList.size()]; finalVertices = vertexList.toArray(finalVertices); return finalVertices; } private Vertex[] createBlock(int x, int y, int z) { ArrayList &lt;Vertex&gt; vertexList = new ArrayList&lt;Vertex&gt; (); int whichTexture = blocks[x][y][z].getBlockType(); if(z &gt; 0) { if(!blocks[x][y][z - 1].isBlockEnabled()) { //Front face vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 3))); } } else if(z == 0) { //Front face vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 3))); } if(z &lt; Z_CHUNK_SIZE - 1) { if(!blocks[x][y][z + 1].isBlockEnabled()) { //Back face vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 3))); } } else { //Back face vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 3))); } if(x &gt; 0) { if(!blocks[x - 1][y][z].isBlockEnabled()) { //Left face vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 3))); } } else if(x == 0) { //Left face vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 3))); } if(x &lt; X_CHUNK_SIZE - 1) { if(!blocks[x + 1][y][z].isBlockEnabled()) { //Right face vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 3))); } } else { //Right face vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 3))); } if(y &gt; 0) { if(!blocks[x][y - 1][z].isBlockEnabled()) { //Bottom face vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 3))); } } else if(y == 0) { //Bottom face vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y, z + 1), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y, z), getTexCoords(whichTexture, 3))); } if(y &lt; Y_CHUNK_SIZE - 1) { if(!blocks[x][y + 1][z].isBlockEnabled()) { //Top face vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 3))); } } else { //Top face vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z + 1), getTexCoords(whichTexture, 1))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x, y + 1, z), getTexCoords(whichTexture, 0))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z + 1), getTexCoords(whichTexture, 2))); vertexList.add(new Vertex(new Vector3f(x + 1, y + 1, z), getTexCoords(whichTexture, 3))); } Vertex[] vertices = new Vertex[vertexList.size()]; vertices = vertexList.toArray(vertices); return vertices; } private Vector2f getTexCoords(int whichTexture, int whichCorner) { if(whichTexture == 1) { switch(whichCorner) { getTexture(); } } else if(whichTexture == 2) { switch(whichCorner) { getTexture(); } } return null; } public Vector2f getChunkValues() { return new Vector2f(chunkXNumber, chunkZNumber); } public Transform getTransform() { return transform; } public void setTransform(Transform transform) { this.transform = transform; } public boolean isChunkUpdateNeeded() { return chunkUpdateNeeded; } public void setChunkUpdateNeeded(boolean chunkUpdateNeeded) { this.chunkUpdateNeeded = chunkUpdateNeeded; } } </code></pre> <p><strong><code>Mesh</code> class:</strong></p> <pre><code>public class Mesh { private int vbo; private int backVbo; private int size; public Mesh(String fileName) { vbo = glGenBuffers(); size = 0; loadMesh(fileName); } public Mesh(Vertex[] vertices, int[] indices) { this(vertices, indices, false); } public Mesh(Vertex[] vertices, int[] indices, boolean calcNormals) { initMeshData(); addVertices(vertices, indices, calcNormals); } private void initMeshData() { vbo = glGenBuffers(); size = 0; } private void addVertices(Vertex[] vertices, int[] indices, boolean calcNormals) { if(calcNormals) { calcNormals(vertices, indices); } size = indices.length; glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, Util.createFlippedBuffer(vertices), GL_DYNAMIC_DRAW); } public void draw() { glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0); glVertexAttribPointer(1, 2, GL_FLOAT, false, Vertex.SIZE * 4, 12); glVertexAttribPointer(2, 3, GL_FLOAT, false, Vertex.SIZE * 4, 20); glDrawArrays(GL_TRIANGLES, 0, size); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } private void calcNormals(Vertex[] vertices, int[] indices) { for(int i = 0; i &lt; indices.length; i += 3) { int i0 = indices[i]; int i1 = indices[i + 1]; int i2 = indices[i + 2]; Vector3f v1 = vertices[i1].getPos().sub(vertices[i0].getPos()); Vector3f v2 = vertices[i2].getPos().sub(vertices[i0].getPos()); Vector3f normal = v1.cross(v2).normalize(); vertices[i0].setNormal(vertices[i0].getNormal().add(normal)); vertices[i1].setNormal(vertices[i1].getNormal().add(normal)); vertices[i2].setNormal(vertices[i2].getNormal().add(normal)); } for(int i = 0; i &lt; vertices.length; i++) { vertices[i].setNormal(vertices[i].getNormal().normalize()); } } private Mesh loadMesh(String fileName) { String[] splitArray = fileName.split("\\."); String ext = splitArray[splitArray.length -1]; if(!ext.equals("obj")) { System.err.println("Error: File format not supported mesh supports Obj you loaded a "+ ext); new Exception().printStackTrace(); System.exit(1); } ArrayList&lt;Vertex&gt; vertices = new ArrayList&lt;Vertex&gt;(); ArrayList&lt;Integer&gt; indices = new ArrayList&lt;Integer&gt;(); BufferedReader meshReader = null; try { meshReader = new BufferedReader(new FileReader("./res/models/" + fileName)); String line; while((line = meshReader.readLine()) != null) { String[] tokens = line.split(" "); tokens = Util.removeEmptyStrings(tokens); if(tokens.length == 0 || tokens[0].equals("#")) { continue; } else if(tokens[0].equals("v")) { vertices.add(new Vertex(new Vector3f(Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), Float.valueOf(tokens[3])))); } else if(tokens[0].equals("f")) { indices.add(Integer.parseInt(tokens[1].split("/")[0]) - 1); indices.add(Integer.parseInt(tokens[2].split("/")[0]) - 1); indices.add(Integer.parseInt(tokens[3].split("/")[0]) - 1); if(tokens.length &gt; 4) { indices.add(Integer.parseInt(tokens[1].split("/")[0]) - 1); indices.add(Integer.parseInt(tokens[3].split("/")[0]) - 1); indices.add(Integer.parseInt(tokens[4].split("/")[0]) - 1); } } } meshReader.close(); Vertex[] vertexData = new Vertex[vertices.size()]; vertices.toArray(vertexData); Integer[] indexData = new Integer[indices.size()]; indices.toArray(indexData); addVertices(vertexData, null, true); } catch(Exception e) { e.printStackTrace(); System.exit(1); } return null; } } </code></pre> <p><strong><code>ChunkManager</code> class:</strong></p> <pre><code>public class ChunkManager { private Chunk[][] currentChunks; public int renderLimit; private int maxChunks; public static boolean chunkUpdateNeeded; public static Vector2f whichChunkUpdate; private boolean xBiggerTrue, zBiggerTrue, xSmallerTrue, zSmallerTrue; private Entity player; public ChunkManager(int renderLimit) { this(renderLimit, renderLimit / (Chunk.X_CHUNK_SIZE)); } public ChunkManager(int renderLimit, int maxChunks) { player = new Player("Hero", 0); player.setCurrentCoords(player.getCurrentCoords()); player.setOldCoords(player.getCurrentCoords()); player.setOldChunkCoords(player.getCurrentChunkCoords()); this.renderLimit = renderLimit; this.maxChunks = maxChunks; currentChunks = new Chunk[(maxChunks * 2) - 1] [(maxChunks * 2) - 1]; firstChunkGen(); } public void chunkUpdates() { if(chunkUpdateNeeded == true) { currentChunks[(int) whichChunkUpdate.getX()][(int) whichChunkUpdate.getY()].setChunkUpdateNeeded(true); chunkUpdateNeeded = false; } } private void firstChunkGen() { for(int i = maxChunks - 1; i &gt; -maxChunks; i--) { for(int j = maxChunks - 1; j &gt; -maxChunks; j--) { if(currentChunks[i + maxChunks - 1][j + maxChunks - 1] == null) { currentChunks[i + maxChunks - 1][j + maxChunks - 1] = new Chunk((int)player.getCurrentChunkCoords().getX() + (i), (int) player.getCurrentChunkCoords().getY() + (j)); } else { continue; } } } } private boolean chunkChangeNeeded() { if((int)player.getCurrentChunkCoords().getX() != (int)player.getOldChunkCoords().getX() || (int)player.getCurrentChunkCoords().getY() != (int)player.getOldChunkCoords().getY()) { System.out.println(player.getCurrentChunkCoords().getY()); System.out.println(player.getOldChunkCoords().getY()); player.setOldChunkCoords(player.getCurrentChunkCoords()); return true; } else { player.setOldChunkCoords(player.getCurrentChunkCoords()); return false; } } private Chunk[][] getChunkChange(Chunk[][] currentChunksCopy, int whichUpdate) { if(whichUpdate == 0) { if(xBiggerTrue) { for(int a = 0; a &lt; currentChunksCopy.length; a++) { for(int b = 0; b &lt; currentChunksCopy[0].length; b++) { if(a == currentChunksCopy.length - 1) { currentChunksCopy[a][b] = new Chunk((int)player.getCurrentChunkCoords().getX() + maxChunks - 1, (int)currentChunksCopy[a][b].getChunkValues().getY()); } else { currentChunksCopy[a][b] = currentChunksCopy[a + 1][b]; } } } return currentChunksCopy; } } else if(whichUpdate == 1) { if(xSmallerTrue) { for(int a = currentChunksCopy.length - 1; a &gt;= 0; a--) { for(int b = currentChunksCopy[0].length - 1 ; b &gt;= 0; b--) { if(a == 0) { currentChunksCopy[a][b] = new Chunk((int)player.getCurrentChunkCoords().getX() - maxChunks + 1, ((int)currentChunksCopy[a][b].getChunkValues().getY())); } else { currentChunksCopy[a][b] = currentChunksCopy[a - 1][b]; } } } return currentChunksCopy; } } else if(whichUpdate == 2) { if(zBiggerTrue) { for(int a = 0; a &lt; currentChunksCopy.length; a++) { for(int b = 0; b &lt; currentChunksCopy[0].length; b++) { if(b == currentChunksCopy[0].length - 1) { currentChunksCopy[a][b] = new Chunk((int)currentChunksCopy[a][b].getChunkValues().getX(), (int)player.getCurrentChunkCoords().getY() + maxChunks - 1); } else { currentChunksCopy[a][b] = currentChunksCopy[a][b + 1]; } } } return currentChunksCopy; } } else if(whichUpdate == 3) { if(zSmallerTrue) { for(int a = currentChunksCopy.length - 1; a &gt;= 0; a--) { for(int b = currentChunksCopy.length - 1; b &gt;= 0; b--) { if(b == 0) { currentChunksCopy[a][b] = new Chunk((int)currentChunksCopy[a][b].getChunkValues().getX(), (int)player.getCurrentChunkCoords().getY() - maxChunks + 1); } else { currentChunksCopy[a][b] = currentChunksCopy[a][b - 1]; } } } return currentChunksCopy; } } return currentChunksCopy; } public void update() { if(chunkChangeNeeded() == true) { if((xBiggerTrue = (currentChunks[(maxChunks * 2) - 2][(maxChunks * 2) - 2].getChunkValues().getX()) &lt; player.getCurrentChunkCoords().getX() + maxChunks - 1)) { currentChunks = getChunkChange(currentChunks , 0); } if((xSmallerTrue = (currentChunks[0][0].getChunkValues().getX()) &gt; player.getCurrentChunkCoords().getX() - maxChunks + 1)) { currentChunks = getChunkChange(currentChunks, 1); } if((zBiggerTrue = (currentChunks[(maxChunks * 2) - 2][(maxChunks * 2) - 2].getChunkValues().getY()) &lt; player.getCurrentChunkCoords().getY() + maxChunks - 1)) { currentChunks = getChunkChange(currentChunks , 2); System.out.println("ZBIG"); } if((zSmallerTrue = (currentChunks[0][0].getChunkValues().getY()) &gt; player.getCurrentChunkCoords().getY() - maxChunks + 1)) { currentChunks = getChunkChange(currentChunks, 3); System.out.println("ZSMALL"); } } chunkUpdates(); } public void input() { if(Input.getKeyDown(Input.KEY_3)) { for(int a = 0; a &lt; currentChunks.length; a++) { for(int b = 0; b &lt; currentChunks[0].length; b++) { System.out.print(" X = " + currentChunks[a][b].getChunkValues().getX() + " Z = " + currentChunks[a][b].getChunkValues().getY()); } System.out.println(); } } } public void render() { for(int i = -maxChunks;i &lt; maxChunks - 1; i++) { for(int j = -maxChunks;j &lt; maxChunks - 1; j++) { float currentChunkX = currentChunks[i + maxChunks][j + maxChunks ].getTransform().getTranslation().getX(); float currentChunkZ = currentChunks[i + maxChunks][j + maxChunks ].getTransform().getTranslation().getZ(); float camX = Game.camera.getPos().getX(); float camZ = Game.camera.getPos().getZ(); if(currentChunkX &lt; camX + renderLimit) { if(currentChunkZ &lt; camZ + renderLimit) { if(currentChunkX &gt; camX - renderLimit) { if(currentChunkZ &gt; camZ - renderLimit) { currentChunks[i + maxChunks][j + maxChunks].render(); } } } } else continue; } } } public int getRenderLimit() { return renderLimit; } public void setRenderLimit(int renderLimit) { this.renderLimit = renderLimit; } public Chunk[][] getCurrentChunks() { return currentChunks; } public void setCurrentChunks(Chunk[][] currentChunks) { this.currentChunks = currentChunks; } public int getMaxChunks() { return maxChunks; } public void setMaxChunks(int maxChunks) { this.maxChunks = maxChunks; } public static boolean isChunkUpdateNeeded() { return chunkUpdateNeeded; } public static void setChunkUpdateNeeded(boolean chunkUpdateNeeded) { ChunkManager.chunkUpdateNeeded = chunkUpdateNeeded; } public static Vector2f getWhichChunkUpdate() { return whichChunkUpdate; } public static void setWhichChunkUpdate(Vector2f whichChunkUpdate) { ChunkManager.whichChunkUpdate = whichChunkUpdate; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:27:26.293", "Id": "54752", "Score": "1", "body": "Your question is not exactly clear. First of all: **Is your code working properly?** If it is not, you should ask it on StackOverflow - but if you do, you will need to improve your question and show more effort of solving the problem first. Asking about backbuffers in OpenGL is off-topic for CodeReview. CodeReview is for reviewing working code, to improve coding style, code readability, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:55:34.683", "Id": "54754", "Score": "0", "body": "Well i was told to post this here instead of normal StackOverflow so im not sure what to do at this point. I'm basically asking for someone to tell me if the method i approached my classes with is correct. My code does compile and it runs decently but slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T21:06:36.780", "Id": "54756", "Score": "2", "body": "If you know your code works, I recommend you update the title to reflect this. It currently suggests that there could be something wrong with the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:14:11.803", "Id": "54763", "Score": "0", "body": "If your code works as it should (except the slow part of course), then you've come to the right place!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:30:09.170", "Id": "54783", "Score": "0", "body": "Ok good to hear! Thanks for replying I was in a temporary state of confusion haha." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T03:11:39.620", "Id": "59384", "Score": "0", "body": "@RylandGoldstein - out of interest, have you solved your performance problem. If you have, you should maybe consider putting in an answer yourself, share the knowledge" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T03:30:46.913", "Id": "59385", "Score": "0", "body": "This is a **lot of code**, you may want to consider breaking it down into several, more specific questions." } ]
[ { "body": "<p>Ok so I actually asked this question a while ago and since I've since figured it out I figured I would go ahead and answer it.</p>\n\n<p>Firstly my issue was not caused by some singular defect in my code or poorly written line but moreso by a culmination of poorly written code as a whole and the specific language I was using.</p>\n\n<p>I'll address the issue that was causing me the most grief first, Garbage collection. Due to the fact that I was using java and creating millions of voxels on the screen at a time from the start I was constantly plagued by issues with garbage collection. Initially the game would play smoothly and then just freeze for 5-10 seconds consistently. I alleviated this problem by switching to Java's concurrent garbage collection system. Although this removed the stop the world aspect of garbage collection it was now replaced with a more constant less severe lag. Full disclosure, I never actually resolved this problem and instead opted to port my entire engine into c++ where the problem doesn't exist in any form.</p>\n\n<p>The second issue was with the way I was handling Geometry creation. I initially didn't use VAO's mostly due to naivety. After switching to VAO's my performance definitely saw a significant increase. But honestly I believe the lag issues I was experiencing can be attributed to the geometry generation itself. Looking back I was culling very few of the vertices that existed in my scene. This combined with overall bad engine design and constant lag from GC really slowed my game down.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-17T22:37:24.457", "Id": "41917", "ParentId": "34061", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:38:57.203", "Id": "34061", "Score": "3", "Tags": [ "java", "optimization", "opengl" ], "Title": "Vertex Buffer Object (VBO) multi-class implementation" }
34061
<p>I'm using <a href="https://github.com/kriskowal/q" rel="nofollow">Q</a> to flatten out some callbacks in my unit tests and return a promise to <a href="http://visionmedia.github.io/mocha/" rel="nofollow">mocha</a> (which knows to wait until the promise is resolved before running the next test).</p> <p>Originally I had this code:</p> <pre><code>it ('resetCount should cause the count to reset as if there were no documents yet.', function () { // Now save user and check if its _id is what nextCount said. user.save(function (err) { should.not.exists(err); user._id.should.eql(0); // Call nextCount to check the next number. Should be one. user.nextCount(function (err, count) { should.not.exists(err); count.should.eql(1); // Now reset the count. user.resetCount(function () { // Call nextCount again to check that the next count is reset. Should be zero. user.nextCount(function (err, count) { should.not.exists(err); count.should.eql(0); done(); }); }); }); }); }); </code></pre> <p>With Q I turned it into this:</p> <pre><code>it('resetCount should cause the count to reset as if there were no documents yet.', function () { var userSchema = new mongoose.Schema({ name: String, dept: String }); userSchema.plugin(autoIncrement.plugin, 'User'); var User = db.model('User', userSchema); // Create user and save it. var user = new User({name: 'Charlie', dept: 'Support'}); // Now save user and check if its _id is what nextCount said. q.nmcall(user, 'save') .then(function (user) { user._id.should.eql(0); return q.nmcall(user, 'nextCount'); }) .then(function (count) { count.should.eql(1); return q.nmcall(user, 'resetCount'); }) .then(q.nmcall(user, 'nextCount')) .then(function (count) { count.should.eql(0); }, function (err) { should.not.exists(err); }); }); </code></pre> <p>I no longer have to call the <code>done</code> callback because of how mocha understands to wait for the promise to resolve. I am new to Q so I'm wondering if I've done things the most efficient way. It seemed like calling node-style mongoose methods with <code>q.nmcall</code> (alias for <a href="https://github.com/kriskowal/q/wiki/API-Reference#promiseinvokemethodname-args" rel="nofollow"><code>q.invoke</code></a>) made the most sense. However, if you think you could write the same code better then please let me know where I can improve it.</p>
[]
[ { "body": "<blockquote>\n<pre><code>.then(q.nmcall(user, 'nextCount'))\n</code></pre>\n</blockquote>\n\n<p>is wrong. The nextCount call does return a promise (and starts its execution right away), while <code>then</code> does expect a [callback] function. You'd rewrite it to</p>\n\n<pre><code>.then(function(result_of_resetcount) {\n return q.nmcall(user, 'nextCount');\n})\n</code></pre>\n\n<p>or shorten it with <a href=\"https://github.com/kriskowal/q/wiki/API-Reference#qdenodeifynodefunc-args\" rel=\"nofollow\"><code>nfbind</code></a>/<a href=\"https://github.com/kriskowal/q/wiki/API-Reference#qnbindnodemethod-thisarg-args\" rel=\"nofollow\"><code>nbind</code></a>:</p>\n\n<pre><code>.then(q.nbind(user.nextCount, user))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T15:20:20.510", "Id": "65690", "Score": "0", "body": "`q.nmcall` returns a promise as I understand it.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T16:49:54.087", "Id": "65694", "Score": "0", "body": "Yes, it does, but you're not allowed to pass one to `then`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T16:53:17.230", "Id": "65695", "Score": "0", "body": "Understood, duh.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T14:26:24.633", "Id": "82139", "Score": "0", "body": "@Marc-Andre: Typo I guess but am not sure. Thanks for spotting it! The difference between `nbind` and `nfbind` is just the handling of the `this` context. If the method doesn't care about its context, you might as well have used `.then(q.nfbind(user.nextCount))`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T14:32:55.063", "Id": "39222", "ParentId": "34062", "Score": "3" } } ]
{ "AcceptedAnswerId": "39222", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T17:59:19.187", "Id": "34062", "Score": "3", "Tags": [ "javascript", "node.js", "asynchronous", "mocha" ], "Title": "Am I using Q the right way or is there a better way to do what I'm doing?" }
34062
<p>Spacing, punctuation, and other such characters are generally ignored when determining whether or not a phrase is a palindrome.</p> <p>Example:</p> <blockquote> <p>A Man, A Plan, A Canal: Panama!</p> <p>amanaplanacanalpanama</p> </blockquote> <p>There are <a href="http://www.palindromelist.net/" rel="nofollow">certain websites dedicated to listing examples of palindromes</a>, and could be used as sample data if testing needs to be done for your script.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:43:20.323", "Id": "34064", "Score": "0", "Tags": null, "Title": null }
34064
Any sequence of units (typically letters or numbers) that are read the same way forward or backward.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:43:20.323", "Id": "34065", "Score": "0", "Tags": null, "Title": null }
34065
<p>I made this nice bit of code that I can insert into any of my projects requiring user input. It seems quite long for what it does and I would love some insight as to how I can do this more efficiently i.e. fewer lines of code.</p> <p>I love to make my code elegant, but I don't see how to do this any better.</p> <pre><code>String x = (JOptionPane.showInputDialog(". Each parameter should be separated with a ',' and without spaces. (eg. 1,2,3)") + ","); int w = 0, a = 0, y = -1; for(int i = 0; i &lt; x.length(); i++) { if(x.charAt(i) == ',') { w++; } } Double[] z = new Double[w]; for(int i = 0; i &lt; x.length(); i++) { if(x.charAt(i) == ',') { z[a] = Double.parseDouble(x.substring((y + 1), i)); y = i; a++; } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>There is absolutely no need to put parentheses around the first statement (small improvement, but it improves readability). \"parameter\" is also misspelled (improving readability but in a different way).</p>\n\n<pre><code>String x = JOptionPane.showInputDialog(\". Each parameter should be separated with a ',' and without spaces. (eg. 1,2,3)\") + \",\";\n</code></pre></li>\n<li><p>There is no need to use <code>Double[]</code> when you can use <code>double[]</code>. The difference is, simply put, that a <code>Double</code> can be <code>null</code> while a <code>double</code> can not.</p></li>\n<li><p>In the rest of your code it seems like you are reading all the doubles from the String (separated by commas), which can be done much easier like this:</p>\n\n<pre><code>String[] splitted = x.split(\",\");\ndouble[] result = new double[splitted.length];\nfor (int i = 0; i &lt; splitted.length; i++) {\n result[i] = Double.parseDouble(splitted[i]);\n}\n</code></pre>\n\n<p>The key here is to use the <code>split</code>-method on the <code>String</code>, which does most of the work for you. For example, it splits the string <code>\"0.37,42,21.4\"</code> into a string array with the three elements <code>\"0.37\"</code>, <code>\"42\"</code> and <code>\"21.4\"</code>. The rest of the code loops through that array and converts from <code>String</code> to <code>double</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:08:31.553", "Id": "34070", "ParentId": "34066", "Score": "3" } }, { "body": "<p>Regular expressions are designed to make this sort of parsing quite easy. For example, your code could look like:</p>\n\n<pre><code>String response = JOptionPane.showInputDialog(\"Each parameter should be separated with a ',' (eg. 1,2,3) : \");\nString[] parts = responses.split(\"\\\\s*,\\\\s*\", -1); // split on commas with optional whitespace.\n\nDouble[] values = new Double[parts.length];\nfor (int i = 0; i &lt; parts.length; i++) {\n if (values[i].length() &gt; 0) {\n // parse places with actual values, empty fields will be treated as 0.0\n values[i] = Double.parseDouble(parts[i]);\n }\n}\n</code></pre>\n\n<p>This is one way to do it, but the parsing could just as easily be done with a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html\" rel=\"nofollow\">StringTokenizer</a> (and some people prefer this method for a variety of reasons even though it is 'Discouraged' in the JavaDoc).</p>\n\n<p>I quite like the simpler process of using String.substring(...). With a simple token system (like a comma) it is easy:</p>\n\n<pre><code> ArrayList&lt;Double&gt; input = new ArrayList&lt;Double&gt;();\n int current = 0;\n do {\n int next = response.indexOf(',', current);\n if (next &lt; 0) {\n next = response.length();\n }\n String val = response.substring(current, next).trim();\n if (val.length() &gt; 0) {\n input.add(Double.parseDouble(val));\n }\n current = next + 1;\n } while (current &lt; response.length());\n Double[] values = input.toArray(new Double[input.size()]);\n System.out.println(Arrays.toString(values));\n</code></pre>\n\n<p>Regardless of which system you use, you should choose the one you understand best.</p>\n\n<p>As for the example code you posted, I think the nit-pick I have is that you do two scans through the input. One to count the sections, and the other to parse them. The second small nitpick is the use of the <code>y</code> variable which is initialized to -1. Really, the <code>y</code> variable is the 'start-of-word' variable, and the first character is <code>0</code>. So, initialize <code>y</code> to 0, and then when you do the substring you can just use plain <code>y</code> and not <code>y+1</code>. Then, you set y to being the start of the next word, which is <code>i+1</code>. This is a small criticisim though.</p>\n\n<p>There are two larger issues I have with your code....</p>\n\n<p>Firstly, it took me a while to figure out that without the <code>+ \",\"</code> at the end of the <code>showInputDialog</code> is a critical component to your loops.... without it you miss the last value. This is a problem because such an important thing is likely to be missed. I think the algorithms above are better for the reason that there is no need for this 'hack'. But, even if you need this hack, you are not documenting it well enough. It should rather be done like:</p>\n\n<pre><code>String x = JOptionPane.showInputDialog(\". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)\");\nx = x + \",\"; // this is needed so that we find the last value in the result.\n</code></pre>\n\n<p>Secondly, your variable names are challenging to understand. I think the following variables should be renamed:</p>\n\n<pre><code>x -&gt; userinput\nw -&gt; words\na -&gt; nextpos\ny -&gt; wordstart\nz -&gt; values\n</code></pre>\n\n<p>With the above variable changes (and the change to the indexing of <code>y</code> or <code>wordstart</code>, your code is much more readable:</p>\n\n<pre><code> String userinput = JOptionPane.showInputDialog(\". Each parameter should be separated with a ',' and without spaces. (eg. 1,2,3)\");\n userinput += \",\"; // needed to make the loops capture the last value on the line.\n int wordcount = 0, nextpos = 0, wordstart = 0;\n for(int i = 0; i &lt; userinput.length(); i++)\n {\n if(userinput.charAt(i) == ',')\n {\n wordcount++;\n }\n }\n Double[] values = new Double[wordcount];\n for(int i = 0; i &lt; userinput.length(); i++)\n {\n if(userinput.charAt(i) == ',')\n {\n values[nextpos] = Double.parseDouble(userinput.substring(wordstart, i));\n wordstart = i + 1;\n nextpos++;\n }\n }\n</code></pre>\n\n<hr>\n\n<p>EDIT: I thought I would point out that there's a way to avoid the 'hack' with the extra comma, even using your mechanism. First, I start with wordcount == 1 (there's always at least one word, plus another word for each comma). Then, I use <code>&lt;= userinput.length()</code> instead of <code>&lt; userinput.length()</code>.... and I use the additional check in the <code>if (i == userinput.length() || ',' == userinput.charAt(i)) {...</code></p>\n\n<pre><code> String userinput = JOptionPane.showInputDialog(\". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)\");\n int wordcount = 1, nextpos = 0, wordstart = 0;\n for(int i = 0; i &lt; userinput.length(); i++)\n {\n if(userinput.charAt(i) == ',')\n {\n wordcount++;\n }\n }\n Double[] values = new Double[wordcount];\n for(int i = 0; i &lt;= userinput.length(); i++)\n {\n if(i == userinput.length() || userinput.charAt(i) == ',')\n {\n values[nextpos] = Double.parseDouble(userinput.substring(wordstart, i));\n wordstart = i + 1;\n nextpos++;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:21:09.863", "Id": "54764", "Score": "0", "body": "I think regex should be avoided for splitting strings, regex could be used to validate the input though. And of course it could be helpful to split with it to allow for extra whitespace. I personally think that all alternatives here except for the one using split are very hard to get a quick understanding of, but then again we all have our preferences :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:29:00.977", "Id": "34072", "ParentId": "34066", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:59:50.513", "Id": "34066", "Score": "3", "Tags": [ "java" ], "Title": "Improving some plugin user-input code" }
34066
<p>I borrowed the code from this <a href="https://stackoverflow.com/questions/19405571/failed-to-understand-the-use-of-delegates-in-real-world-scenarios">question</a>. I'm trying to implement the delegate in that code. Below is my outcome so far.</p> <p>What else can be done to improve this code? Any suggestions? I would appreciate suggestions regarding delegate, code reuse, etc.</p> <pre><code>class Program { static void Main(string[] args) { var flights = new List&lt;Flight&gt; { new Flight {Number = "FL001", DepartureTime = DateTime.Now}, new Flight {Number = "FL002", DepartureTime = DateTime.Now.AddHours(1)}, new Flight {Number = "FL003", ArrivalTime = DateTime.Now.AddMinutes(30)}, new Flight {Number = "FL004", ArrivalTime = DateTime.Now.AddHours(1.30)}, }; var tower = new FlightTower(flights); // Flight 003 asking for landing var flightAskingForLanding= flights.FirstOrDefault(x =&gt; x.Number == "FL003"); if (flightAskingForLanding != null) { Console.WriteLine(string.Format("Flight {0} \t: Okay to land?", flightAskingForLanding.Number)); Console.WriteLine(string.Format("Flight Tower \t: {0}", tower.CanLand(flightAskingForLanding))); } Func&lt;Flight, bool&gt; checkSchedule = x =&gt; flightAskingForLanding.ArrivalTime.IsConflictWithFlightTime(x.ArrivalTime) &amp;&amp; flightAskingForLanding.Number != x.Number; checkSchedule += x =&gt; flightAskingForLanding.ArrivalTime.IsConflictWithFlightTime(x.DepartureTime) &amp;&amp; flightAskingForLanding.Number != x.Number; if (flightAskingForLanding != null) { Console.WriteLine(string.Format("Flight {0} \t: Okay to land?", flightAskingForLanding.Number)); Console.WriteLine(string.Format("Flight Tower \t: {0}", tower.CheckRunwayStatus(flightAskingForLanding, checkSchedule, x =&gt; x.ArrivalTime == flights.Min(f =&gt; f.ArrivalTime)))); } Console.ReadKey(); } } public class FlightTower { private readonly List&lt;Flight&gt; _schedule; public FlightTower(List&lt;Flight&gt; schedule) { _schedule = schedule; } //this method is to show my initial implementation public bool CanTakeOff(Flight flight) { //todo: add code to check for both arrival time and departure time as in the CanLand method var arrivingFlights = _schedule.Where(x =&gt; x.ArrivalTime == DateTime.Now); if (arrivingFlights.ToList().Count == 0) { var flightInQueue = _schedule.FirstOrDefault(x =&gt; x.DepartureTime == _schedule.Min(c =&gt; c.DepartureTime)); if (flightInQueue != null &amp;&amp; flightInQueue.Number == flight.Number) { return true; } } return false; } //this method is to show my initial implementation public bool CanLand(Flight flight) { var arrvingFlight = _schedule.Where(x =&gt; flight.ArrivalTime.IsConflictWithFlightTime(x.ArrivalTime) &amp;&amp; flight.Number != x.Number); var depatingFlight = _schedule.Where(x =&gt; flight.ArrivalTime.IsConflictWithFlightTime(x.DepartureTime) &amp;&amp; flight.Number != x.Number); if (arrvingFlight.ToList().Count == 0 &amp;&amp; depatingFlight.ToList().Count == 0) { var flightInQueue = _schedule.FirstOrDefault(x =&gt; x.ArrivalTime == _schedule.Min(c =&gt; c.ArrivalTime)); if (flightInQueue != null &amp;&amp; flightInQueue.Number == flight.Number) return true; } return false; } //this will replace above CanLand and CanTakeOff methods public bool CheckRunwayStatus(Flight flight, Func&lt;Flight, bool&gt; checkSchedule, Func&lt;Flight, bool&gt; checkFlightQueue) { var flightStatus = _schedule.Where(checkSchedule); if (flightStatus.ToList().Count == 0 ) { var flightInQueue = _schedule.FirstOrDefault(checkFlightQueue); if (flightInQueue != null &amp;&amp; flightInQueue.Number == flight.Number) return true; } return false; } } public class Flight { public string Number { get; set; } public DateTime DepartureTime { get; set; } public DateTime ArrivalTime { get; set; } public int TotalCrew { get; set; } } public static class DateTimeExtension { public static bool IsConflictWithFlightTime(this DateTime currentFlightTime, DateTime nextFlightTime) { TimeSpan timeDiff= nextFlightTime - currentFlightTime; double totalMinutes = timeDiff.TotalMinutes; if (totalMinutes &lt; 0) totalMinutes = totalMinutes * -1; totalMinutes = Math.Round(totalMinutes); if (totalMinutes &lt;= 30.0D) return true; else return false; } } </code></pre> <p>Here's my implementation of <code>ConductFlightOperations</code>. I'm not sure if this is proper way of doing it.</p> <pre><code>public void ConductFlightOperations() { // Flight 003 asking for landing var flightAskingForLanding = _schedule.FirstOrDefault(x =&gt; x.Number == "FL003"); if (flightAskingForLanding != null) { Console.WriteLine(string.Format("Flight {0} \t: Okay to land?", flightAskingForLanding.Number)); LandingClearance(flightAskingForLanding); flightAskingForLanding.Land(); } } </code></pre> <p>Here's my implementation of <code>Deconflict</code>. Right now it only check for <code>someFlight.ArrivalTime</code> (which is for Landing flights), what should be proper way to reuse same code to check for <code>someFlight.DepartureTime</code>(for Departing flights)? Should I pass some flag or create new method or something else?</p> <pre><code> protected bool Deconflict(Flight someFlight) { if (_schedule.Any(x =&gt; x.Number != someFlight.Number &amp;&amp; Math.Abs((x.ArrivalTime - someFlight.ArrivalTime).TotalMinutes) &lt; 20D)) return false; if (_schedule.Any(x =&gt; x.Number != someFlight.Number &amp;&amp; Math.Abs((x.DepartureTime - someFlight.ArrivalTime).TotalMinutes) &lt; 20D)) return false; return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T22:01:34.140", "Id": "56884", "Score": "0", "body": "Thanks all for their time and efforts. @radarbob most of the pieces are clear now. Please advice for the EDIT in my questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-12T14:45:39.720", "Id": "57028", "Score": "0", "body": "@radarbob could you please spend few minutes from your valuable time to give answer on my EDIT part?" } ]
[ { "body": "<h2>Be more Object Oriented</h2>\n\n<p>Most of the code in <code>Main()</code> should be in the <code>Flight</code> or <code>FlightTower</code> classes. Seems to me that if it's in an appropriate class then its re-usable.</p>\n\n<h3>What does a Tower <em>DO</em>?</h3>\n\n<ul>\n<li>Clear flights to land (i.e. process a landing request)</li>\n<li>Clear flights to takeoff</li>\n<li>Deconflict in/out bound traffic</li>\n</ul>\n\n<h3>What does a Flight <em>DO</em>?</h3>\n\n<ul>\n<li>Actually lands</li>\n<li>Actually takes off</li>\n</ul>\n\n<p></p>\n\n<pre><code>public class FlightTower {\n // I dont know what if anything to return just yet\n public xxx LandingClearance(Flight incomingFlight) {}\n public xxx TakeoffClearance(Flight outgoingFlight) {}\n}\n\npublic class Flight {\n public xxx Takeoff() {}\n public xxx Land() {}\n}\n</code></pre>\n\n<h3>Making up an excuse to use delegates</h3>\n\n<p>Flight just \"does what it's told\" - i.e. whatever method the <code>delegate</code> holds. Takeoff/landing requests gives context as to what kind of instructions we're talking about.</p>\n\n<pre><code>public delegate void FlightInstructions()\n\npublic class Tower {\n public void LandingInstructions() {}\n public void HoldingInstructions() {}\n public void TakeoffInstructions() {}\n public void HoldForTakeoffInstructions() {}\n\n public xxx LandingClearance(Flight incomingFlight) {\n If (Deconflict(incomingFlight)) {\n incomingFlight.Instructions = LandingInstructions;\n else\n incomingFlight.Instructions = HoldingInstructions;\n }\n }\n\n protected bool Deconflict(Flight someFlight) {}\n}\n\npublic class Flight {\n public FlightInstructions Instructions;\n\n public xxx Takeoff() { Instructions(); }\n public xxx Land() { Instructions(); }\n}\n</code></pre>\n\n<h3>An abstract <code>Main()</code> is a good thing</h3>\n\n<pre><code>public static void Main() {\n FlightTower tower = new FlightTower(BuildFlightSchedule());\n\n tower.ConductFlightOperations(); // iterates the _schedule - all that junk exposed in the original Main()\n}\n\npublic static List&lt;Flight&gt; BuildFlightSchedule() {}\n</code></pre>\n\n<h3>Miscellaneous</h3>\n\n<p>This:</p>\n\n<pre><code>double totalMinutes = timeDiff.TotalMinutes;\nif (totalMinutes &lt; 0)\n totalMinutes = totalMinutes * -1;\n</code></pre>\n\n<p>Could be this:</p>\n\n<pre><code>double totalMinutes = Math.Abs(timeDiff.TotalMinutes);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T05:36:09.653", "Id": "34090", "ParentId": "34073", "Score": "7" } }, { "body": "<p>In addition to @radarbobs answer, a few more technical points about your code (mainly related to your usage of Linq):</p>\n\n<ol>\n<li><code>flightAskingForLanding</code> is obtained using <code>FirstOrDefault</code>, yet your code will crash when building <code>checkSchedule</code> as you unconditionally access the variable. </li>\n<li><p>In <code>FlightTower.CanTakeOff()</code>, you do this:</p>\n\n<pre><code>var arrivingFlights = _schedule.Where(x =&gt; x.ArrivalTime == DateTime.Now);\n\nif (arrivingFlights.ToList().Count == 0)\n{\n ...\n}\n</code></pre>\n\n<ul>\n<li>It's not necessary to create a list to get the count, the Linq extensions define a <code>Count()</code> extension method on <code>IEnumerable&lt;T&gt;</code>.</li>\n<li>Furthermore there is an <a href=\"http://msdn.microsoft.com/en-us/library/bb535181%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">overload for <code>Count()</code></a> which accepts a predicate so you can shorten this to: <code>if (_schedule.Count(x =&gt; x.ArrivalTime == DateTime.Now) == 0)</code></li>\n<li>But actually you are not really interested in the count. What you want is \"check if there aren't any flight arriving now\" so you should use <a href=\"http://msdn.microsoft.com/en-us/library/bb534972%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>Any()</code></a> (which can break early if the sequence is not empty): <code>if (!_schedule.Any(x =&gt; x.ArrivalTime == DateTime.Now))</code></li>\n</ul></li>\n<li>This <code>_schedule.FirstOrDefault(x =&gt; x.DepartureTime == _schedule.Min(c =&gt; c.DepartureTime))</code> is an O(N<sup>2</sup>) operation (for every item in schedule find the minimum in schedule and compare). Unfortunately there is no nice \"return object where a certain property has the minimum\" built into Linq but there are <a href=\"https://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value\">some alternative options</a> (worst case: first find the minimum and store in a local variable and then search the object)</li>\n<li>Above two points also apply to <code>CanLand()</code> and <code>CheckRunwayStatus</code>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T10:11:29.673", "Id": "34092", "ParentId": "34073", "Score": "2" } } ]
{ "AcceptedAnswerId": "34090", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T20:44:53.573", "Id": "34073", "Score": "2", "Tags": [ "c#", "delegates" ], "Title": "Implementation of delegates for flight operations" }
34073
<p>I have a script that separates the date from a datepicker into day, month, and year. It works fine when there is one form on the page but not when there is a second one (presumably due to the id being the same). How can I add a value to my id and name so that they are unique values if the script runs twice on the same page? </p> <pre><code>var now = new Date(); var date = jQuery('.form-date'); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day) ; date.val(today); jQuery('form').on('submit', function() { var newVal = date.val().split('-'), dateParts = { year: parseInt(newVal[0], 10), month: parseInt(newVal[1], 10), day: parseInt(newVal[2], 10) }; jQuery('.anchor').append(jQuery.map(dateParts, function (index, key) { var name = 'date_' + key; return jQuery('&lt;input&gt;', { type: 'hidden', name: name, id: name, value: dateParts[key] }); })); }); </code></pre> <p>Here is the form that isn't posting the correct date:</p> <pre><code>&lt;form id="modal_res" action="http://www.site.com/search.php" method="get" name="disponibilita" target="_blank" class="custom"&gt; &lt;ul&gt; &lt;li&gt; &lt;label for="modal_date" class="anchor1"&gt;&lt;?php _e('Date:', 'hostel_mama' )?&gt;&lt;/label&gt;&lt;input type="date" name="date" id="modal_date" class="form-date datepicker"&gt; &lt;/li&gt; &lt;li&gt; &lt;label for="modal_nights"&gt;&lt;?php _e('Nights:', 'hostel_mama' )?&gt;&lt;/label&gt;&lt;input type="number" name="nights" id="modal_nights" value="2"&gt; &lt;/li&gt; &lt;li&gt; &lt;label for="modal_people"&gt;&lt;?php _e('Guests:', 'hostel_mama' )?&gt;&lt;/label&gt;&lt;input type="number" name="people" id="modal_people" value="1"&gt; &lt;/li&gt; &lt;input name="ref" type="hidden" id="modal_ref" value="558" /&gt; &lt;input name="langClient" type="hidden" id="modal_langClient" value="eng" /&gt; &lt;li class="select-container"&gt; &lt;label for="modal_expr"&gt;&lt;?php _e('Currency:', 'hostel_mama' )?&gt;&lt;/label&gt; &lt;select name="expr" id="modal_expr"&gt; &lt;option value="EUR" selected="selected"&gt;&lt;?php _e('EURO', 'hostel_mama' )?&gt;&lt;/option&gt; &lt;option value="USD"&gt;&lt;?php _e('US Dollar', 'hostel_mama' )?&gt;&lt;/option&gt; &lt;option value="GBP"&gt;&lt;?php _e('British Pound', 'hostel_mama' )?&gt;&lt;/option&gt; &lt;/select&gt; &lt;/li&gt; &lt;/ul&gt; &lt;input type="submit" name="submit" class="button radius text-center" value="Click to Book"&gt; &lt;/form&gt; </code></pre>
[]
[ { "body": "<p>Use a closure, so everything will be only inside it's scope. Additionally you can use $ now!</p>\n\n<pre><code>(function ($) {\n var now = new Date();\n var date = $('.form-date');\n var day = (\"0\" + now.getDate()).slice(-2);\n var month = (\"0\" + (now.getMonth() + 1)).slice(-2);\n var today = now.getFullYear() + \"-\" + (month) + \"-\" + (day);\n\n date.val(today);\n\n var form = $('form');\n\n form.on('submit', function (e) {\n var currentForm = $(this);\n var newVal = currentForm.find('.form-date').val().split('-'),\n\n dateParts = {\n year: parseInt(newVal[0], 10),\n month: parseInt(newVal[1], 10),\n day: parseInt(newVal[2], 10)\n };\n\n currentForm.find('.anchor').append($.map(dateParts, function (index, key) {\n console.log(['date', form.index(currentForm), key].join('_'));\n return $('&lt;input&gt;', {\n type: 'hidden',\n name: ['date', key].join('_'),\n id: ['date', form.index(currentForm), key].join('_'),\n value: dateParts[key]\n });\n }));\n\n });\n})(jQuery);\n</code></pre>\n\n<p>Also change class=\"anchor1\" to class=\"anchor\"</p>\n\n<p>Edit: Whoops, looks like I'm wrong. You have to scope your selectors as $('.anchor').append will work on all .anchor elements. I'm assuming that it's the child of form now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:31:34.027", "Id": "54767", "Score": "0", "body": "No still doesn't work. I think the problem is the id because it works when there is only one on a page. I think I need a unique value for `name`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:45:23.250", "Id": "54770", "Score": "0", "body": "You are completely right - I've added form index as part of id/name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:00:37.573", "Id": "54775", "Score": "0", "body": "I kept the name the same because thats what the form accepts and added another value for id. But apparently that's not the problem. It keeps posting `date_year=2013&date_month=11&date_day=8`which is what the form is initialised to. I think it is finding `.form_date` on the second form so I need a unique class for the second form. I'm going to test my theory now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:04:56.113", "Id": "54779", "Score": "0", "body": "Aha, it works if I change the class in the second form to `form-date1`. Now can I do something like .find('.form-date', 'form-date1')?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:11:36.933", "Id": "54780", "Score": "0", "body": "Nope, change it back. You have to change all form.find to currentform.find, also change class in your html from anchor1 to anchor. http://jsfiddle.net/nmjP3/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T21:45:12.303", "Id": "34076", "ParentId": "34075", "Score": "1" } } ]
{ "AcceptedAnswerId": "34076", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T21:01:03.207", "Id": "34075", "Score": "1", "Tags": [ "javascript", "php", "jquery" ], "Title": "Refactor to provide for multiple instances on a single page" }
34075
<p>I have much more experience with PAWN scripting language, but I'm digging into K&amp;R book (I think it is it), and trying some stuff on my own.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define ITEMS_COUNT 16 unsigned int randr(unsigned int min, unsigned int max); inline short randomType(); inline char* randomCompanyName(); inline char* randomPersonName(); inline char* randomPersonSurname(); void populateItems(); void dumpItems(); typedef unsigned short int DBID; typedef struct { char name[64]; char surname[64]; } Person; typedef struct { char name[128]; } Company; typedef struct { unsigned short int type; DBID dbID; union { Person PersonItem; Company CompanyItem; } chosenItem; } Item; enum E_TYPE { TYPE_PERSON, TYPE_COMPANY }; Item itemList[ITEMS_COUNT]; int main(int argc, char* argv[]) { /* Init stuff */ srand(time(NULL)); populateItems(); dumpItems(); return 0; } void populateItems() { Item singleItem; size_t i = 0; for(; i != ITEMS_COUNT; ++i) { singleItem.dbID = i + 1; singleItem.type = randomType(); if(TYPE_PERSON == singleItem.type) { strncpy(singleItem.chosenItem.PersonItem.name, randomPersonName(), sizeof(singleItem.chosenItem.PersonItem.name)); strncpy(singleItem.chosenItem.PersonItem.surname, randomPersonSurname(), sizeof(singleItem.chosenItem.PersonItem.surname)); } else { strncpy(singleItem.chosenItem.CompanyItem.name, randomCompanyName(), sizeof(singleItem.chosenItem.CompanyItem.name)); } memcpy(&amp;itemList[i], &amp;singleItem, sizeof(singleItem)); } } void dumpItems() { Item *currentItem; size_t i = 0; char str[256]; for(; i != ITEMS_COUNT; ++i) { currentItem = &amp;itemList[i]; //Not safe sprintf! sprintf(str, "Row %d: { dbID: %d,", i + 1, currentItem-&gt;dbID); if(TYPE_PERSON == currentItem-&gt;type) { sprintf(str, "%s name: %s, surname: %s }", str, currentItem-&gt;chosenItem.PersonItem.name, currentItem-&gt;chosenItem.PersonItem.surname); } else { sprintf(str, "%s company name: %s }", str, currentItem-&gt;chosenItem.CompanyItem.name); } printf("%s\n", str); } } inline short randomType() { return randr(0, 1); } inline char* randomCompanyName() { static char* nameList[32] = { "Microsoft", "Valve", "Vamonos pest", "Hello folks!", "Just a program inc" }; return nameList[randr(0, 4)]; } inline char* randomPersonName() { static char* nameList[32] = { "John", "Mike", "Emily", "Jessica", "Steven" }; return nameList[randr(0, 4)]; } inline char* randomPersonSurname() { static char* nameList[32] = { "Ross", "Litt", "Hellyeah" }; return nameList[randr(0, 2)]; } unsigned int randr(unsigned int min, unsigned int max) { double scaled = (double) rand() / RAND_MAX; return (max - min + 1) * scaled + min; } </code></pre> <p>I'd like you to tell me if I've made any major mistakes, and how's my coding style. Additionally I have a question about unions. I thought that it simply pointed to regions, and that you didn't have to care later which one you are using, like:</p> <pre><code>//instead of singleItem.chosenItem.PersonItem.name //use singleItem.chosenItem.name </code></pre> <p>which would point at either PersonItem.name, or CompanyItem.name. How to achieve somthing similar?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-12T12:54:36.840", "Id": "57010", "Score": "0", "body": "K&R is about _the C language_, `inline` is C++'s alternative/answer/attempt at solving macro issues" } ]
[ { "body": "<p>My little bit of input:</p>\n\n<ol>\n<li><p><code>inline</code> is a C++ keyword, and it's only a hint to the compiler. The only reason to explicitly use <code>inline</code> is when you define function's body inside a header file, which is included in more than one source file.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/9834747/reasons-to-use-or-not-stdint\">Avoid basic data types like <code>int</code>, use types from <code>stdint.h</code> instead</a></p></li>\n<li><p><a href=\"http://improvingsoftware.com/2011/06/27/5-best-practices-for-commenting-your-code/\" rel=\"nofollow noreferrer\">Use comments to explain why are you doing something, and what are function arguments for</a></p></li>\n<li><p>No reason to break a line after declaring a type.</p></li>\n<li><p>No reason to give <code>nameList[32]</code> a size - the compiler will guess it on its own. Just do it as</p>\n\n<pre><code>static char* nameList[] = {\n \"Ross\",\n \"Litt\",\n \"Hellyeah\"\n}; \n</code></pre></li>\n<li><p>Use <code>sizeof(nameList) - 1</code> instead of a magic number to indicate last array index - there will be less changes if you ever add more names.</p></li>\n</ol>\n\n<p>Regarding your union questions:</p>\n\n<p><code>union</code> is kinda like a <code>struct</code>; the only difference is how it's handled in memory.\nSince your <code>union</code> has two fields (<code>PersonItem</code> and <code>CompanyItem</code>), you must say which one is to be used. Every object created with your <code>struct</code> will contain both fields. What you're trying to do is called polymorphism, and you have it with classes in C++. Original C does not have such option.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:42:17.087", "Id": "54769", "Score": "0", "body": "Also: read this, it should help you with code quality, even though it's not for C :) http://net.tutsplus.com/tutorials/html-css-techniques/top-15-best-practices-for-writing-super-readable-code/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:53:20.237", "Id": "54771", "Score": "0", "body": "You might cringe a little, but I'm a professional webdeveloper (+ php scripter) (as in earn money for living with, not skill level yet) - don't worry though, I stick to php-psr.\n\nI didn't know that inline is C++ only, and I had no clue about badness of builtin datatypes - thanks for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:55:56.793", "Id": "54772", "Score": "0", "body": "I know that unions are structs with each element pointing to index 0 (I guess). And those 32 were to tell future coders that you can't go over 31 + NUL limit.\n\nI wanted to master C (at least syntax) before moving on to C++, but I think I know what you're talking about (virtual classes and stuff)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:56:10.143", "Id": "54773", "Score": "0", "body": "I'm glad I could help :) I know what you mean, I'm a professional C++ developer as in earn money for a living, not skill level yet :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:58:45.670", "Id": "54774", "Score": "1", "body": "Ok :) In that case, since you know what you're doing I have nothing to add :) Good luck :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:01:50.810", "Id": "54777", "Score": "0", "body": "Regarding the `inline`, I believe everything included in the header becomes inline by default (I'm not sure if you were implying that)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:14:02.053", "Id": "54781", "Score": "0", "body": "No. Directive \"#include\" makes everything from the header pasted into source file, but it doesn't mean inlining. If you have `void someFunction() {}` in a header, which is not inline, and you include that header in more than one source file you'll get linking error \"multiple definitions\". It's likely that a good compiler will inline such function by itself, and solve the problem, but there is no guarantee of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T00:06:36.373", "Id": "54785", "Score": "0", "body": "Oh! I've found out about anonymous unions (part of C11), so instead currentItem->chosenItem.PersonItem.name I can use currentItem->PersonItem.name. Good to know that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T00:39:23.540", "Id": "54786", "Score": "1", "body": "@DarthHunterix your point 1 is untrue, `inline` is in c99. Your point 2 is not appropriate here. There is no reason not to use int/char etc in this code. Your point 6 is wrong - `sizeof(nameList)` is the size in bytes of `nameList`, not the number of `char*` entries in the array." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:33:58.177", "Id": "34080", "ParentId": "34077", "Score": "2" } }, { "body": "<p>Your code has a number of issues.</p>\n\n<p>It is often better to layout the code in reverse order. This avoids the need\nfor local prototypes. For example, <code>main</code> goes last in the file and the\nfunctions it calls are above it. <code>inline</code> functions must be defined before\nthey are used - another reason for doing things backwards. Note that the\ncompiler can decide for itself what should be inline and what not, so using\n'inline' is normally unnecessary.</p>\n\n<p>You have defined <code>emum E_TYPE</code> but not used it in <code>struct Item</code>, where it is\nneeded. Instead you use <code>unsigned short int type</code>. Note that all-caps names\nare usually constants, so <code>E_TYPE</code> would be better as <code>type</code>. Function\n<code>randomType</code> should return an <code>enum type</code>, not a <code>short</code> and should use the\nvalues defined for the enum. The union in your <code>Item</code> struct need not have a\nname and its field names are verbose. Here is how I would simplify it:</p>\n\n<pre><code>typedef struct {\n enum type type;\n DBID id;\n union {\n Person person;\n Company company;\n };\n} Item;\n</code></pre>\n\n<p>General point: don't put the type and variable on separate lines. Nobody does that.</p>\n\n<p>Functions with no parameters should be defined with a <code>void</code> in the parameter\nlist. The compiler should warn you about that (compile with warnings turned\non - use at least the option -W with gcc).</p>\n\n<p>In your <code>randomCompanyName</code> etc functions, the name list should be <code>const</code>.\nWhen selecting the random name using</p>\n\n<pre><code>return nameList[randr(0, 4)];\n</code></pre>\n\n<p>instead of an explicit 4, you should derive the value from the array:</p>\n\n<pre><code>const char* nameList[] = {\n \"Microsoft\",\n \"Valve\",\n \"Vamonos pest\",\n \"Hello folks!\",\n \"Just a program inc\"\n};\nconst int listSize = sizeof nameList / sizeof nameList[0];\nreturn nameList[randr(0, listSize - 1)];\n</code></pre>\n\n<p>You can do this only if you omit the size of the array.</p>\n\n<p>Your <code>randr</code> is almost correct, but should divide by <code>RANDMAX + 1</code></p>\n\n<pre><code>double scaled = rand() / (1.0 + RAND_MAX);\n</code></pre>\n\n<p>Your <code>populateItems</code> function is not very readable. For a start, it is\ngenerally best not to exceed about 80 characters per line. It is also odd to\ncreate an <code>Item</code> and then copy that into the global array. Why not create it\ndirectly in the correct array entry? Also, define the loop variable in the\nloop, not above it.</p>\n\n<p>Your use of <code>strncpy</code> in the loop is a problem. <code>strncpy</code> does not do what\nyou might expect when there is not enough space. It does not terminate the\ntruncated string! To do it properly you must terminate each string\nexplicitly. This is messy. The alternative copy function <code>strlcpy</code> that gets\nit right but is not universally available (and hence is non-portable).\nAn alternative, perhaps nicer , is to get your <code>randomCompanyName</code> etc\nfunctions, to fill the string buffer themselves:</p>\n\n<pre><code>static char* randomCompanyName(char *buf, size_t size)\n{\n static char* nameList[] = { ...\n };\n const int listSize = sizeof nameList / sizeof nameList[0];\n const char *name = nameList[randr(0, listSize - 1)];\n strncpy(buf, name, size);\n buf[size - 1] = '\\0';\n return buf;\n}\n</code></pre>\n\n<p>Putting these together, <code>populateItems</code> then becomes rather easier to read:</p>\n\n<pre><code>static void populateItems(void)\n{\n for (int i = 0; i &lt; ITEMS_COUNT; ++i) { // note &lt; not !=\n Item *it = &amp;itemList[i];\n it-&gt;id = i + 1;\n it-&gt;type = randomType();\n\n if (it-&gt;type = TYPE_PERSON) {\n randomPersonName(it-&gt;person.name, sizeof it-&gt;person.name);\n randomPersonSurname(it-&gt;person.surname, sizeof it-&gt;person.surname);\n } else {\n randomCompanyName(it-&gt;company.name, sizeof it-&gt;company.name);\n }\n }\n}\n</code></pre>\n\n<p>Your <code>dumpItems</code> uses <code>sprintf</code> to create a string but overwrites the first\npart (\"Row %ld: { dbID: %d,\") with the second part (\"%s name: %s, surname: %s\n}\") as it does not index into <code>str</code>. <code>sprintf</code> like <code>strcpy</code> etc is a common\nsource of buffer overruns. You could use <code>snprintf</code> instead, but really why\nbother? It would be much easier just to print the two parts of the string\ndirectly to <code>stdout</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T02:50:18.710", "Id": "54797", "Score": "0", "body": "Thanks for your feedback! I have question though: is using static for every function some kind of convention? (even if the program is single file) Didn't know that bit about strncpy, I was a little confused when I saw 20 diffrent strcpy variations. \n\nOh, and I don't know why I used the new instance -> memcpy thingy, I think I didn't know then about the -> operator and thought I'd have to use (*it).stuff all the time. \n\nhttp://pastebin.com/Tp30jhTE - much more readable now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T11:42:45.763", "Id": "54807", "Score": "0", "body": "Functions should be `static` if they will never be used outside the file that defines them. For a single-file program this doesn't matter, but adding the `static` to each function keeps my compiler silent (gcc warning `-Wmissing-prototypes`). I just forgot to remove them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T01:58:00.153", "Id": "34086", "ParentId": "34077", "Score": "2" } } ]
{ "AcceptedAnswerId": "34080", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T21:54:42.150", "Id": "34077", "Score": "0", "Tags": [ "c++", "c" ], "Title": "C code displaying random datasets" }
34077
<p>It is nice to be able to set your data in a domain object like so:</p> <pre><code>$order-&gt;setId($id); $order-&gt;setCustomer($customer); $order-&gt;setItems($items); </code></pre> <p>And then be able to do</p> <pre><code>if( !$order-&gt;validate() ) { // Invalid data } </code></pre> <p>Which will validate all the set data and tell you if it was valid or not. I have an implementation of this I came up with but it is sort of messy and limited to only certain common validation rules like checking the type, length/range and format of the data.</p> <p>I have been doing a lot of Javascript lately and I like the idea of the anonymous functions and I just found out you can do them in PHP 5.3+ and you can use the <code>$this</code> keyword from PHP 5.4.</p> <pre><code>abstract class AbstractEntity { private $id = 0; private $validations = array(); public function setId($id) { $this-&gt;id = $id; // A function to validate the Id $this-&gt;addValidation( function() { return ( $this-&gt;id &gt; 0 ); }); } public function getId() { return $this-&gt;id; } public function validate() { foreach($this-&gt;validations as $validation) { if( $validation() === false ) { return false; } } return true; } protected function addValidation($function) { $this-&gt;validations[] = $function; } } </code></pre> <p>The <code>Order</code> class:</p> <pre><code>class Order extends AbstractEntity { private $customer; private $items = array(); private $status; public function setCustomer(Customer $customer) { $this-&gt;customer = $customer; // Make sure the customers account is active $this-&gt;addValidation( function() { return ( $this-&gt;customer-&gt;isActive() ); }); // Do as many complex validations as needed } public function setStatus($status) { $this-&gt;status = $status; // The status has to be 'Pending' or 'Complete'. $this-&gt;addValidation( function() { return ( ($this-&gt;status === 'Pending') || ($this-&gt;status === 'Complete') ); }); } </code></pre> <p>Doing it this way validations of all different levels of complexity can be done. I was thinking of adding in another parameter to the <code>addValidation()</code> method so you can group validation rules together so they execute in a certain order.</p> <p>It needs extra functionality like setting error messages but that should not be too hard to implement.</p> <p>I was also thinking of maybe making the <code>addValidation()</code> method public so you can add validations outside of the class that will execute when the <code>validate()</code> method is called. This could be handy in some scenarios.</p> <p>Is this a good or bad idea? I would like to see some opinions before I go and change all my code to using this sort of implementation.</p>
[]
[ { "body": "<p>my two cents :</p>\n\n<ul>\n<li>I think tying validation activation to setters is not really good. What if you never set any value on your object ? It will be considered valid ! And what happens if you set the property more than once ?</li>\n<li>Some implementations use external validator objects, which allow more flexibility (validation rules often vary, according to which user requests saving for instance). When you call <code>validate()</code>, you either pass a validator instance or let the object use a default validator. As a side note, coming from Rails / ActiveRecord, I can tell that complex projects often do not turn well when your domain object's lifecycle is so tightly tied to a single validation scheme !</li>\n<li>Speaking DDD lingo, some of your problems might be efficiently solved using <a href=\"http://en.wikipedia.org/wiki/Value_object\" rel=\"nofollow\">Value objects</a>. For instance, your <code>Id</code> property could be a value object that has a <code>isValid()</code> method (it would be responsible for its own validation). Wether or not this is a good idea depends on your domain.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T14:53:59.640", "Id": "34096", "ParentId": "34078", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:07:33.090", "Id": "34078", "Score": "3", "Tags": [ "php", "object-oriented" ], "Title": "Closures with validation rules for domain object properties" }
34078
<p>I have a <code>while</code> loop below, but I'm not quite sure if it's the most 'pythonic' thing. I've omitted most of the code, and have the skeletal structure below (but have all the code necessary to understand my <code>game_status()</code> function). And the main thing in question is whether/how to use a function as a condition in a <code>while</code> statement. (In my case, the <code>game_status()</code> function).</p> <pre><code>#Legal board positions BOARD_POSITIONS = list(range(1, 10)) #All possible combinations of board positions giving 8 winning lines. WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]] def game_status(board): """Updates the status of the game based on three outcomes: Returning 'X' or 'O' is either has three in a row; 'tie' if the board is full, but no players have won; or 'unfinished' otherwise""" for i, j, k in WINNING_LINES: if not available(board, i) and board[i] == board[j] == board[k]: return board[i] if any(available(board, i) for i in BOARD_POSITIONS): return 'unfinished' return 'tie' while True: game_board = (' ' for i in range(10)) while game_status(game_board) is 'unfinished': #Main game code else: if game_status(game_board) is 'X': #Code for X winning goes here elif game_status(game_board) is 'O': #Code for O winning goes here else: #Code for a tie goes here </code></pre> <p>As you notice, I've got to call <code>game_status()</code> multiple times in the <code>else</code> part of my <code>while</code> statement in order to check the value of <code>game_status()</code> so that I know to print who won or if the game was a tie.</p> <p>One idea I had is the following:</p> <pre><code>else: status = game_status(game_board) if status = 'X': #Code elif status = 'O': #Code </code></pre> <p>and so on. However, I am quite curious as to the most pythonic way to do things, as well as whether or not using a function as a conditional is pythonic.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T01:11:42.600", "Id": "54789", "Score": "0", "body": "Okay. :O I know that on CodeReview, I was previously criticized for calling a function repeadetly in this manner, so I was curious if there was a simpler way, or more pythonic way. :P I'll check out codereview though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T01:22:07.077", "Id": "54790", "Score": "2", "body": "You should probably get out of the habit of caring quite so much whether something is \"pythonic\" or not. Most of the time if you ask someone for an opinion on that, they will answer with their own preferred style. Almost nobody says, \"I would do this this way, which I prefer, but the other way is more pythonic\". Which means that almost nobody has an objective idea what pythonicism is. What you're asking for, is an opinion on code style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T01:31:06.770", "Id": "54791", "Score": "2", "body": "What I can say objectively, is that I don't believe you're guaranteed that those `is` checks work. As it happens, CPython (and presumably other Python implementations) will use the same object for equal string literals in different places, but I don't believe the language guarantees that this will always be the case http://stackoverflow.com/questions/17679861/does-python-intern-strings" } ]
[ { "body": "<p>When you make \"the same\" function call repeatedly, you can create a question in the reader's mind whether or not it will return the same value every time (especially where the arguments are mutable objects, but even if not).</p>\n\n<p>This is probably to be avoided where it's easy to do so. In your code the expectation is that the function <em>will</em> eventually change what value it returns to terminate the loop, and then <em>won't</em> change value across the <code>if ... elif</code></p>\n\n<p>Separately, there is a question of the performance of the code. Strictly speaking it is premature optimization to consider the performance of a function without measuring it to determine whether or not it is significant, but I think most programmers would avoid executing <code>game_status</code> more times than they have to.</p>\n\n<p>On this occasion both concerns are dealt with much the same way -- assign the value to a variable and use the variable repeatedly. This minimizes the number of calls made for performance, <em>and</em> it indicates to the reader when you think you've changed something such that the result might have changed.</p>\n\n<p>There is nothing inherently wrong with using the result of a function call as a condition:</p>\n\n<pre><code>if \"foo\".startswith(\"f\"):\n print('as expected')\n</code></pre>\n\n<p>Out of interest - what is the condition in the \"main game code\" that will <code>break</code> out of the loop, avoiding the loop's <code>else</code> clause? Match abandoned?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T01:37:15.780", "Id": "34085", "ParentId": "34084", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T01:08:39.387", "Id": "34084", "Score": "3", "Tags": [ "python", "python-2.x" ], "Title": "Pythonic loop logic for Tic-Tac-Toe game board" }
34084
<p>I am working on a code where I represent a <code>MonadPlus</code> using a <code>Tree</code> data structure and then explore it, summing over all of the leaves (whose type must be an instance of <code>Monoid</code>); I need to use a <code>Tree</code> representation to do this (rather than using the <code>List</code> representation) because as I explore the tree I want to manually keep track of things like my position in the <code>Tree</code> for checkpointing and workload balancing purposes.</p> <p>My problem is that using a <code>Tree</code> data structure is slower than using the <code>List</code> data structure by a factor of ~ 4 for small depths (~ 1-10) and ~ 2.5 for higher depths (~15), and I am having trouble understanding exactly why this is; in particular I am wondering if there are tricks that I can employ to make my code faster.</p> <p>The remainder of this question will be some code that I wrote to benchmark <code>Tree</code> versus List. I will present my code in sections. First, the prelude:</p> <pre><code>{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} import Control.DeepSeq import Control.Monad import Control.Monad.Operational import Criterion.Main import Data.Functor.Identity import Data.Monoid </code></pre> <p>My <code>Tree</code> type is defined using functionality in the <code>operational</code> package by specifying the type of instructions and then use <code>operational</code> to obtain a <code>Program</code> monad from this.</p> <pre><code>data TreeTInstruction m α where Choice :: TreeT m α -&gt; TreeT m α -&gt; TreeTInstruction m α Null :: TreeTInstruction m α newtype TreeT m α = TreeT { unwrapTreeT :: ProgramT (TreeTInstruction m) m α } deriving (Monad) type Tree = TreeT Identity instance Monad m =&gt; MonadPlus (TreeT m) where mzero = TreeT . singleton $ Null left `mplus` right = TreeT . singleton $ Choice left right </code></pre> <p>The following two functions respectively build a perfect binary tree with <code>Sum Int</code> at all the leaves (which can be any type that is an instance <code>MonadPlus</code>) and explore a given <code>Tree</code>.</p> <pre><code>makeTree :: MonadPlus m =&gt; Int -&gt; m (Sum Int) makeTree 0 = return (Sum 1) makeTree d = makeTree (d-1) `mplus` makeTree (d-1) exploreTree :: Tree (Sum Int) -&gt; Sum Int exploreTree v = case view (unwrapTreeT v) of Return x -&gt; x Choice left right :&gt;&gt;= k -&gt; let x = exploreTree $ left &gt;&gt;= TreeT . k y = exploreTree $ right &gt;&gt;= TreeT . k xy = mappend x y in xy </code></pre> <p>As a technicality we need to write an instance of <code>NFData</code> for <code>Sum Int</code> for the benchmarking code.</p> <pre><code>instance NFData (Sum Int) where rnf s@(Sum x) = x `seq` s `seq` () </code></pre> <p>Finally, we have the benchmarking code. First, it benchmarks using <code>makeTree</code> to construct a tree using the List monad and then using <code>mconcat</code> to sum over all the results, and second, it benchmarks using <code>makeTree</code> using the <code>Tree</code> monad and sums over all the leaves using the <code>exploreTree</code> function.</p> <pre><code>main = defaultMain [bench "list" $ nf (mconcat . makeTree) depth ,bench "tree" $ nf (exploreTree . makeTree) depth ] where depth = 1 -- this is a knob that controls the tree size </code></pre> <p>For benchmarks, the list and tree times were as follows on my machine:</p> <pre><code> List Tree Tree/List 1: 140ns 460ns 3.3x 2: 330ns 1300ns 4.0x 4: 1600ns 6300ns 3.9x 8: 32us 130us 4.0x 10: 150us 600us 4.0x 12: 990us 2900us 2.9x 14: 4.6ms 12ms 2.6x 16: 24ms 55ms 2.3x 17: 50ms 110ms 2.2x </code></pre> <p>(17 is the largest depth because after that exploring the list causes a stack overflow.)</p> <p>If anyone has advice on exactly what the cause is of this slow down and if anything can be done about it then I would greatly appreciate it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T14:34:25.843", "Id": "68475", "Score": "0", "body": "Could you please describe in more detail what task you'd like to solve? This would help to understand the program and offer alternative solutions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T23:45:26.843", "Id": "70289", "Score": "0", "body": "My project involves automatically parallelizing searches through trees; to do this I need an efficient representation for non-deterministic computations as a Monad that I can interpret as a tree, as the branches in the tree give me workloads that I can send to other workers to explore in parallel. For more details, project page is [here](https://github.com/gcross/LogicGrowsOnTrees)." } ]
[ { "body": "<p>A bit late, but perhaps it'll still help someone.</p>\n\n<p>From the benchmark it's not clear if the time difference is caused by producing a tree or consuming it. I'm not very familiar with <em>operational</em> to make a guess.</p>\n\n<p>It seems that what you're looking for is a <a href=\"http://www.haskellforall.com/2012/07/free-monad-transformers.html\" rel=\"nofollow noreferrer\">free</a> <code>MonadPlus</code>. The closest to this is probably <code>FreeT f []</code> using <a href=\"https://hackage.haskell.org/package/free-4.12.4/docs/Control-Monad-Trans-Free.html#t:FreeT\" rel=\"nofollow noreferrer\"><code>FreeT</code></a>, see also <a href=\"https://stackoverflow.com/q/32185389/1333025\">this question</a>. I tried to benchmark it with your code with</p>\n\n<pre><code>exploreFreeTree :: FreeT Identity [] (Sum Int) -&gt; Sum Int\nexploreFreeTree = mconcat . iterT runIdentity\n</code></pre>\n\n<p>that flattens a tree into a list and then concatenates it, and it was almost as fast as plain <code>[]</code>.</p>\n\n<p>But there is another potential problem. For free monads the bind operation <code>&gt;&gt;=</code> needs to traverse the whole sequence of operations in the left argument, which can cause performance issues. It's similar to appending two lists. I don't know if <em>operational</em> has a similar problem or not. For free monads the solution is to use the <code>Codensity</code> monad, in particular it's enough to just wrap your computation with <a href=\"https://hackage.haskell.org/package/kan-extensions-5.0.1/docs/Control-Monad-Codensity.html#v:improve\" rel=\"nofollow noreferrer\"><code>improve</code></a>. For this it might be better to use <code>Free []</code> instead of <code>FreeT [] Identity</code> (although I haven't checked the details), as <code>Codensity</code> works only on <code>Free</code>, not <code>FreeT</code>.</p>\n\n<p>It might be relevant to read <a href=\"https://stackoverflow.com/q/32252312/1333025\">\nIs there a Codensity MonadPlus that asymptotically optimizes a sequence of MonadPlus operations?</a>, although it's somewhat complicated stuff.</p>\n\n<p>An good alternative could be to use <a href=\"https://hackage.haskell.org/package/logict-0.6.0.2/docs/Control-Monad-Logic.html\" rel=\"nofollow noreferrer\">logict</a>. You could express your computations using <a href=\"https://hackage.haskell.org/package/logict-0.6.0.2/docs/Control-Monad-Logic-Class.html#t:MonadLogic\" rel=\"nofollow noreferrer\"><code>MonadLogic</code></a> and then <a href=\"https://hackage.haskell.org/package/logict-0.6.0.2/docs/Control-Monad-Logic.html#v:runLogicT\" rel=\"nofollow noreferrer\">run</a> your computation in <code>LogicT</code> to do whatever processing you need to do. The advantage of this is that <code>LogicT</code> is internally build with continuations, which alleviates the problem with <code>&gt;&gt;=</code> performance of <code>Free</code>, and is built exactly to deal with branching computations. If you'd be interested, I could try to work out an example.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-24T20:32:40.947", "Id": "254421", "Score": "0", "body": "I've moved on from that problem, but thank you for the information! :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-23T18:32:43.203", "Id": "135713", "ParentId": "34089", "Score": "1" } } ]
{ "AcceptedAnswerId": "135713", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T05:32:54.453", "Id": "34089", "Score": "4", "Tags": [ "haskell", "tree", "monads" ], "Title": "Performance of List representation of MonadPlus versus Tree representation" }
34089
<p>Please check my code, did i get some things wrong<br> I'm a newbie in jquery and ajax, please check and show me how to fix this </p> <p>In jsp page :</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;AJAX calls using Jquery in Servlet&lt;/title&gt; &lt;link rel="stylesheet" href="jquery-ui.css" /&gt; &lt;script src="jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script src="jquery-ui.js"&gt;&lt;/script&gt; &lt;script&gt; var availableTags = []; function getData (request, response) { var value = []; var username = $('#user').val(); $.get('autocompleteServlet', {user : username}, function(responseText){ $('#welcometext').text(responseText); value = [responseText]; response(value); }); return value; }; $(document).ready(function() { $('#user').keydown(function(){ availableTags = getData(request, response); }); $('#user').autocomplete({ source: availableTags }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1"&gt; &lt;h1&gt;AJAX Demo using Jquery in JSP and Servlet&lt;/h1&gt; Enter your Name: &lt;input type="text" id="user" /&gt; &lt;div id="welcometext"&gt;&lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In my servlet : </p> <pre><code>@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value = request.getParameter("user"); System.out.println("user : "+ value); try { Connection cnn = XJdbc.getConnection(); String sql = "SELECT Name FROM reported_tasks WHERE Name LIKE '%"+ value + "%'"; Statement stm = cnn.createStatement(); ResultSet rs = stm.executeQuery(sql); String result = ""; while (rs.next()) { result = result + rs.getString("Name") + ","; } cnn.close(); System.out.println("Request :" + result); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(result); } catch (Exception e) { System.out.println("Error : " + e.getMessage()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T16:57:42.200", "Id": "54813", "Score": "0", "body": "do you need to fix it? does it work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T03:10:00.953", "Id": "56827", "Score": "0", "body": "Are you aware that building a query out of user-supplied data is a very bad idea? http://en.wikipedia.org/wiki/SQL_injection" } ]
[ { "body": "<p>I can't talk for the java part, but here's my two cents on your js.</p>\n\n<h3>favor placing scripts at the bottom of your page.</h3>\n\n<p>...just before the <code>&lt;/body&gt;</code>tag. Many reasons to do so can be found <a href=\"http://codecraftingblueprints.com/put-scripts-at-the-bottom/\" rel=\"nofollow\">out there</a> ; mainly it's because script links in the <code>&lt;head&gt;</code> block page loading while the external js is being loaded and parsed.</p>\n\n<h3>use a closure</h3>\n\n<p>Your <code>availableTags</code> var is in global scope. If you want to avoid this, use a closure :</p>\n\n<pre><code>// create a function and execute it immediatly, effectively encapsulating vars :\n(function(){ var my = \"myvar\"; })();\n\n// same thing with a function expression - one less keystroke \\o/ \n!function(){ var my = \"myvar\"; }();\n</code></pre>\n\n<h3>cache your jquery elements</h3>\n\n<p>Looking for an element in the DOM is expensive, you want to avoid doing it multiple times for the same element whenever it's possible. Just store the element in a var and use it in your function calls and callbacks.</p>\n\n<h3>getData doesn't return what you think it returns</h3>\n\n<p>sure, you return <code>value</code>. But just before you issue an AJAX request, that is an <em>asynchronous</em> (non blocking) request. What happens here is that the browser fires the request, but doesn't wait for an answer to go on and return <code>value</code> immediately - potentialy before your callback even has a chance to change <code>value</code>.</p>\n\n<p>That's why you have to use callbacks. Given all these remarks, I would go for something like this : </p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"&gt;\n&lt;title&gt;AJAX calls using Jquery in Servlet&lt;/title&gt;\n&lt;link rel=\"stylesheet\" href=\"jquery-ui.css\" /&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form id=\"form1\"&gt;\n &lt;h1&gt;AJAX Demo using Jquery in JSP and Servlet&lt;/h1&gt;\n Enter your Name: &lt;input type=\"text\" id=\"user\" /&gt;\n &lt;div id=\"welcometext\"&gt;&lt;/div&gt;\n &lt;/form&gt;\n &lt;script src=\"jquery-1.9.1.js\"&gt;&lt;/script&gt;\n &lt;script src=\"jquery-ui.js\"&gt;&lt;/script&gt;\n &lt;script&gt;\n !function(){\n\n var availableTags = [],\n $user = $('#user'),\n $welcome = $('#welcometext');\n\n $user.keydown(function(){\n $.get('autocompleteServlet', {user : $user.val()}, function(responseText){\n $welcome.text(responseText);\n availableTags.push(responseText);\n // fire update for your autocomplete ? \n });\n });\n\n $user.autocomplete({\n source: availableTags\n });\n\n }();\n &lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T12:44:34.660", "Id": "34094", "ParentId": "34091", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T05:59:43.683", "Id": "34091", "Score": "-1", "Tags": [ "javascript", "jquery", "ajax", "servlets" ], "Title": "Please check my example about jquery autocomple with servlet" }
34091
<p>Just looking for some feedback on my solution for <a href="http://tour.golang.org/#24" rel="nofollow">Tour of Go Exercise 24 - Loops and Functions</a>. Is there anything that looks like a wrong way to do things in go? anything I could have done better?</p> <pre><code>package main import ( "fmt" "math" ) func Approx(x float64, z float64) float64 { return z - (((z * z) - x) / (2 * z)) } func Sqrt(x float64) float64 { previous := 0.0 delta := 1.0 z := x for delta &gt; 0.005 { z = Approx(x, z) if previous &gt; 0.0 { delta = previous - z } previous = z } return z } func main() { for i := 1; i &lt; 11; i++ { value := float64(i) fmt.Println("Calculating Sqrt for ", value) real := math.Sqrt(value) approx := Sqrt(value) fmt.Println("Real ", real) fmt.Println("Approx ", approx) } } </code></pre>
[]
[ { "body": "<p>One tiny thing: If you drop one set of parentheses:</p>\n\n<pre><code>return z - ((z * z - x) / (2 * z))\n</code></pre>\n\n<p>and then run <code>go fmt</code>, it will change it to</p>\n\n<pre><code>return z - ((z*z - x) / (2 * z))\n</code></pre>\n\n<p>The expressions around the <code>*</code> are close to the <code>*</code> and the expressions around the <code>-</code> are spaced out. In other words, <code>go fmt</code> implies the correct precedence.</p>\n\n<p>Also, using line breaks to separate \"sections\" of a function is good, but there's no need to add an extra linebreak at the very beginning of a function or just before a <code>}</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T17:30:42.120", "Id": "35542", "ParentId": "34095", "Score": "2" } } ]
{ "AcceptedAnswerId": "35542", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T14:06:05.580", "Id": "34095", "Score": "4", "Tags": [ "go", "mathematics" ], "Title": "Approximating square root (loops and functions exercise)" }
34095
<p>Not sure how subjective this question is however I am looking for a peer review and general feedback on the intuitiveness and scaffolding potential of a framework concept. I have a gist on GitHub here: <a href="https://gist.github.com/bsawyer/fbfe8b597cff32e0c73b" rel="nofollow">node.js MVVM framework concept</a></p> <p>Is this more or less intuitive then using pseudo code and a template engine, such as handlebars, for rendering html?</p> <p>The markup module will use three objects, the first being out design object:</p> <pre><code>var welcomeDesign = [{ handle:'pageTitle' tag:'h1', attr:{ class:'mainHeading' } },{ tag:'p', handle:'welcomeParagraph', content:[{ content:'Welcome!', handle:'welcomeContent' },{ tag:'img' handle:'welcomeBanner' }] }]; </code></pre> <p>The second object is our data:</p> <pre><code>var data = [{ published:'11-8-13', title:'Hello World', content:'Welcome to...' assets:[{ type:'img', path:'/images/' name:'cat.jpg' }] }]; </code></pre> <p>The third will be our mapping logic:</p> <pre><code>var imageAsset = { attr:{ src:{ key:'assets', map:function(obj, values){ return values[0].path + values[0].name } } } }; var welcome = { pageTitle:{ content: { key:['published','title'] map: function(object, values){ return values[0] + ': ' + values[1]; } } }, welcomeContent:{ content:{ key:'content' } }, welcomeBanner:imageAsset }; </code></pre> <p>and finally the methods for bringing them together:</p> <pre><code>var markup = require('markup'); //our module var welcomeMessage = markup.design(welcomeDesign); //create a design instance var homeWelcome = new welcomeMessage(data); //instantiate with our data homeWelcome.render(welcome); //render with our logic </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T17:02:47.883", "Id": "55812", "Score": "1", "body": "you need to include the code that you want Reviewed. Follow These [Rules](http://codereview.stackexchange.com/help/how-to-ask) as well as not linking to the code that you want reviewed. if the question doesn't make sense with out the link it's not being asked properly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T04:14:26.420", "Id": "56830", "Score": "0", "body": "@Malachi Since he's asking for review of the *utility* of the library, not its own code quality, this *is* the code he wants reviewed. I think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T04:52:48.237", "Id": "56832", "Score": "0", "body": "@sqykly when I wrote that comment he didn't have any code posted. I left my comment for the sake of the question. and the link in it." } ]
[ { "body": "<p>It's better than rendering HTML in some other language manually, but it's at a disadvantage to HTML super-set template languages. </p>\n\n<p>Mirroring the structure of HTML in JS makes the design more verbose because you need to map object fields to HTML tokens like <code>attr:</code> and not tangibly better than HTML that's parameterized with jQuery. Mistakes in such a scheme, while not as bad as rendering HTML directly, are easier to make and harder to find than writing straight HTML or a super-set thereof because no IDE is going to understand how the JS object maps to an HTML snippet to validate it. Most HTML super-set template languages have the same problem with IDEs, to be fair, but it's usually easier to see what the HTML emitted is going to look like.</p>\n\n<p>Another thing I might look into refactoring is the mapping object, which is using specific attribute names. You have an abstraction in the design, <code>handle</code>, that could just as easily be applied to attribute names, and your mapping would not have to reference the design's HTML at all. That might be an idealistic complaint, though.</p>\n\n<p>In summary, what I would rather see is roughly the same data and mapping methodology, but make the design something my IDE (and eyes) will better understand as HTML.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T05:52:55.583", "Id": "56835", "Score": "0", "body": "That was definitely one of my concerns, were an application to scale, syntax and error checking would become very difficult. I think you make a good point also in terms of legibility. I wonder if it would be possible to provide an html string, parse it into the design object, making sure to set a data-handle attribute on elements in the string passed in order to declare the handle for the logic. Not sure... but I really appreciate the consideration and response." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T08:38:10.133", "Id": "56845", "Score": "0", "body": "@Ben no problem - I've been wrestling with some of the same issues while working with templates, and there's definitely no perfect solution. In case I didn't get it across in my answer, this *is* way better than dealing with HTML & JS entirely by hand. If you don't mind introducing dependencies, a headless browser like zombie.js + jQuery could make it relatively painless to switch to HTML-based templates, and as bonus, you get to never deal with the DOM thanks to jQuery." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T04:11:21.963", "Id": "35113", "ParentId": "34098", "Score": "3" } } ]
{ "AcceptedAnswerId": "35113", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T16:25:29.933", "Id": "34098", "Score": "3", "Tags": [ "javascript", "node.js", "mvvm" ], "Title": "node.js MVVM framework concept" }
34098
<p>I'm creating a program that reads data from two .dat files: one for food-bank location and the other for residence. Right now, the program can calculate the distance between food-bank and residence and insert it into a distances vector.</p> <p>My concerns are:</p> <ol> <li>Is my logic right?</li> <li>Can I determine the distance, in miles, between each location in residences and the closest food bank in <code>foodbanks</code>? Note: the function will calculate in meters.</li> </ol> <p></p> <pre><code>#include &lt;iostream&gt; #include &lt;math.h&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include&lt;iterator&gt; using namespace std; struct Foodbank { double x; double y; //input stream overload friend std::istream &amp;operator&gt;&gt;(std::istream &amp;is, Foodbank &amp;f) { return is&gt;&gt;f.x&gt;&gt;f.y; } //output stream overload friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, Foodbank const &amp;f) { return os &lt;&lt; f.x &lt;&lt; "\t"&lt;&lt; f.y&lt;&lt;"\t"; } }; struct Residence { double x; double y; //input stream overload friend std::istream &amp;operator&gt;&gt;(std::istream &amp;is, Residence &amp;r) { return is&gt;&gt;r.x&gt;&gt;r.y; } //output stream overload friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, Foodbank const &amp;r) { return os &lt;&lt; r.x &lt;&lt; "\t"&lt;&lt; r.y&lt;&lt;"\t"; } }; double distanceCalculate(double x1, double y1, double x2, double y2); int main(int argc, const char * argv[]) { ifstream foodbankFile("foodbanks.dat"); ifstream residenceFile("residences.dat"); //vectors data vector&lt;Foodbank&gt; foodbankData; vector&lt;Residence&gt; residenceData; vector&lt;double&gt; distances; copy(std::istream_iterator&lt;Foodbank&gt;(foodbankFile), std::istream_iterator&lt;Foodbank&gt;(), std::back_inserter&lt;std::vector&lt;Foodbank&gt;&gt;(foodbankData)); std::cout&lt;&lt;"read "&lt;&lt;foodbankData.size()&lt;&lt;" data: "&lt;&lt;std::endl; copy(std::istream_iterator&lt;Residence&gt;(residenceFile), std::istream_iterator&lt;Residence&gt;(), std::back_inserter&lt;std::vector&lt;Residence&gt;&gt;(residenceData)); std::cout&lt;&lt;"read "&lt;&lt;residenceData.size()&lt;&lt;" data: "&lt;&lt;std::endl; for(auto r:residenceData) { for(auto f:foodbankData) { //std::cout&lt;&lt;f.x &lt;&lt;", "&lt;&lt;f.y &lt;&lt;", "&lt;&lt;std::endl; distances.push_back(distanceCalculate(f.x,f.y,r.x,r.y)); } //std::cout&lt;&lt;r.x &lt;&lt;", "&lt;&lt;r.y &lt;&lt;", "&lt;&lt;std::endl; } std::cout&lt;&lt;"read "&lt;&lt;distances.size()&lt;&lt;" data: "&lt;&lt;std::endl; return 0; } // the distance in metres double distanceCalculate(double x1, double y1, double x2, double y2) { double x = x1 - x2; double y = y1 - y2; double dist; dist = pow(x,2)+pow(y,2); //calculating distance by euclidean formula dist = sqrt(dist); //sqrt is function in math.h return dist; } </code></pre>
[]
[ { "body": "<p>Stop doing this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Yes every text book does this. But once you start writing programs more than 10 lines long it causes issues. Prefix items in the standard namespace with <code>std::</code> (it was designed to be short). See detailed explanation here: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is using namespace std considered bad practice</a></p>\n\n<p>OK. What is the difference between <code>Foodbank</code> and <code>Residence</code> looks like they should simply be a <code>Location</code> class. If in later code you you add differences you can derive from the <code>Location</code> (or better use a location member (prefer composition over inheritance)).</p>\n\n<p>Be consistent (and neat with your spacing).</p>\n\n<pre><code>return os &lt;&lt; r.x &lt;&lt; \"\\t\"&lt;&lt; r.y&lt;&lt;\"\\t\";\n// ^^^ ^^^ Hard to read\n\nreturn os &lt;&lt; r.x &lt;&lt; \"\\t\" &lt;&lt; r.y &lt;&lt; \"\\t\";\n</code></pre>\n\n<p>When initializing your arrays. No need to use std::copy. Just use the iterators in the vectors constructor.</p>\n\n<pre><code>vector&lt;Foodbank&gt; foodbankData;\ncopy(std::istream_iterator&lt;Foodbank&gt;(foodbankFile),\n std::istream_iterator&lt;Foodbank&gt;(),\n std::back_inserter&lt;std::vector&lt;Foodbank&gt;&gt;(foodbankData));\n\n\n// Can be replaced by a single line:\nvector&lt;Foodbank&gt; foodbankData(std::istream_iterator&lt;Foodbank&gt;(foodbankFile),\n std::istream_iterator&lt;Foodbank&gt;());\n</code></pre>\n\n<p>Not sure why you are pushing the distance into a long single array. That does not help you work stuff out.</p>\n\n<pre><code>for(auto r:residenceData)\n{\n for(auto f:foodbankData)\n {\n //std::cout&lt;&lt;f.x &lt;&lt;\", \"&lt;&lt;f.y &lt;&lt;\", \"&lt;&lt;std::endl;\n distances.push_back(distanceCalculate(f.x,f.y,r.x,r.y));\n }\n}\n</code></pre>\n\n<p>I would suspect that what you want is a 2D array. The <code>FoodBanks</code> on the Y axis and the <code>Residences</code> on the X axis (as an example). Then given any <code>Residences</code> you just need to scan the array vertically to find the closest <code>FoodBank</code>.</p>\n\n<pre><code>std::vector&lt;std::vector&lt;double&gt;&gt; distance;\nfor(auto r:residenceData)\n{\n distance.push_back(std::vector&lt;double&gt;());\n\n for(auto f:foodbankData)\n {\n //std::cout&lt;&lt;f.x &lt;&lt;\", \"&lt;&lt;f.y &lt;&lt;\", \"&lt;&lt;std::endl;\n distances.back().push_back(distanceCalculate(f.x,f.y,r.x,r.y));\n }\n}\n</code></pre>\n\n<p>Wow thats a lot of parameters</p>\n\n<pre><code>double distanceCalculate(double x1, double y1, double x2, double y2)\n</code></pre>\n\n<p>If your <code>FoodBank</code> and <code>Residence</code> just inherited from a base of <code>Location</code> (or had a location member) then you can pass location as the start and end point and calculate the distance between them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T17:09:07.287", "Id": "34102", "ParentId": "34099", "Score": "5" } } ]
{ "AcceptedAnswerId": "34102", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T16:26:04.467", "Id": "34099", "Score": "2", "Tags": [ "c++", "c++11" ], "Title": "Reading two .dat files for calculating location distance" }
34099
<p>I am using Django multi-table inheritance: <code>Video</code> and <code>Image</code> are models derived from <code>Media</code>. There are two views: <code>video_list</code> and <code>image_list</code>, which are just proxies to <code>media_list</code>. <code>media_list</code> returns images or videos (based on input parameter <code>model</code>) for a certain object, which can be of type <code>Event</code>, <code>Member</code>, or <code>Crag</code>. The view alters its rendering behaviour based on input parameter <code>mode</code>, which can be of value "edit" or "view".</p> <p>The problem is that I need to ask whether the input parameter <code>model</code> contains <code>Video</code> or <code>Image</code> in <code>media_list</code> so that I can do the right thing. Similar condition is also in helper method <code>media_edit_list</code> that is called from the view. </p> <p>I don't particularly like it but the only alternative I can think of is to have separate (but almost the same) logic for <code>video_list</code> and <code>image_list</code> and then probably also separate helper methods for videos and images: <code>video_edit_list</code>, <code>image_edit_list</code>, <code>video_view_list</code>, <code>image_view_list</code>. So four functions instead of just two. That I like even less because the video functions would be very similar to the respective image functions. What do you recommend?</p> <p><a href="http://pastebin.com/07t4bdza" rel="nofollow">Here</a> is extract of relevant parts. I'll also paste the code here:</p> <h3>URLs</h3> <pre><code>url(r'^media/images/(?P&lt;rel_model_tag&gt;(event|member|crag))/(?P&lt;rel_object_id&gt;\d+)/(?P&lt;action&gt;(view|edit))/$', views.image_list, name='image-list') url(r'^media/videos/(?P&lt;rel_model_tag&gt;(event|member|crag))/(?P&lt;rel_object_id&gt;\d+)/(?P&lt;action&gt;(view|edit))/$', views.video_list, name='video-list') </code></pre> <h3>Views</h3> <pre><code>def image_list(request, rel_model_tag, rel_object_id, mode): return media_list(request, Image, rel_model_tag, rel_object_id, mode) def video_list(request, rel_model_tag, rel_object_id, mode): return media_list(request, Video, rel_model_tag, rel_object_id, mode) def media_list(request, model, rel_model_tag, rel_object_id, mode): rel_model = tag_to_model(rel_model_tag) rel_object = get_object_or_404(rel_model, pk=rel_object_id) if model == Image: star_media = rel_object.star_image else: star_media = rel_object.star_video media_list = model.get_object_media(rel_object).filter(~Q(id=star_media.id)).order_by('date_added') context = { 'media_list': media_list, 'star_media': star_media, } if mode == 'edit': return media_edit_list(request, model, rel_model_tag, rel_object_id, context) return media_view_list(request, model, rel_model_tag, rel_object_id, context) def media_view_list(request, model, rel_model_tag, rel_object_id, context): if request.is_ajax(): context['base_template'] = 'boxes/base-lite.html' return render(request, 'media/list-items.html', context) def media_edit_list(request, model, rel_model_tag, rel_object_id, context): if model == Image: get_media_edit_record = get_image_edit_record else: get_media_edit_record = get_video_edit_record media_list = [get_media_edit_record(media, rel_model_tag, rel_object_id) for media in context['media_list']] if context['star_media']: star_media = get_media_edit_record(context['star_media'], rel_model_tag, rel_object_id) else: star_media = None json = simplejson.dumps({ 'star_media': star_media, 'media_list': media_list, }) return HttpResponse(json, content_type=json_response_mimetype(request)) def get_image_edit_record(image, rel_model_tag, rel_object_id): record = { 'url': image.image.url, 'name': image.title or image.filename, 'type': mimetypes.guess_type(image.image.path)[0] or 'image/png', 'thumbnailUrl': image.thumbnail_2.url, 'size': image.image.size, 'id': image.id, 'media_id': image.media_ptr.id, 'starUrl':reverse('image-star', kwargs={'image_id': image.id, 'rel_model_tag': rel_model_tag, 'rel_object_id': rel_object_id}), } return record def get_video_edit_record(video, rel_model_tag, rel_object_id): record = { 'url': video.embed_url, 'name': video.title or video.url, 'type': None, 'thumbnailUrl': video.thumbnail_2.url, 'size': None, 'id': video.id, 'media_id': video.media_ptr.id, 'starUrl': reverse('video-star', kwargs={'video_id': video.id, 'rel_model_tag': rel_model_tag, 'rel_object_id': rel_object_id}), } return record </code></pre> <h3>Models</h3> <pre><code>class Media(models.Model, WebModel): title = models.CharField('title', max_length=128, default='', db_index=True, blank=True) event = models.ForeignKey(Event, null=True, default=None, blank=True) crag = models.ForeignKey(Crag, null=True, default=None, blank=True) member = models.ForeignKey(Member, null=True, default=None, blank=True) tagged_in_members = models.ManyToManyField(Member, blank=True, related_name='tagged_in_media_set') added_by = models.ForeignKey(Member, related_name='added_images') date_added = models.DateTimeField('date added', auto_now_add=True, null=True, default=None, editable=False) @classmethod def get_object_media(cls, rel_object): filter_params = {} if rel_object.__class__ == Event: filter_params['event'] = rel_object.id elif rel_object.__class__ == Member: filter_params['member'] = rel_object.id elif rel_object.__class__ == Crag: filter_params['crag'] = rel_object.id return cls.objects.filter(**filter_params).all() class Image(Media): image = ProcessedImageField(upload_to='uploads', processors=[ResizeToFit(width=1024, height=1024, upscale=False)], format='JPEG', options={'quality': 75}) thumbnail_1 = ImageSpecField(source='image', processors=[SmartResize(width=178, height=134)], format='JPEG', options={'quality': 75}) thumbnail_2 = ImageSpecField(source='image', #processors=[SmartResize(width=256, height=192)], processors=[ResizeToFit(height=164)], format='JPEG', options={'quality': 75}) class Video(Media): url = models.URLField('url', max_length=256, default='') embed_url = models.URLField('embed url', max_length=256, default='', blank=True) author = models.CharField('author', max_length=64, default='', blank=True) thumbnail = ProcessedImageField(upload_to='uploads', processors=[ResizeToFit(width=1024, height=1024, upscale=False)], format='JPEG', options={'quality': 75}, null=True, default=None, blank=True) thumbnail_1 = ImageSpecField(source='thumbnail', processors=[SmartResize(width=178, height=134)], format='JPEG', options={'quality': 75}) thumbnail_2 = ImageSpecField(source='thumbnail', #processors=[SmartResize(width=256, height=192)], processors=[ResizeToFit(height=164)], format='JPEG', options={'quality': 75}) class Crag(models.Model, WebModel): name = models.CharField('name', max_length=64, default='', db_index=True) normalized_name = models.CharField('normalized name', max_length=64, default='', editable=False) type = models.IntegerField('crag type', null=True, default=None, choices=crag_types) description = models.TextField('description', default='', blank=True) country = models.ForeignKey('country', null=True, default=None) #TODO: make this not null when db enables it latitude = models.FloatField('latitude', null=True, default=None) longitude = models.FloatField('longitude', null=True, default=None) location_index = FixedCharField('location index', length=24, default='', editable=False, db_index=True) # handled by db, used for marker clustering added_by = models.ForeignKey('member', null=True, default=None) #route_count = models.IntegerField('route count', null=True, default=None, editable=False) date_created = models.DateTimeField('date created', auto_now_add=True, null=True, default=None, editable=False) last_modified = models.DateTimeField('last modified', auto_now=True, null=True, default=None, editable=False) star_image = models.ForeignKey('Image', null=True, default=None, related_name='star_crags', on_delete=models.SET_NULL) star_video = models.ForeignKey('Video', null=True, default=None, related_name='star_crags', on_delete=models.SET_NULL) </code></pre>
[]
[ { "body": "<p>You could avoid the \"is Image or Video\" checks in <code>media_list</code>, by passing in some extra arguments, for example in <code>image_list</code>:</p>\n\n<pre><code>def image_list(request, rel_model_tag, rel_object_id, mode):\n get_star_media = lambda rel_object: rel_object.star_image\n return media_list(request, Image, get_star_media, get_image_edit_record, rel_model_tag, rel_object_id, mode)\n</code></pre>\n\n<p>I added two extra arguments there, the <code>get_star_media</code> function to extract <code>rel_object.star_image</code> and <code>get_image_edit_record</code>. Similarly for <code>video_list</code>:</p>\n\n<pre><code>def video_list(request, rel_model_tag, rel_object_id, mode):\n get_star_media = lambda rel_object: rel_object.star_video\n return media_list(request, Video, get_star_media, get_video_edit_record, rel_model_tag, rel_object_id, mode)\n</code></pre>\n\n<p>This way you could rewrite the <code>media_list</code> and <code>media_edit_list</code> methods without the Image/Video checks like this:</p>\n\n<pre><code>def media_list(request, model, get_star_media, get_media_edit_record, rel_model_tag, rel_object_id, mode):\n rel_model = tag_to_model(rel_model_tag)\n rel_object = get_object_or_404(rel_model, pk=rel_object_id)\n star_media = get_star_media(rel_object)\n\n media_list = model.get_object_media(rel_object).filter(~Q(id=star_media.id)).order_by('date_added')\n\n context = {\n 'media_list': media_list,\n 'star_media': star_media,\n }\n\n if mode == 'edit':\n return media_edit_list(request, get_media_edit_record, rel_model_tag, rel_object_id, context)\n\n return media_view_list(request, model, rel_model_tag, rel_object_id, context)\n\ndef media_edit_list(request, get_media_edit_record, rel_model_tag, rel_object_id, context):\n media_list = [get_media_edit_record(media, rel_model_tag, rel_object_id) for media in context['media_list']]\n\n if context['star_media']:\n star_media = get_media_edit_record(context['star_media'], rel_model_tag, rel_object_id)\n else:\n star_media = None\n\n json = simplejson.dumps({\n 'star_media': star_media,\n 'media_list': media_list,\n })\n return HttpResponse(json, content_type=json_response_mimetype(request))\n</code></pre>\n\n<hr>\n\n<p>You're passing many arguments to <code>media_view_list</code> that are not used:</p>\n\n<pre><code>def media_view_list(request, model, rel_model_tag, rel_object_id, context):\n if request.is_ajax():\n context['base_template'] = 'boxes/base-lite.html'\n return render(request, 'media/list-items.html', context)\n</code></pre>\n\n<p>You could simplify by dropping <code>model</code>, <code>rel_model_tag</code> and <code>rel_object_id</code> from the argument list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T18:02:48.883", "Id": "48075", "ParentId": "35103", "Score": "3" } }, { "body": "<p>Since posting this question I have rewritten the code completely. However, to solve this particular issue, one could rewrite:</p>\n\n<pre><code>if model == Image:\n star_media = rel_object.star_image\nelse:\n star_media = rel_object.star_video\n</code></pre>\n\n<p>to</p>\n\n<pre><code>star_media = model.get_star_media(rel_object)\n</code></pre>\n\n<p><code>get_star_media</code> would be class method of <code>Video</code> and <code>Image</code> models (defined as stub in <code>Media</code>) that returns star media of the respective type. Shifting the problem to model layer and using polymorfism is the key. Otherwise, the approach of using one view is alright.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T13:58:13.600", "Id": "48149", "ParentId": "35103", "Score": "4" } } ]
{ "AcceptedAnswerId": "48149", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T19:45:38.543", "Id": "35103", "Score": "3", "Tags": [ "python", "object-oriented", "mvc", "django" ], "Title": "Is one view that handles two sibling models a good idea?" }
35103
<p>Is this image uploading script safe? I have spent my day researching this and it would be very much appreciated if you could point out any errors or ways to make it safer.</p> <pre><code>&lt;?php $max_file_size = 1048576; // expressed in bytes // 10240 = 10 KB // 102400 = 100 KB // 1048576 = 1 MB // 10485760 = 10 MB $upload_errors = array( // http://www.php.net/manual/en/features.file-upload.errors.php UPLOAD_ERR_OK =&gt; "No Errors", UPLOAD_ERR_INI_SIZE =&gt; "Larger than upload_max_filesize", UPLOAD_ERR_FORM_SIZE =&gt; "Larger than form MAX_FILE_SIZE", UPLOAD_ERR_PARTIAL =&gt; "Partial upload", UPLOAD_ERR_NO_FILE =&gt; "No file", UPLOAD_ERR_NO_TMP_DIR =&gt; "No temporary directory", UPLOAD_ERR_CANT_WRITE =&gt; "Can't write to disk", UPLOAD_ERR_EXTENSION =&gt; "File upload stopped by extension" ); $image_types = array ( IMAGETYPE_GIF =&gt; "gif", IMAGETYPE_JPEG =&gt; "jpg", IMAGETYPE_PNG =&gt; "png" ); $image_whitelist = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF); $message = ""; if (isset($_POST['submit'])) { // This would store the actual user id $userId = 1; // store uploaded file's temp path. $tmp_file = $_FILES['file_upload']['tmp_name']; if($_FILES['file_upload']['error'] &gt; 0){ $error = $_FILES['file_upload']['error']; die($upload_errors[$error]); } // check to see if file is an image, if not die. if(!getimagesize($tmp_file)) { die('Please ensure you are uploading an image.'); } // check to see if image is a valid type, if not die. if (!in_array(exif_imagetype($tmp_file), $image_whitelist)) { die('Please upload a valid image. (.jpg, .png or .gif)'); } $target_file = md5($userId . date('U')) . "." . $image_types[exif_imagetype($tmp_file)]; $upload_dir = "uploaded"; // check to see if file already exsits if it does die. if (file_exists($upload_dir."/".$target_file)) { die('file already exists'); } //move_uploaded file will return false if $tmp_file is not a valid upload file // or if it cannot be moved for any other reason if (move_uploaded_file($tmp_file, $upload_dir."/".$target_file)) { $message = "File uploaded successfully."; } else { die("move_uploaded_file() error."); } } ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;File Upload&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php if(!empty($message)) { echo "&lt;p&gt;{$message}&lt;/p&gt;"; } ?&gt; &lt;form action="fileupload.php" enctype="multipart/form-data" method="POST"&gt; &lt;input type="hidden" name="MAX_FILE_SIZE" value="&lt;?php echo $max_file_size; ?&gt;"&gt; &lt;input type="file" name="file_upload"&gt; &lt;input type="submit" name="submit" value="Upload"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Many Thanks</p>
[]
[ { "body": "<p>It is pretty solid for saving images on a single web server. Some optional/extra things you could do are:</p>\n\n<ul>\n<li>Host the images on a CDN. That way if there was any PHP or JS injected in, it would not be able to access any cookies or directories on the web server you use to serve content.</li>\n<li><p>Your code would block out PHP files in disguise from being uploaded because of the getimagesize() and the exif_imagetype(). You can add this bit to an htaccess file in the images directory as well to disable PHP files from being executed on their own. This wouldn't stop the file from being executed though if your code automatically included the \"image\" in the code somewhere.</p>\n\n<p>&lt;IfModule mod_php5.c&gt;<br />\nphp_flag engine off<br />\n&lt;/IfModule&gt;</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T00:26:51.693", "Id": "35109", "ParentId": "35104", "Score": "3" } }, { "body": "<p>I think Levi covered your question fairly well, +1 to him. The following does not deal with security so much as good practice.</p>\n\n<p>You might consider returning early. If you reverse your if logic you can remove the indent level of your whole script by 1. However, this wont work in your case as it appears that you have combined your form with your submission. It might be beneficial to abstract the two, but that is entirely dependent upon the application.</p>\n\n<pre><code>//returning early\nif( ! isset( $_POST[ 'submit' ] ) ) {\n return;\n}\n\n//abstraction\nif( isset( $_POST[ 'submit' ] ) ) {\n include '/path/to/fileupload_submit.php';\n}\n</code></pre>\n\n<p>Comments should be used to explain complex code. When you use comments to explain everything then you are cluttering your workspace. Use self-documenting code to make your code easier to read, though that doesn't seem to be a problem here. Consider removing most of these comments for enhanced legibility. For instance, you don't need a commented list of bytes to KB and MB conversion. You can explain that you are limiting your uploads to 1MB, but the rest are pointless and easily looked up.</p>\n\n<p>There are more elegant ways of terminating your code than to return, exit, or die. You took the trouble of converting the error definitions to readable text, you should present this on the page in a pleasant error box, thus presenting them with the opportunity to correct the issue. You could then even use the previous submission to repopulate the fields, assuming of course there were more than the one.</p>\n\n<pre><code>//die($upload_errors[$error]);\n$message = 'There were errors with your submission';\n$errors[] = $upload_errors[ $error ];\n\nif( ! empty( $errors ) ) {\n //don't upload\n}\n</code></pre>\n\n<p>You are not using the hidden input field \"MAX_FILE_SIZE\". Don't worry, this is a good thing. Relying on hidden input fields to restrict access is just asking for trouble. Hidden fields, despite the name, are still visible and modifiable by users. For instance, using Chrome or Firefox, I could right click on your form, choose inspect element, change the value of that hidden field, and presumably bypass the max file size restriction. But, since it is not being used and the restriction is hard coded into your script, you can just remove this field and not worry about it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T20:38:36.737", "Id": "35383", "ParentId": "35104", "Score": "2" } } ]
{ "AcceptedAnswerId": "35109", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:00:58.653", "Id": "35104", "Score": "3", "Tags": [ "php", "security" ], "Title": "Is this file image upload safe?" }
35104
<p>Just wanted to post my registration controller and see what anybody thought about it.</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Register * */ class Register extends CI_Controller { /** * Register::__construct() * * @return */ public function __construct() { parent::__construct(); $this-&gt;load-&gt;model('user_model', 'user'); } /** * Register::index() * * @return */ public function index() { $this-&gt;data['assets']['css_includes'] = array('mycss.css'); $this-&gt;data['assets']['js_includes'] = array('register.js'); $this-&gt;template -&gt;title('Wrestling Manager', 'Register') -&gt;set_layout('usermanagement_layout_view') -&gt;set_partial('header', 'partials/header_view') -&gt;set_partial('footer', 'partials/footer_view') -&gt;build('registration_form_view', $this-&gt;data); } /** * Register::process() * * @return */ public function process() { $output_array = array(); $output_array['status'] = 'notice'; $output_array['message'] = 'The following action failed to submit. Please try again later.'; $output_array['errors'] = 'No errors to report.'; $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|xss_clean|callback__unique_username'); $this-&gt;form_validation-&gt;set_rules('email_address', 'Email Address', 'trim|required|xss_clean|valid_email|callback__unique_email_address'); $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'trim|required|xss_clean|min_length[6]|max_length[12]'); if ($this-&gt;form_validation-&gt;run() == FALSE) { // Form validation did not pass successfully. Report back to the user there was error(s) on the form. $output_array['status'] = 'error'; $output_array['message'] = 'The following form did not validate successfully. Please fix the form errors and try again.'; $output_array['errors'] = $this-&gt;form_validation-&gt;error_array(); } else { // Form validation passed successfully. // Set up variables from post data. $post_username = $this-&gt;input-&gt;post('username'); $post_email_address = $this-&gt;input-&gt;post('email_address'); $post_password = $this-&gt;input-&gt;post('password'); $registration_date = gmdate('Y-m-d H:i:s', time()); $hashed_password = $this-&gt;user-&gt;generate_password_hash($post_password); $registration_key = sha1($registration_date.';;'.$post_email_address.';;'.$hashed_password[0]); // Develop the array of post data for sending to the model. $data = array( 'username' =&gt; $post_username, 'email_address' =&gt; $post_email_address, 'password' =&gt; $hashed_password[0], 'password_hash' =&gt; $hashed_password[1], 'registration_date' =&gt; $registration_date, 'registration_key' =&gt; $registration_key ); $user_id = $this-&gt;user-&gt;create_user($data); // Create the user. if (!is_numeric($user_id)) { // User was not created successfully. $output_array['status'] = 'error'; $output_array['message'] = 'The user was not created successfully.'; } else { // User was successfully created and the user needs to verify their account. // Send registered an email informing them how to validate their account. $company_name = $this-&gt;config-&gt;item('company_name'); $company_email_address = $this-&gt;config-&gt;item('company_email'); $this-&gt;load-&gt;library('email'); $this-&gt;email-&gt;from($company_email_address, $company_name); $this-&gt;email-&gt;to($post_email_address); $this-&gt;email-&gt;subject($company_name.' Registration'); $message = 'Welcome to '.$company_name.','."\r\n \r\n"; $message .= 'Thank you for joining the '.$company_name.' Team. '; $message .= 'We have listed your registration details below. Make sure you save this email.'; $message .= 'To verify this account please click the following link.'."\r\n \r\n"; $message .= anchor('register/verify/'.$registration_key, 'Click Here To Activate Your Account', '')."\r\n"; $message .= 'Please verfiy your account within 2 hours, otherwise your registration will become invalid and you will have to register again.'."\r\n \r\n"; $message .= 'Your email address: '.$post_email_address."\r\n"; $message .= 'Your Password: '.$post_password."\r\n \r\n"; $message .= 'Enjoy your stay here at '.$company_name.'.'."\r\n \r\n"; $message .= 'The '.$company_name.' Team'; $this-&gt;email-&gt;message($message); $this-&gt;email-&gt;send(); $output_array['status'] = 'success'; $output_array['message'] = 'The user was created successfully. Please check your email for the link to activate your account.'; } } echo json_encode($output_array); } /** * Register::verify() * * @return */ public function verify() { } /** * Register::_unique_email_address() * * @param mixed $str * @return */ public function _unique_email_address($str) { $this-&gt;db-&gt;where('user_login.email_address', $this-&gt;input-&gt;post('email_address')); $user = $this-&gt;user-&gt;get_user(); if (count($user)) { $this-&gt;form_validation-&gt;set_message('_unique_email_address', 'This email address is already available'); return FALSE; } return TRUE; } /** * Register::_unique_username() * * @param mixed $str * @return bool */ public function _unique_username($str) { $this-&gt;db-&gt;where('user_info.username', $this-&gt;input-&gt;post('username')); $user = $this-&gt;user-&gt;get_user(); if (count($user)) { $this-&gt;form_validation-&gt;set_message('_unique_username', 'This username is already available'); return FALSE; } return TRUE; } } </code></pre>
[]
[ { "body": "<p>Direct access to a class file will just result in a blank page as there is no output being produced by it. However, there are better ways of doing what you are trying to do. For instance, you could use an .htaccess file. The following .htaccess file, if placed in the base directory of your site, will prevent all direct access to PHP files, excepting the index file.</p>\n\n<pre><code>&lt;Files *.php&gt;\n Order Deny,Allow\n Deny from all\n&lt;/Files&gt;\n\n&lt;Files index.php&gt;\n Order Allow,Deny\n Allow from all\n&lt;/Files&gt;\n</code></pre>\n\n<p>There are caveats, such as AJAX scripts being considered direct access, but this is easily overcome with another .htaccess file and a header check.</p>\n\n<p>Your doccomments are more or less useless. Doccomments are meant to provide documentation about methods and classes and are usually used in conjunction with an IDE to provide hoverable tooltips or autocompletion. Your short description, which should briefly describe the purpose, instead reiterates the method's address, which, if this isn't obvious in context, will automatically be provided in a good IDE. Additionally, you emphasize that each method has a return, but don't explain what its supposed to be returning, nor does it actually return anything. No comments are better than misleading comments. See this documentation on <a href=\"http://en.wikipedia.org/wiki/PHPDoc\" rel=\"nofollow\">doccomments</a> for appropriate usage.</p>\n\n<p>Appending variable type to a variable name is redundant and just adds to the amount of typing you have to do. It should be obvious from its context that <code>$output_array</code> is an array. However, this is minor and could be considered a stylistic choice.</p>\n\n<p>If you find yourself performing a similar task more than once, you can more easily perform said task with a loop/function. This also makes extending functionality later much easier.</p>\n\n<pre><code>$ruleset = array(\n array(\n 'username',\n 'Username',\n 'trim|required|xss_clean|callback__unique_username',\n ),\n //etc...\n);\n\nforeach( $ruleset AS $set ) {\n list( $field, $title, $rules ) = $set;\n $this-&gt;form_validation-&gt;set_rules( $field, $title, $rules );\n}\n</code></pre>\n\n<p>Here's another form of repetition that would be easier to encapsulate in a private method. Every field in your <code>$output_array</code> seems to be changed depending on the state. The overall structure remains the same, just the contents change.</p>\n\n<pre><code>private function _getOutput( $status, $message, $errors = 'No errors to report.' ) {\n return compact( 'status', 'message', 'errors');\n}\n\n//usage\n$output_array = $this-&gt;_getOutput(\n 'notice',\n 'The following action failed to submit. Please try again later.'\n);\n</code></pre>\n\n<p>Some things you might want to look into would be <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a> and <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">Don't Repeat Yourself (DRY)</a>. Both areas would significantly improve your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T00:31:07.987", "Id": "58495", "Score": "0", "body": "That's awesome. However I made some changes and don't like how big my controller is. What is there that I can do to fix this. http://pastebin.com/sXH06ds2" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T23:00:49.103", "Id": "59159", "Score": "0", "body": "Any additional ideas? Check my update." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T22:16:32.633", "Id": "35385", "ParentId": "35106", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:06:50.117", "Id": "35106", "Score": "1", "Tags": [ "php", "codeigniter" ], "Title": "Codeigniter Registration Controller" }
35106
<pre><code>def minval(xs): minum = xs[0] for i in range(len(xs)): if xs[i] &lt; minum: #difference in code: xs[i] minum = xs[i] return minum </code></pre> <p>or</p> <pre><code>def minval(xs): minum = xs[0] for i in range(len(xs)): if i &lt; minum: #difference in code: i minum = xs[i] return minum </code></pre> <p>It gives me the same results:</p> <pre><code>lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] print minval(lst) 1 </code></pre> <p>Which one is better? Why do they both give the same result?</p> <p>Is there a better more shorter way to get the same result, without resorting to pythons own functions? </p> <p>Edit: I got it why it works, I ran the second one, it looped through the "i" which was just the numbers from the range of the len of xs and not the actual indexes of xs.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T12:38:18.427", "Id": "56855", "Score": "4", "body": "What's wrong with Python's built-in function [`min`](http://docs.python.org/3/library/functions.html#min)?" } ]
[ { "body": "<p>They aren't the same: The second gives <code>-1</code> for <code>[-1,-2,-3]</code> and is simply spuriously correct, while the first gives the correct answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T09:04:48.583", "Id": "35118", "ParentId": "35117", "Score": "4" } }, { "body": "<p>A slight improvement would be:</p>\n\n<pre><code>def minval(xs):\n minimum = xs[0]\n for x in xs[1:]:\n if x &lt; minimum:\n minimum = x\n return minimum\n</code></pre>\n\n<p>In general you should loop through the values in a list rather than finding the range and then looping through the indices. If you really need the indices you can also use <code>enumerate</code>.</p>\n\n<p>But as others have said, you would simply use <code>min</code> for this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T13:39:59.457", "Id": "35124", "ParentId": "35117", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T08:50:15.563", "Id": "35117", "Score": "-1", "Tags": [ "python" ], "Title": "Which loop code is better practice?" }
35117
<p>I am learning <a href="https://class.coursera.org/algs4partI-003/class/index" rel="nofollow">Algorithms, Part I on coursera.org</a>. I just watched the first lecture then tried to write some code in C#. The class basically stores list of connected numbers. You can add numbers that connected together by calling <code>Union</code> and check if they are connected by calling <code>AreConnected</code>. Code is as follows:</p> <pre><code>public class UnionFind { private readonly List&lt;HashSet&lt;int&gt;&gt; source; public static UnionFind Create() { return new UnionFind(); } private UnionFind() { this.source = new List&lt;HashSet&lt;int&gt;&gt;(); } public void Union(int left, int right) { var isLeftExist = this.source.FirstOrDefault(o =&gt; o.Contains(left)); var isRightExist = this.source.FirstOrDefault(o =&gt; o.Contains(right)); if (isLeftExist == null &amp;&amp; isRightExist == null) { var hash = new HashSet&lt;int&gt;(); hash.Add(left); hash.Add(right); this.source.Add(hash); } else if (isLeftExist != null &amp;&amp; isRightExist == null) { isLeftExist.Add(right); } else if (isRightExist != null &amp;&amp; isLeftExist == null) { isRightExist.Add(left); } else { // found left and right this.source.Remove(isRightExist); foreach (var item in isRightExist) { isLeftExist.Add(item); } } } public bool AreConnected(int left, int right) { return this.source .Any(o =&gt; o.Contains(left) &amp;&amp; o.Contains(right)); } </code></pre> <p>To make it easier to understand, this is unit test class.</p> <pre><code>[TestClass] public class UnionFindTests { [TestMethod] public void SimpleUnionTest() { int left = 10; int right = 20; var uf = UnionFind.Create(); uf.Union(left, right); Assert.IsTrue(uf.AreConnected(left, right)); } [TestMethod] public void DuplicateUnionTest() { int left = 10; int right = 10; var uf = UnionFind.Create(); uf.Union(left, right); Assert.IsTrue(uf.AreConnected(left, right)); } [TestMethod] public void MultipleLinksUnionTest() { int left1 = 10; int left2 = 20; int left3 = 30; int right1 = 15; int right2 = 25; int right3 = 35; var uf = UnionFind.Create(); uf.Union(left1, right1); uf.Union(left2, right2); uf.Union(left3, right3); uf.Union(left1, right2); Assert.IsTrue(uf.AreConnected(left2, right1)); } } </code></pre> <p><code>UnionFind</code> works find and pass all tests in unit test. The problem is I found method Union has many if-else and I want to get rid of it. Is there a simpler way of implementing Union method?</p>
[]
[ { "body": "<p>Your naming of <code>isLeftExist</code> is not correct. The variable holds a list containing th number <code>left</code>. So its name should be <code>listContainingLeft</code>. The same applies to the <code>isRightExist</code> list.</p>\n\n<p>Regarding the if-else construct: One clause is redundant (the second <code>isRightExist</code>) so you my either omit this or rewrite the conditions like this. </p>\n\n<pre><code>public void Union(int left, int right)\n{\n var listContainingLeft = this.source.FirstOrDefault(o =&gt; o.Contains(left));\n var listContainingRight = this.source.FirstOrDefault(o =&gt; o.Contains(right));\n\n if (listContainingLeft == null)\n if (listContainingRight == null)\n AddBranch(left, right);\n else\n listContainingRight.Add(left);\n else if (listContainingRight == null)\n listContainingLeft.Add(right);\n else\n Combine(listContainingLeft, listContainingRight);\n}\n\nprivate void AddBranch(int left, int right)\n{\n var hash = new HashSet&lt;int&gt;();\n hash.Add(left);\n hash.Add(right);\n this.source.Add(hash);\n}\n\nprivate void Combine(HashSet&lt;int&gt; isLeftExist, HashSet&lt;int&gt; isRightExist)\n{\n this.source.Remove(isRightExist);\n foreach (var item in isRightExist)\n {\n isLeftExist.Add(item);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T11:19:38.040", "Id": "56852", "Score": "3", "body": "I think that whenever you're writing multiline `if` bodies, you should always use braces, even if they are not necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T12:01:19.150", "Id": "56854", "Score": "2", "body": "That's a matter of taste. I tend not do do things which are unnecessary. One exception: If it increases readability. In this special case (as all conditional actions are one-liners) I did not use braces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T13:22:04.450", "Id": "56856", "Score": "1", "body": "Without becoming a bashing exercise, in my experience the braces on 1-liners are important. They do two things: Stop bugs appearing when someone adds something to the 'block' (yeah, it's a stupid thing to do but I have seen it often). The second thing is that adding 1 line to a brace-less `if` statement now becomes a 3-line diff (including the line with the conditional) whereas if there were already braces there, the 1-line added becomes a 1-liner diff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T13:58:13.803", "Id": "56858", "Score": "0", "body": "I know the arguments for using braces in one.liners. However, I prefer to avoid useless code. I can give you another argument to use braces: Say I would add another inner condition without paying attention: This would make the code wrong: But I pay attention and so until now I did not make the experience in making mistakes you described (I make enough other foolish things though). But, if the team wants it like that, I will add those braces (and other coding standards) without discussion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T23:45:06.327", "Id": "56895", "Score": "1", "body": "If you define useful as \"creates customer value\", then braces are useless. But if you add \"or makes development easier/safer/faster\", then suddenly those braces have value. \"Pay attention\" is a kind of effort, and that part of your brain is no longer available for thinking about other things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T07:28:00.020", "Id": "56918", "Score": "1", "body": "I am writing software for 32 years and I am sure I have quite an understanding in what is valuable for programmers and what not. Most of my programmer colleagues tend to use the braces like I do (i.e. whenever necessary), and they're all 10+ years in the business. In my eyes, vertical formatting (e.g. emtpy lines, braces) makes the code harder to read but that is a matter of taste. Some programmers use `== false` instead of `!` while others don't. Some programmers use braces in one liners, others don't. Just accept it. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T16:12:50.210", "Id": "60641", "Score": "0", "body": "Clearly if you add the braces you get credit for two more LOC / hour." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T23:10:48.483", "Id": "60683", "Score": "0", "body": "Got me on that: Now I know why I struggle in my life and my colleage can afford a Ferrari. Damned ;-)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T10:29:42.623", "Id": "35123", "ParentId": "35120", "Score": "2" } }, { "body": "<p>Building on @alzaimar's answer:</p>\n\n<p>You can unfold the conditionals with early return. The linear flow makes it slightly easier to follow.</p>\n\n<pre><code>if (listContainingLeft == null &amp;&amp; listContainingRight == null)\n{\n AddBranch(left, right);\n return;\n}\n\nif (listContainingLeft != null &amp;&amp; listContainingRight != null)\n{\n Combine(listContainingLeft, listContainingRight);\n return;\n}\n\nif (listContainingLeft != null)\n{\n listContainingLeft.Add(right);\n return;\n}\n\nif (listContainingRight != null)\n{\n listContainingRight.Add(left);\n return;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T16:18:55.673", "Id": "60644", "Score": "0", "body": "This doesn't look good at all. There **is** a principle that a function should have only one return point. This seems simple now, but once the logic gets more complicated these returns out of nowhere can make for some nasty misunderstandings and fitful bug-tracing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T23:08:23.470", "Id": "60682", "Score": "0", "body": "Is there? Why should you have unreadable and complicated `if..else` constructs just to follow that principle? The only principle there is and which has to be followed *every time* (except for the exception) is: Make it correct, readable, simple, maintainable and sustainable. \n\nThere are various ways helping programmers to achieve these **only** valid principles, and one of them (more like a rule of thumb:) have one return value. But it's not a must, believe me. Imho early and multiple returns make the rest of the code **more** readable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T23:41:25.187", "Id": "35144", "ParentId": "35120", "Score": "3" } }, { "body": "<p>I find these practices helpful:</p>\n\n<ul>\n<li>Buy a licence of Resharper or something similar. It points out\npotential improvements ;-)</li>\n<li>Extract all conditions as variables and name them after their\nmeaning. </li>\n<li>Check all positives first, then it's easier to understand the\nfollowing ifs.</li>\n<li><p>As a bonus, I can remove the comment in the (initial) last branch</p>\n\n<pre><code>public void Union(int left, int right)\n{\n var lefts = source.FirstOrDefault(o =&gt; o.Contains(left));\n var rights = source.FirstOrDefault(o =&gt; o.Contains(right));\n\n var foundRight = rights != null;\n var foundLeft = lefts != null;\n\n if (foundLeft &amp;&amp; foundRight)\n {\n source.Remove(rights);\n\n foreach (var item in rights)\n {\n lefts.Add(item);\n }\n }\n else if (foundRight)\n {\n rights.Add(left);\n }\n else if (foundLeft)\n {\n lefts.Add(right);\n }\n else\n {\n var hash = new HashSet&lt;int&gt; {left, right};\n source.Add(hash);\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:13:03.930", "Id": "36813", "ParentId": "35120", "Score": "3" } }, { "body": "<p>Here is my code for <code>Union</code> method:</p>\n\n<pre><code>public class UnionFind\n{\n private readonly List&lt;HashSet&lt;int&gt;&gt; source;\n\n public static UnionFind Create()\n {\n return new UnionFind();\n }\n\n private UnionFind()\n {\n this.source = new List&lt;HashSet&lt;int&gt;&gt;();\n }\n\n private readonly HashSet&lt;int&gt; selfConnectedSet = new HashSet&lt;int&gt;();\n\n private HashSet&lt;int&gt; AddSet() {\n var hash = new HashSet&lt;int&gt;();\n this.source.Add(hash);\n return hash;\n }\n\n public void Union(int left, int right)\n {\n if (left == right)\n {\n selfConnectedSet.Add(left);\n }\n else\n {\n var leftSet = this.source.FirstOrDefault(o =&gt; o.Contains(left));\n var rightSet = this.source.FirstOrDefault(o =&gt; o.Contains(right));\n if (leftSet != null &amp;&amp; rightSet != null)\n {\n // found left and right\n this.source.Remove(rightSet);\n leftSet.UnionWith(rightSet);\n }\n else\n {\n var hash = leftSet ?? (rightSet ?? AddSet());\n hash.Add(left);\n hash.Add(right);\n }\n }\n }\n\n public bool AreConnected(int left, int right)\n {\n if (left == right)\n {\n return selfConnectedSet.Contains(left);\n }\n else\n {\n return this.source\n .Any(o =&gt; o.Contains(left) &amp;&amp; o.Contains(right));\n }\n }\n}\n</code></pre>\n\n<p>Few points for my refactoring</p>\n\n<ul>\n<li><code>is</code> should be used for <code>boolean</code> variable only, as some already mentioned earlier.</li>\n<li>Except the first <code>if</code>, the logic just to find the target <code>HashSet</code> to add the values to, so I normalised that by using conditional operator. We can add <code>left</code> and <code>right</code> no matter it's <code>leftSet</code> or <code>rightSet</code> because it's a <code>HashSet</code> so the value could never be duplicated.</li>\n<li>Same value for <code>left</code> and <code>right</code> has to be supported according to the unit test, so I add a separated <code>HashSet</code> to keep self-connected number</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T16:17:22.370", "Id": "60643", "Score": "0", "body": "Be sure that the caller of Union is well aware that you are throwing an exception. At least in the test case presented, the caller will be blythely unaware and totally unprepared to catch such an exception, and attempt to do something meaningful. The point is be careful and have a plan before adding NEW exceptions and using exceptions as a 'escape hatch' to your architecture" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:24:04.727", "Id": "60666", "Score": "0", "body": "Thanks for comment. I just found out the test case of duplication. I will fix accordingly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T03:31:08.053", "Id": "36836", "ParentId": "35120", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T09:48:17.527", "Id": "35120", "Score": "3", "Tags": [ "c#", "algorithm", "unit-testing" ], "Title": "Complexity in multiple if-else algorithms" }
35120
<p>Please review the code.</p> <pre><code>document.addEventListener("keydown", function(e) { // shortcuts if (e.ctrlKey) { // Ctrl+ if (/^(82|79|83|66|191)$/.test(e.keyCode)) { e.preventDefault(); } switch (e.keyCode) { case 82: // R newDoc(); break; case 79: // O openDoc(); break; case 83: // S saveDoc(); break; case 66: // B showHideStatusBar(statusBarOn ? false : true); // toggle break; case 191: // / alert("Welcome to " + appname + "!"); break; } } if (e.keyCode == 9) { // tab e.preventDefault(); var sStart = textarea.selectionStart, text = textarea.value; textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd); textarea.selectionEnd = sStart + 1; } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T11:14:31.820", "Id": "56850", "Score": "0", "body": "What's the background/usage of your app? On what basis you want to review your code? readability/clean-code/optimization? Please mention them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T11:17:34.017", "Id": "56851", "Score": "0", "body": "optimization and simplifying mainly...\nit is for a text-editing webapp.." } ]
[ { "body": "<p>In JS, when you have a switch, it's usually better to go with a dispatch table.</p>\n\n<pre><code>var mapping = {\n 82: newDoc,\n 79: openDoc,\n 83: saveDoc,\n 66: function() {\n showHideStatusBar(statusBarOn ? false : true);\n },\n 191: function() {\n alert(\"Welcome to \" + appname + \"!\");\n }\n};\nmapping[e.keyCode]();\n</code></pre>\n\n<p>Or if you don't want to give a name:</p>\n\n<pre><code>({\n 82: newDoc,\n 79: openDoc,\n 83: saveDoc,\n 66: function() {\n showHideStatusBar(statusBarOn ? false : true);\n },\n 191: function() {\n alert(\"Welcome to \" + appname + \"!\");\n }\n})[e.keyCode]();\n</code></pre>\n\n<p>Also, use <code>===</code> instead of <code>==</code> for multiple reasons. Google \"triple equal javascript\" if you want more information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T11:03:41.723", "Id": "56847", "Score": "0", "body": "It's generally a good idea to use a *dispatch table* instead of a *switch*. However, you have to handle a default case during lookup, something like `var fn = mapping[e.keyCode]; if (fn !== undefined) { fn() } else { default() }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T13:35:43.977", "Id": "56857", "Score": "0", "body": "There is no default case in his code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T15:01:27.137", "Id": "56864", "Score": "0", "body": "Except there is an `if` preventing this :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T15:03:20.663", "Id": "56865", "Score": "0", "body": "/me crawls back in shame for not reading the code carefully… thanks." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T10:18:01.123", "Id": "35122", "ParentId": "35121", "Score": "3" } } ]
{ "AcceptedAnswerId": "35122", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T10:12:16.723", "Id": "35121", "Score": "1", "Tags": [ "javascript" ], "Title": "Handling keyboard shortcuts for webapp" }
35121
<p>I am after a peer review of a C# implementation of the Barnes-Hut algorithm which I have translated from F#. The F# version is the base for comparison, therefore the C# version is suppose to reflect the F# in structure and behaviour. I have tried to translate the F# implementation as accurately as possible, however i would like a second opinion. </p> <p>I would be grateful for any advice e.g. on any problems, or on how to make the algorithm further reflect the F# version. Also, any suggestions on how improve parallel performance, if any. </p> <p>F# version main algorthim <a href="http://pastebin.com/AMb9AnNd" rel="nofollow">http://pastebin.com/AMb9AnNd</a></p> <p>C# version:</p> <pre><code>/* * * * usage: * args[0] = algorithm version * args[1] = load balanced * args[2] = body count * args[3] = core count * args[4] = test discription * args[5] = eps value */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BHTuned { #region BHMain: attributes /// &lt;summary&gt; /// /// &lt;/summary&gt; public class Body { public double x { get; set; } public double y { get; set; } public double z { get; set; } public double vx { get; set; } public double vy { get; set; } public double vz { get; set; } public double m { get; set; } public Body(double x, double y, double z, double vx, double vy, double vz, double mass) { this.x = x; this.y = y; this.z = z; this.vx = vx; this.vy = vy; this.vz = vz; this.m = mass; } } /// &lt;summary&gt; /// /// &lt;/summary&gt; public class Accel { public double ax { get; set; } public double ay { get; set; } public double az { get; set; } public Accel(double ax, double ay, double az) { this.ax = ax; this.ay = ay; this.az = az; } } /// &lt;summary&gt; /// /// &lt;/summary&gt; public class Centroid { public double cx { get; set; } public double cy { get; set; } public double cz { get; set; } public double cm { get; set; } public Centroid(double cx, double cy, double cz, double cm) { this.cx = cx; this.cy = cy; this.cz = cz; this.cm = cm; } } /// &lt;summary&gt; /// /// &lt;/summary&gt; public class Bbox { public List&lt;Body&gt; bs; public double minx { get; set; } public double miny { get; set; } public double minz { get; set; } public double maxx { get; set; } public double maxy { get; set; } public double maxz { get; set; } public Bbox(double minx, double miny, double minz, double maxx, double maxy, double maxz) { bs = new List&lt;Body&gt;(); this.minx = minx; this.miny = miny; this.minz = minz; this.maxx = maxx; this.maxy = maxy; this.maxz = maxz; } } /// &lt;summary&gt; /// /// &lt;/summary&gt; public class BHTree { public List&lt;BHTree&gt; subTrees = new List&lt;BHTree&gt;(); public double size { get; set; } public double centerx { get; set; } public double centery { get; set; } public double centerz { get; set; } public double mass { get; set; } public BHTree(double size, double centerx, double centery, double centerz, double mass, List&lt;BHTree&gt; subTrees) { this.size = size; this.centerx = centerx; this.centery = centery; this.centerz = centerz; this.mass = mass; this.subTrees = subTrees; } } #endregion /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="ba"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public abstract class BHMain { // If the distance between the points is smaller than this public double eps; //= 0.01F; // then ignore the forces between them. public LinkedList&lt;Body&gt; ba = new LinkedList&lt;Body&gt;(); protected static float timeStep = 0.001F; public static float threshold = 0.25F; public int N; public BHMain(int N, double eps) { this.N = N; this.eps = eps; } /// &lt;summary&gt; /// Determine 3D boundaries /// &lt;/summary&gt; /// &lt;param name="ba"&gt; All Bodys &lt;/param&gt; /// &lt;returns&gt; Bounding box &lt;/returns&gt; public static Bbox findBounds(List&lt;Body&gt; ba) { double minx = 0.0, miny = 0.0, minz = 0.0, maxx = 0.0, maxy = 0.0, maxz = 0.0; foreach (Body b in ba) { minx = Math.Min(minx, b.x); miny = Math.Min(minx, b.y); minz = Math.Min(minx, b.z); maxx = Math.Max(maxx, b.x); maxy = Math.Max(maxx, b.y); maxz = Math.Max(maxx, b.z); } return new Bbox(minx, miny, minz, maxx, maxy, maxz); } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="bl"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Centroid calcCentroid(List&lt;Body&gt; bl) { double x = 0.0, y = 0.0, z = 0.0, m = 0.0; foreach (Body b in bl) { x = b.m * b.x + x; y = b.m * b.y + y; z = b.m * b.z + z; m = m + b.m; } return new Centroid(x / m, y / m, z / m, m); } /// &lt;summary&gt; /// Generate Bodys /// &lt;/summary&gt; /// &lt;param name="n"&gt;&lt;/param&gt; /// &lt;returns&gt;Bodys List &lt;/returns&gt; public List&lt;Body&gt; getBodies(int seed) { List&lt;Body&gt; d = new List&lt;Body&gt;(); Random rnd = new Random(seed); for (int i = 0; i &lt; seed; i++) { d.Add(new Body(rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble(), rnd.NextDouble())); } /* * test data d.Add(new Body(0.72624327, 0.8173253596, 0.7680226894, 0.5581611914, 0.206033154, 0.5588847946, 0.906027066)); d.Add(new Body(0.2486685842, 0.1107439772, 0.4670106799, 0.771604122, 0.6575188938, 0.4327826013, 0.3540837636)); d.Add(new Body(0.7710938983, 0.4041625948, 0.1659986703, 0.9850470526, 0.1090046336, 0.306680408, 0.8021404612)); d.Add(new Body(0.2935192125, 0.6975812124, 0.8649866608, 0.1984899832, 0.5604903733, 0.1805782147, 0.2501971588)); d.Add(new Body(0.8159445267, 0.99099983, 0.5639746513, 0.4119329138, 0.01197611308, 0.05447602135, 0.6982538564)); d.Add(new Body(0.3383698409, 0.2844184475, 0.2629626418, 0.6253758444, 0.4634618528, 0.928373828, 0.146310554)); d.Add(new Body(0.8607951551, 0.5778370651, 0.9619506323, 0.8388187749, 0.9149475926, 0.8022716347, 0.5943672515)); d.Add(new Body(0.3832204693, 0.8712556827, 0.6609386227, 0.05226170553, 0.3664333324, 0.6761694414, 0.04242394913)); d.Add(new Body(0.9056457835, 0.1646743003, 0.3599266132, 0.2657046361, 0.8179190721, 0.5500672481, 0.4904806467)); d.Add(new Body(0.4280710977, 0.4580929179, 0.05891460369, 0.4791475667, 0.2694048119, 0.4239650548, 0.9385373443)); */ return d; } /// &lt;summary&gt; /// Determine a bodies position in relation to bounding box /// &lt;/summary&gt; /// &lt;param name="bb"&gt;&lt;/param&gt; /// &lt;param name="b"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static bool inbox(Bbox bb, Body b) { if ((b.x &gt; bb.minx) &amp;&amp; (b.x &lt;= bb.maxx) &amp;&amp; (b.y &gt; bb.miny) &amp;&amp; (b.y &lt;= bb.maxy) &amp;&amp; (b.z &gt; bb.minz) &amp;&amp; (b.z &lt;= bb.maxz)) return true; else return false; } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="bb"&gt;&lt;/param&gt; /// &lt;param name="bl"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Bbox[] splitPoints(Bbox bb, List&lt;Body&gt; bl) { Bbox[] box = new Bbox[8]; double midx = (bb.maxx + bb.minx) / 2; double midy = (bb.maxy + bb.miny) / 2; double midz = (bb.maxz + bb.minz) / 2; for (int i = 0; i &lt; 8; i++) box[i] = new Bbox(bb.minx, bb.miny, bb.minz, midx, midy, midz); foreach (Body b in bl) for (int i = 0; i &lt; 8; i++) if (inbox(box[i], b)) box[i].bs.Add(b); Bbox[] bbf = new Bbox[8]; for (int i = 0; i &lt; 8; i++) if (box[i].bs.Count != 0) bbf[i] = (box[i]); return bbf; } /// &lt;summary&gt; /// Populate the oct-tree /// &lt;/summary&gt; /// &lt;param name="bb"&gt;&lt;/param&gt; /// &lt;param name="bl"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static int count = 0; public static BHTree buildTree(Bbox bb, List&lt;Body&gt; bl, int N) { List&lt;BHTree&gt; subTrees = new List&lt;BHTree&gt;(); double[] s = { Math.Abs(bb.maxx - bb.minx), Math.Abs(bb.maxy - bb.miny), Math.Abs(bb.maxz - bb.minz) }; double size = s.Min(); Centroid cent = calcCentroid(bl); count++; Bbox[] boxesAndPts = splitPoints(bb, bl); if (boxesAndPts[0] == null) return new BHTree(size, cent.cx, cent.cy, cent.cz, cent.cm, subTrees); else { foreach (Bbox b in boxesAndPts) subTrees.Add(buildTree(boxesAndPts[0], boxesAndPts[0].bs, N)); return new BHTree(size, cent.cx, cent.cy, cent.cz, cent.cm, subTrees); } } /// &lt;summary&gt; /// calculate the acceleration on a point due to some other point /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Accel accel(BHTree BHT, Body b, double eps) { double dx = b.x - BHT.centerx, dy = b.y - BHT.centery, dz = b.z - BHT.centerz; double dsqr = (dx * dx) + (dy * dy) + (dz * dz) + eps; double d = Math.Sqrt(dsqr); double mag = timeStep / (dsqr * d); double mmag = BHT.mass * mag; return new Accel((dx * mmag), (dy * mmag), (dz * mmag)); } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="BHT"&gt;&lt;/param&gt; /// &lt;param name="b"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static bool isFar(BHTree BHT, Body b) { double dx = b.x - BHT.centerx, dy = b.y - BHT.centery, dz = b.z - BHT.centerz; double dist = Math.Sqrt(dx * dx + dy * dy + dz * dz); if ((BHT.size / dist) &lt; threshold) return true; else return false; } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="a1"&gt;&lt;/param&gt; /// &lt;param name="a2"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Accel addAccel(Accel a1, Accel a2) { return new Accel((a1.ax + a2.ax), (a1.ay + a2.ay), (a1.az + a2.az)); } /// &lt;summary&gt; /// Recursively calculate relative body acceleration within the tree /// &lt;/summary&gt; /// &lt;param name="BHT"&gt;Populated oct-tree&lt;/param&gt; /// &lt;param name="b"&gt;Current body&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Accel calcAccel(BHTree BHT, Body b, double eps) { if (BHT.subTrees.Count == 0 || isFar(BHT, b)) return accel(BHT, b, eps); else { Accel acc = new Accel(0, 0, 0); foreach (BHTree t in BHT.subTrees) { Accel a = (calcAccel(t, b, eps)); addAccel(acc, a); } return acc; } } /// &lt;summary&gt; /// Checking function /// &lt;/summary&gt; /// &lt;param name="acc"&gt;&lt;/param&gt; /// &lt;param name="b"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public double f(Double acc, Body b) { return acc + b.x + b.y + b.z + b.vx + b.vy + b.vz; } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="args"&gt;&lt;/param&gt; public virtual void doSteps(string args, string testName, int coreCount) { } } /// &lt;summary&gt; /// Sequential Abtraction /// &lt;/summary&gt; public class Seq : BHMain { public Seq(int N, double eps) : base(N, eps) { this.N = N; this.eps = eps; } public override void doSteps(string args, string testDescription, int coreCount) { Console.WriteLine("Sequential" + " Cores: " + coreCount); List&lt;Body&gt; ba = getBodies(N); List&lt;Body&gt; bl = ba; SetFiles sf = new SetFiles(testDescription, testDescription + "/seq/", "seq", coreCount); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i &lt; 16; i++) { Bbox bb = findBounds(ba); BHTree BHT = buildTree(bb, ba, N); for (int j = 0; j &lt; N; j++) { Accel acc = calcAccel(BHT, ba[j], eps); Body nb = new Body(ba[j].x, ba[j].y, ba[j].z, (ba[j].vx - acc.ax), (ba[j].vy - acc.ay), (ba[j].vz - acc.az), ba[j].m); bl[j] = (new Body((nb.x + timeStep * nb.vx), (nb.y + timeStep * nb.vy), (nb.z + timeStep * nb.vz), nb.vx, nb.vy, nb.vz, nb.m)); } ba = bl; } stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed.TotalSeconds); // sf.addData(stopwatch.ElapsedMilliseconds); // sf.buildDataFile(); // sf.buildRefFile(); } } /// &lt;summary&gt; /// Parallel.For abstraction /// &lt;/summary&gt; public class PFor : BHMain { public PFor(int N, double eps) : base(N, eps) { this.N = N; this.eps = eps; } public override void doSteps(string args, string testName, int coreCount) { List&lt;Body&gt; ba = getBodies(N); List&lt;Body&gt; bl = ba; //populate list for iteration /* Naive parallel ditribution. N Parallel loop iterations */ if (args == "bf") // brute-force { Console.WriteLine("Brute-force PFor" + " Cores: " + coreCount); SetFiles sf = new SetFiles(testName, testName + "/pf/bf/", "pfbf", coreCount); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i &lt; 16; i++) { Bbox bb = findBounds(ba); BHTree BHT = buildTree(bb, ba, N); try { Parallel.For(0, (N - 1), j =&gt; { Accel acc = calcAccel(BHT, ba[j], eps); Body nb = new Body(ba[j].x, ba[j].y, ba[j].z, (ba[j].vx - acc.ax), (ba[j].vy - acc.ay), (ba[j].vz - acc.az), ba[j].m); bl[j] = (new Body((nb.x + timeStep * nb.vx), (nb.y + timeStep * nb.vy), (nb.z + timeStep * nb.vz), nb.vx, nb.vy, nb.vz, nb.m)); }); } catch (AggregateException e) { Console.Write(e); } } stopwatch.Stop(); sf.addData(stopwatch.ElapsedMilliseconds); sf.buildDataFile(); sf.buildRefFile(); } /* Tuned parallel ditribution. Course grainuality, load is evenly balanced */ else if (args == "lb") // load balanced { Console.WriteLine("load balanced PFor" + " Cores: " + coreCount); SetFiles sf = new SetFiles(testName, testName + "/pf/lb/", "pflb", coreCount); Stopwatch stopwatch = new Stopwatch(); int partition = N / 4; BHTree BHT; Bbox bb; stopwatch.Start(); for (int k = 0; k &lt; 16; k++) { bb = findBounds(ba); BHT = buildTree(bb, ba, N); Parallel.For(0, 4, new ParallelOptions { MaxDegreeOfParallelism = 4 }, j =&gt; { int c = 0, d = partition; if (j == 0) { c = 0; d = partition; } else if (j == 1) { c = partition; d = partition * 2; } else if (j == 2) { c = partition * 2; d = partition * 3; } else if (j == 3) { c = partition * 3; d = partition * 4; } for (; c &lt; d; c++) { Accel acc = calcAccel(BHT, ba[c], eps); Body nb = new Body(ba[c].x, ba[c].y, ba[c].z, (ba[c].vx - acc.ax), (ba[c].vy - acc.ay), (ba[c].vz - acc.az), ba[c].m); bl[c] = (new Body((nb.x + timeStep * nb.vx), (nb.y + timeStep * nb.vy), (nb.z + timeStep * nb.vz), nb.vx, nb.vy, nb.vz, nb.m)); } ba = bl; }); } stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed.TotalSeconds); // sf.addData(stopwatch.Elapsed.TotalSeconds); // sf.buildDataFile(); // sf.buildRefFile(); } } } /// &lt;summary&gt; /// Parallel.Invoke abstraction /// &lt;/summary&gt; public class PInvoke : BHMain { public PInvoke(int N, double eps) : base(N, eps) { this.N = N; this.eps = eps; } public override void doSteps(string args, string testName, int coreCount) { List&lt;Body&gt; ba = getBodies(N); Bbox bb = findBounds(ba); BHTree BHT = buildTree(bb, ba, N); List&lt;Body&gt; bl = ba; /* Naive parallel ditribution. N Parallel.Invoke's are created */ if (args == "bf") { Console.WriteLine("Brute-force PInvoke" + " Cores: " + coreCount); SetFiles sf = new SetFiles(testName, testName + "/pi/bf/", "pibf", coreCount); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i &lt; 16; i++) for (int j = 0; j &lt; N; j++) { Parallel.Invoke(() =&gt; { Accel acc = calcAccel(BHT, ba[j], eps); Body nb = new Body(ba[j].x, ba[j].y, ba[j].z, (ba[j].vx - acc.ax), (ba[j].vy - acc.ay), (ba[j].vz - acc.az), ba[j].m); bl[j] = (new Body((nb.x + timeStep * nb.vx), (nb.y + timeStep * nb.vy), (nb.z + timeStep * nb.vz), nb.vx, nb.vy, nb.vz, nb.m)); }); ba = bl; } stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed.TotalSeconds); // sf.addData(stopwatch.ElapsedMilliseconds); // sf.buildDataFile(); // sf.buildRefFile(); } /* Tuned parallel ditribution. Course grainuality, load is evenly balanced */ else if (args == "lb") { Console.Write("load balanced PInvoke" + " Cores: " + coreCount+"\n"); int partition = N / 4; SetFiles sf = new SetFiles(testName, testName + "/pi/lb/", "pilb", coreCount); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int k = 0; k &lt; 4; k++) // iteration loop for (int j = 0; j &lt; 4; j++) // distribution loop { Parallel.Invoke(new ParallelOptions { MaxDegreeOfParallelism = 4 },() =&gt; { int c = 0, d = partition; if (j == 0) { c = 0; d = partition; } else if (j == 1) { c = partition; d = partition * 2; } else if (j == 2) { c = partition * 2; d = partition * 3; } else if (j == 3) { c = partition * 3; d = partition * 4; } for (; c &lt; d; c++) { Accel acc = calcAccel(BHT, ba[c], eps); Body nb = new Body(ba[c].x, ba[c].y, ba[c].z, (ba[c].vx - acc.ax), (ba[c].vy - acc.ay), (ba[c].vz - acc.az), ba[c].m); bl[c] = (new Body((nb.x + timeStep * nb.vx), (nb.y + timeStep * nb.vy), (nb.z + timeStep * nb.vz), nb.vx, nb.vy, nb.vz, nb.m)); } }); ba = bl; } stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed.TotalSeconds); //sf.addData(stopwatch.ElapsedMilliseconds); //sf.buildDataFile(); //sf.buildRefFile(); } } } } using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BHTuned { class EntryPoint { /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="args"&gt; &lt;/param&gt; static void Main(string[] args) { Process Proc = Process.GetCurrentProcess(); long AffinityMask = (long)Proc.ProcessorAffinity; if (Convert.ToInt16(args[3] )== 1) AffinityMask &amp;= 0x0001; // use only any of the first 4 available processors; else if (Convert.ToInt16(args[3]) == 2) AffinityMask &amp;= 0x0003; else if (Convert.ToInt16(args[3]) == 3) AffinityMask &amp;= 0x0007; else if (Convert.ToInt16(args[3]) == 4) AffinityMask &amp;= 0x000F; Proc.ProcessorAffinity = (IntPtr)AffinityMask; // Render r = new Render("esp"); switch (args[0]) { case "seq": // Sequential BHMain bf = new Seq(Convert.ToInt32(args[2]), Convert.ToDouble(args[5])); bf.doSteps(args[1], args[4], Convert.ToInt32(args[3])); break; case "pf": // parallel.For BHMain pf = new PFor(Convert.ToInt32(args[2]), Convert.ToDouble(args[5])); pf.doSteps(args[1], args[4], Convert.ToInt32(args[3])); break; case "pi": // parallel.Invoke BHMain pi = new PInvoke(Convert.ToInt32(args[2]), Convert.ToDouble(args[5])); pi.doSteps(args[1], args[4], Convert.ToInt32(args[3])); break; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T17:54:53.843", "Id": "56867", "Score": "1", "body": "Please include the code you want to get reviewed in your question (you can keep external links). This prevents your question and the answers to become useless when the link goes away." } ]
[ { "body": "<p>I think there is a lot in the code which can be improved especially from design point of view. A few points which caught my eye follow but it can probably improved further. I would start with what I've written below and then possibly go through another round of refactoring.</p>\n\n<p><strong>Naming conventions.</strong></p>\n\n<ol>\n<li>C# standard naming convention for methods and public properties is CamelCase.</li>\n<li>Please don't try and save characters on class names. Ideally reading the class name should give you a good indication of what it's purpose. It's not easy to find a good yet concise name but it pays of to spent 5min thinking about it. Some suggestions:\n<ul>\n<li><code>BBox</code> -> <code>BoundingBox</code></li>\n<li><code>Accel</code> -> <code>Acceleration</code></li>\n<li><code>BHMain</code> -> <code>BarnesHutBase</code></li>\n<li><code>Seq</code> -> <code>BarnesHutSequential</code></li>\n<li><code>PFor</code> -> <code>BarnesHutParallel</code></li>\n</ul></li>\n<li>Please give your local variables some more meaningful names. Reading all this <code>bb</code>, <code>ba</code>, <code>b</code>, <code>bl</code>, etc. just hurts the eye. Intellisense and auto completions have been invented a long time ago, no need to try and save characters for sake of typing. Using names like <code>boundingBox</code>, <code>bodies</code>, etc. would make the code much easier to read.</li>\n</ol>\n\n<p><strong>Design</strong></p>\n\n<ol>\n<li>Consider making your plain data classes like <code>Accel</code>, <code>Centroid</code> etc. <code>structs</code> and immutable. Their properties don't change after they have been constructed if I read your code correctly so you might want to reflect this in your design. Immutability makes a lot of things easier. Eric Lippert has written some <a href=\"http://blogs.msdn.com/b/ericlippert/archive/tags/immutability/\" rel=\"nofollow\">very interesting blog articles about immutability</a>. At least consider making the properties which don't change either <code>readonly</code> fields or give them a <code>private set</code>.</li>\n<li>The <code>findBounds</code> method in <code>BHMain</code> should probably live as a factory method in <code>BBox</code> instead.</li>\n<li>The <code>calcCentroid</code> method in <code>BHMain</code> should probably live as a factory method in <code>Centroid</code> instead.</li>\n<li><code>splitPoints</code> should live in <code>BBox</code> (factory method)</li>\n<li><code>buildTree</code> should live in <code>BHTree</code> (factory method)</li>\n<li><code>accel</code> should live in <code>Accel</code> (factory method)</li>\n<li><code>inbox</code> should live as <code>IsInBox</code> on <code>BBox</code> (non-static)</li>\n<li>There seems to be a magic <code>for i: 1 -&gt; 16</code> loop in your <code>doSteps</code> implementations which seems odd.</li>\n<li>Once you actually remove all those static helper classes from <code>BHMain</code> then there is not much left in <code>BHMain</code> so ask yourself: What should be the purpose of this class?</li>\n<li><p>You repeat a lot of code in <code>Seq</code>, <code>PFor</code> and <code>PInvoke</code> - especially the last two share a lot. The central point of the calculations seems to be this block:</p>\n\n<pre><code>Accel acc = calcAccel(BHT, ba[j], eps);\nBody nb = new Body(ba[j].x, ba[j].y, ba[j].z, (ba[j].vx - acc.ax), (ba[j].vy - acc.ay), (ba[j].vz - acc.az), ba[j].m);\nbl[j] = (new Body((nb.x + timeStep * nb.vx), (nb.y + timeStep * nb.vy), (nb.z + timeStep * nb.vz), nb.vx, nb.vy, nb.vz, nb.m));\n</code></pre>\n\n<p>You should make this a <code>SingleStep</code> method on <code>BHMain</code> which you can call when needed (which gives some purpose back to <code>BHMain</code>)</p>\n\n<p>I would consider a design along these lines:</p>\n\n<pre><code>class BarnesHutBase\n{\n protected void SingleStep(....)\n {\n ...\n }\n}\n\ninterface IStepable\n{\n void PerformSteps(int numberOfSteps);\n}\n\nclass BarnesHutSequential : BarnesHutBase, IStepable\n{\n public void PerformSteps(int numberOfSteps)\n {\n ...\n }\n}\n</code></pre></li>\n<li><p>The timing and recording of things should be encapsulated in <code>SetFiles</code> as a <code>RecordTime</code> method. Something along these lines:</p>\n\n<pre><code>class RecordingSetFiles : IDisposable\n{\n private Stopwatch _Stopwatch ;\n private SetFiles _SetFiles;\n public RecordingSetFiles(SetFiles files)\n {\n _SetFiles = files;\n _Stopwatch = new Stopwatch();\n _Stopwatch.Start();\n }\n\n public void Dispose()\n {\n _Stopwatch.Stop();\n _SetFiles.addData(_Stopwatch.ElapsedMilliseconds);\n _SetFiles.buildDataFile();\n _SetFiles.buildRefFile();\n }\n}\n\nclass SetFiles\n{\n public RecordingSetFiles RecordTime()\n {\n return new RecordingSetFiles(this);\n }\n}\n</code></pre>\n\n<p>Then you can use it like this: </p>\n\n<pre><code>using (sf.RecordTime())\n{\n ....\n}\n</code></pre></li>\n</ol>\n\n<p><strong>Possible Bugs</strong></p>\n\n<ol>\n<li><p>In <code>PFor</code> and <code>PInvoke</code> you do this:</p>\n\n<pre><code>List&lt;Body&gt; bl = ba; //populate list for iteration\n</code></pre>\n\n<p>This will not create a new list <code>bl</code> but just assign the reference to <code>bl</code>, so <code>bl</code> and <code>ba</code> now point to the same list. Did you actually meant to do <code>bl = new List&lt;Body&gt;(ba)</code>?</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T23:10:10.533", "Id": "56893", "Score": "0", "body": "Many thanks for the advice. I will defo re-factor further. Something else... when testing, my results differ slightly from the F# version. Over one iteration each body value mantissa is accurate to four decimal places. From the code samples, it is possible to tell why? however, again, cheers for your input." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T19:56:31.443", "Id": "35129", "ParentId": "35125", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T16:41:56.917", "Id": "35125", "Score": "2", "Tags": [ "c#", "performance", ".net", "f#", "task-parallel-library" ], "Title": "Barnes-Hut implementation of the N-Body problem translated from F# to C#" }
35125
<p>This script uses robocopy purge with list command to out what would be purged it then parses that log file and checks each file and only deletes files older than 7 days. Is there way it could be simplified to maybe use less log files in the process?</p> <pre><code>$Log = "D:\IT\Backups\Logs\list.txt" $extrafile = "D:\IT\Backups\Logs\extrafile.txt" $extradir = "D:\IT\Backups\Logs\extradir.txt" $extraparsed = "D:\IT\Backups\Logs\extraparsed.txt" $purged = "D:\IT\Backups\Logs\purged.txt" $now = Get-Date $days = "7" $Lastwrite = $now.AddDays(-$days) $datetime = get-date -f MM-dd-yy-hhmmtt If (Test-Path "D:\IT\Backups\Logs\list.txt"){ Remove-Item "D:\IT\Backups\Logs\list.txt" } robocopy "\\10.10.10.9\tcart" "\\192.168.1.44\tcartbkup" /e /Purge /R:1 /W:1 /l /TEE /FP /LOG:"D:\IT\Backups\Logs\list.txt" /MT:16 If (Test-Path $extradir){ Remove-Item $extradir } If (Test-Path $extrafile){ Remove-Item $extrafile } If (Test-Path $extraparsed){ Remove-Item $extraparsed } If (Test-Path $purged){ rename-item $purged -newname ("purged-" + $datetime + ".txt") } Get-Content $Log | Select-String "EXTRA File" | Out-File $extrafile -Width 5000 Get-Content $Log | Select-String "EXTRA Dir" | Out-File $extradir -Width 5000 cat $extradir | %{$_.Substring(28)} | Out-File $extraparsed cat $extrafile | %{$_.Substring(38)} | Out-File $extraparsed -Append $files = Get-Content $extraparsed | Select-String "\\" | ForEach-Object {(Get-Item "$_")} | Where {ForEach-Object {($_.LastWriteTime -le "$Lastwrite")}} foreach ($file in $files) { if ($File -ne $NULL) { Write-Host "Deleting File $File" -ForegroundColor "DarkRed" Write-Output "Deleting File $File" | Out-File $purged -Append Remove-Item $file.FullName -Recurse | Out-Null } else { Write-Host "No More files to delete" -ForegroundColor "Green" Write-Output "No More files to delete" | Out-File $purged -Append } } </code></pre>
[]
[ { "body": "<p>To reduce the amount of log files I would keep things in memory:</p>\n\n<pre><code>$Log = \"C:\\scripts\\list.txt\"\n$purged = \"C:\\scripts\\purged.txt\"\n$now = Get-Date\n$days = \"7\"\n$Lastwrite = $now.AddDays(-$days)\n$datetime = get-date -f MM-dd-yy-hhmmtt\n\n#Robocopy will automatically overwrite the log file unless you specifiy /log+:\nrobocopy \"c:\\downloads\" \"c:\\downloads1\" /e /Purge /R:1 /W:1 /l /TEE /FP /LOG:\"$log\" /MT:16 \n\n#Save purged log\nrename-item $purged ($purged -replace('.txt', \"_$datetime.txt\"))\n\nGet-Content $Log | foreach {\n\n #Split columns by tab\n $fileType = ( $_ -split(\"`t\") )[1]\n $filePath = ( $_ -split(\"`t\") )[2]\n\n\n if ( ($fileType -like \"*Extra File*\") -or ($fileType -like \"*Extra Dir*\") ){\n if ( (Get-Item $filePath).LastWriteTime -le $Lastwrite){\n \"Deleting File: $filePath\" | Out-File $purged -Append\n remove-item $filePath -WhatIf -Recurse\n }\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-17T19:50:04.603", "Id": "41906", "ParentId": "35126", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T19:11:10.163", "Id": "35126", "Score": "5", "Tags": [ "powershell" ], "Title": "Robopurging expired files" }
35126
<p>Need to write a function that takes an open file as the only parameter and returns a dictionary that maps a string to a list of strings and integers. </p> <p>each line in the text will have a username, first name, last name, age, gender and an e-mail address. The function will insert each person's information into a dictionary with their username as the key, and the value being a list of [last name, first name, e-mail, age, gender].</p> <p>basically what im trying to do is open a text file that contains this:</p> <pre><code> ajones Alice Jones 44 F alice@alicejones.net </code></pre> <p>and return something like this:</p> <pre><code> {ajones: ['Jones', 'Alice', 'alice@alicejones.net', 44, 'F']} </code></pre> <p>so far i have done this, but is there any other easier way?</p> <pre><code>def create_dict(file_name): '''(io.TextIOWrapper) -&gt; dict of {str: [str, str, str, int, str]} ''' newdict = {} list2 = [] for line in file_name: while line: list1 = line.split() #for a key, create a list of values if list2(0): value += list1(1) if list2(1): value += list1(2) if list2(2): value += list1(3) if list2(3): value += list1(4) newdict[list1(0)] = list2 for next_line in file_name: list1 = line.split() newdict[list1(0)] = list1 return newdict def helper_func(fieldname): '''(str) -&gt; int Returns the index of the field in the value list in the dictionary &gt;&gt;&gt; helper_func(age) 3 ''' if fieldname is "lastname": return 0 elif fieldname is "firstname": return 1 elif fieldname is "email": return 2 elif fieldname is "age": return 3 elif fieldname is "gender": return 4 </code></pre>
[]
[ { "body": "<p>There are more efficient ways to implement this:</p>\n\n<p>1) If you only need a dictionary to keep your data together without semantics, you could split as follows:</p>\n\n<pre><code>&gt;&gt; line = \"ajones Alice Jones 44 F alice@alicejones.net\"\n&gt;&gt; identifier, *userdata=line.split()\n</code></pre>\n\n<p>results in:</p>\n\n<pre><code>&gt;&gt; identifier\n'ajones'\n&gt;&gt; userdata\n['Alice', 'Jones', '44', 'F', 'alice@alicejones.net']\n</code></pre>\n\n<p>That's a simple point to start, but as mentinoed, the resulting array is very dumb, i.e. you have no semantics about what is what. You end up with a simple array.</p>\n\n<p>2) Another way is using <a href=\"http://docs.python.org/2/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields\" rel=\"nofollow\">named tuples</a></p>\n\n<pre><code>from collections import namedtuple\n\n[...]\nUserdata = namedtuple(\"Userdata\", \"first_name last_name age gender email\")\n[...]\nkey, firstname, lastname, age, gender, email = a.split()\nuser=Userdata(firstname, lastname, age, gender, email)\n</code></pre>\n\n<p>Now your <code>user</code> contains the data in a meaningful way:</p>\n\n<pre><code>&gt;&gt; user.last_name\n'Jones'\n</code></pre>\n\n<p>Besides:\nYour code looks a little bit messy. It's really hard, to get ones head around what you wrote. If you come again in 3 months i doubt, you understand anything you did above.</p>\n\n<p>Your naming of variables is not only <em>poor</em> (<code>list</code>,<code>value</code>,<code>newdict</code>) but <em>terribly misleading</em>: </p>\n\n<pre><code>for line in file_name:\n</code></pre>\n\n<p>You are not iterating over <code>lines</code> in <code>file_name</code> you are iterating over <code>lines</code>, which are perhaps from a <code>file</code>; in the function (and for python) it doesn't matter what the source is, but you should choose an apropriate name.</p>\n\n<p>You make your and your peers life easier, if you try to write better, i.e. <em>cleaner</em> code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T21:30:53.040", "Id": "35134", "ParentId": "35128", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T19:31:58.613", "Id": "35128", "Score": "2", "Tags": [ "python", "hash-map", "file" ], "Title": "opening a text file and building a dictionary" }
35128
<p>I have a single file of a java Bingo program that I want to split into three separate classes (BingoMain, BingoGUI, BingoCard). Extending a program across several files is something I have never really done, so a little help is appreciated. I also want to add the ability to extend the current program to include functionality for up to 5 players. I know that all the code I need is pretty much in here already. Which lines/parts would go in which class and what would I edit in order to add the desired functionality? I don't expect any code, just some directions to get me on my way.</p> <pre><code>import java.awt.Container; import java.awt.Font; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import javax.swing.*; public class Bingo extends JFrame { public static void main (String[] args) { Integer[][] bingoCard = new Integer[5][5]; boolean[][] called = new boolean[][] { {false,false,false,false,false}, {false,false,false,false,false}, {false,false,true ,false,false}, {false,false,false,false,false}, {false,false,false,false,false}}; JFrame myBingoGUI; /* * Fill an array with 15 numbers (1-15) for the "B" column, put the numbers in random order, and * put the first 5 of those numbers in the "B" column of the bingo card. Continue with I,N,G,and O columns. */ Integer[] row = new Integer[15]; for (int i=0; i&lt;5; i++) { fillRow(row, i*15+1); randomize (row); putRowInBingoCard(bingoCard,i,row); } /* * Print the bingo card. */ myBingoGUI=new JFrame(); myBingoGUI.setSize(250, 250); myBingoGUI.setLocation(400, 400); myBingoGUI.setTitle("BINGO"); myBingoGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myBingoGUI.setVisible(true); Container myContentPane = myBingoGUI.getContentPane(); JTextArea myTextArea = new JTextArea(); myTextArea.setFont(new Font("Monospaced", Font.PLAIN,14)); myContentPane.add(myTextArea); myTextArea.append(toStringBingoCard(bingoCard,called)); System.out.println(toStringBingoCard(bingoCard,called)); /* * Play the game: */ while (!winner(called)) { String calledNumber = JOptionPane.showInputDialog(null,"Enter a BINGO call:"); int calledColumn=-1; /* * The first character of the input string is converted to a column number between 0 and 4 */ if (Character.toUpperCase(calledNumber.charAt(0))=='B') calledColumn=0; if (Character.toUpperCase(calledNumber.charAt(0))=='I') calledColumn=1; if (Character.toUpperCase(calledNumber.charAt(0))=='N') calledColumn=2; if (Character.toUpperCase(calledNumber.charAt(0))=='G') calledColumn=3; if (Character.toUpperCase(calledNumber.charAt(0))=='O') calledColumn=4; /* * The remainder of the input string is converted to an integer */ int calledValue = Integer.parseInt(calledNumber.substring(1,calledNumber.length())); /* * The matrix of called numbers is update to show the number has been called. */ for (int i=0;i&lt;5;i++) if (bingoCard[i][calledColumn]==calledValue) called[i][calledColumn]=true; /* * Print the updated BINGO card. */ myTextArea.setText(""); myTextArea.append(toStringBingoCard(bingoCard,called)); System.out.println(toStringBingoCard(bingoCard,called)); } // while myTextArea.append("\n\nBINGO!!"); } // main //====================================================================================================== /* * This method is just here for purposes of testing the program while it is being developed */ public static void printArray (Integer[] a) { for (int i=0; i&lt;a.length; i++) System.out.print(" "+ a[i].intValue()); System.out.println(); } /* * Fill an array of Integers with 15 numbers with a given starting value. */ public static void fillRow(Integer[] theRow, int startValue){ for (int i = 0; i&lt; 15; i++) theRow[i]= new Integer(startValue++); } /* * Take the array of sequential Integers and put them in random order. */ public static void randomize (Integer[] theArray) { Collections.shuffle(Arrays.asList(theArray)); } /* * The BINGO card needs only five of the shuffled numbers, so just put in the first five. */ public static void putRowInBingoCard(Integer[][]card, int column, Integer[] row){ for (int i=0; i&lt;5; i++) card[i][column] = row[i]; } /* * Print the BINGO card. */ public static void printBingoCard(Integer[][] bcard,boolean[][] called) { System.out.println(" B I N G O"); for (int i=0;i&lt;5;i++) { for (int j=0; j&lt;5;j++) { if (i==2 &amp;&amp; j==2) System.out.print("&lt;**&gt;"); else if (called[i][j]) System.out.print("&lt;"+bcard[i][j]+"&gt;"); else System.out.print(" "+bcard[i][j]+" "); if (bcard[i][j]&lt;10) System.out.print(" "); else System.out.print(" "); } // for j System.out.println(); } // for i } //printBingoCard public static String toStringBingoCard(Integer[][] bcard,boolean[][] called) { String returnString=""; returnString+= (" B I N G O \n"); for (int i=0;i&lt;5;i++) { for (int j=0; j&lt;5;j++) { if (i==2 &amp;&amp; j==2) returnString+= ("&lt;**&gt;"); else if (called[i][j]) returnString+= ("&lt;"+bcard[i][j]+"&gt;"); else returnString+= (" "+bcard[i][j]+" "); if (bcard[i][j]&lt;10) returnString+= (" "); else returnString+= (" "); } // for j returnString+= "\n"; } // for i return returnString; } //toStringBingoCard public static boolean winner(boolean[][] called){ boolean iAmAWinner = true; // winner in a row? for (int i=0;i&lt;5;i++) { for (int j=0;j&lt;5;j++) iAmAWinner &amp;= called[i][j]; if(iAmAWinner) return true; else iAmAWinner= true; } //for // winner in a column? for (int i=0;i&lt;5;i++) { for (int j=0;j&lt;5;j++) iAmAWinner &amp;= called[j][i]; if(iAmAWinner) return true; else iAmAWinner= true; } //for // winner in a diagonal? iAmAWinner=true; for (int i=0;i&lt;5;i++) iAmAWinner &amp;= called[i][i]; if(iAmAWinner) return true; iAmAWinner=true; for (int i=4;i&gt;=0;i--) iAmAWinner &amp;= called[i][4-i]; if(iAmAWinner) return true; return false; } </code></pre>
[]
[ { "body": "<p>Your choice of classes to split the code in to is a little off, in my opinion. I would create three classes and an interface...</p>\n\n<p>The interface would look like this:</p>\n\n<pre><code>package bingo;\n\npublic interface BingoCardListener {\n public void setup(String name, int columns, int rows, int[][] values);\n public void called(int col, int row, int value);\n public void complete(boolean winner);\n}\n</code></pre>\n\n<p>This is used by the <code>BingoCard</code> class to tell anyone who's interested in what is happening to it.</p>\n\n<p>The three classes I would have are:</p>\n\n<ol>\n<li><code>BingoMain</code> -> The <code>main()</code> method, and the control flow for selecting (and notifying) numbers.</li>\n<li><code>BingoCard</code> -> This controls what the card state is. Changes to the state will be communicated to any listeners.</li>\n<li><code>BingoCardPanel</code> -> This is the visual representation of the <code>BingoCard</code>. It implements the <code>BingoCardListener</code> interface.</li>\n</ol>\n\n<p>I have taken the liberty of adding 5 cards (and their panels) to the system. It makes the logic for why things are done this way more sensible.</p>\n\n<p>I have messed around with a few things in your code, but here are the three classes I have. Note, each <code>BingoCard</code> class chooses its own values, and manages its own state. The logic about what is selected and whether it wins or not is completely contained within <code>BingoCard</code>.</p>\n\n<p><code>BingoCardPanel</code> is purely a display tool. It does not contain any Bingo logic, but it changes the display state to match the <code>BingoCard</code>.</p>\n\n<p><code>BingoMain</code> is the main method only (and some constants).</p>\n\n<p>I have put everything in the package 'bingo'.</p>\n\n<p>The BingoCard class is a logical place to start:</p>\n\n<pre><code>package bingo;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Random;\n\npublic class BingoCard {\n\n public static int[] randomCol(int startValue, final int cols, final int rows, final int colrange){\n // this method essentially chooses 5 random values from a set of 15.\n int[] candidates = new int[colrange];\n for (int i = 0; i &lt; candidates.length; i++) {\n candidates[i] = startValue + i;\n }\n // shuffle the candidates. If only there was an Arrays.shuffle(...).\n final Random rand = new Random(System.nanoTime());\n // Fischer-Yates shuffle.\n // http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\n int i = candidates.length;\n while (--i &gt; 0) {\n int tmp = candidates[i];\n int swap = rand.nextInt(i + 1);\n candidates[i] = candidates[swap];\n candidates[swap] = tmp;\n }\n // pull the first count values from the suffled result.\n return Arrays.copyOf(candidates, rows);\n }\n\n private final boolean[][] called; // = new boolean[COLS][ROWS];\n private int remaining; // how many values need to be called....\n private final int[][] values; // = new int[COLS][];\n private final String name;\n private final ArrayList&lt;BingoCardListener&gt; listeners = new ArrayList&lt;&gt;();\n private final int rows, cols;\n\n public BingoCard(final String name, final int columns, final int rows, final int colrange) {\n this.name = name;\n this.cols = columns;\n this.rows = rows;\n called = new boolean[columns][rows];\n called[columns / 2][rows / 2] = true;\n remaining = columns * rows - 1;\n values = new int[columns][];\n for (int i = 0; i &lt; columns; i++) {\n values[i] = randomCol((i * colrange) + 1, columns, rows, colrange);\n }\n }\n\n public void addListener(BingoCardListener listener) {\n listeners.add(listener);\n\n // listener has been added. Let's catch it up with our current state.\n listener.setup(name, cols, rows, values);\n\n for (int c = 0; c &lt; called.length; c++) {\n for (int r = 0; r &lt; called[c].length; r++) {\n if (called[c][r]) {\n listener.called(c, r, values[c][r]);\n }\n }\n }\n }\n\n public boolean called(final int col, final int value) {\n for (int r = 0; r &lt; values[col].length; r++) {\n if (values[col][r] == value) {\n // we have a match;\n if (!called[col][r]) {\n called[col][r] = true;\n remaining--;\n for (BingoCardListener listener : listeners) {\n listener.called(col, r, value);\n }\n } else {\n System.out.println(\"For some reason value \" + value + \" has been called multiple times\");\n }\n }\n }\n return remaining &lt;= 0;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (int r = 0; r &lt; rows; r++) {\n for (int c = 0; c &lt; cols; c++) {\n if (called[c][r]) {\n sb.append(String.format(\" &lt; %02d &gt; \", values[c][r]));\n } else {\n sb.append(String.format(\" %02d \", values[c][r]));\n }\n }\n sb.append(\"\\n\");\n }\n sb.setLength(sb.length() - 1);\n return sb.toString();\n }\n\n public void gameOver() {\n for (BingoCardListener listener : listeners) {\n listener.complete(remaining &lt;= 0);\n }\n }\n\n}\n</code></pre>\n\n<p>The <code>toString()</code> method is perhaps the most complicated ... ;-) Kidding, the <code>randomCol()</code> method is the most complex, but there are other ways to do it and I don't like converting <code>int</code>s to <code>Integer</code>s and messing with <code>Collections.shuffle()</code> when I don't have to.</p>\n\n<p>The <code>BingoCardPanel</code> is the next logical thing to show. It is actually quite simple, when you get around the fact that it really only contains a 2D array of Labels. The order the array is initialized is row-at-a-time. This is different to the <code>BingoCard</code> which does things column-at-a-time. This is OK, though, and makes sense for displaying things...</p>\n\n<p>Really there's nothing complicated in this class except for a potential bug if you ever use more than 5 columns (<code>\"BINGO\".substring(6,1)</code> will fail - fix it):</p>\n\n<pre><code>package bingo;\n\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.GridLayout;\n\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.SwingConstants;\nimport javax.swing.SwingUtilities;\nimport javax.swing.plaf.basic.BasicBorders;\n\npublic class BingoCardPanel extends JPanel implements BingoCardListener {\n\n private final JPanel valuepanel = new JPanel();\n private final JLabel namelabel = new JLabel(\"Unknown\");\n private JLabel[][] labels = null;\n\n public BingoCardPanel() {\n super();\n setBorder(BasicBorders.getInternalFrameBorder());\n setLayout(new BorderLayout(0, 5));\n add(namelabel, BorderLayout.PAGE_START);\n add(valuepanel, BorderLayout.CENTER);\n }\n\n @Override\n public void setup(String name, int columns, int rows, int[][] values) {\n namelabel.setText(name);\n namelabel.setHorizontalAlignment(SwingConstants.CENTER);\n GridLayout layout = new GridLayout(rows + 1, columns, 5, 5);\n\n String bingo = \"BINGO\";\n for (int i = 0; i &lt; columns; i++) {\n JLabel label = new JLabel(bingo.substring(i, i+1));\n label.setHorizontalAlignment(SwingConstants.CENTER);\n valuepanel.add(label);\n }\n valuepanel.setLayout(layout);\n labels = new JLabel[columns][rows];\n for (int r = 0; r &lt; rows; r++) {\n for (int c = 0; c &lt; columns; c++) {\n labels[c][r] = new JLabel(\"\" + values[c][r]);\n labels[c][r].setHorizontalAlignment(SwingConstants.CENTER);\n valuepanel.add(labels[c][r]);\n }\n }\n\n }\n\n @Override\n public void called(final int col, final int row, int value) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n labels[col][row].setOpaque(true);\n labels[col][row].setBackground(Color.GREEN);\n }\n });\n\n }\n\n @Override\n public void complete(final boolean winner) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n setBackground(winner ? Color.GREEN : Color.RED);\n }\n });\n }\n\n}\n</code></pre>\n\n<p>Finally, <code>BingoMain</code> does the control loops. I have added some validation, and other controls. Note, it is now only a single main method.</p>\n\n<pre><code>package bingo;\nimport java.awt.Container;\nimport java.awt.GridLayout;\n\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\n\n\n\npublic class BingoMain extends JFrame {\n\n private static final int ROWS = 5;\n private static final int COLS = 5;\n private static final int MAX_BINGO = 15 * COLS;\n\n public static void main (String[] args) throws InterruptedException {\n\n// \"BINGO\".substring(6,1);\n\n JFrame myBingoGUI=new JFrame();\n myBingoGUI.setSize(600, 600);\n myBingoGUI.setLocation(100, 100);\n myBingoGUI.setTitle(\"BINGO\");\n myBingoGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n Container myContentPane = myBingoGUI.getContentPane();\n myContentPane.setLayout(new GridLayout(0, 4));\n\n BingoCard[] cards = new BingoCard[5];\n for (int i = 0; i &lt; cards.length; i++) {\n cards[i] = new BingoCard(\"Card \" + (i + 1), COLS, ROWS, MAX_BINGO / COLS);\n BingoCardPanel cpanel = new BingoCardPanel();\n cards[i].addListener(cpanel);\n myContentPane.add(cpanel);\n }\n\n myBingoGUI.setVisible(true);\n\n System.out.println(cards[0]);\n System.out.println();\n /*\n * Play the game: \n */\n boolean winner = false;\n while (!winner) {\n String error = \"\";\n int calledValue = -1;\n int calledColumn=-1;\n do {\n String calledNumber = JOptionPane.showInputDialog(null, error + \" Enter a BINGO call:\");\n error = \"\";\n calledColumn = -1;\n calledValue = -1;\n\n if (calledNumber == null) {\n Thread.sleep(5000);\n error = \"Cancelled... \";\n continue;\n }\n /*\n * The first character of the input string is converted to a column number between 0 and 4\n */\n if (Character.toUpperCase(calledNumber.charAt(0))=='B') calledColumn=0;\n if (Character.toUpperCase(calledNumber.charAt(0))=='I') calledColumn=1;\n if (Character.toUpperCase(calledNumber.charAt(0))=='N') calledColumn=2;\n if (Character.toUpperCase(calledNumber.charAt(0))=='G') calledColumn=3;\n if (Character.toUpperCase(calledNumber.charAt(0))=='O') calledColumn=4;\n if (calledColumn &lt; 0) {\n error = \"Called Column '\" + Character.toUpperCase(calledNumber.charAt(0)) + \"' must be one of BINGO\";\n } else {\n /*\n * The remainder of the input string is converted to an integer\n */\n try {\n calledValue = Integer.parseInt(calledNumber.substring(1,calledNumber.length()));\n if (calledValue &lt; 1 || calledValue &gt; MAX_BINGO) {\n error = \"Illegal value \" + calledValue + \" (1 &lt;= value &lt;= \" + MAX_BINGO + \")\";\n }\n } catch (NumberFormatException nfe) {\n error = \"Illegal number \" + calledNumber.substring(1,calledNumber.length());\n }\n }\n } while (error.length() != 0);\n /*\n * The matrix of called numbers is update to show the number has been called.\n */\n for (BingoCard card : cards) {\n if (card.called(calledColumn, calledValue)) {\n winner = true;\n }\n }\n if (winner) {\n for (BingoCard card : cards) {\n card.gameOver();\n }\n }\n System.out.println(cards[0]);\n System.out.println();\n\n } // while\n\n } // main\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T00:34:34.170", "Id": "60685", "Score": "0", "body": "very helpful thank you. Was able to start most of it. I am trying to add file and quit buttons at the top of the window in a menuBar. I can get the file and quit buttons on, but I am having trouble adding the listener, partly because I am not sure where in the code or class it would go. I would post the code I'm trying to use but not sure how. Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T03:31:10.660", "Id": "35148", "ParentId": "35131", "Score": "3" } }, { "body": "<h2>Review of Existing Code</h2>\n\n<ul>\n<li><strong>Not object oriented:</strong> As you probably already realize, your code is written in a procedural style, not object-oriented, which is the norm in Java. You can tell because every function is <code>static</code>. Note that although you declared <code>public class Bingo extends JFrame</code>, it runs just the same if you remove <code>extends JFrame</code>. What's actually happening is that your <code>myBingoGUI</code> is the <code>JFrame</code>.</li>\n<li><strong>Prefer unboxed types:</strong> Unless you have a good reason to use boxed types (<code>Integer</code>), you should use the unboxed primitive instead (<code>int</code>). Boxed types make your code clumsy and incur unnecessary overhead. Although you do need to use an <code>ArrayList&lt;Integer&gt;</code> to take advantage of <code>Collections.shuffle()</code> while randomizing the board, I would still store the board using an unboxed <code>int[][]</code>.</li>\n<li><p><strong>Initialization of <code>called</code>:</strong> This takes less code:</p>\n\n<pre><code>boolean[][] called = new boolean[5][5];\ncalled[5/2][5/2] = true;\n</code></pre></li>\n<li><strong>Helper functions should be <code>private</code>:</strong> Some of your functions are obviously intended for internal use only — for example, <code>fillRow()</code>, <code>randomize()</code>, <code>putRowInBingoCard()</code>. You would never want any other code to call <code>putRowInBingoCard()</code>, so mark it <code>private</code> instead of <code>public</code>. That goes for <code>randomize()</code> too — even though the function has some conceivable general utility, you wouldn't want to let a hypothetical Blackjack game use <code>Bingo.randomize()</code>, so don't expose it.</li>\n<li><strong>Misnomer:</strong> <code>fillRow()</code> and <code>putRowInBingoCard()</code> actually work on a column, not a row.</li>\n<li><strong>Dead code:</strong> <code>printBingoCard()</code> is never used. Likewise with <code>printArray()</code>, as you noted.</li>\n<li><p><strong>Simplification:</strong> The code to assign <code>calledColumn</code> and <code>calledValue</code> is unnecessarily verbose. The following is equivalent:</p>\n\n<pre><code>int calledColumn = \"BINGO\".indexOf(Character.toUpperCase(calledNumber.charAt(0)));\nint calledValue = Integer.parseInt(calledNumber.substring(1));\n</code></pre></li>\n<li><p><strong>Error handling:</strong> If you input an empty string, it crashes with a <code>StringIndexOutOfBoundsException</code>. If you give it just a number, it crashes with an <code>ArrayIndexOutOfBoundsException</code>. If you hit \"Cancel\" in the input dialog, it crashes with a <code>NullPointerException</code>. (I would expect it to exit gracefully — call <code>dispose()</code> on the frame and <code>break</code> from the loop.)</p></li>\n<li><strong>Use a <code>StringBuilder</code>:</strong> For repeated concatenation, use a <code>StringBuilder</code> for efficiency.</li>\n<li><strong>Naming convention for predicates:</strong> In Java, a convention is to name a method <code>isSomething()</code> if the method takes no arguments, performs a test with no side effects, and returns a boolean. Therefore, you should rename <code>winner()</code> to <code>isWinner()</code>.</li>\n</ul>\n\n<h2>OOP Refactoring: First step</h2>\n\n<p>Notice that you pass the arrays <code>bingoCard</code> and <code>called</code> nearly everywhere. That is the state that should be stored as instance variables in a <code>BingoCard</code> object. I'll provide an outline of a <code>BingoCard</code> class for you to fill in:</p>\n\n<pre><code>public class BingoCard {\n private int[][] numbers;\n private boolean[][] called;\n\n public BingoCard() {\n numbers = new int[5][5];\n called = new boolean[5][5];\n called[5/2][5/2] = true;\n\n // Fill in numbers randomly as appropriate\n ...\n }\n\n public String toString() {\n ...\n }\n\n public boolean isWinner() {\n ...\n }\n\n public void mark(String calledNumber) throws IllegalArgumentException {\n ...\n }\n\n // Let's keep this here for now...\n public static void main (String[] args) {\n BingoCard card = new BingoCard();\n\n JFrame myBingoGUI;\n myBingoGUI=new JFrame();\n myBingoGUI.setSize(250, 250);\n myBingoGUI.setLocation(400, 400);\n myBingoGUI.setTitle(\"BINGO\");\n myBingoGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n myBingoGUI.setVisible(true);\n Container myContentPane = myBingoGUI.getContentPane();\n JTextArea myTextArea = new JTextArea();\n myTextArea.setFont(new Font(\"Monospaced\", Font.PLAIN,14));\n myContentPane.add(myTextArea);\n\n myTextArea.setText(card.toString());\n System.out.println(card);\n\n // Play the game: \n String error = \"\";\n String calledNumber = null;\n while (!card.isWinner() &amp;&amp;\n null != (calledNumber = JOptionPane.showInputDialog(null, error + \"Enter a BINGO call:\")) {\n try {\n card.mark(calledNumber);\n error = \"\";\n } catch (IllegalArgumentException badCall) {\n error = \"Invalid input: \" + badCall.getMessage() + \"\\n\";\n }\n\n // Print the updated BINGO card.\n myTextArea.setText(card.toString());\n System.out.println(card);\n\n }\n if (card.isWinner()) {\n myTextArea.append(\"\\n\\nBINGO!!\");\n }\n if (null == calledNumber) {\n myBingoUI.dispose();\n }\n }\n}\n</code></pre>\n\n<p>If you need to, you can add helper methods. Remember, however, such helper methods should not be part of the class's interface, and should therefore be marked <code>private</code>. (Personally, I don't think that helpers are needed, when about a dozen lines of code in the constructor would suffice.)</p>\n\n<h2>Second Step: Separate UI from Model</h2>\n\n<p>The purpose of the <code>BingoCard</code> class is to represent the state of a card. The next step is to purge UI code from <code>BingoCard</code>. You should then be able to reuse the same <code>BingoCard</code> for a text console UI, a Swing UI, or a web-based UI.</p>\n\n<p>The <code>BingoCard</code> and its UI should be loosely coupled. The UI needs to know when the state of a <code>BingoCard</code> has changed, so that it can redraw it. A common mechanism for this communication is to use a <strong>listener</strong>. Augment <code>BingoCard</code> with the following members:</p>\n\n<pre><code>public class BingoCard {\n public static interface Listener {\n void handleBingoCardChanged(BingoCard card);\n }\n\n private HashSet&lt;Listener&gt; listeners = new HashSet&lt;Listener&gt;;\n\n // ... the previously developed the BingoCard code here ...\n\n public void addListener(Listener l) {\n this.listeners.add(l);\n }\n\n public void removeListener(Listener l) {\n this.listeners.remove(l);\n }\n\n private void fireChangeEvent() {\n for (Listener l : this.listeners) {\n l.handleBingoCardChanged(this);\n }\n }\n}\n</code></pre>\n\n<p>You should be able to figure out where to call <code>fireChangeEvent()</code>.</p>\n\n<p>Then you can implement the UI as</p>\n\n<pre><code>public class BingoUI extends JFrame implements BingoCard.Listener {\n private JTextArea textArea;\n\n public BingoUI(BingoCard card) {\n // Rough outline\n this.setSize(...);\n ...\n this.textArea = new JTextArea();\n card.addChangeListener(this);\n this.textArea.setText(card.toString());\n }\n\n public void handleBingoCardChanged(BingoCard card) {\n this.textArea.setText(card.toString());\n if (card.isWinner()) {\n this.textArea.append(\"\\n\\nBINGO!!\");\n }\n }\n}\n</code></pre>\n\n<p>At this point, you could implement a <code>main()</code> method in <code>BingoUI</code>. The initialization code will be much shorter, since you'll simply be calling the <code>BingoCard</code> and <code>BingoUI</code> constructors. The main loop will be not much different.</p>\n\n<h2>Generalizing to Multiple Players</h2>\n\n<p>I'll leave you with a challenge to implement a two-player game:</p>\n\n<pre><code>public class BingoMain {\n public BingoMain(int players) { ... }\n public void play() { ... }\n\n public static void main(String[] args) {\n new BingoMain(2).play();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T09:57:24.473", "Id": "56920", "Score": "0", "body": "Sanity check: When you're done, `BingoCard` should only need to import `java.util.*`; `BingoUI` should only need to import `java.awt.*` and `javax.swing.*`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T03:43:19.733", "Id": "57356", "Score": "0", "body": "I don't really see, using what you call boxed types, as being clumsy. I can possible see it having extra overhead at runtime, but question if it has that much of an impact. I think this is more a personal preference thing, but I'm willing to be persuaded otherwise. Of coarse, I'm just nit picking a bit here, as either way doesn't hurt, in my opinion. Great answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T09:47:50.730", "Id": "35170", "ParentId": "35131", "Score": "8" } }, { "body": "<p>When you have a working code, even if not in ideal shape, you should not try to impose preconceived <em>architecture</em> on it. Instead make small changes that do not change behavior, but takes you to your goal one step closer, or alleviate one problem. This method of evolving code while maintaining functionality is called <strong>Refactoring</strong>.</p>\n\n<p>This is a number of small changes I made. I try give the names of automatic refactorings from Eclipse as much as I can.</p>\n\n<ol>\n<li><p>Remove <code>extend Jframe</code> from Bingo</p></li>\n<li><p>Extract method: called column parsing to <code>int calledColumnOf(String)</code> method</p></li>\n<li><p>Extract method: called value parsing to <code>int calledValueOf(String)</code> </p></li>\n<li><p>Introduce parameter object: toStringBingoCard(bingoCard, called) --> toStringBingoCard(new BingoCard(bingoCard, called))</p></li>\n<li><p>Move method: toStringBingoCard -> BingoCard.toString</p>\n\n<ul>\n<li>Copy&amp;paste (only for a moment) <code>toStringBingoCard</code> to <code>toStringBingoCard_temp</code></li>\n<li>Override <code>toString</code> as just <code>return toStringBingoCard_temp(this);</code></li>\n<li>Inline method <code>toStringBingoCard_temp</code></li>\n<li>change body of <code>toStringBingoCard</code> as jus <code>return bingoCard.toString()</code></li>\n<li>Inline method <code>toStringBingoCard</code></li>\n</ul></li>\n<li><p>Extract local variable: <code>BingoCard theBingoCard = new BingoCard(bingoCard, called)</code></p></li>\n<li><p>Remove unused method: <code>printBingoCard</code></p></li>\n<li><p>Remove unused method: <code>printArray</code></p></li>\n<li><p>Extract method: the loop that updates <code>called</code> to <code>void numberCalled(Integer[][], boolean[][] ...)</code></p></li>\n<li><p>Make <code>numberCalled</code> and instance method of <code>BingoCard</code> as with <code>toString</code> </p></li>\n<li><p>Introduce parameter object: <code>numberCalled</code> to <code>BingoNumber</code></p></li>\n<li><p>Extract method: code to get called number to <code>getCalledNumber</code></p></li>\n<li><p>Move method: getCalledNumber to a class <code>NumberCaller</code>, make it an instance method.</p></li>\n<li><p>Extract method: extract everything in the <code>main(...)</code> except initialization to a method called <code>gameLoop</code></p></li>\n<li><p>Introduce parameter object: <code>theBingoCard</code>, <code>bingoCardView</code>, <code>numberCaller</code> to <code>BingoGame</code></p></li>\n<li><p>Move method: make <code>gameLoop</code> and instance method of <code>BingoGame</code></p></li>\n<li><p>Move method: <code>getInitialCard</code> and helpers to a new class <code>BingoCardFactory</code>. </p></li>\n<li><p>Rename method: <code>getInitialCard</code> to <code>create</code>.</p></li>\n<li><p>Move method: <code>createView</code> to a new class <code>BingoViewFactory</code>. </p></li>\n<li><p>Rename method: <code>createView</code> to <code>create</code>.</p></li>\n<li><p>Encapsulate field: <code>BingoNumber</code>s fields. no setters.</p></li>\n<li><p>Encapsulate field: <code>BingoGame</code>s fields. no setters.</p></li>\n</ol>\n\n<p>End result thus far:</p>\n\n<pre><code>public class Bingo {\n public static void main(String[] args) {\n BingoCard theBingoCard = BingoCardFactory.create();\n BingoCardView bingoCardView = BingoViewFactory.creteView();\n NumberCaller numberCaller = new NumberCaller();\n\n BingoGame bingoGame = new BingoGame(theBingoCard, bingoCardView, numberCaller);\n\n bingoGame.gameLoop();\n }\n}\n\n\npublic class BingoCard {\n private Integer[][] bcard;\n private boolean[][] called;\n\n public BingoCard(Integer[][] bcard, boolean[][] called) {\n this.bcard = bcard;\n this.called = called;\n }\n\n @Override\n public String toString() {\n // former toStringBingoCard method....\n }\n\n public void numberCalled(BingoNumber bingoNumber) {\n for (int i = 0; i &lt; 5; i++)\n if (this.bcard[i][bingoNumber.getColumn()] == bingoNumber.getValue())\n this.called[i][bingoNumber.getColumn()] = true;\n }\n\n public boolean isWinner() {\n // former winner method....\n }\n}\n\n\npublic class BingoCardFactory {\n public static BingoCard create() {\n Integer[][] bingoCard = new Integer[5][5];\n boolean[][] called = new boolean[][] {\n { false, false, false, false, false },\n { false, false, false, false, false },\n { false, false, true, false, false },\n { false, false, false, false, false },\n { false, false, false, false, false } };\n\n for (int i = 0; i &lt; 5; i++) {\n Integer[] row = new Integer[15];\n fillRow(row, i * 15 + 1);\n randomize(row);\n putRowInBingoCard(bingoCard, i, row);\n }\n\n BingoCard theBingoCard = new BingoCard(bingoCard, called);\n return theBingoCard;\n }\n\n private static void fillRow(Integer[] theRow, int startValue) {\n for (int i = 0; i &lt; 15; i++)\n theRow[i] = new Integer(startValue++);\n }\n\n private static void randomize(Integer[] theArray) {\n Collections.shuffle(Arrays.asList(theArray));\n }\n\n private static void putRowInBingoCard(Integer[][] card, int column,\n Integer[] row) {\n for (int i = 0; i &lt; 5; i++)\n card[i][column] = row[i];\n }\n\n}\n\npublic class BingoCardView {\n private JTextArea myTextArea;\n\n public BingoCardView(JTextArea myTextArea) {\n this.myTextArea = myTextArea;\n }\n\n public void updateBingoCardView(BingoCard theBingoCard) {\n this.myTextArea.setText(theBingoCard.toString());\n }\n public void showWinMessage() {\n this.myTextArea.append(\"\\n\\nBINGO!!\");\n }\n}\n\npublic class BingoGame {\n private BingoCard bingoCard;\n private BingoCardView bingoCardView;\n private NumberCaller numberCaller;\n\n public BingoGame(BingoCard bingoCard, BingoCardView bingoCardView,\n NumberCaller numberCaller) {\n //......\n }\n\n public void gameLoop() {\n this.bingoCardView.updateBingoCardView(this.bingoCard);\n\n while (!this.bingoCard.isWinner()) {\n BingoNumber bingoNumber = this.numberCaller.getCalledNumber();\n this.bingoCard.numberCalled(bingoNumber);\n\n this.bingoCardView.updateBingoCardView(this.bingoCard);\n System.out.println(this.bingoCard.toString());\n\n } \n this.bingoCardView.showWinMessage();\n }\n}\n\npublic class BingoNumber {\n private int column;\n private int value;\n\n public BingoNumber(int column, int value) {\n this.column = column;\n this.value = value;\n }\n\n public int getColumn() {\n return column;\n }\n\n public int getValue() {\n return value;\n }\n}\n\npublic class BingoViewFactory {\n public static BingoCardView creteView() {\n JFrame myBingoGUI;\n myBingoGUI = new JFrame();\n myBingoGUI.setSize(250, 250);\n myBingoGUI.setLocation(400, 400);\n myBingoGUI.setTitle(\"BINGO\");\n myBingoGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n myBingoGUI.setVisible(true);\n Container myContentPane = myBingoGUI.getContentPane();\n JTextArea myTextArea = new JTextArea();\n myTextArea.setFont(new Font(\"Monospaced\", Font.PLAIN, 14));\n myContentPane.add(myTextArea);\n BingoCardView bingoCardView = new BingoCardView(myTextArea);\n return bingoCardView;\n }\n\n}\n\npublic class NumberCaller {\n public BingoNumber getCalledNumber() {\n String calledNumber = JOptionPane.showInputDialog(null,\n \"Enter a BINGO call:\");\n int calledColumn = calledColumnOf(calledNumber);\n int calledValue = calledValueOf(calledNumber);\n\n BingoNumber bingoNumber = new BingoNumber(calledColumn, calledValue);\n return bingoNumber;\n }\n\n private static int calledValueOf(String calledNumber) {\n int calledValue = Integer.parseInt(calledNumber.substring(1,\n calledNumber.length()));\n return calledValue;\n }\n\n private static int calledColumnOf(String calledNumber) {\n int calledColumn = -1;\n if (Character.toUpperCase(calledNumber.charAt(0)) == 'B')\n calledColumn = 0;\n if (Character.toUpperCase(calledNumber.charAt(0)) == 'I')\n calledColumn = 1;\n if (Character.toUpperCase(calledNumber.charAt(0)) == 'N')\n calledColumn = 2;\n if (Character.toUpperCase(calledNumber.charAt(0)) == 'G')\n calledColumn = 3;\n if (Character.toUpperCase(calledNumber.charAt(0)) == 'O')\n calledColumn = 4;\n return calledColumn;\n }\n}\n</code></pre>\n\n<p><strong>We can go on still much further.</strong> There still remains many things to be fixed. But in this state each code snippet is still recognizable from the original, to me at least.</p>\n\n<p>Note, keeping to single responsibility principle, we ended up with more classes than initially asked for.</p>\n\n<p>Separating classes according to functionality allows us to further modify our program more easily.</p>\n\n<p>See for example, how easy would it be to change the view to use console instead of a JFrame.</p>\n\n<p>A view does not <em>extend</em> <code>JFrame</code> or anything. It can be a frame, many frames, just console, or a network server. We do not know or care.</p>\n\n<p>Same goes for the number caller also. It is quite easy to re-imagine this program as one of the clients of a server, where numbers are called centrally.</p>\n\n<p>Next on the refactoring list should be, before altering behavior, extracting interfaces of these classes, such that it follows LID part of <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID principles</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T10:17:28.147", "Id": "59028", "Score": "0", "body": "I might have got bored and skipped some steps. I can explaing any steps that you cannot follow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T10:15:04.807", "Id": "36123", "ParentId": "35131", "Score": "3" } } ]
{ "AcceptedAnswerId": "36123", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T20:59:04.643", "Id": "35131", "Score": "5", "Tags": [ "java", "object-oriented", "game" ], "Title": "How to split this Bingo game into 3 separate classes?" }
35131
<p>If you write a VS extension, you can get access to VS services with the IServiceProvider interface:</p> <pre><code>var vsUIShell = (IVsUIShell)serviceProvider.GetService(typeof(SVsVsUIShell)); vsUIShell.SetWaitCursor(); // for example </code></pre> <p>To reduce duplication every time I need this, I created a class like this:</p> <pre><code>static class VisualStudioServices { public static IVsUIShell UIShell { get { return vsUIShell.Service; } } static readonly LazyService&lt;SVsUIShell, IVsUIShell&gt; vsUIShell = new LazyService&lt;SVsUIShell, IVsUIShell&gt;(); class LazyService&lt;TService, T&gt; { static T GetService() { return (T)ServiceProvider.GlobalProvider.GetService(typeof(TService)); } readonly Lazy&lt;T&gt; serviceLazy = new Lazy&lt;T&gt;(GetService); public T Service { get { return this.serviceLazy.Value; } } } } </code></pre> <p>To add a new service to the list, I have to mention its name 8 time (assuming the Service type and the interface type are the same, which is not always true).</p> <p>I'm looking for a way to reduce this duplication further. Any suggestions?</p>
[]
[ { "body": "<p>Well, one option is to use reflection to instantiate all the static fields:</p>\n\n<pre><code> static VisualStudioServices()\n {\n var fields = typeof(VisualStudioServices).GetFields(bindingAttr: BindingFlags.Static | BindingFlags.NonPublic);\n foreach (var field in fields)\n {\n field.SetValue(null, field.FieldType.GetConstructor(Type.EmptyTypes).Invoke(new object[] { }));\n }\n }\n</code></pre>\n\n<p>That reduces the duplication of service name from 8 to 6. </p>\n\n<p>I do feel a little uncomfortable using reflection in a static ctor.</p>\n\n<p>I also think it makes the code slightly obfuscated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T21:24:06.970", "Id": "35133", "ParentId": "35132", "Score": "1" } }, { "body": "<p>Your current design will potentially make unit testing code which uses it hard. Consider making the <code>VisualStudioServices</code> class non-static and create an interface for it. You could then inject the <code>ServiceProvider</code> as a dependency rather having an implicit dependency on the static <code>GlobalProvider</code>. Something like this:</p>\n\n<pre><code>interface IVisualStudioServices\n{\n IVsUIShell UIShell { get; }\n}\n\nclass VisualStudioServices : IVisualStudioServices\n{\n public IVsUIShell UIShell { get { return _VsUiShell.Service; } }\n\n private readonly LazyService&lt;SVsUIShell, IVsUIShell&gt; _VsUiShell; \n\n public VisualStudioServices(ServiceProvider serviceProvider)\n {\n _VsUiShell = new LazyService&lt;SVsUIShell, IVsUIShell&gt;(serviceProvider);\n }\n\n class LazyService&lt;TService, T&gt;\n {\n ServiceProvider _ServiceProvider;\n LazyService(ServiceProvider serviceProvider)\n {\n _ServiceProvider = serviceProvider;\n }\n\n readonly Lazy&lt;T&gt; serviceLazy = new Lazy&lt;T&gt;(() =&gt; (T)_ServiceProvider.GetService(typeof(TService)));\n\n public T Service { get { return serviceLazy.Value; } }\n }\n}\n</code></pre>\n\n<p>Any code requiring access to it should have a dependency on <code>IVisualStudioServices</code> which can be easily mocked out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T23:15:37.480", "Id": "56894", "Score": "0", "body": "Yeah, unit testing is a valid concern. At least the \"before\" code was no worse. And as usual, difficult-to-test equals needs-refactoring, and your suggestion is a good first step. However, at this point, I'm happy with the ease of use of making everything static. If I really do need to redirect services for testing, I'll probably do something like `class VSS { public static ServiceProvider ServiceProvider = ServiceProvider.GlobalProvider }`, at least until the rest of the code improves." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T22:18:23.167", "Id": "35138", "ParentId": "35132", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T21:10:22.417", "Id": "35132", "Score": "2", "Tags": [ "c#", "visual-studio" ], "Title": "Reduce duplication while accessing Visual Studio services" }
35132
<p>I've made this script the other day, and I need some input from you telling me how could I improve the code / style. There aren't problems with the code (it does the job) but I want it more organized and "simple" so that in 1 week I still remember what the hell was I thinking!</p> <p>The problem was: I needed a program that moves for me some files, particularly, some video files, from one directory to another. All the video files are about Tv Shows, so they have this format:</p> <p>Showname.SxxExx.Episode Title.mp4 (where S = season and E = episode)</p> <p>But that's not it. I wanted also to create the apropriate folders for every Tv Show i moved in another directory. So if the directory "Show Name" doesn't exists, my script creates it and then checks if the season folder exists inside. If it doesn't, it creates that too and finally it moves the file.</p> <p>Here is the code: <a href="http://bpaste.net/show/148514/" rel="nofollow">http://bpaste.net/show/148514/</a></p> <pre><code>import string import glob import os import shutil import re import sys import hashlib ############################################# from colorama import Fore, Back, init init(autoreset=True) #print(Fore.RED + 'some red text') #print(Back.GREEN + 'and with a green background') #print(Style.DIM + 'and in dim text') #print(Fore.RESET + Back.RESET + Style.RESET_ALL) #print('back to normal now') #Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. #Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. #Style: DIM, NORMAL, BRIGHT, RESET_ALL # https://pypi.python.org/pypi/colorama#downloads ############################################# class TvShow(object): def __init__(self, path): self.path = path # The complete path to the video file. Example: D:\Movies\Somefolder\showname.showseason.avi self.show_name = None # This will hold the show's name. Example: "xFactor" (shit program btw) self.show_season = None # This will hold the show's season number. Example: "S06" for season 6. self.show_video_file_name = None # The complete file name. Example: "Showname.SxxExx.Xvid.avi" def create(self): #First we split the path by "\" and put it in a list. REMEMBER: Linux uses slash and not backslash. splitted_path_by_slash = string.split(self.path, "\\") #Then we get the *last* item from the list, which will hold the complete name of our video file #and put it into the TvShow's variable. self.show_video_file_name = splitted_path_by_slash[-1] #Now we split the name by dots (.) to get the show's name and season splitted_video_file_name_by_dot = string.split(self.show_video_file_name, ".") #Here we finaly assign the show name to our variable. self.show_name = splitted_video_file_name_by_dot[0] #Here we get the "SxxExx" section and put it in a string tvshow_season_and_episode = splitted_video_file_name_by_dot[1] #Now we need to split that string to extract only the "Sxx" part. temp = string.split(tvshow_season_and_episode, "E") #Finaly we assign the value of season to it's variable. self.show_season = temp[0] def checkIfValidFolder(destination, source): err = 0 if os.path.exists(destination) is True and os.path.exists(source) is True: if os.listdir(source) == []: print("The source folder exists, but directory is empty. No videos?") else: for tvshowname in os.listdir(source): if re.match(r'(?P&lt;name&gt;[^.]+)\.S(?P&lt;S&gt;\d+)E(?P&lt;E&gt;\d+)\.(?P&lt;title&gt;[^.]+)\.(?P&lt;ext&gt;.*)', tvshowname) is None: #Regex explanation: http://regex101.com/r/gG9nK2 print("The following file is not valid: " + tvshowname) err += 1 if err == 0: print("Source and Destination folders exist! Nice one!") return True else: print("Errors were found") return False #do stuff... else: if os.path.exists(source) is False: print "The " + Fore.RED + "SOURCE" + Fore.RESET + " folder, " + str(source) + ", does not appear to exist." if os.path.exists(destination) is False: print "The " + Fore.RED + "DESTINATION" + Fore.RESET + " folder, " + str( destination) + ", does not appear to exist." def md5_for_file(path, block_size=256*128, hr=True): ''' Block size directly depends on the block size of your filesystem to avoid performances issues Here I have blocks of 4096 octets (Default NTFS) ''' md5 = hashlib.md5() with open(path,'rb') as f: for chunk in iter(lambda: f.read(block_size), b''): md5.update(chunk) if hr: return md5.hexdigest() return md5.digest() def summary(folders_created, subfolders_created): print("") print("------------------------------------------------------------------") if not folders_created: print ("No new show has been added to your collection master!") print("") else: print ("") print("New show(s) added:") for item in folders_created: print item print("") print("------------------------------------------------------------------") if not subfolders_created: print ("No new season has been added master!") print("") else: print ("") print("New season(s) added:") for item in subfolders_created: print item def copyThisShit(from_dir, to_dir): i = 0 j = 0 new_fold = [] new_sub_folder = [] for filename in sorted(glob.glob(os.path.join(from_dir + "\\", '*.*'))): show = TvShow(filename) show.create() dest_show_folder = to_dir + "\\" + show.show_name if os.path.exists(dest_show_folder): dest_show_folder_season = dest_show_folder + "\\" + show.show_season if os.path.exists(dest_show_folder_season): if os.path.isfile(dest_show_folder_season + "\\" + show.show_video_file_name): print( "The file " + dest_show_folder + "\\" + show.show_season + "\\" + Back.GREEN + show.show_video_file_name + Back.RESET + " already exists. I'll SKIP it master") else: print( "The file " + dest_show_folder + "\\" + Back.RED + show.show_video_file_name + Back.RESET + " DOESN'T exist. I'll COPY it master") #shutil.copy(filename, dest_show_folder_season) copy_with_prog(filename, dest_show_folder_season + "\\" + show.show_video_file_name) print("") else: print( "The subfolder " + dest_show_folder + "\\" + Back.RED + show.show_season + Back.RESET + " DOESN'T exist. I'll create it for you master") new_sub_folder.insert(i, dest_show_folder + "\\" + Fore.MAGENTA + show.show_season + Fore.RESET) i += 1 os.mkdir(dest_show_folder_season) print ("The file " + dest_show_folder_season + "\\" + Back.RED + show.show_video_file_name + Back.RESET + " DOESN'T exist. I'll COPY it master") copy_with_prog(filename, dest_show_folder_season + "\\" + show.show_video_file_name) print("") #shutil.copy(filename, dest_show_folder_season) else: print ( "The directory " + to_dir + "\\" + Back.RED + show.show_name + Back.RESET + " DOESN'T exists. I'll create it for you master") new_fold.insert(j, to_dir + "\\" + Fore.MAGENTA + show.show_name + Fore.RESET) j += 1 i += 1 new_sub_folder.insert(i, dest_show_folder + "\\" + Fore.MAGENTA + show.show_season + Fore.RESET) os.mkdir(dest_show_folder) print("The subfolder " + dest_show_folder + "\\" + Back.RED + show.show_season + Back.RESET + " DOESN'T exist. I'll create it for you master") os.mkdir(dest_show_folder + "\\" + show.show_season) dest_show_folder_season = dest_show_folder + "\\" + show.show_season print ("The file " + dest_show_folder_season + "\\" + Back.RED + show.show_video_file_name + Back.RESET + " DOESN'T exist. I'll COPY it master") copy_with_prog(filename, dest_show_folder_season + "\\" + show.show_video_file_name) print("") #shutil.copy(filename, dest_show_folder + "\\" + show.show_season) summary(new_fold, new_sub_folder) def checkInput(): valid = False while valid is False: source_folder = raw_input("Source Video Directory?") destination_folder = raw_input("Destination Video Directory?") if checkIfValidFolder(destination_folder, source_folder) is True: valid = True print ("Everything Looks good!") copyThisShit(source_folder, destination_folder) class ProgressBar: def __init__(self, minValue = 0, maxValue = 10, totalWidth=12): self.progBar = "[]" # This holds the progress bar string self.min = minValue self.max = maxValue self.span = maxValue - minValue self.width = totalWidth self.amount = 0 # When amount == max, we are 100% done self.updateAmount(0) # Build progress bar string def updateAmount(self, newAmount = 0): if newAmount &lt; self.min: newAmount = self.min if newAmount &gt; self.max: newAmount = self.max self.amount = newAmount # Figure out the new percent done, round to an integer diffFromMin = float(self.amount - self.min) percentDone = (diffFromMin / float(self.span)) * 100.0 percentDone = round(percentDone) percentDone = int(percentDone) # Figure out how many hash bars the percentage should be allFull = self.width - 2 numHashes = (percentDone / 100.0) * allFull numHashes = int(round(numHashes)) # build a progress bar with hashes and spaces self.progBar = "[" + '#'*numHashes + ' '*(allFull-numHashes) + "]" # figure out where to put the percentage, roughly centered percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) percentString = str(percentDone) + "%" # slice the percentage into the bar self.progBar = (self.progBar[0:percentPlace] + Back.BLUE + percentString + Back.RESET + self.progBar[percentPlace+len(percentString):]) def __str__(self): return str(self.progBar) def copy_with_prog(src_file, dest_file, overwrite = False, block_size = 256*128): if not overwrite: if os.path.isfile(dest_file): raise IOError("File exists, not overwriting") # Open src and dest files, get src file size src = open(src_file, "rb") dest = open(dest_file, "wb") src_size = os.stat(src_file).st_size # Set progress bar prgb = ProgressBar(totalWidth = 79, maxValue = src_size) # Start copying file cur_block_pos = 0 # a running total of current position while True: cur_block = src.read(block_size) # Update progress bar prgb.updateAmount(cur_block_pos) cur_block_pos += block_size sys.stdout.write( '\r%s\r' % str(prgb) ) # If it's the end of file if not cur_block: # ..write new line to prevent messing up terminal sys.stderr.write('\n') break else: # ..if not, write the block and continue dest.write(cur_block) #end while # Close files src.close() dest.close() #Check MD5 of the file to see if it was copied correctly. print(Back.YELLOW + Fore.BLACK + "Checking MD5 hash..." + Fore.RESET + Back.RESET ), if md5_for_file(src_file) == md5_for_file(dest_file): print (Back.GREEN + "MD5 GOOD!" + Back.RESET) else: print (Back.RED + "MD5 BAD!" + Back.RESET) raise IOError( "The two files don't have the same MD5 code!" ) # Check output file is same size as input one! #dest_size = os.stat(dest_file).st_size # #if dest_size != src_size: # raise IOError( # "New file-size does not match original (src: %s, dest: %s)" % ( # src_size, dest_size) # ) checkInput() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-07T15:25:18.127", "Id": "126302", "Score": "0", "body": "Do you have an updated version of this script?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-08T20:24:02.467", "Id": "126475", "Score": "0", "body": "@FahadYousuf Yes, as a matter of fact I do have a well improved version of this script. It still doesn't have any error detection or handling, and it may need some tweaks from time to time, but usually I just set it up in windows scheduler and I never have to worry about it. If you are interested, leave me an email, I can share the code and explain how it works. Email: con7e@hmamail.com" } ]
[ { "body": "<p>I'm just going to mention a few quick observations rather than do a thorough review.</p>\n\n<p>You're concatenating backslashes everywhere. Use <strong><code>os.path.join()</code></strong> like you're supposed to. (The one place where you call <code>os.path.join()</code>, you're manually adding a backslash unnecessarily.) Conversely, in <code>TvShow.create()</code>, call <strong><code>os.path.split()</code></strong> instead of <code>string.split(…, \"\\\\\")</code>.</p>\n\n<p>Why does <code>TvShow</code> have an <code>__init__()</code> and a separate <code>create()</code> method? That suggests that your <code>__init__()</code> is a <strong>half-assed constructor</strong>, producing objects in a not-quite-usable state. If it's possible for objects to be in a weird state, then your class is poorly designed.</p>\n\n<p>Your <code>checkIfValidFolder()</code> does not <strong>consistently return a value</strong>. Make up your mind what it is supposed to do.</p>\n\n<p>In <code>copyThisShit()</code>, the <strong>logic is repetitive</strong>. The following flow would work better:</p>\n\n<pre><code>for filename in …:\n if not os.path.exists(to_dir):\n # Dest folder missing? Fix it!\n …\n if not os.path.exists(dest_show_folder):\n # Dest show folder missing? Fix it!\n …\n if not os.path.exists(dest_show_folder_season):\n # File not there? Fix it!\n …\n</code></pre>\n\n<p>Instead of concatenating <code>blahblah + RED + string + RESET + blah</code> all the time, find a way to call some <strong>function to set and reset the color</strong> like <code>blahblah + fgRed(string) + blah</code>. It would be cleaner and less error prone.</p>\n\n<p>You have some <strong>naming</strong> issues. <code>md5_for_file()</code> is your only function_with_underscores. <code>checkInput()</code> is a crazy name for your main function. Who would guess that <code>check…()</code> does more than just checking something? Also, \"prog\" is usually short for \"program\", I would have guessed that <code>copy_with_prog()</code> meant \"copy using a program\" (like <code>copy.exe</code> or <code>rsync</code>), not \"copy with a progress bar\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T12:16:40.497", "Id": "56932", "Score": "0", "body": "Thank you so much for all the tips! I'll make sure to follow them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T16:47:16.480", "Id": "56951", "Score": "0", "body": "If you find an answer useful, please vote it up. That's how this site works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T16:47:50.480", "Id": "56952", "Score": "0", "body": "Unfortunately, I have insufficient rep, so I am not allowed to \"upvote\" anything :(" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T11:17:04.497", "Id": "35172", "ParentId": "35137", "Score": "2" } }, { "body": "<p>I notice that you have a lot of long strings sprinkled in your code. </p>\n\n<pre><code>\" DOESN'T exists. I'll create it for you master\"\n</code></pre>\n\n<p>Put those sorts of strings into constants. I did a quick count, and you have only 3 unique strings, yet your instance count of them is 7. Oh, and one of them had a typo, which would have made it 4 unique strings, if I hadn't fixed it. How you get rid of the duplicates is up to you, however I would do it like so (as per the PEP8 standard):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>N_EX_COPY_CONST = \" DOESN'T exist. I'll COPY it master\"\nEX_SKIP_CONST = \" already exists. I'll SKIP it master\"\nN_EX_CREATE_CONST = \" DOESN'T exist. I'll create it for you master\"\n</code></pre>\n\n<p>As the poster above mentioned. You have naming issues, definitely. But they're compounded by your lack of proper use of functions/methods. Your \"copyThisShit\" function is about 50 lines long. One of the main reasons why it's so long is because it does too much. Issues with that function:</p>\n\n<ul>\n<li>You perform a large block of code on a single item. Yet you include the logic that loops through the items inside the same method. Rather, take the large block of code out as a separate method. Call it \"copyThisShittyItem\" if you like, and call it inside the loop.</li>\n<li>You seem to have repeated logic nested within itself. Is there any particular reason why you're hard-coding the structure of the data you're copying from/to? You check for a root folder, then you check for the season folder within it. Perhaps a more generic solution might work better? I can't really offer more info than that, without knowing your use case.</li>\n<li>You include an index (i and j) while going through a list. Since the order is going in one direction, and doesn't get affected by anything, you might as well just append to the list, which would save you keeping track of an index and incrementing it.</li>\n<li>Moving the main body of the copyThisShit function into a separate function will require you to pass back the \"summary\". From the looks of it, summary is a two lists of string. Either return them as a tuple, or create a simple data structure to pass them back, like your \"TvShow\" class.</li>\n<li>As per above, it becomes very important to know how to pass data around. Keeping it all in semi-global scope does make things easier, but you shoot yourself in the foot by leaving you very incapable of separating code out into smaller chunks that do one thing each.</li>\n</ul>\n\n<p>On a side note, I can recommend a really good book by Martin Fowler, called refactoring. It codifies a lot of the common concepts that go into refactoring code, and it helped me quite a bit to get rid of some of my rather bad habits when programming. <a href=\"http://rads.stackoverflow.com/amzn/click/0201485672\" rel=\"nofollow\">Here</a> is a link to the Amazon page for it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:09:56.997", "Id": "35783", "ParentId": "35137", "Score": "2" } } ]
{ "AcceptedAnswerId": "35783", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T22:14:35.643", "Id": "35137", "Score": "3", "Tags": [ "python", "optimization", "file-system" ], "Title": "Improve my script to organize a video collection" }
35137
<p>In this function, the copy (<code>Write XML</code>) is inside, but I want it to be separated from the function. How can I improve this function?</p> <pre><code>Sub ExporttoFolder(ByVal POSPath As String, ByVal dt As DataSet, ByVal FolderCopyto As String,ByVal SelectedItem As DataTable) If MsgBox("Do you want to Export Invoice to " &amp; _WhouseToComboBox.textBox.Text &amp; " ? ", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then Dim Whouse As String For Each dr As DataRow In SelectedItem.Rows Whouse = dr.Item("whouseDesc") ProcessCopy(POSPath, dt, FolderCopyto, Whouse) Next dr End If End Sub Sub ProcessCopy(ByVal targetDirectory As String, ByVal File As DataSet, ByVal FolderTarget As String, ByVal DirectoryFather As String) Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory) Dim Filepath As String = Nothing Dim subdirectory As String For Each subdirectory In subdirectoryEntries Try If Path.GetFileName(subdirectory) = DirectoryFather Then If IO.Directory.Exists(subdirectory &amp; "\" &amp; FolderTarget) Then File.WriteXml(subdirectory &amp; "\" &amp; FolderTarget &amp; "\" &amp; File.Tables(0).Rows(0).Item("InvoiceID") &amp; ".xml") End If End If ProcessCopy(subdirectory, File, FolderTarget, DirectoryFather) Catch ex As Exception End Try Next subdirectory End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T04:33:55.130", "Id": "56906", "Score": "0", "body": "Why is `ProcessCopy` recursive? Can you give an example of what the folder structure looks like?" } ]
[ { "body": "<blockquote>\n <p>In this function, the copy (Write XML) is inside, but I want it to be separated from the function.</p>\n</blockquote>\n\n<p><H2>Shallow Observations</H2></p>\n\n<p>In no particular order:</p>\n\n<ul>\n<li><strong>You need to <em>indent</em> your code</strong>, it makes it much easier to read. Give that <kbd>Tab</kbd> button some lovin'!</li>\n<li><strong>Exceptions are like urine samples</strong>: there's a lot of information in there to analyze if and when you need to, and the last thing you want to do is to swallow them.</li>\n</ul>\n\n<hr>\n\n<p><H2>Separation of Concerns</H2></p>\n\n<p>I think both procedures do more than they claim. Let's break down what needs to happen:</p>\n\n<ul>\n<li>Prompt the user for confirmation, do nothing without user's consent.</li>\n<li>Get the names of all target folders.</li>\n<li>Find the destination folders.</li>\n<li>Determine the name of the file.</li>\n<li>Write the file.</li>\n</ul>\n\n<p><H3>Implementation</H3></p>\n\n<p><strong>Prompt the user for confirmation, do nothing without user's consent</strong></p>\n\n<p>Asking for user confirmation before exporting stuff is probably a good idea. This doesn't mean the actual prompting needs to happen in the method that performs the actual export. Consider this:</p>\n\n<pre><code>Public Function GetUserConfirmation(ByVal prompt As String) As Boolean \n Return (MsgBox(prompt, MsgBoxStyle.YesNo) = MsgBoxResult.Yes)\nEnd If\n</code></pre>\n\n<p>Yes, it's a one-liner. That doesn't make it less of a useful function. We don't <em>really</em> care about <code>MsgBoxResult</code>, we just want to know if the user answered <kbd>Yes</kbd> to a question. This function <em>abstracts away</em> the <code>MsgBox</code> call and the need for knowing about <code>MsgBoxResult</code>, which makes it much more <code>If</code>-friendly - whether you're reading:</p>\n\n<pre><code>If GetUserConfirmation(confirmationMessage) Then\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>If Not GetUserConfirmation(confirmationMessage) Then\n</code></pre>\n\n<p>You know exactly what's going on and you don't need to worry about how it's implemented.</p>\n\n<p>Now in your code, this would translate to:</p>\n\n<pre><code>Sub ExportToFolder() 'parameters omitted\n If GetUserConfirmation(confirmationMessage) Then\n ' do all that stuff\n End If\nEnd Sub\n</code></pre>\n\n<p>I think this is a bad construct, it <em>smells</em> like the code in the <code>If</code> statement is begging you to be surrounding a call to that method, so you can do this:</p>\n\n<pre><code>If GetUserConfirmation(confirmationMessage) Then ExportToFolder 'parameters omitted\n</code></pre>\n\n<p>And have <code>ExportToFolder</code> look like that:</p>\n\n<pre><code>Sub ExportToFolder() 'parameters omitted\n ' do all that stuff\nEnd Sub\n</code></pre>\n\n<p>This means the logic that grabs an instance variable to come up with the prompt message is also moved outside of the method. Actually by doing this we have just separated the concerns of <em>coming up with a prompt message</em> and <em>prompting the user with some message</em>.</p>\n\n<p>So we've got user confirmation. One down.</p>\n\n<p><strong>Get the names of all target folders</strong></p>\n\n<p>We have some <code>DataTable</code> that represents a <em>selected item</em> which contains a column called <code>\"whouseDesc\"</code> which is the name of the \"parent\" folder we want to use. Your code knows about a lot of things it doesn't need to be bothered with: in fact all this <code>DataTable</code> boilerplate just doesn't belong there. The method doesn't <em>want</em> a <code>DataTable</code>, it <em>needs</em> what's it in.</p>\n\n<p>I would replace <code>SelectedItem As DataTable</code> with <code>TargetSubfolderNames As IEnumerable(Of String)</code>, it makes the intent much clearer: we need an enumerable bunch of folder names, and we're going to expect they're the names of subfolders of a target folder.</p>\n\n<p>Reading the <code>DataTable</code> that contains the folder names is out of scope here.</p>\n\n<p>The procedure now looks like this, notice how much more focused it's starting to be:</p>\n\n<pre><code>Sub ExportToFolder(ByVal POSPath As String, _\n ByVal dt As DataSet, _\n ByVal FolderCopyto As String, _\n ByVal TargetSubfolderNames As IEnumerable(Of String))\n\n Dim subfolderName As String\n For Each subfolderName In TargetSubfolderNames\n ProcessCopy(POSPath, dt, FolderCopyTo, subfolderName)\n Next\n\nEnd Sub\n</code></pre>\n\n<p><strong>Find the destination folder</strong></p>\n\n<p><code>ExportToFolder</code> takes the <code>POSPath</code> parameter only to pass it down to <code>ProcessCopy</code> at each iteration. It's the same folder every time you call <code>ProcessCopy</code>, and yet every time the method runs, you're fetching the subdirectories <em>and looping through all of them</em> every time, verifying if the target folder exists under that subdirectory. I'm exhausted, aren't you?</p>\n\n<p>If each call to <code>ExportToFolder()</code> exports stuff into 1 file in 1 folder, then it's not exactly clear why you're looping directories here, why the method is recursive, and how you're coming up with the filename.</p>\n\n<p>My guess is that you want to be sure you're writing to a directory that exists. That's fine, but if there's only 1 file to write to, you're over-complicating it.</p>\n\n<p><strong>Determine the name of the file</strong></p>\n\n<p>If I understand correctly, you know the full file name from the start, and given <code>InvoiceId</code> which is <code>dt.Tables(0).Rows(0).Item(\"InvoiceID\")</code> this would be your file name:</p>\n\n<pre><code>Path.Combine(Whouse, FolderCopyTo) + InvoiceId + \".xml\"\n</code></pre>\n\n<p>So we can have a <code>GetExportXmlFileName</code> function that does it, and that can return an empty string if the folder doesn't exist:</p>\n\n<pre><code>Function GetExportXmlFileName(ByVal ParentFolder As String, ByVal TargetFolder As String, ByVal InvoiceId As String) As String\n\n Dim result = String.Format(\"{0}.xml\", _\n Path.Combine(ParentFolder, TargetFolder), _\n InvoiceId)\n\n If Not Directory.Exists(Path.GetDirectoryName(result)) Then result = String.Empty\n\nEnd Function\n</code></pre>\n\n<p>Your method is starting to look like this:</p>\n\n<pre><code>Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _\n ByVal TargetFolder As String, _\n ByVal Content As DataSet)\n\n Dim SubfolderName As String, FileName As String\n Dim InvoiceId As String = Content.Tables(0).Rows(0).Item(\"InvoiceID\")\n\n For Each SubfolderName In TargetSubfolderNames\n FileName = GetExportXmlFileName(SubfolderName, TargetFolder, InvoiceId)\n If Not String.IsNullOrEmpty(FileName) Then ProcessCopy FileName, Content\n Next\n\nEnd Sub\n</code></pre>\n\n<p><strong>Write the file</strong></p>\n\n<p>At this point I'm questioning the need for <code>ProcessCopy</code> altogether:</p>\n\n<pre><code>Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _\n ByVal TargetFolder As String, _\n ByVal Content As DataSet)\n\n Dim SubfolderName As String, FileName As String\n Dim InvoiceId As String = Content.Tables(0).Rows(0).Item(\"InvoiceID\")\n\n For Each SubfolderName In TargetSubfolderNames\n FileName = GetExportFileName(SubfolderName, TargetFolder, InvoiceId)\n If Not String.IsNullOrEmpty(FileName) Then Content.WriteXml(FileName)\n Next\n\nEnd Sub\n</code></pre>\n\n<p>Let's see, if we have 4 files to export, and the 2nd one blows up, we can't try the 3rd and 4th like this - we'll have an exception to <strong>deal with</strong> (read: not swallow).</p>\n\n<pre><code>Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _\n ByVal TargetFolder As String, _\n ByVal Content As DataSet)\n\n Dim SubfolderName As String, FileName As String\n Dim InvoiceId As String = Content.Tables(0).Rows(0).Item(\"InvoiceID\")\n Dim Errors As IList(Of String) = New List(Of String)\n\n For Each SubfolderName In TargetSubfolderNames\n FileName = GetExportFileName(SubfolderName, TargetFolder, InvoiceId)\n If Not String.IsNullOrEmpty(FileName) Then \n Try\n\n Content.WriteXml(FileName)\n\n Catch ex As Exception\n Errors.Add(ex) 'fine, don't do anything with it.\n 'at least you can break and inspect it.\n End Try\n End If\n Next\n\nEnd Sub\n</code></pre>\n\n<p>This is where we can extract a method to wrap the <code>Try...Catch</code> block and, incidentally, the <code>Content.WriteXml</code> call - I'll pretend you want to log errors with an instance-level NLog logger:</p>\n\n<pre><code>Sub ExportToFile(FileName as String, Content As DataSet)\n Try\n\n Content.WriteXml(FileName)\n\n Catch ex As Exception\n _logger.ErrorException(FileName, ex)\n\n End Try\nEnd Sub\n</code></pre>\n\n<p>This last refactoring has given its final shape to the <code>ExportToFolder</code> method:</p>\n\n<pre><code>Sub ExportToFolder(ByVal TargetSubfolderNames As IEnumerable(Of String), _\n ByVal TargetFolder As String, _\n ByVal Content As DataSet)\n\n Dim SubfolderName As String, FileName As String\n Dim InvoiceId As String = Content.Tables(0).Rows(0).Item(\"InvoiceID\")\n\n For Each SubfolderName In TargetSubfolderNames\n FileName = GetExportFileName(SubfolderName, TargetFolder, InvoiceId)\n If Not String.IsNullOrEmpty(FileName) Then ExportToFile(FileName, Content)\n Next\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T23:45:56.017", "Id": "57195", "Score": "0", "body": "Thank you, your answer help me :) , but i have one more question, you have miss declared \"_Logger\" => _logger.ErrorException(FileName, ex)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T23:49:45.910", "Id": "57196", "Score": "0", "body": "@AhmadAlHalabi That's always good to read! Thank *you* for the green tick!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T23:58:27.423", "Id": "57197", "Score": "0", "body": ":) no, thank you\nbut What about \"_Logger\" => _logger.ErrorException(FileName, ex)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T00:02:51.833", "Id": "57198", "Score": "0", "body": "I was refering to [this](https://github.com/ninject/ninject.extensions.logging/wiki/Using), but that's just what *I* would do - if you don't know what to do with an exception, at least log it :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T05:34:49.663", "Id": "35153", "ParentId": "35139", "Score": "3" } } ]
{ "AcceptedAnswerId": "35153", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T22:37:49.050", "Id": "35139", "Score": "3", "Tags": [ "vb.net" ], "Title": "Improving my invoice generator" }
35139
<p>Is this reliable?</p> <p>While there are many backup programs out there, it is still hard to find free software that allows unattended differential backup on Windows. Completely rolling something from scratch is usually not the way to go and after some searching I found that 7-Zip can be utilized to achieve full and differential backups that are highly compressed. </p> <p>My goal was to create a small script that can run unattended to create full backups every 30 days and in the intervals in between create differential backups to safe space. While the script runs nicely in a few tests, I am far from being a "pythonista" and would appreciate any feedback on code quality and reliability. </p> <p>The program requires 7zip.exe in the path or current directory and requires two command line parameters, <code>--dest-dir destination_directory</code>, and the directories to be backed up given by <code>--input-dirs input_directory/ies</code>.</p> <pre><code>import os import sys import logging import argparse import subprocess from datetime import datetime, date, timedelta ARCHIVE_FILENAME_PATTERN = "py_backup_*_*.7z" FULL_ARCHIVE_PREFIX = "py_backup_full_" DIFF_ARCHIVE_PREFIX = "py_backup_diff_" MAX_DAYS_BETWEEN_FULL = 30 MAX_DAYS_FOR_DIFF = 30 logger = logging.getLogger(__name__) def parse_date_in_filename(filename): import re date_in_name_pattern = '_[0-9]{4}-[0-9]{2}-[0-9]{2}' match = re.search(date_in_name_pattern, filename) if (match): date_object = datetime.strptime(match.group(0), '_%Y-%m-%d') return (True, date_object) else: # log that we could not match this filename return (False, None) def get_valid_dir(parser, arg): if not os.path.isdir(arg): parser.error("The directory %s could not be found!" % arg) else: return arg def archive_ok(file_path): """Tests whether the archive can be sucessfully decompressed with 7zip.""" if (not os.path.isfile(file_path)): file_path = file_path + '.7z' test_command_string = u'7z.exe t ' dest_path_string = file_path full_command = test_command_string + '\"' + dest_path_string + '\" ' logger.debug("Testing archive with command: %s", full_command) encoded_form = full_command.encode(sys.getfilesystemencoding()) return_value = subprocess.call(encoded_form, shell=False) if (return_value == 0): logger.info('Backup successful') return True else: logger.warn('Archive file test failed') return False def run_backup(input_dirs, dest_dir, last_full_name, differential=False): """ Runs the actual backup using 7zip in archive or update mode.""" current_date = date.today() input_dir_string = ' '.join("\"%s\"" % x for x in input_dirs) if differential: filename = DIFF_ARCHIVE_PREFIX + str(current_date) diff_path = os.path.join(dest_dir, filename) dest_path = os.path.join(dest_dir, last_full_name) try: os.remove(diff_path + ".7z") except OSError: pass differential_command_string = u'7z.exe u ' options = " -ms=off -mx=5 -t7z -u- -up0q3r2x2y2z0w2!" full_command = differential_command_string + '\"' + dest_path + '\" ' \ + input_dir_string + options + '\"' + diff_path + '\"' else: filename = FULL_ARCHIVE_PREFIX + str(current_date) dest_path = os.path.join(dest_dir, filename) archive_command_string = u"7z.exe a " full_command = archive_command_string + '\"' + dest_path + "\" " \ + input_dir_string logger.info("Executing command: %s", full_command) encoded_form = full_command.encode(sys.getfilesystemencoding()) return_value = subprocess.call(encoded_form, shell=False) if (return_value == 0): logger.info('Backup successful') else: logger.warn('Something went wrong, return value of 7zip is %d', return_value) # 1 if directory to backup cannot be found # 2 means output file does already exist if (archive_ok(dest_path)): return True else: return False def search_backup_files(input_dirs, dest_dir): """Collects previous full and differential archives in the destination directory and sorts according to their creation date (encoded in file name) """ import glob archives_path = os.path.join(dest_dir, ARCHIVE_FILENAME_PATTERN) archive_files = glob.glob(archives_path) logger.debug('Processing archive files: %s', (' '.join(archive_files))) full_backups = [] diff_backups = [] for path in archive_files: (directory, fname) = os.path.split(path) success, file_date = parse_date_in_filename(fname) if success: if (fname.startswith(FULL_ARCHIVE_PREFIX)): full_backups.append((file_date, fname)) elif (fname.startswith(FULL_ARCHIVE_PREFIX)): diff_backups.append((file_date, fname)) else: # skip file names that are not part of this set pass full_backups.sort() diff_backups.sort() return (full_backups, diff_backups) def decide_backup(input_dirs, dest_dir, full_backups, diff_backups): """ Decides whether a full backup is required, i.e. the no full backup exists or last full backup is too old. Otherwise a differential backup is sufficient. """ differential = False # Consider a diff backup if a recent full backup is available if (len(full_backups) &gt; 0): last_full_date = full_backups[-1][0] last_full_name = full_backups[-1][1] delta = datetime.today() - last_full_date if (delta &lt; timedelta(days=MAX_DAYS_BETWEEN_FULL)): logger.info("Only differential backup required, time delta is %s", str(delta)) differential = True run_backup(input_dirs, dest_dir, last_full_name, differential) def remove_old_diffs(dest_dir, full_backups, diff_backups): """ Removes differential backup files which are older than MAX_DAYS_FOR_DIFF.""" for (file_date, filename) in diff_backups: delta = datetime.today() - file_date if (delta &gt; timedelta(days=MAX_DAYS_FOR_DIFF)): logger.info("Removing old diff-file: %s" %str(filename)) os.remove(os.path.join(dest_dir, filename)) def main(argv=None): if argv is None: argv = sys.argv parser = argparse.ArgumentParser() parser.add_argument(u"-d", u"--dest-dir", help="destination directory", required=True, type=lambda x: get_valid_dir(parser, x)) parser.add_argument(u"-i", u'--input-dirs', help="directories to be backed up", nargs='+', required=True, type=lambda x: get_valid_dir(parser, x)) parser.add_argument(u"-r", u'--remove', help="removes differential backups older than 30 days", action='store_true') args = parser.parse_args() handler = logging.FileHandler('py_backup.log', 'a', 'utf-8') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) logger.addHandler(handler) logger.setLevel(logging.DEBUG) # file names can contain non-ascii characters but windows does not use utf-8 # http://stackoverflow.com/questions/12764589/python-unicode-encoding dest_dir = args.dest_dir.decode('mbcs') input_dirs = [x.decode('mbcs') for x in args.input_dirs] (full_backups, diff_backups) = search_backup_files(input_dirs, dest_dir) decide_backup(input_dirs, dest_dir, full_backups, diff_backups) if (args.remove): remove_old_diffs(args.dest_dir, full_backups, diff_backups) if __name__ == "__main__": sys.exit(main()) </code></pre>
[]
[ { "body": "<p><strong>Code Quality</strong></p>\n\n<p><em>1. PEP8/PyLint</em>:</p>\n\n<p>Fix <a href=\"http://pep8online.com/s/YnHEYUA5\" rel=\"nofollow\">http://pep8online.com/s/YnHEYUA5</a>\nI also suggest you to read these documents:</p>\n\n<ul>\n<li><a href=\"http://www.python.org/dev/peps/pep-0008/bvm=bv.56146854,d.d2k\" rel=\"nofollow\">Python PEP8</a></li>\n<li><a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">Python docstrings</a></li>\n</ul>\n\n<p><em>2. Other improvements</em></p>\n\n<ul>\n<li>You don't need to check that \"a list is None\": you can just use <code>if not sys.argv</code>. BTW, you never use <em>argv</em>.</li>\n<li>You don't need parentheses around operators in \"if\" statements. This is Python, not Java :)</li>\n<li>Remove imports from functions.</li>\n<li>All methods should be documented. Avoid comments that could be explained in the docstrings.</li>\n<li>Don't use \"+\" to concatenate strings. Use <em>.format()</em>.</li>\n</ul>\n\n<p><strong>Code reliability.</strong></p>\n\n<p>Code has no tests. How can it be reliable? \nUse <a href=\"http://pytest.org/latest/tmpdir.html\" rel=\"nofollow\">pytest</a>.</p>\n\n<p>What if '7z.exe' is not in the SYS PATH? </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T10:46:55.953", "Id": "56925", "Score": "0", "body": "+1, but I'd recommend starting with [`unittest`](http://docs.python.org/3/library/unittest.html) (which is built into Python) and looking at third-party software like [pytest](http://pytest.org/latest/) only if the built-in facilities prove inadequate in some way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T12:01:28.017", "Id": "56930", "Score": "0", "body": "I agree. If the OP is new to tests in general pytest is too much, but pytest is very powerful (it may include pep8, pylint, ...)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-12T14:13:06.457", "Id": "57022", "Score": "0", "body": "Thank you, these are all valid points. I am currently working on implementing the suggestions. While I agree with PEP8 the 80 character limit is difficult as it requires splitting up many strings which make the code sometimes less readable. I looked into testing frameworks and went for nose, which seems easy to work with and already helped." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-12T14:29:04.973", "Id": "57025", "Score": "0", "body": "Very good that you start with nose - excellent tool! \nAlso, try to use tools like pep8/pylint - they are very important!\nPS: Yeah, the limit of 80 characters is being discussed in the pep8 draft, in particular: http://bugs.python.org/issue18472#msg193785" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T10:10:49.153", "Id": "35171", "ParentId": "35147", "Score": "2" } } ]
{ "AcceptedAnswerId": "35171", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T03:31:04.213", "Id": "35147", "Score": "5", "Tags": [ "python", "file-system" ], "Title": "Small backup script in Python based on 7-Zip" }
35147
<p>I'm trying to build a framework similar to Scrapy ItemPipelines or <a href="http://asperous.github.io/pipeless/" rel="nofollow">Pipeless</a>. The motivation is to be able to build generic data pipelines via defining a modular collection of "pipe" classes that handle distinct steps within the pipeline. I've taken some tips from <a href="http://asperous.github.io/pipeless/" rel="nofollow">here</a>. I'm looking for general feedback.</p> <h3>interfaces.py</h3> <pre><code>from zope.interface import Interface, Attribute class IPipe(Interface): """A pipe is responsible for processing a single item and yields one or more iterables """ def process_item(item): """process single item """ pass class IPipeline(Interface): """ Master pipeline interface """ pipe_runners = Attribute('a collection of pipe_runners') def run(it): """begin pipeline execution given iterable """ pass class IPipelineRunner(Interface): """Handles execution of pipe and skip item exceptions """ pipe = Attribute('single pipe being wrapped') def execute(it): """execute pipe with given iterable """ pass </code></pre> <h3>components.py</h3> <pre><code>from pipeable.interfaces import IPipeline, IPipe, IPipelineRunner from pipeable.exceptions import InvalidPipeInput, SkipPipeItem from zope.interface import implements, implementer import collections class Pipeline(object): implements(IPipeline) def __init__(self, pipes): """ """ #xxx TODO handle list of pipes of now, later handle dict with order numbers, and yaml file constructor params self.pipe_runners = [] for pipe in pipes: pipe_runner = PipeRunner(implementer(IPipe)(pipe())) self.pipe_runners.append(pipe_runner) def run(self, it): if not hasattr(it, '__iter__'): raise InvalidPipeInput("Pipeline requires iterable input, got: " + it) res = it for pipe_runner in self.pipe_runners: res = pipe_runner.execute(res) return res class PipeRunner(object): implements(IPipelineRunner) def __init__(self, pipe): self.pipe = pipe def execute(self, item_gen): for item in item_gen: try: for res in self.pipe.process_item(item): #process_items can produce multiple yields yield res except SkipPipeItem: continue </code></pre> <h3>tests/example</h3> <pre><code>import unittest class TestPipeline(unittest.TestCase): def _getTargetClass(self): from pipeable.components import Pipeline return Pipeline def _makeOne(self, pipes): return self._getTargetClass()(pipes) def test_class_conforms_to_IPipeline(self): from zope.interface.verify import verifyClass from pipeable.interfaces import IPipeline verifyClass(IPipeline, self._getTargetClass()) def test_should_run_simple_pipes_add_one_add_two(self): test_pipes = self._getSimpleTestPipes() pipe_line = self._makeOne(test_pipes) res_gen = pipe_line.run([1]) res = res_gen.next() self.assertEquals(4, res, res) def test_should_yield_forward_and_backward(self): test_pipes = self._getForwardReverseTitles() pipe_line = self._makeOne(test_pipes) res = pipe_line.run(['foo', 'bar']) self.assertEquals(['Foo', 'Oof', 'Bar', 'Rab'], list(res), list(res)) def test_should_skip_foo(self): from pipeable.exceptions import SkipPipeItem class ForwardReverseNoFoo(object): def process_item(self, str_item): if str_item == 'foo': raise SkipPipeItem yield str_item yield str_item[::-1] test_pipes = [ForwardReverseNoFoo] pipe_line = self._makeOne(test_pipes) res = pipe_line.run(['foo', 'bar']) self.assertEquals(['bar', 'rab'], list(res), list(res)) def test_should_raise_invalid_pipe_input_on_non_iterable(self): from pipeable.exceptions import InvalidPipeInput test_pipes = self._getForwardReverseTitles() pipe_line = self._makeOne(test_pipes) self.assertRaises(InvalidPipeInput, pipe_line.run, 'bad_input_non_iterable') def _getSimpleTestPipes(self): class TestPipe1(object): def process_item(self, item): yield item + 1 class TestPipe2(object): def process_item(self, item): yield item + 2 return [TestPipe1, TestPipe2] def _getForwardReverseTitles(self): class ForwardReverse(object): def process_item(self, str_item): yield str_item yield str_item[::-1] class Title(object): def process_item(self, str_item): yield str_item.title() return [ForwardReverse, Title] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T16:02:57.883", "Id": "57152", "Score": "1", "body": "Your `Pipeline.run()` *requires* an iterable, but you then proceed to hand that iterable to multiple pipeline runners; this won't work because an iterable can only be iterated over *once*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T16:03:39.793", "Id": "57153", "Score": "1", "body": "I am not certain *why* you support multiple pipelines in the `IPipeline` interface here either, and why the runner needs to be separated. Won't a simpler `IPipeline` interface that can be run directly, containing just *one* actual sequence of pipes, be easier to understand and use?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T16:07:03.297", "Id": "57154", "Score": "1", "body": "Also, in my original post I talked about the need to have a central 'blackboard', to maintain shared state between pipe segments for a given run of the pipeline. Your `IPipe` interface has no access to anything else; should implementations take care of referencing a per-pipeline global state themselves? Without a pipeline context, they have no means to distinguish one run from another." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T16:55:38.280", "Id": "60646", "Score": "0", "body": "Thanks for the feedback @MartijnPieters . In the latest iteration I believe I've simplified it, as well as added access to a pipeline context. https://github.com/bcajes/pipeable" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T06:11:13.190", "Id": "35155", "Score": "2", "Tags": [ "python", "design-patterns" ], "Title": "Data pipeline processing framework" }
35155
Visual Studio is an integrated development environment (IDE) from Microsoft. THIS TAG SHOULD ONLY BE USED FOR CODE INVOLVING THE IDE ITSELF, NOT FOR CODE SIMPLY WRITTEN WITH IT.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T06:56:40.643", "Id": "35157", "Score": "0", "Tags": null, "Title": null }
35157
Data mining is the process of analyzing large amounts of data in order to find patterns and commonalities.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T06:58:48.953", "Id": "35159", "Score": "0", "Tags": null, "Title": null }
35159