body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>The task is to compress a string.</p>
<p>eg. "abcbcdabcbcd"</p>
<p>Here as you can see some characters are repeated, so it can be compressed.</p>
<p>"abcbcdabcbcd" -> "(a(bc2)d2)$"</p>
<p>'$' denotes end of string.</p>
<p>My code:</p>
<pre><code>import java.util.*;
class compress
{
public static void main(String[] ar)
{
System.out.print(">> ");
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(compress(s));
}
public static String compress(String s)
{
String a = "";
boolean found = false;
for(int l = 0; l < s.length(); l++)
{
for(int i = l; i < s.length(); i++)
{
String t = s.substring(l,i+1);
try
{
int q = 1;
int st = i+1;
String p = "";
while(st + t.length() <= s.length())
{
p = s.substring(st,st+t.length());
if(p.equals(t))
q++;
else break;
st += t.length();
}
if(q != 1)
{
a += "(" + compress(t) + q + ")";
l = st-1;
i = st;
found = true;
}
}catch(Exception e){}
}
if(!found)
a += s.charAt(l);
found = false;
}
return a;
}
}
</code></pre>
<p>Please help to improve my code and suggest a better solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:09:18.037",
"Id": "62728",
"Score": "2",
"body": "Is the double-indent of the first 2 lines of `void main` a paste glitch? FWIW I'm not buying `catch(Exception e){}`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:10:19.270",
"Id": "62729",
"Score": "0",
"body": "It's a paste glitch. What is FWIW?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:10:38.043",
"Id": "62730",
"Score": "1",
"body": "*For what it's worth* :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:00:01.847",
"Id": "62740",
"Score": "4",
"body": "Daniel Cook answered [your previous question](http://codereview.stackexchange.com/questions/37763/decompressing-a-string) 37 minutes before you asked this one. He told you to use better variable names. I won't review this until you use better variable names. That is why I am downvoting this. Please edit it and use better variable names and I will gladly review it and give it an upvote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:36:12.890",
"Id": "62906",
"Score": "0",
"body": "not sure I know what format is coming out, but shouldn't `(a(bc2)d2)$` be something like `((a(bc2)d)2)$` ? logically I would think that you want the pattern `a(bc2)d` to repeat twice, not have `d` repeat twice at the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:43:53.573",
"Id": "62934",
"Score": "0",
"body": "@Malachi Yes, you're correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:09:26.310",
"Id": "62945",
"Score": "0",
"body": "@user2369284, if that is the case then your examples on both questions are misleading and you should fix them."
}
] |
[
{
"body": "<p>Your naming is awful. Even <code>void main(String[] args)</code> has been <em>butchered</em> to <code>void main(String[] ar)</code>... and the only identifier that's more than 2 letters in this code, is called <code>found</code> - which implies a <em>search</em>, but the method is called <code>compress</code>.</p>\n\n<p>What exceptions are you swallowing, and why? I'm no <a href=\"/questions/tagged/java\" class=\"post-tag\" title=\"show questions tagged 'java'\" rel=\"tag\">java</a> guru, but an empty <code>catch</code> clause is <em>always</em> a code smell.</p>\n\n<p>The main issue with this code is the naming. Variables should always have meaningful names. Naming doesn't make your code run any better or worse. But writing code that works is usually 20% of the job. Reading (/maintaining) the code is usually the other 80%. You'll thank yourself in 6 months when you go back to this code and you can tell the meaning of <code>q</code> without having to fully understand everything that's going on in that loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:21:40.053",
"Id": "62733",
"Score": "0",
"body": "I am more interested in competitive programming at the moment so short variable names suit me"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:22:47.527",
"Id": "62734",
"Score": "7",
"body": "We don't do code golf here. The purpose of CR is to write *good code*. If you're looking for golfed code, I'm afraid you've knocked the wrong door; please see [help/on-topic]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:57:08.893",
"Id": "62739",
"Score": "5",
"body": "@user2369284 The only competition we like here is who writes the **best** code. Too short variable names = Not the best code. If you are interested in writing short and obfuscated code, [Code Golf](http://codegolf.stackexchange.com) might be something for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:02:57.240",
"Id": "62741",
"Score": "0",
"body": "There is no Exception that should be thrown there. Possibly a `RuntimeException` of some kind, but those shouldn't be caught like that. Ever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:46:56.953",
"Id": "62745",
"Score": "5",
"body": "@user2369284: if you're talking about timed code competitions, you will save more time in the long run by using long variable names. Typing speed is not your bottleneck - thinking speed is, and thinking speed will decrease if your variables are not named properly."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:19:35.730",
"Id": "37770",
"ParentId": "37769",
"Score": "10"
}
},
{
"body": "<h1>import.util.*</h1>\n\n<p>One thing I have notice from reading other Java Reviews is that you don't want to import more libraries than you have to, really this goes for any language I would think. so figure out what you need in <code>java.util</code> and import that. I know that in C or C++ there is a library that when imported really annoys other programmers, but I can't remember what it is, not sure if there is a similar library in Java though.</p>\n\n<hr>\n\n<p>If you aren't going to do anything with the exception don't catch it. don't use a <code>Try ... Catch</code> let it tell you what you are doing wrong every time so that you can code it right. this should give you a little bit of performance.</p>\n\n<p>not sure what type of competitive programming that you are doing, but in some competitions they go by number of lines so removing the <code>Try Catch</code> would save you lines.</p>\n\n<hr>\n\n<p><strong>From my Comment</strong></p>\n\n<p>shouldn't <code>(a(bc2)d2)$</code> be something like <code>((a(bc2)d)2)$</code> ? logically I would think that you want the pattern <code>a(bc2)d</code> to repeat twice, not have <code>d</code> repeat twice at the end.</p>\n\n<p>I hope that makes sense.</p>\n\n<hr>\n\n<h1>Eliminate an If Statement</h1>\n\n<p>this code here can be changed</p>\n\n<pre><code>while(st + t.length() <= s.length())\n{\n p = s.substring(st,st+t.length());\n if(p.equals(t))\n q++;\n else break;\n st += t.length();\n}\nif(q != 1)\n{\n a += \"(\" + compress(t) + q + \")\";\n l = st-1;\n i = st;\n found = true;\n}\n</code></pre>\n\n<p>to something like this:</p>\n\n<pre><code>while(st + t.length() <= s.length())\n{\n p = s.substring(st,st+t.length());\n if(p.equals(t))\n {\n q++;\n a += \"(\" + compress(t) + q + \")\";\n st += t.length();\n l = st-1;\n i = st;\n found = true;\n }\n else break;\n}\n</code></pre>\n\n<p>because if you increment <code>q</code> it will not be equal to 1, and the rest of the logic stays the same, this should also increase the performance.</p>\n\n<hr>\n\n<p>another thing that I just noticed, and this may go against the whole competitive programming thing, and may make the code more unreadable but you are adding two variables together the same way multiple times.</p>\n\n<p>create another variable perhaps <code>stt</code> and use that to represent <code>st+t.length</code> then you can write it like this.</p>\n\n<pre><code>int st = i+1;\nint stt = st + t.length\n\nwhile(stt <= s.length())\n{\n p = s.substring(st,stt);\n if(p.equals(t))\n {\n q++;\n a += \"(\" + compress(t) + q + \")\";\n l = st-1;\n i = stt;\n found = true;\n }\n else break;\n}\n</code></pre>\n\n<p>Here we removed an assignment and redundancy by creating another variable called <code>stt</code> (<em>whatever that is</em>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T17:06:36.653",
"Id": "37816",
"ParentId": "37769",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37816",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:03:40.040",
"Id": "37769",
"Score": "-3",
"Tags": [
"java",
"strings"
],
"Title": "Compressing a string"
}
|
37769
|
<p>I'm trying to improve the following code for testability.</p>
<pre><code>public function can_apply_extension()
{
$search_dates = [
Carbon::createFromTimestamp(strtotime($this->billing_verified_to))->subMonth(1),
$this->billing_verified_to
];
$record = ORM::factory('a model')
->where('created_at', 'BETWEEN', $search_dates)
->find();
if( !$record->loaded() )
{
return true;
}
return false;
}
</code></pre>
<p>Here's how I think I can improve it:</p>
<pre><code>public function can_apply_extension($search_from = null, $search_to = null)
{
$search_from = is_null($search_from) ? Carbon::createFromTimestamp(strtotime($this->billing_verified_to))->subMonth(1) : $search_from;
$search_to = is_null($search_to) ? $this->billing_verified_to : $search_to
$search_dates = [$search_from, $search_to];
$record = ORM::factory('a model')
->where('created_at', 'BETWEEN', $search_dates)
->find();
if( !$record->loaded() )
{
return true;
}
return false;
}
</code></pre>
<p>I still have to mock ORM part. I think the only option is that I pass an object as a parameter or make a method that injects the ORM object. </p>
<p>Are there any other better ways? I'm aware of IoC container, but I can't use it in our current environment.</p>
<p><strong>Update</strong>: Beside passing ORM as a parameter so that I can just swap it out, I found another workaround.</p>
<p>Since <code>ORM::factory()</code> actually returns an object, I was able to add a method and modify the factory method.</p>
<pre><code>public function testing($bool)
{
$this->_testing = $bool;
}
public function instead($when_this_passed, ORM $use_this_instead)
{
$this->_instead_map[$when_this_passed] = $use_this_instead;
}
public function factory($name)
{
if($this->_testing && array_key_exists($name, $this->_instead_map))
{
return $this->_instead_map[$name];
}
else
{
parent::factory($name);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T15:55:28.653",
"Id": "62901",
"Score": "1",
"body": "Get rid of all the static calls, because an `ORM::factory` implies a static property that holds a reference to an object. Testing classes with static properties is hard... really hard"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:33:19.973",
"Id": "62927",
"Score": "0",
"body": "@EliasVanOotegem // Thank you for the input. As I mentioned, that's one of the options. Are there any others?"
}
] |
[
{
"body": "<p>(I've not coded in PHP recently, my examples are Java or Java-like pseudocode.)</p>\n\n<p>In his <em>Working Effectively with Legacy Code</em> book <em>Michael C. Feathers</em> describes a lot of techniques which help making any code testable. Another good resource is the following article: <a href=\"http://blogs.msdn.com/b/nickmalik/archive/2005/09/07/462054.aspx\" rel=\"nofollow\">Killing the Helper class, part two</a></p>\n\n<p>The usual way to breaking static dependencies is the following: Create a non-static interface which has a similar method than the original static class:</p>\n\n<pre><code>public interface OrmFactory {\n OrmSomething create($name);\n}\n</code></pre>\n\n<p>Then create an implementation which calls the static method/class:</p>\n\n<pre><code>public class OrmFactoryImpl implements OrmFactory {\n public OrmSomething create($name) {\n return ORM::factory($name);\n }\n}\n</code></pre>\n\n<p>Finally, use the interface in the <code>can_apply_extension</code> function:</p>\n\n<pre><code>public class MyClass {\n\n private OrmFactory ormFactory;\n\n public MyClass(OrmFactory ormFactory) {\n this.ormFactory = ormFactory;\n }\n\n public void can_apply_extension() {\n ...\n $record = ormFactory.create('a model')\n ->where('created_at', 'BETWEEN', $search_dates)\n ->find();\n ...\n }\n}\n</code></pre>\n\n<p>In tests you can pass a mocked <code>OrmFactory</code> to the class while in production code you can use the original one through the <code>OrmFactoryImpl</code> wrapper/delegate. (I guess PHP also has some mocking framework implementations which makes testing easier but you can implement a <code>TestOrmFactory</code> which emulates some behaviour of the original one without the need of any database.)</p>\n\n<p>The second snippet in the question has <a href=\"http://xunitpatterns.com/Test%20Logic%20in%20Production.html\" rel=\"nofollow\">test logic in production</a> smell. I would avoid that and use the much cleaner dependency breaking above. The linked page contains some disadvantages of the smell. One of them is the following:</p>\n\n<blockquote>\n <p>Code that was not designed to work in production \n and which has not been verified to work properly\n in the production environment could accidently be \n run in production and cause serious problems. </p>\n</blockquote>\n\n<p>And another one is:</p>\n\n<blockquote>\n <p>Software that is added to the SUT For Tests Only \n makes the SUT more complex. It can confuse potential\n clients of the software's interface by introducing\n additional methods that are not intended to be\n used by any code other than the tests. This \n code may have been tested only in very specific \n circumstances and might not work in the typical\n usage patterns used by real clients. </p>\n</blockquote>\n\n<p>(SUT means System Under Test, in this case the class with <code>can_apply_extension()</code>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:57:27.263",
"Id": "43246",
"ParentId": "37776",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43246",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:00:19.603",
"Id": "37776",
"Score": "5",
"Tags": [
"php",
"unit-testing"
],
"Title": "Testable code with ORM factory"
}
|
37776
|
<p>On the attached fiddle is what I hope will the be future UI for navigation on my own personal portfolio site. I was hoping you guys could critique the JavaScript I wrote to accomplish the most compatibility with the most browsers. I've tested as far back as IE 7 with this code and it works. Whereas the CSS solution is only IE 10+, and the jQuery Animate method is only usable in Chrome. </p>
<p>Below is the attached fiddle and all of the script I use to facilitate this process. Please be as brutal as possible. I am very new to JS and would like to know as much as possible!</p>
<p><a href="http://jsfiddle.net/PhilFromHeck/um8Pp/" rel="nofollow">http://jsfiddle.net/PhilFromHeck/um8Pp/</a></p>
<pre><code>var key = "off";
var menuKey=["off","off","off","off"];
var menuID = [];
var menuState=[0,0,0,0];
$(document).ready(function () {
init();
$('.menu').mouseenter(function () {
for (var i = 0; i < 4; i++) {
if(menuID[i] == this){
menuKey=["off","off","off","off"];
menuKey[i] = "on";
}
}
if(key=="off"){
key="on";
doMove();
}
});
$('.menu').mouseleave(function () {
menuKey=["off","off","off","off"];
});
});
function init() {
menuID[0] = document.getElementById('menuOne');
menuID[1] = document.getElementById('menuTwo');
menuID[2] = document.getElementById('menuThree');
menuID[3] = document.getElementById('menuFour');
}
function doMove() {
var check = "no";
if(key == "on"){
for (var i = 0; i < 4; i++) {
if(menuKey[i] == "on"){
check = "yes";
if(menuState[i] < 100){
menuState[i] = menuState[i]+2;
menuID[i].style.backgroundPosition="0px " + menuState[i] + "px";
}
}
if(menuKey[i] == "off"){
if(menuState[i] > 0){
check = "yes";
menuState[i] = menuState[i]-2;
menuID[i].style.backgroundPosition="0px " + menuState[i] + "px";
}
}
}
if(check=="yes"){
setTimeout(doMove,1); // call doMove in 20msec
}
else{
key = "off";
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>For beginner code, that's reasonably good.</p>\n\n<ul>\n<li>Instead of calling <strong>setTimeout()</strong> yourself, why not let jQuery handle the animation for you with <a href=\"http://api.jquery.com/animate/\" rel=\"nofollow\"><code>.animate()</code></a>?</li>\n<li><p>Your <strong>indentation</strong> is wrong, as evidenced by</p>\n\n<pre><code> }\n }\n}\n</code></pre>\n\n<p>at the end. I believe that two spaces is too stingy for readability, and also encourages excessive nesting, which is poor programming practice. For example, the entire <code>doMove()</code> function should do nothing unless <code>key == \"on\"</code>, so you could eliminate one layer of nesting by returning early:</p>\n\n<pre><code>function doMove() {\n if (key != \"on\") {\n return;\n }\n ...\n}\n</code></pre></li>\n<li>You use <strong>magic numbers</strong> 4 and 100. Don't hard-code 4; detect it as <code>menuID.length</code> instead. You should be able to detect the height as well; it not, then hard-code 100 as a named constant rather than being casually embedded as a loop limit.</li>\n<li><p><strong>Storage of state</strong> feels clumsy. Use booleans (<code>true</code> and <code>false</code>) instead of strings (<code>\"on\"</code> and <code>\"off\"</code>). Naming could be better — I suggest <code>menuElements</code> rather than <code>menuID</code>, and <code>animationPosition</code> rather than <code>menuState</code>. You should be able to use fewer variables. For example, <code>key</code> and <code>menuKey</code> could be collapsed down to one scalar called <code>activeMenuItem</code>.</p>\n\n<pre><code>var activeMenuItem;\nvar menuElements = [];\nvar animationPosition = [0, 0, 0, 0];\n\n$(document).ready(function () {\n init();\n $('.menu').mouseenter(function () {\n activeMenuItem = this;\n doMove();\n });\n $('.menu').mouseleave(function () {\n activeMenuItem = null;\n });\n});\n\nfunction doMove() {\n var check = false;\n for (var i = 0; i < menuElements.length; i++) {\n if (menuElements[i] == activeMenuItem) {\n if (animationPosition[i] < 100) {\n animationPosition[i] += 2;\n menuElements[i].style.backgroundPosition=\"0px \" + animationPosition[i] + \"px\";\n }\n check = true;\n } else if (animationPosition[i] > 0) {\n animationPosition[i] -= 2;\n menuElements[i].style.backgroundPosition=\"0px \" + animationPosition[i] + \"px\";\n check = true;\n }\n }\n if (check) {\n setTimeout(doMove, 1); // call doMove in 20msec\n }\n}\n</code></pre></li>\n<li><strong>Initialization</strong> of <code>menuID</code> scales poorly with additional menu items. Try selecting all <code>$('.menu')</code> instead of individually named elements.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T22:02:41.623",
"Id": "62752",
"Score": "0",
"body": "Thank you kindly! However, the JQuery animate doesn't work for background position, you can do background position y but it was only supported in Chrome; from what I could tell anyways!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T23:14:09.140",
"Id": "62758",
"Score": "0",
"body": "Check [the CSS hooks plugin](http://stackoverflow.com/a/14218768/146513). That plugin also works on most browsers (I tested with Chrome, FF and IE 11), and you would need to write just a few lines of code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T21:59:49.573",
"Id": "37785",
"ParentId": "37782",
"Score": "3"
}
},
{
"body": "<p>In addition to my <a href=\"https://codereview.stackexchange.com/a/37785/9357\">original answer</a>, I'd like to point out three issues with your use of <code>setTimeout()</code>.</p>\n\n<p>First, your comment says that you wish to call <code>doMove()</code> again after 20 milliseconds, but your code actually sets the timer for 1 millisecond. Let's set it to 20, which produces a slow animation.</p>\n\n<p>Next, you'll observe that if the pointer leaves a menu item and immediately moves over another, the animation can run at double speed. That is, while the original sequence of timers is still running, your <code>mouseenter</code> handler kicks off a second sequence of timers. You can prevent this by keeping track of whether a <code>setTimeout()</code> is still scheduled:</p>\n\n<pre><code>var mutex;\n\n$(document).ready(function() {\n init();\n $('.menu').mouseenter(function() {\n activeMenuItem = this;\n if (!mutex) {\n doMove();\n }\n });\n ...\n});\n\nfunction doMove() {\n ...\n if (check) {\n mutex = setTimeout(doMove, 20);\n } else {\n mutex = null;\n }\n}\n</code></pre>\n\n<p>Finally, there is an efficiency issue. As long as the pointer is hovering over a menu item, you will be frantically polling to see when to undo the animation. That would be bad for battery life on mobile devices. Instead, you want rest when nothing is moving, and trigger the reverse animation when the pointer leaves the active item.</p>\n\n<pre><code> $(document).ready(function () {\n init();\n $('.menu').mouseenter(function () {\n activeMenuItem = this;\n if (!mutex) {\n doMove();\n }\n })\n .mouseleave(function () { // You can chain jQuery calls\n activeMenuItem = null;\n if (!mutex) { // Also trigger animation here\n doMove();\n }\n });\n });\n\n function doMove() {\n var animating = false;\n for (var i = 0; i < menuElements.length; i++) {\n if (menuElements[i] == activeMenuItem) {\n if (animationPosition[i] < 100) {\n animationPosition[i] += 2;\n menuElements[i].style.backgroundPosition=\"0px \" + animationPosition[i] + \"px\";\n animating = true; // Set animating=true only if something moved\n }\n } else if (animationPosition[i] > 0) {\n animationPosition[i] -= 2;\n menuElements[i].style.backgroundPosition=\"0px \" + animationPosition[i] + \"px\";\n animating = true;\n }\n }\n if (animating) {\n mutex = setTimeout(doMove, 20); // call doMove in 20msec\n } else {\n mutex = null;\n }\n }\n</code></pre>\n\n<p>With that change, <code>check</code> is true only when an animation is in progress. As a side benefit, then, we can give it a clearer name: <code>animating</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:53:37.433",
"Id": "37992",
"ParentId": "37782",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T21:18:35.123",
"Id": "37782",
"Score": "7",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "jQuery-animated navigation menu"
}
|
37782
|
<p>My needs outpace my abilities. This code (mostly) works, but it is really ugly, doesn't always add correctly, and is in desperate need of some help refactoring. I can't wrap my head around what needs done with it.</p>
<p>I have a SQLite table <code>WorkLog</code> which contains rows of <code>int</code>, <code>long</code>, <code>long</code>, <code>long</code>, and <code>long</code>. They are <code>_id</code>, <code>unused</code>, <code>dayStartTimestamp</code>, <code>activityStartTime</code>, and <code>activityStopTime</code>. Timestamps are stored as epoch time <code>long</code>s. It is possible to have multiple activities on the same day. I am trying to calculate the total time working in a time period defined by <code>lookBackHours</code>.</p>
<p>Time should be the difference between <code>dayStartTime</code> and <code>activityStopTime</code> + 15 minutes for each day. Since there can be many rows with the same <code>dayStartTime</code>, I want to discard entries with duplicate <code>dayStartTimes</code>, only keeping the row with the longest time between <code>activityStartTime</code> and <code>activityStopTime</code>. I am assuming rows in the db/cursor are sorted by <code>dayStartTime</code> and <code>activityStopTime</code>.</p>
<p>In the code below, <code>activityStartTime</code> is represented by <code>TrackerContract.WorkLog.BLOCK_OUT</code> and <code>activityStopTime</code> is rep by <code>TrackerContract.WorkLog.BLOCK_IN</code>. <code>currentTimeMilliMinutes()</code> can be assumed to be the same as <code>System.currentTimeMillis()</code>, and unrelated to the problem of kludgey, buggy code. It simply takes a <code>System.currentTimeMillis()</code> call, constructs a <code>Calendar</code>, then returns a millisecond time constructed from the calendar's Year, Month, Date, Hour, and Minute (stripping seconds and milliseconds from the time).</p>
<p>Here is the basic logic:</p>
<ul>
<li><p>This method searches a db for entries matching the criteria "anything that ended in <code>lookbackHours</code>+15 minutes, or more recently". It puts them into a List of long[2] arrays, storing the <code>dayStartTime</code> and <code>activityStopTime</code> in position 0 and 1 in the array.</p></li>
<li><p>The next loop goes through and attempts to throw away a list entry if the next one has the same <code>dayStartTime</code> and a higher (more recent) <code>activityStopTime</code>.</p></li>
<li><p>The final loop takes the surviving entries and sums the difference in [0] and [1] in millis:</p></li>
</ul>
<p></p>
<pre><code>public long timeInHours(long lookbackHours) {
//returns total time in past hours up to minute
long sumTotal = 0;
//search DB for activityStopTime lookBackHours + 15 minutes
long timeStamp = currentTimeMilliMinutes() - ((ONE_MINUTE*60L*lookbackHours) + (ONE_MINUTE*15L));
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor result = db.rawQuery("SELECT * FROM WorkLog WHERE " +
TrackerContract.WorkLog.COLUMN_BLOCK_IN + ">=" + timeStamp, null);
result.moveToFirst();
//define paramaters for loops below
int fdpStartIndex = result.getColumnIndex(TrackerContract.WorkLog.COLUMN_FDP_BEGIN);
int blockInIndex = result.getColumnIndex(TrackerContract.WorkLog.COLUMN_BLOCK_IN);
//insert contents of cursor into list of arrays
List<long[]> list = new ArrayList<long[]>();
while (!result.isAfterLast()) {
long[] temp = new long[2];
temp[0] = result.getLong(fdpStartIndex);
temp[1] = result.getLong(blockInIndex);
list.add(temp);
result.moveToNext();
}
//process list of arrays, if current and next start times are the same, and next end time is bigger, drop current row
//multiple entries may have same start time, but multiple end times
//trying to remove all but the longest period per start time
int length = list.size();
Calendar c1 = new GregorianCalendar();
Calendar c2 = new GregorianCalendar();
for (int i = 0; i < length; i++) {
if ((i+1) >= length) {
} else {
c1.setTimeInMillis(list.get(i)[0]);
c2.setTimeInMillis(list.get(i+1)[0]);
if (c1.get(Calendar.MINUTE) == c2.get(Calendar.MINUTE) &&
c1.get(Calendar.HOUR_OF_DAY) == c2.get(Calendar.HOUR_OF_DAY) &&
c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR) &&
c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) {
if (list.get(i)[1] < list.get(i+1)[1]) {
list.remove(i);
length--;
}
}
}
}
//for each remaining entry, find total duration in millis from start to end, add 15 minutes, add to total millis.
int size = list.size();
for (int i = 0; i < size; i++) {
sumTotal += list.get(i)[1] - list.get(i)[0] + (ONE_MINUTE*15L);
}
return sumTotal;
}
</code></pre>
<p>I'm not explicitly asking for someone to rewrite this, but just pointing out the egregious errors and suggesting ways to make it more manageable/maintainable.</p>
|
[] |
[
{
"body": "<p>Your code is a bit too messy to understand what you are doing - or why you are doing it, but here are some pointers that can get you started:</p>\n\n<ul>\n<li><p>Your method is way too long. Break it up into a couple of sub-methods.</p></li>\n<li><p>Using a <code>List<long[]></code> and using the indexes 0 and 1 for that <code>long[]</code> like you are doing tells me that you should instead use a class to represent your values in the <code>long[]</code>. This will make it a lot clearer about what the 0 index actually <strong>is</strong>. (Assuming you use proper naming for it)</p></li>\n<li><p>Your indentation is a bit off. All the code in your method should be indented one step.</p></li>\n<li><p>In your for-loop, you can use:</p>\n\n<pre><code>for (int i = 0; i < length; i++) {\n if ((i+1) >= length)\n continue;\n</code></pre>\n\n<p>To get rid of the <code>else</code> statement entirely.</p></li>\n</ul>\n\n<p>As I said, this is just a start. I am still not sure about what it actually is that you are doing, but this will be more clear once you divide your method into a couple of sub-methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T00:08:08.400",
"Id": "62764",
"Score": "0",
"body": "What can I do to make the code clearer? I tried to explain the logic, the structure of the DB table, and provide comments in the code. I will try and break it up and post back when I have a substantial update. I will incorporate your other suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T00:25:43.627",
"Id": "62768",
"Score": "0",
"body": "@nexus_2006 Once you have a major update fixed (preferably with amon's suggestions incorporated as well), if you are not happy with the cleaniness then please post a *new* question. Questions shouldn't be edited to invalidate answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T00:30:16.810",
"Id": "62771",
"Score": "0",
"body": "Understood, thanks. When I posted the question I didn't realize the indentation didn't copy correctly, I was trying to make the post reflect the code I have in Eclipse, but I won't do that again :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T23:55:34.810",
"Id": "37790",
"ParentId": "37787",
"Score": "5"
}
},
{
"body": "<p>I suggest you follow everything what <a href=\"https://codereview.stackexchange.com/a/37790/21609\">Simon said in his answer</a>. I would like to point out some additional issues:</p>\n\n<ul>\n<li><p>Don't <em>ever</em> concatenate strings to build an SQL query (unless you have meticulously checked that there is no possibility of injection attacks, e.g. by properly escaping everything). While it is probably safe in this case, it is a massive code smell. Use parameterized queries instead.</p></li>\n<li><p><code>SELECT *</code> and then extracting those columns you are interested in is totally unecessary. Only ask for what you need.</p></li>\n<li><p>When using a C-style <code>for</code> loop over an index `i', you will usually want to specify the upper bound directly and not introduce an extra variable. Instead of </p>\n\n<pre><code>int length = list.size();\nfor (int i = 0; i < length; i++) {\n</code></pre>\n\n<p>just do <code>for (int i = 0; i < list.size; i++)</code>. Of couse this shouldn't be done for more complex bounds (because performance), but here introducing variables is just obfuscation. It also avoids useless names like:</p>\n\n<pre><code>int length = list.size();\nint size = list.size();\n</code></pre></li>\n<li><p>Talking about names: <code>list</code> isn't a good name for a <code>List<…></code> – I can see from the type what it is. Would <code>timeIntervals</code> be a better name?</p></li>\n<li><p>Your three loops can be mostly joined into a single loop, once you view the <code>timeIntervals</code> list as a stack: On every step, you pop the previous element off from the stack, compare the previous and the current element, and if they are sufficiently different, push the both onto the stack.</p>\n\n<p>The next step is to see that you don't need a whole stack and only the previous interval, and the sum. As an extra, this saves you some memory :-)</p></li>\n<li><p>IIRC, the <code>Calendar</code> API shouldn't be used. You might want to look into <a href=\"http://www.joda.org/\" rel=\"nofollow noreferrer\">JodaTime</a>.</p></li>\n<li><p>Please don't rely on the ordering of rows from an SQL query. If you need some order, specify an <code>ORDER BY</code> clause in the SQL.</p></li>\n<li><p>The 15-Minute extra shouldn't be hardcoded – take it as a parameter to your function and ultimately from a configuration file. Business rules don't belong into compiled code.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T00:23:04.097",
"Id": "62767",
"Score": "0",
"body": "Thank you for the help. I will also try to incorporate these suggestions. The main reason I use an extra variable for the size of the for loop is because the Android best practices recommend this specifically, rather than re-querying the `size()` each time. Your other points, especially viewing the list as a stack and on better naming and SQL techniques are very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T00:17:12.627",
"Id": "37791",
"ParentId": "37787",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T23:30:11.600",
"Id": "37787",
"Score": "3",
"Tags": [
"java",
"android",
"datetime",
"sqlite"
],
"Title": "Searching database, filtering results, adding longs"
}
|
37787
|
<p>I have this code that shows date pickers when the browser doesn't support <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local" rel="nofollow noreferrer"><code><input type="datetime-local"></code></a>.</p>
<p>Any tips on optimizing <a href="http://jsfiddle.net/LkpPJ/15/" rel="nofollow noreferrer">this code</a>?</p>
<pre><code>if (!Modernizr.inputtypes.date) {
$(function () {
var d = Date.parse($('#StartDatePicker').val());
$('#StartDatePicker').val($.format.date(d, "yyyy-MM-dd hh:mm a"));
d = Date.parse($('#EndDatePicker').val());
$('#EndDatePicker').val($.format.date(d, "yyyy-MM-dd hh:mm a"));
var startDateTextBox = $('#StartDatePicker');
var endDateTextBox = $('#EndDatePicker');
startDateTextBox.datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "hh:mm TT",
minuteGrid: 10,
addSliderAccess: true,
sliderAccessArgs: {
touchonly: false
},
onClose: function (dateText, inst) {
if (endDateTextBox.val() != '') {
var testStartDate = startDateTextBox.datetimepicker('getDate');
var testEndDate = endDateTextBox.datetimepicker('getDate');
if (testStartDate > testEndDate) endDateTextBox.datetimepicker('setDate', testStartDate);
} else {
endDateTextBox.val(dateText);
}
},
onSelect: function (selectedDateTime) {
endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate'));
}
});
endDateTextBox.datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "hh:mm TT",
minuteGrid: 10,
addSliderAccess: true,
sliderAccessArgs: {
touchonly: false
},
onClose: function (dateText, inst) {
if (startDateTextBox.val() != '') {
var testStartDate = startDateTextBox.datetimepicker('getDate');
var testEndDate = endDateTextBox.datetimepicker('getDate');
if (testStartDate > testEndDate) startDateTextBox.datetimepicker('setDate', testEndDate);
} else {
startDateTextBox.val(dateText);
}
},
onSelect: function (selectedDateTime) {
startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate'));
}
});
});
}
</code></pre>
|
[] |
[
{
"body": "<p>Yes there is a fair amount of repeated code - e.g. the options:</p>\n<blockquote>\n<pre><code> dateFormat: "yy-mm-dd",\n timeFormat: "hh:mm TT",\n minuteGrid: 10,\n addSliderAccess: true,\n sliderAccessArgs: {\n touchonly: false\n },\n</code></pre>\n</blockquote>\n<p>These could be abstracted to a common object that gets extended with each call to <code>datetimepicker()</code> using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\"><code>Object.assign()</code></a></p>\n<pre><code>const commonOptions = {\n dateFormat: "yy-mm-dd",\n timeFormat: "hh:mm TT",\n minuteGrid: 10,\n addSliderAccess: true,\n sliderAccessArgs: {\n touchonly: false\n }\n};\n\nstartDateTextBox.datetimepicker(Object.assign({\n onClose: function (dateText, inst) {\n if (endDateTextBox.val() != '') {\n const testStartDate = startDateTextBox.datetimepicker('getDate');\n const testEndDate = endDateTextBox.datetimepicker('getDate');\n if (testStartDate > testEndDate) endDateTextBox.datetimepicker('setDate', testStartDate);\n } else {\n endDateTextBox.val(dateText);\n }\n },\n onSelect: function (selectedDateTime) {\n endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate'));\n }\n}, commonOptions));\nendDateTextBox.datetimepicker(Object.assign({ \n onClose: function (dateText, inst) {\n if (startDateTextBox.val() != '') {\n const testStartDate = startDateTextBox.datetimepicker('getDate');\n const testEndDate = endDateTextBox.datetimepicker('getDate');\n if (testStartDate > testEndDate) startDateTextBox.datetimepicker('setDate', testEndDate);\n } else {\n startDateTextBox.val(dateText);\n }\n },\n onSelect: function (selectedDateTime) {\n startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate'));\n }\n}, commonOptions));\n</code></pre>\n<p>The <code>onClose</code> function could be abstracted to a function that accepts the picker to modify as a parameter.</p>\n<p>It appears there is an option in the <a href=\"https://xdsoft.net/jqplugins/datetimepicker/\" rel=\"nofollow noreferrer\">datetimepicker documentation</a> for a <a href=\"https://xdsoft.net/jqplugins/datetimepicker/#range\" rel=\"nofollow noreferrer\">Range between date</a> selection - it uses just the <code>onShow</code> option to set the min and max dates:</p>\n<blockquote>\n<pre><code>jQuery(function(){\n jQuery('#date_timepicker_start').datetimepicker({\n format:'Y/m/d',\n onShow:function( ct ){\n this.setOptions({\n maxDate:jQuery('#date_timepicker_end').val()?jQuery('#date_timepicker_end').val():false\n })\n },\n timepicker:false\n });\n jQuery('#date_timepicker_end').datetimepicker({\n format:'Y/m/d',\n onShow:function( ct ){\n this.setOptions({\n minDate:jQuery('#date_timepicker_start').val()?jQuery('#date_timepicker_start').val():false\n })\n },\n timepicker:false\n });\n});\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T21:14:55.093",
"Id": "259914",
"ParentId": "37794",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-12-20T02:40:57.103",
"Id": "37794",
"Score": "1",
"Tags": [
"javascript",
"performance",
"jquery",
"datetime",
"event-handling"
],
"Title": "Date/Time picker for browsers that don't support the datetimelocal input"
}
|
37794
|
<p>Check out the fiddle <a href="http://jsfiddle.net/Hh5jg/1" rel="nofollow">here</a>. This JavaScript will take the row that a user clicks on and make an object with the key coming from the <code>thead</code> element in the table and the value coming from the data in the text in the table cell value. I'm looking for a more professional/succint way of doing this: </p>
<p>JS</p>
<pre><code>$(document).ready(function () {
$('tr').click(function () {
var tableData = $(this).children('td').map(function () {
return $(this).text();
}).get();
var props = $('thead > tr th');
var array = [];
props.each(function () { array.push($(this).text()) });
//keys
console.log(array);
//values
console.log(tableData);
var obj = {};
for (var i = 0; i < tableData.length; i++) {
obj[array[i]] = tableData[i];
}
console.log(obj);
});
});
</code></pre>
<p>HTML</p>
<pre><code><table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th scope="col">PersonId</th><th scope="col">FirstName</th><th scope="col">LastName</th>
</tr>
</thead><tbody>
<tr>
<td>1</td><td>John</td><td>Doe</td>
</tr><tr>
<td>2</td><td>Jane</td><td>Doe</td>
</tr><tr>
<td>3</td><td>Time</td><td>Smith</td>
</tr>
</tbody>
</table>
</code></pre>
|
[] |
[
{
"body": "<p>The selector <code>$('thead > tr th')</code> is not specific enough, if you have multiple tables in the page. You want the headings of the same table that was clicked: <code>$(this).closest('table').find('thead > tr th')</code>.</p>\n\n<p><code>var array</code> is an unsatisfying name. I can see that it's an array — but what does it do? How about calling it <code>tableHeadings</code>?</p>\n\n<p>You formed <code>tableData</code> using <code>Array.map()</code>; why not do the headings the same way?</p>\n\n<pre><code>var tableHeadings = $(this).closest('table')\n .find('thead > tr th')\n .map(function() {\n return $(this).text();\n}).get();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T03:21:37.307",
"Id": "37798",
"ParentId": "37795",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37798",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T02:50:56.293",
"Id": "37795",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Get jQuery object from table row click"
}
|
37795
|
The manipulation of individual bits. Operators used may include bit-wise and/or (&/|), left-shift (<<), and right-shift (>>).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T02:51:20.047",
"Id": "37797",
"Score": "0",
"Tags": null,
"Title": null
}
|
37797
|
<p>I'm writing a helper for asynchronous operations.
By default, winjs does not provide a way to wait x seconds before the execution of another function. So I decided to write a helper.</p>
<pre><code>(function asyncOperation() {
"use strict";
// -------------------------------------------------------------------
// awaitTime(time_milliseconde)
// Description:
// Waits a specified amount of time.
// Returns:
// //
// Usage:
// foo.helpers.asyncOperation.awaitTime(1000).done(function(){
// //your logic
// });
//
// -------------------------------------------------------------------
function awaitTime(milliseconds) {
if(!milliseconds || +milliseconds) {
// need to ensure that milliseconds can be used
milliseconds = 0;
}
// create a new promise and use set time out to wait x milliseconds.
return new WinJS.Promise(function (complete) {
setTimeout(function () {
// informe the promise that it ended.
complete();
}, milliseconds);
});
}
WinJS.Namespace.define("foo.helpers.asyncOperation", {
awaitTime: awaitTime
});
})();
</code></pre>
<p>I want my code to be as safe as possible. That's why I'm using "+value" in my "if".
I saw that in some cases the performance of the setTimeout is not good.
Also, is it better to define the function and assign it to the namespace at the end? (<a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh967793.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/apps/hh967793.aspx</a>) </p>
<p>So, I want to know if my code can be refactored/safer. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T13:56:07.383",
"Id": "62880",
"Score": "0",
"body": "What ( kind of ) async process are you waiting for ? Can you give us a specific sample ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T14:02:10.757",
"Id": "62881",
"Score": "0",
"body": "I do not have any specific process in mind. But sometimes you need to wait some time before doing something. Maybe, you are playing an advertising and you need to wait 30seconds before redirecting the user."
}
] |
[
{
"body": "<p>I think WinJS already provides this:</p>\n\n<p><code>WinJS.Promise.timeout(timeout)</code> creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. </p>\n\n<p>See also <a href=\"http://msdn.microsoft.com/en-us/library/windows/apps/br229729.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/apps/br229729.aspx</a></p>\n\n<p>If you wish to continue with your own function, then you should review how promises ought to work, I don't think you are using the promises object the way it was intended.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T14:14:15.673",
"Id": "37804",
"ParentId": "37802",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37804",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T10:32:26.723",
"Id": "37802",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Safer way to wait amount of time"
}
|
37802
|
<p>I'm trying to make a program that calculates your k/d ratio (kill/death, which is used in FPS games to make people believe that it's skill), how many kills you need without dying once to reach a goalKD. It also has a part that calculates how many battles you need if you give the program your average battle kills and battle deaths.</p>
<p>Is there a efficient way to program it? Currently, the way I'm doing it is getting me into programmer-efficiency hell.</p>
<pre><code>For i = 1 to 100000 {
While GoalKD>KDratio {
Kills = BattleKills + Kill
Deaths = BattleDeaths + Death
KDratio = Kills / Deaths
i++
}
}
</code></pre>
<p>I'm programming this in SmallBasic because I'm most familiar with it, and I think it's easily readable. Also, if possible, don't give the answer right away; give me some hints for me to practice my mind. Add the answer in a spoiler box.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T01:36:06.013",
"Id": "62888",
"Score": "3",
"body": "There is nothing that changes in the `while` loop that affects its condition, so you would get stuck there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T13:13:24.427",
"Id": "62889",
"Score": "0",
"body": "Always prefer ++i over i++. When you do i++, it sets a temp value to i, then adds one to i, then returns the temp for you to use. With ++i, it increments i, then returns i. Very very small efficiency gain, but still worth it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T14:05:43.970",
"Id": "62890",
"Score": "1",
"body": "As far as general hints, there a reason why there are a lot of math classes for CS majors. Some problem just get much less complex if you use math on them instead of trying to bruteforce a solution with general computing principles."
}
] |
[
{
"body": "<p>For the kills needed part, you are trying to solve this equation:</p>\n\n<pre><code>k{current} + n\n-------------- = r\n d{current}\n</code></pre>\n\n<p>Where <code>r</code> is the target rate and <code>n</code> is the number you're looking for. Some basic algebra:</p>\n\n<pre><code>n = rd - k\n</code></pre>\n\n<p>For the battles part, you need to solve</p>\n\n<pre><code>k{current} + b * k{battle} // current kills + additional kills\n-------------------------- = r\nd{current} + b * d{battle} // current deaths + additional deaths\n\nk{current} + b * k{battle} = r * (d{current} + b * d{battle}) // multiply both sides by d{current} + b * d{battle}\n\nk{current} + b * k{battle} = r * d{current} + r * b * d{battle}) // just showing multiplication of r\n\nb * (k{battle} - r * d{battle}) = r * d{current} - k{current} // subtracting terms from each side\n\n r * d{current} - k{current}\nb = --------------------------- // dividing by k{battle} - r * d{battle}\n k{battle} - r * d{battle}\n</code></pre>\n\n<p>In your code above, this becomes</p>\n\n<pre><code>need = Math.ceiling( GoalKD * Deaths - Kills )\nbattles = Math.ceiling( ( GoalKD * Deaths - Kills ) / (BattleKills - GoalKD * BattleDeaths) )\n</code></pre>\n\n<p>[I'm not a SmallBasic guy, so please forgive any syntax errors above.]</p>\n\n<p>(Edited to fix math error re battles required and add comments to the math.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T12:45:42.173",
"Id": "62891",
"Score": "0",
"body": "The code works perfectly, however I don't understand the r that's multiplying dbattle at the 3rd line? Where did it come from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T13:11:42.103",
"Id": "62892",
"Score": "0",
"body": "I added some comments above. When you multiply both sides by `d{current} + b * d{battle}`, you end up with a term `r * b * d{battle}` on the right. Subtracting that from both sides moves it to the left. Pulling `b` out of both terms on the left gives you the `r * d{battle}` term on the next to last line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T15:14:21.577",
"Id": "62893",
"Score": "0",
"body": "SmallBasic, not SmallTalk ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T15:17:00.750",
"Id": "62894",
"Score": "0",
"body": "@tomdemuyt, good point. I'm not a SmallBasic guy, either! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:39:44.500",
"Id": "62930",
"Score": "0",
"body": "Uhm. Subtracting from both sides? What do you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:42:51.727",
"Id": "62932",
"Score": "0",
"body": "This is the \"subtraction property of equality.\" If `a + b = c`, then you can subtract `b` from both sides, so `a + b - b = c - b`, which simplifies to `a = c - b`. That's what I did above (subtract `r * b * d{battle}` from both sides)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:48:38.503",
"Id": "62938",
"Score": "0",
"body": "Ah, didn't notice the b that's multiplying kbattle, yet I did know that property. Oh well =]. Thanks for your help, it really amazed me how fast you replied with the efficient code!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:52:38.247",
"Id": "62940",
"Score": "1",
"body": "Glad to help out! And they say algebra is useless in the real world... :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T22:58:51.730",
"Id": "37807",
"ParentId": "37806",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "37807",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T22:21:49.063",
"Id": "37806",
"Score": "1",
"Tags": [
"performance",
"homework",
"basic-lang"
],
"Title": "Calculating kills and deaths in a game"
}
|
37806
|
<p>I have a function - <code>TriggerNotifications</code> - that accepts a <code>NotificationType</code>. The Type determines which settings I should pull from the <code>User</code>. </p>
<p>The code looks like this: </p>
<pre><code>public void TriggerNotification(DbContext db, User user, NotificationType type, string content) {
switch (type) {
case NotificationType.Followed:
CreateNotification(db, user, user.Followed, content);
return;
case NotificationType.Unfollowed:
CreateNotification(db, user, user.Unfollowed, content);
return;
case NotificationType.Messaged:
CreateNotification(db, user, user.Messaged, content);
return;
default:
throw new InvalidDataContractException("Invalid Notification Type");
}
}
</code></pre>
<p>So the only purpose of this method is to determine which settings should be used. Every <code>User</code> has a property matching each of the enum <code>NotificationTypes</code>. </p>
<p>I think this is a good use case for reflection, but want to ask if there's any other way to reduce redundancy here. I don't like reflection because it's not as straightforward to debug, and it's slow (right?). </p>
<p><strong>UPDATE</strong></p>
<p><strong>CreateNotification:</strong> </p>
<pre><code>private void CreateNotification(DbContext db, User user, NotificationSetting setting, string content) {
// send email, notification, or both
if (setting.Equals(NotificationSetting.None))
return;
var notification = new Notification() {
UserId = user.userId
Description = content,
Email = email,
};
if (setting.Equals(NotificationSetting.Email) || setting.Equals(NotificationSetting.Both)) {
// tell worker role to pick it up
notification.PendingEmail = true;
}
// signalR stuff here
db.Add(notification);
}
</code></pre>
<p><strong>User:</strong> </p>
<pre><code>public class User : Settings {
// other stuff
}
</code></pre>
<p><strong>Settings:</strong> </p>
<pre><code>public abstract class Settings {
// notifications
public NotificationSetting Followed { get; set; }
public NotificationSetting Unfollowed { get; set; }
public NotificationSetting Messaged { get; set; }
}
</code></pre>
<p><strong>NotificationSetting:</strong> </p>
<pre><code>// values stored in the db for each setting property - messaged, unfollowed, etc
public enum NotificationSetting {
Navbar,
Email,
Both,
None
}
</code></pre>
<p><strong>NotificationType:</strong></p>
<pre><code>// values used in logic only to tell the notification builder which setting to pull
public enum NotificationType {
Followed,
Unfollowed,
Messaged
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T00:57:30.810",
"Id": "63035",
"Score": "0",
"body": "It's good to be aware what is slow, but unless you actually have a good reason to worry about the performance of this code, don't base your decisions on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T01:03:43.353",
"Id": "63037",
"Score": "0",
"body": "Though using reflection *is* a code smell and you are right to ask about ways of avoiding it."
}
] |
[
{
"body": "<p>The redundancy is hard to remove and constructions like these make it hard to extend the options later. It would require updates to both data contracts and all classes implementing them.</p>\n\n<p>You could use a delegate instead of a switch/case to improve extensibility, it would not completely remove the redundancy:</p>\n\n<pre><code>var actions = Dictionary<NotificationType, Func<DbContext, User, content>>()\n{\n { \n NotificationType.Followed, (context, user, content) => CreateNotification(context, user.Followed, content),\n NotificationType.Messaged, (context, user, content) => CreateNotification(context, user.Messaged, content),\n NotificationType.Unfollowed, (context, user, content) => CreateNotification(context, user.Unfollowed, content)\n };\n }\n</code></pre>\n\n<p>That way you can invoke it like this:</p>\n\n<pre><code> Action<DbContext, User, content>> action = null;\n if (actions.TryGetValue(notification, out action)\n {\n action.Invoke(context, user, content);\n }\n else\n {\n // throw exception?\n }\n</code></pre>\n\n<p>You can also change your baseclass to be more extensible:</p>\n\n<pre><code> public abstract class Settings\n {\n\n void SetNotificationAction(NotificationType nt, Func action)\n {\n // you could also replace the action if you so desire\n actions.Add(nt, action);\n }\n\n void ClearNotificationAction(NotificationType nt)\n {\n // you could also replace the action if you so desire\n actions.Remove(nt);\n }\n\n virtual void SetDefaultActions()\n {\n SetNotificationAction(NotificationSetting.Followed, () => return );\n ...\n ...\n }\n }\n</code></pre>\n\n<p>That does away with the enum passing and you can fetch the action using the method above. Each class inheriting can override the <code>SetDefaultActions</code> or manipulate the actions in the actions dictionary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:57:40.497",
"Id": "62910",
"Score": "0",
"body": "Why not just pull the value from the `Dictionary`? If it's an invalid value, you'll have your exception for free! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T17:51:26.353",
"Id": "62913",
"Score": "2",
"body": "Because then you get some stupid, unintelligible exception message. This way you can actually throw somethign useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:44:50.377",
"Id": "62935",
"Score": "0",
"body": "The `KeyNotFoundException` would (should?) never be thrown in production code, so a custom exception makes no sense to me. \"The given key was not present in the dictionary\" says exactly what's going on, and the stack trace will point to `Dictionary.GetValue` in the very method you're doing that, which is all you need to debug the issue. I don't see the added value of a custom exception message in this case, it's overkill."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T18:43:58.923",
"Id": "63020",
"Score": "0",
"body": "enum's are trivially serializable, delegates not. How would you store notification setting for each user in db?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T20:57:58.910",
"Id": "63021",
"Score": "0",
"body": "The enums are still stored in the DB. The delegates are replacing te handling code, not the actual values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T21:42:52.313",
"Id": "63024",
"Score": "0",
"body": "If so, `SetNotificationAction` being an instance method (non static) doesn't make sense. In fact `actions` should also be static and noone should be changing it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T22:23:18.687",
"Id": "63027",
"Score": "0",
"body": "Why not? Other classes that inherit might want to configure a different handlign method, it still doesn't change the actual Enum values. But how theyre handled can change from class to class."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:46:49.007",
"Id": "37814",
"ParentId": "37809",
"Score": "2"
}
},
{
"body": "<p>Some of the redundancy is accidental, and some essential to your design (not essential to problem though, if it were essential to problem reflection wouldn't help).</p>\n\n<p>Accidental redundancy can be removed thus:</p>\n\n<pre><code>private static NotificationSetting GetNotificationSetting(User user, NotificationType type)\n{\n switch (type) {\n case NotificationType.Followed: return user.Followed;\n case NotificationType.Unfollowed: return user.Unfollowed;\n case NotificationType.Messaged: return user.Messaged;\n default: \n throw new InvalidEnumArgumentException(\"Invalid Notification Type\");\n }\n}\n\npublic void TriggerNotification(object db, User user, NotificationType type, string content) {\n CreateNotification(db, user, GetNotificationSetting(user,type), content);\n}\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li><p>I changed the exception as <code>InvalidDataContractException</code> seems to be serialization related.</p></li>\n<li><p><code>GetNotificationSetting</code> should be moved to <code>User</code> (or made an extension method of that class).</p></li>\n</ul>\n\n<p>Now that this is out of the way,</p>\n\n<h2>What can you change in the design to remove redundancy?</h2>\n\n<p>Your user entity is not normalized. If you really were doing code-first design, <code>User</code> would look like this instead:</p>\n\n<pre><code>class User: Settings\n{\n}\n\npublic abstract class Settings {\n public IDictionary<NotificationType, NotificationSetting> NotificationSettings { get; set; }\n}\n</code></pre>\n\n<p>Then <code>TriggerNotification</code> becomes just:</p>\n\n<pre><code>public void TriggerNotification(object db, User user, NotificationType type, string content) {\n CreateNotification(db, user, user.NotificationSettings[type], content);\n}\n</code></pre>\n\n<p>Another redundancy is in <code>NotificationSetting</code>. It clearly is a bitmask.</p>\n\n<pre><code>[Flags]\npublic enum NotificationSetting : uint\n{\n Navbar = 1,\n Email = 2,\n// can add more like so\n Telegram = 4,\n PersonalVisit = 8,\n}\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>if (setting.Equals(NotificationSetting.Email) || setting.Equals(NotificationSetting.Both))\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if (setting.HasFlag(NotificationSetting.Email))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T01:01:23.967",
"Id": "63036",
"Score": "0",
"body": "`class User {}` Did you mean to make `User` inherit from `Settings`, just like in the original design? Though I'm not sure that's actually a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T07:47:47.780",
"Id": "63055",
"Score": "0",
"body": "@svick Yes. Fixed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T09:01:05.173",
"Id": "63056",
"Score": "0",
"body": "@svick There are other points as you point out. `User` is not a `Settings`, `User` has a `Settings`. `CreateNotification` should be just a factory method. Number of `NotificationX` suggest some sort of event setup."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T21:53:19.643",
"Id": "37893",
"ParentId": "37809",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:31:09.593",
"Id": "37809",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Are redundancy and reflection my only options here?"
}
|
37809
|
<p>In computer science, type conversion, type casting, and type coercion are different ways of changing an entity of one data type into another. An example would be the conversion of an integer value into a floating point value or its textual representation as a string, and vice versa. Type conversions can take advantage of certain features of type hierarchies or data representations. Two important aspects of a type conversion is whether it happens implicitly or explicitly, and whether the underlying data representation is converted from one representation into another, or a given representation is merely reinterpreted as the representation of another data type. In general, both primitive and compound data types can be converted.</p>
<p>Each programming language has its own rules on how types can be converted. Languages with strong typing typically do little implicit conversion and discourage the reinterpretation of representations, while languages with weak typing perform many implicit conversions between data types. Weak typing language often allow forcing the compiler to arbitrarily interpret a data item as having different representations -- this can be a non-obvious programming error, or a technical method to directly deal with underlying hardware.</p>
<p>Source: <a href="https://en.wikipedia.org/wiki/Type_conversion" rel="nofollow">Type conversion Wikipedia article</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:31:10.273",
"Id": "37810",
"Score": "0",
"Tags": null,
"Title": null
}
|
37810
|
Converting involves changing data from one data type or format to another.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:31:10.273",
"Id": "37811",
"Score": "0",
"Tags": null,
"Title": null
}
|
37811
|
<p>Context: I've been learning Python for a few months and I'm able to write codes which do work, but they normally look very ugly and contain a lot of unnecessary code. But I normally struggle to find better ways to do things because of my limited knowledge.</p>
<p>I would like some advice on what I can improve on the code below. FYI - it works perfectly well, but I'm guessing there must be ways to improve it. I know I'm repeating myself in the loops, for example.</p>
<pre><code>def getTableGroupTopMember_Test1(coordinates):
'''
Depending on the number of coordinates given, this function/code returns a unique coordinate.
'''
mylist = coordinates
for adc in activeDataConnections:
if mylist.Count == 1:
for table in adc:
if table.Name == mylist[0]:
print "/"
elif mylist.Count == 2:
for table in adc:
if table.Name == mylist[0]:
for topgroup in table.TopAxis.Groups:
if topgroup.Name == mylist[1]:
print topgroup.Address
elif mylist.Count == 3:
for table in adc:
if table.Name == mylist[0]:
for topgroup in table.TopAxis.Groups:
if topgroup.Name == mylist[1]:
for topmember in topgroup:
if topmember.Name == mylist[2]:
print topmember.Address
else:
print "your code is shit!"
getTableGroupTopMember_Test1(["Table10"])
getTableGroupTopMember_Test1(["Table10", "profile_julesage",])
getTableGroupTopMember_Test1(["Table10", "profile_julesage", "_25_to_34"])
</code></pre>
<p>Output:</p>
<pre><code>/
/2
/2[3]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:43:51.657",
"Id": "62933",
"Score": "2",
"body": "What is the API you're working with? Or to put it another way, what does activeDataConnections contain?\n\nMost database modules (eg sqllite) include query functionality which would eliminate most of the repetitive loop based code"
}
] |
[
{
"body": "<p>This is what I would do.</p>\n\n<p>First, rename <code>coordinates</code> to <code>coord_list</code> so you can eliminate <code>mylist</code> which is kind of useless since you only use immediately assign it to <code>coordinates</code>. To make things slightly simpler I assigned <code>count</code> to <code>coord_list.Count</code> so now you can just check <code>count</code> instead of <code>coord_list.Count</code>. Instead of executing the loop if the Count is bad, we check that <code>count</code> is between 1 and 3 before entering the loop. From here it loops though the <code>activeDataConnections</code> and has been changed so it checks <code>count</code> instead of repetition of the same logic.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>def getTableGroupTopMember_Test1(coord_list):\n '''\n Depending on the number of coordinates given, this function/code returns a unique coordinate. \n '''\n count = coord_list.Count\n\n # thanks to 200_success\n if not 0 < count < 4:\n print \"your code is shit!\"\n return\n\n for adc in activeDataConnections:\n for table in adc:\n if table.Name == coord_list[0] and count == 1:\n print \"/\"\n elif table.Name == coord_list[0]:\n for topgroup in table.TopAxis.Groups:\n if topgroup.Name == coord_list[1] and count == 2:\n print topgroup.Address\n elif topgroup.Name == coord_list[1]:\n for topmember in topgroup:\n if topmember.Name == coord_list[2]:\n print topmember.Address\n\n\n\ngetTableGroupTopMember_Test1([\"Table10\"])\ngetTableGroupTopMember_Test1([\"Table10\", \"profile_julesage\",])\ngetTableGroupTopMember_Test1([\"Table10\", \"profile_julesage\", \"_25_to_34\"])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:52:08.437",
"Id": "62939",
"Score": "0",
"body": "Your indentation is off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:53:39.223",
"Id": "62941",
"Score": "0",
"body": "Python supports double-ended comparisons. Also, I'd suggest reversing the condition and returning early. `if not 1 <= count < 4: print \"blah\"; return;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:40:09.003",
"Id": "62955",
"Score": "0",
"body": "That should be it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T13:27:18.850",
"Id": "63996",
"Score": "0",
"body": "I can now see how I could have improved my code. Thanks for the effort."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:47:58.157",
"Id": "37824",
"ParentId": "37813",
"Score": "3"
}
},
{
"body": "<p>This could be even a little shorter if you use list comprehension, yields and iteration to avoid all the if-tests (and, btw, use named variables instead of indices for clarity!)</p>\n\n<pre><code>def extract_all_coords (tablename, groupname, membername):\n valid_tables = [t for t in activeDataConnections.tables if t.Name == tablename]\n for t in tables:\n yield ('table', t)\n valid_groups = [g for g in t.TopAxis.Groups if g.Name == groupname]\n for g in valid_groups:\n yield ('group', g)\n valid_members =[m for m in g if m.Name == membername]\n for m in valid_members:\n yield ('member', m)\n\ndef extract_coords( tablename, groupname, membername):\n return dict([k for k in extract_all_coords(tablename, groupname, membername)])\n</code></pre>\n\n<p>In general I'd try to avoid functions that are open ended on both ends -- in your case, taking a variable number of inputs and returning a variable number of outputs. In this case, returning a dictionary means you should always get one answer to the question your asking and not have to write too much conditional logic to parse the answer later</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:47:49.623",
"Id": "37850",
"ParentId": "37813",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37824",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:46:30.270",
"Id": "37813",
"Score": "4",
"Tags": [
"python"
],
"Title": "Removing redundant lines from script"
}
|
37813
|
<p>Here's the current code: </p>
<pre><code> static string GetResources(string header, string filter, string resourceTemplate)
{
string themeName;
if (!TryGetHeaderValue(header, "theme", out themeName)) return "";
var resources = "";
var path = Path.Combine(HtmlPreview.BaseDirectory, themeName);
foreach (var resource in Directory.GetFiles(path, filter))
{
resources += String.Format(
resourceTemplate,
themeName,
Path.GetFileName(resource));
}
return resources;
}
</code></pre>
<p>I was wondering if I should use string builder instead: </p>
<pre><code>static string GetResources(string header, string filter, string resourceTemplate)
{
string themeName;
if (!TryGetHeaderValue(header, "theme", out themeName)) return "";
var resourcesStringBuilder = new StringBuilder();
var path = Path.Combine(HtmlPreview.BaseDirectory, themeName);
foreach (var resource in Directory.GetFiles(path, filter))
{
resourcesStringBuilder.Append(String.Format(
resourceTemplate,
themeName,
Path.GetFileName(resource)));
}
return resourcesStringBuilder.ToString();
}
</code></pre>
<p>Resharper simply suggests it is possible to replace the original code with a LINQ statement:</p>
<pre><code> static string GetResources(string header, string filter, string resourceTemplate)
{
string themeName;
if (!TryGetHeaderValue(header, "theme", out themeName)) return "";
var path = Path.Combine(HtmlPreview.BaseDirectory, themeName);
return Directory.GetFiles(path, filter)
.Aggregate("",
(current, resource) => current +
String.Format(resourceTemplate,
themeName,
Path.GetFileName(resource)));
}
</code></pre>
<p>Thank you! The original code with context is also on <a href="https://github.com/kusl/DownmarkerWPF/blob/master/src/MarkPad/Document/DocumentParser.cs#L117" rel="nofollow">github</a>. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:18:11.403",
"Id": "62949",
"Score": "5",
"body": "This question appears to be off-topic because it is about understanding the fundamentals of the framework, not a code review."
}
] |
[
{
"body": "<p>Strings in C# are immutable which means that this:</p>\n\n<pre><code> resouces += string.Format(...);\n</code></pre>\n\n<p>will create 2 strings: one from <code>string.Format</code> and then the new string created by appending it to the existing string.</p>\n\n<p>A <code>StringBuilder</code> will just keep a list of all the strings to append and create one result string at the end when you call <code>ToString()</code>. So instead of <code>2*n</code> strings you only create <code>n+1</code> strings. The <code>Aggregate</code> has the same problem.</p>\n\n<p>There are some optimizations in the C# compiler which can transform <code>string + string + string + ...</code> sequences into <code>Append</code> calls on a <code>StringBuilder</code> but you should not really rely on this.</p>\n\n<p>In the end it doesn't matter too much if your strings a short. However when you hit the 85kb limit then the strings will be placed on the large object heap which can cause problems because it doesn't get compacted and you can get holes. This can lead to weird out of memory situations (you can find more with google).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:16:34.513",
"Id": "62918",
"Score": "0",
"body": "Thank you. These are local file paths so I doubt we'd hit the 85kb limit here but that is really good to know."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:11:35.257",
"Id": "37820",
"ParentId": "37815",
"Score": "7"
}
},
{
"body": "<p>Using <code>string +=</code> in a loop is a very severe code smell, the worst possible solution both in terms of performance and memory fragmentation. Never do that, the <code>StringBuilder</code> class is designed exactly for such scenarios.</p>\n\n<p><strong>Edit</strong>\nThe reason in short is that string concatenation with <code>+=</code> will result in reallocation of the entire string for each loop cycle, whereas a <code>StringBuilder</code> is using a preallocated buffer which is filled with the individual parts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:12:30.030",
"Id": "62947",
"Score": "2",
"body": "this sounds like the start to a very good answer, I am tempted to upvote it, as is, but I think you should elaborate a little bit more on why it is a code smell and how `StringBuilder` is designed to handle this situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T07:05:09.393",
"Id": "62989",
"Score": "1",
"body": "@Malachi Here you go..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:27:11.263",
"Id": "37822",
"ParentId": "37815",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T17:02:47.660",
"Id": "37815",
"Score": "3",
"Tags": [
"c#",
".net",
"strings"
],
"Title": "Should I create an empty string and append through a foreach loop or should I use StringBuilder?"
}
|
37815
|
<p>I have to protect really sensitive information and I have to do it both ways: encryption and decryption. How safe is it?</p>
<pre><code>function encrypt($mprhase) {
$MASTERKEY = "KEY PHRASE!";
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $MASTERKEY, $iv);
$crypted_value = mcrypt_generic($td, $mprhase);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($crypted_value);
}
function decrypt($mprhase) {
$MASTERKEY = "KEY PHRASE!";
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $MASTERKEY, $iv);
$decrypted_value = mdecrypt_generic($td, base64_decode($mprhase));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $decrypted_value;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:24:40.167",
"Id": "62922",
"Score": "2",
"body": "What kind of data are you encrypting? User passwords? Top secret documents? Your e-mail address?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:31:39.757",
"Id": "62926",
"Score": "0",
"body": "It's a college exam questions that shouldn't be released until final exams, and it's for computer science department."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:36:24.220",
"Id": "62928",
"Score": "1",
"body": "Both ECB and TripleDES have known problems, you might want to look into other algorithms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:23:57.167",
"Id": "62951",
"Score": "0",
"body": "if this question is about how safe the encryption algorithms are you might want to try [ITSecurity](http://security.stackexchange.com/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:43:55.373",
"Id": "62957",
"Score": "1",
"body": "I am sorry you might want to try the new Beta site [Cryptography](http://crypto.stackexchange.com/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T16:41:15.583",
"Id": "63019",
"Score": "1",
"body": "@AliAbdulkarimSalem: Just a side-note: `MCRYPT_DEV_URANDOM` would be considered safer than using `MCRYPT_RAND`, as the latter relies on the system's RNG. They're not always as random as they claim to be. I know it's a tad paranoid, but seeing as this is for the CS division, you never know..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:25:32.610",
"Id": "63137",
"Score": "1",
"body": "Do you really need to write code to encrypt your files? Couldn't you just use a utility like PGP/GnuPG?"
}
] |
[
{
"body": "<p>In all reality the safety of the Data can be affected by any part of the transportation process, So just seeing how you encrypt and decrypt the information doesn't really help us help you in determining the safety of the data.</p>\n\n<hr>\n\n<h1>Nothing to do with the Security of the Functions</h1>\n\n<p>what you should do is create one function that will accept a parameter of <code>encrypt</code> or <code>decrypt</code> most of the information that you are using in both functions is duplicated.</p>\n\n<pre><code>function encryptOrDecrypt($mprhase, $crypt) {\n $MASTERKEY = \"KEY PHRASE!\";\n $td = mcrypt_module_open('tripledes', '', 'ecb', '');\n $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);\n mcrypt_generic_init($td, $MASTERKEY, $iv);\n if ($crypt == 'encrypt')\n {\n $return_value = base64_encode(mcrypt_generic($td, $mprhase));\n }\n else\n {\n $return_value = mdecrypt_generic($td, base64_decode($mprhase));\n }\n mcrypt_generic_deinit($td);\n mcrypt_module_close($td);\n return $return_value;\n} \n</code></pre>\n\n<p>obviously some of the variables have been changed to protect the innocent, (<em>in other words you should change the variable <code>$return_value</code> to something more meaningful</em>)</p>\n\n<p>(<strong>another note:</strong> <em>you might want to fiddle around with the input parameter that I added as well.</em>) </p>\n\n<hr>\n\n<h1>Additional Important Information</h1>\n\n<p>As Corbin Pointed out, this should be a class/object that has methods for encrypting and deciphering and the whole works that go along with a class/object, unfortunately I don't know PHP syntax well enough to write it out.</p>\n\n<p>a Function can do this, but it is sloppy coding, and I should have said this from the get go, I apologize.</p>\n\n<p>I will look into the syntax when I have time or you can Visit this <strong><a href=\"http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/\" rel=\"nofollow\">Fun page</a></strong> Or you can use <strong><a href=\"https://www.google.com/search?q=php%20class%20tutorial&oq=php%20class&aqs=chrome.4.69i57j0l5.5404j0j8&sourceid=chrome&espv=210&es_sm=93&ie=UTF-8\" rel=\"nofollow\">ol' reliable</a></strong> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:54:27.680",
"Id": "63139",
"Score": "1",
"body": "Something about this just doesn't feel quite right to me. Having a flag change behavior is typically a major red flag that the function should be split into more than one function. I think I would prefer slightly duplicated code than a non-single-responsibility function. I also think it's dangerous to use a string flag and not check for a valid input to it. That's just waiting for some kind of misuse to fall through the cracks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T14:39:21.887",
"Id": "63161",
"Score": "0",
"body": "@Corbin, you are completely right, this should be a class/object that has methods for encrypting and deciphering and the whole works that go along with a class/object, unfortunately I don't know PHP syntax well enough to write it out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:34:36.030",
"Id": "37828",
"ParentId": "37821",
"Score": "3"
}
},
{
"body": "<p>As @grasGendarme says, neither the Triple-DES cipher nor the ECB cipher mode is considered to offer good security.</p>\n\n<p>ECB mode is fast and easy to use, but is easy to cryptanalyze and <a href=\"https://crypto.stackexchange.com/q/225\">generally not recommended</a>. ECB mode encrypts each block independently, so if a block appears twice in the plaintext, then it will be encrypted into two identical blocks in the ciphertext. It may be acceptable to use ECB if your plaintext is short and random — for example, if you are encrypting a crypto key — and it has no predictable elements such as a standard header.</p>\n\n<p>In <em>Applied Cryptography</em>, Second Edition, §9.11, Bruce Schneier recommends:</p>\n\n<ul>\n<li>For encrypting short random data, such as other keys, ECB is OK.</li>\n<li>For normal plaintext, use CBC, CFB, or OFB.</li>\n<li>CBC is generally best for encrypting files.</li>\n<li>CFB — specifically 8-bit CFB — is generally the mode of choice for encrypting streams, as in a link between a terminal and a host.</li>\n<li>OFB/Counter is the mode of choice in an error-prone environment.</li>\n</ul>\n\n<p>My guess is that you want CBC, but you should make that determination for yourself.</p>\n\n<p>Triple-DES is considered an old standard; it has been <a href=\"https://security.stackexchange.com/q/26179\">superseded by AES</a>. While Triple-DES hasn't been cracked, if you had to choose a cipher from scratch, you ought to pick AES.</p>\n\n<p>It's a bad idea to hard-code the key in your code. Store it in a separate file, where it may be better protected by filesystem permissions and encrypted with a passphrase.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:22:55.147",
"Id": "37943",
"ParentId": "37821",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37828",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:21:37.140",
"Id": "37821",
"Score": "2",
"Tags": [
"php",
"security",
"cryptography"
],
"Title": "Encrypt/decrypt PHP function"
}
|
37821
|
<p>I'm pretty new to ASP/MVC but have had some prior programming experience.</p>
<p>I am trying to retrieve statistics about URL clicks - total clicks and unique clicks by IP address. I started with:</p>
<pre><code>ViewBag.ClicksToday = context.EmailLinkClicks
.Where(c => c.CreatedOn == DateTime.Today).Count();
ViewBag.ClicksWeek = context.EmailLinkClicks
.Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7)).Count();
ViewBag.ClicksMonth = context.EmailLinkClicks
.Where(c => c.CreatedOn.Month == DateTime.Today.Month).Count();
ViewBag.UniqueClicksToday = context.EmailLinkClicks.Where(c => c.CreatedOn == DateTime.Today)
.Select(c => c.IPAddress).Distinct().Count();
ViewBag.UniqueClicksWeek = context.EmailLinkClicks.Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7))
.Select(c => c.IPAddress).Distinct().Count();
ViewBag.UniqueClicksMonth = context.EmailLinkClicks.Where(c => c.CreatedOn.Month == DateTime.Today.Month)
.Select(c => c.IPAddress).Distinct().Count();
</code></pre>
<p>Then I thought why not make it a function:</p>
<pre><code>private static int GetClicks(AppContext context, string period, bool unique)
{
int Clicks = 0;
switch (period)
{
case "today":
var ClicksToday = context.EmailLinkClicks
.Where(c => c.CreatedOn == DateTime.Today);
Clicks = unique ? ClicksToday.Select(c => c.IPAddress).Distinct().Count()
: ClicksToday.Count();
break;
case "week":
var ClicksWeek = context.EmailLinkClicks
.Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7));
Clicks = unique ? ClicksWeek.Select(c => c.IPAddress).Distinct().Count()
: ClicksWeek.Count();
break;
case "month":
var ClicksMonth = context.EmailLinkClicks
.Where(c => c.CreatedOn.Month == DateTime.Today.Month);
Clicks = unique ? ClicksMonth.Select(c => c.IPAddress).Distinct().Count()
: ClicksMonth.Count();
break;
}
return Clicks;
}
</code></pre>
<p>But I still have to call quite a lot of code:</p>
<pre><code>ViewBag.ClicksToday = GetClicks(context, "today", false);
ViewBag.ClicksWeek = GetClicks(context, "week", false);
ViewBag.ClicksMonth = GetClicks(context, "month", false);
ViewBag.UniqueClicksToday = GetClicks(context, "today", true);
ViewBag.UniqueClicksWeek = GetClicks(context, "week", true);
ViewBag.UniqueClicksMonth = GetClicks(context, "month", true);
</code></pre>
<p>My questions:</p>
<ol>
<li><p>Is there any way to further simplify/reduce this code?</p>
<ul>
<li>perhaps have the total & unique in one value? [total],[unique]</li>
</ul></li>
<li><p>Is it poor practice to pass <strong>period</strong> as a string and then interrogate it?</p></li>
<li><p>Where should you store these kind of database queries? It currently resides in my controller and then returned to the view.</p></li>
</ol>
|
[] |
[
{
"body": "<p>Here's the first thing I came up with. Wrote it in Notepad, so it might not compile exactly as is. </p>\n\n<pre><code>private static int GetClicks(AppContext context, Period period, bool unique)\n{\n int Clicks = 0;\n switch (period)\n {\n var query = context.EmailLinkClicks.AsQueryable();\n case Period.Today:\n query = query.Where(c => c.CreatedOn == DateTime.Today);\n break;\n case Period.Week:\n query = query.Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7));\n break;\n case Period.Month:\n query = query.Where(c => c.CreatedOn.Month == DateTime.Today.Month);\n break;\n }\n\n var ipAddresses = query.Select(c => c.IpAddress);\n\n if (unique)\n {\n query = query.Distinct();\n }\n\n return query.Count();\n}\n\nenum Period \n{\n Today,\n Week,\n Month\n}\n</code></pre>\n\n<p><strong>Update:</strong> As to where to store these queries... Doing it in your controller isn't the worst thing in the world. There are a ton of different places you could put that code though. The Repository pattern seems to be popular. I'm not strict about that kind of thing though.</p>\n\n<p><strong>Update:</strong> if you wanted to get both the total and unique stats in the same call, you could do something like this: <a href=\"https://gist.github.com/alexdresko/8059762/bcf233b86869042c4b6f360f6b461999b2bf4899\" rel=\"nofollow\">https://gist.github.com/alexdresko/8059762/bcf233b86869042c4b6f360f6b461999b2bf4899</a></p>\n\n<p><strong>Update:</strong> But what you probably want, assuming you want to create some kind of report, is this: <a href=\"https://gist.github.com/alexdresko/8059762/c4afa948f020e8395bb27d565269c914aad926a7\" rel=\"nofollow\">https://gist.github.com/alexdresko/8059762/c4afa948f020e8395bb27d565269c914aad926a7</a></p>\n\n<p>That one will allow you to simply iterate over the collections of stats in your view, display all relevant information. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T01:10:14.803",
"Id": "63038",
"Score": "0",
"body": "Good advice in general, but: 1. I'm not completely sure about the use of `.AsQueryable()`, I think the omitting that and explicitly specifying the type of `query` would be cleaner. 2. What happens when `period` has an invalid value? 3. You're not using `ipAddresses` anywhere, which means you're not calculating the case when `unique == true` correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T03:28:38.063",
"Id": "63042",
"Score": "0",
"body": "1. You _have_ to use AsQueryable() or the query chaining I'm doing in the example won't work. 2. Period won't have an invalid value because I'm using an enum. 3. Oops, you're right about that. I did mention in my OP that I wrote that code in notepad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T04:13:21.133",
"Id": "63044",
"Score": "0",
"body": "1. You don't, you can write `IQueryable<EmailLinkClick> query = context.EmailLinkClicks;` and it will work. 2. That's not how `enum`s work in .Net, you can always do something like `(Period)42` and you're going to get an invalid value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T04:33:25.957",
"Id": "63046",
"Score": "0",
"body": "1. What's the difference between what you wrote and what I wrote, except that mine is quite a bit shorter? 2. Who does that? :) And how would you get around it without a bunch of silly code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T11:13:21.197",
"Id": "63065",
"Score": "0",
"body": "1. The difference is very small, yes. I *think* that my approach makes it easier to understand what does the line actually do. But your way is okay too. 2. I don't think `default: throw InvalidOperationException();`, or something like that is silly code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T12:05:16.843",
"Id": "63070",
"Score": "0",
"body": "1. Ah, the var/no-var debate. I'm pro-var. You'd have a hard time convincing me that this is a bad place to use var. But, 2, you did convince me that the default: is a good idea. :) I likely won't remember to do that 99% of the time, but it's a good idea. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T11:44:31.097",
"Id": "63147",
"Score": "0",
"body": "Thanks Alex. I amended your code slightly. I've been reading online and a lot of people seem to disapprove of the ViewBag/Data concepts and favour strongly-typed models. So what I did was put the Stats class and Period Enum in the EmailLinksClick class and then return the model back to the partial view. Then simply loop through the @model List<Models.Stats> object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T14:57:36.417",
"Id": "63162",
"Score": "0",
"body": "Very good @JakkyD. That's absolutely the better thing to do in this case."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:00:13.240",
"Id": "37826",
"ParentId": "37823",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37826",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:47:54.747",
"Id": "37823",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"beginner",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Retrieving statistics about URL clicks"
}
|
37823
|
<p>Problem statement is at <a href="http://www.codechef.com/DEC13/problems/MARBLEGF" rel="nofollow">http://www.codechef.com/DEC13/problems/MARBLEGF</a></p>
<blockquote>
<p>Lira is given array A, which contains elements between 1000 and 2000.
Three types of queries can be performed on this array: add a given value to a single element on it, subtract a given value from a single element on it and find the sum of the values between indexes i and j, i.e. A[i]+...+A[j]. Check input and example section for details.</p>
<h3>Input</h3>
<p>The first line of the input contains two integers: N and Q, denoting respectively, the number of students that there are present to receive the marbles as a gift and the number of actions Lira's mom will perform.</p>
<p>These actions can be of three different types:</p>
<ul>
<li>S i j - if the mom wants to find the sum of the number of marbles from students i to j.</li>
<li>G i num_marbles - if the mom decides to give num_marbles to student i</li>
<li>T i num_marbles - if the mom decides to take away num_marbles from student i</li>
</ul>
<h3>Output</h3>
<p>The output should contain as many lines as the number of queries S and it should contain the answer for each query on a separate line</p>
<h3>Constraints</h3>
<ul>
<li>2 ≤ N ≤ 1000000</li>
<li>3 ≤ Q ≤ 50000</li>
<li>The array is 0-indexed.</li>
<li>1000 ≤ A[i] ≤ 2000</li>
<li>A student can never have a negative value of marbles. (i.e. there's no data which can cause a student to have a negative value of marbles)</li>
<li>0 ≤ i, j ≤ N-1, and i ≤ j for the sum query</li>
<li>At any given time, it is assured that the maximum number of marbles each student can have (num_marbles) never exceeds the size of the int data type.</li>
</ul>
<h3>Example</h3>
<p>Input:</p>
<pre><code>5 3
1000 1002 1003 1004 1005
S 0 2
G 0 3
S 0 2
</code></pre>
<p>Output:</p>
<pre><code>3005
3008
</code></pre>
</blockquote>
<p>My code gives time limit exceeded.</p>
<p>My code:</p>
<pre><code>import java.util.*;
class funny_marbles
{
public static void main(String[] ar)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = sc.nextInt();
for(int i = 0; i < q; i++)
{
String s = sc.next();
int t1 = sc.nextInt();
int t2 = sc.nextInt();
if(s.equals("S"))
{
long sum = 0;
for(int j = t1; j <= t2; j++)
sum+=a[j];
System.out.println(sum);
}
else if(s.equals("G"))
a[t1]+=t2;
else if(s.equals("T"))
a[t1]-=t2;
}
}
}
</code></pre>
<p><strong>Updated</strong> to use cumulative sum, but still exceeding time limit:</p>
<pre><code>import java.util.*;
class funny_marbles
{
public static void main(String[] ar)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++)
{
if(i == 0)
a[i] = sc.nextInt();
else
a[i] = a[i-1] + sc.nextInt();
}
for(int i = 0; i < q; i++)
{
String s = sc.next();
int t1 = sc.nextInt();
int t2 = sc.nextInt();
if(s.equals("S"))
{
int x;
if(t1 == 0)
x = 0;
else
x = a[t1-1];
System.out.println(a[t2]-x);
}
else if(s.equals("G"))
{
update(a,t2);
}
else if(s.equals("T"))
{
update(a,-t2);
}
}
}
public static void update(int[] a, int t)
{
for(int i = 0; i < a.length; i++)
a[i] += t;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:05:54.970",
"Id": "62943",
"Score": "0",
"body": "How are you timing it? What input values are you using? Also please add a short description of the problem itself *within* the question. Also please describe your approach a little so that it is easier to understand your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:09:06.330",
"Id": "62944",
"Score": "0",
"body": "@SimonAndréForsberg I am not timing it, I submitted it at CodeChef and it gave TLE.It works for sample input.I haven't done special, just simulated what was written in the question.But I think brute force will not work here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:35:06.040",
"Id": "62953",
"Score": "0",
"body": "@user2369284 Very nicely formatted question."
}
] |
[
{
"body": "<p>Given the constraints, the maximum sum, <em>N</em> * max(<em>A</em>), would be 2000000000, which fits within a Java <code>int</code>. You don't need a <code>long</code>.</p>\n\n<p>Your code is a straightforward implementation of the challenge; there's nothing to micro-optimize. Your only hope is to use a different approach.</p>\n\n<p>Assuming that the test is heavy on \"S\" queries, you would be better off keeping an array of cumulative sums. Then you could answer an \"S\" query in constant time.</p>\n\n<p>What to do with \"G\" and \"T\" operations, though? The elegant approach would be to update the entire cumulative sums array for each \"G\" or \"T\". However, since <em>N</em> is likely to be larger than <em>Q</em>, you might get better performance keeping the \"G\" and \"T\" operations as a list of exceptions instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:42:38.810",
"Id": "62956",
"Score": "0",
"body": "What do you mean by cumulative sums?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:46:06.847",
"Id": "62958",
"Score": "0",
"body": "For the example, store `{ 1000, 2002, 3005, 4009, 5014 }`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:52:52.777",
"Id": "62960",
"Score": "1",
"body": "In short, I have to make a cumulative array, apply \"G\" and \"T\" on all elements and for \"S\" return array[j] - array[i]. Is that correct ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:09:16.337",
"Id": "62961",
"Score": "0",
"body": "Updated my code. Still giving TLE"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:50:27.537",
"Id": "62963",
"Score": "1",
"body": "Please don't edit away the original code; doing so invalidates any reviews. I've restored the original code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:51:21.837",
"Id": "62964",
"Score": "0",
"body": "The updated code in Rev 6 is now wrong. Hint: what do you do with `t1`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:41:07.383",
"Id": "62974",
"Score": "0",
"body": "It turns out that you have to use a more sophisticated variant of the cumulative sum idea. You'll actually learn more by looking at one of the successful submissions and figuring out how it works than for me to hint at what to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T15:06:31.217",
"Id": "63015",
"Score": "0",
"body": "I don't understand what the participants have done. Please help ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T09:36:21.927",
"Id": "63887",
"Score": "0",
"body": "The data structure to use is called a [binary indexed tree](http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees) or [Fenwick tree](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.14.8917&rep=rep1&type=pdf). The [leading Java solution](http://www.codechef.com/viewsolution/3029781) uses zero-based arrays, so the code looks different from the tutorial and the paper, which use one-based arrays. The principle is the same, though."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:38:20.053",
"Id": "37829",
"ParentId": "37825",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T18:54:23.950",
"Id": "37825",
"Score": "5",
"Tags": [
"java",
"performance",
"array",
"mathematics"
],
"Title": "Optimising Funny Marbles"
}
|
37825
|
Programming associated with creating and managing networks as well as adding network connectivity to a (set of) programs.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:39:40.463",
"Id": "37832",
"Score": "0",
"Tags": null,
"Title": null
}
|
37832
|
<p>A structure can be a:</p>
<ul>
<li>A <strong>data structure</strong>: a particular way of storing and organizing data in a computer so that it can be used efficiently.</li>
<li>A <strong>struct</strong> (short for "structure") is a computer science term for a record that is used to store more than one value.</li>
<li>A structure in <strong>mathematical logic</strong>: in universal algebra and in model theory, a structure consists of a set along with a collection of finitary operations and relations which are defined on it.</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:45:14.403",
"Id": "37833",
"Score": "0",
"Tags": null,
"Title": null
}
|
37833
|
A structure is a fundamental, tangible or intangible notion referring to the recognition, observation, nature, and permanence of patterns and relationships of entities.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:45:14.403",
"Id": "37834",
"Score": "0",
"Tags": null,
"Title": null
}
|
37834
|
A block of arbitrary information, or resource for storing information, accessible by the string-based name or path. Files are available to computer programs and are usually based on some kind of persistent storage.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:49:49.183",
"Id": "37836",
"Score": "0",
"Tags": null,
"Title": null
}
|
37836
|
A generator is a generalization of a subroutine, primarily used to simplify the writing of iterators. The yield statement in a generator does not specify a co-routine to jump to, but rather passes a value back to a parent routine.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:52:23.083",
"Id": "37838",
"Score": "0",
"Tags": null,
"Title": null
}
|
37838
|
<p><a href="https://en.wikipedia.org/wiki/Syntax_%28programming_languages%29" rel="nofollow">From Wikipedia</a>:</p>
<blockquote>
<p>In computer science, the <strong>syntax</strong> of a computer language is the set of
rules that defines the combinations of symbols that are considered to
be a correctly structured document or fragment in that language. This
applies both to programming languages, where the document represents
source code, and markup languages, where the document represents data.
The syntax of a language defines its surface form. Text-based
computer languages are based on sequences of characters, while visual
programming languages are based on the spatial layout and connections
between symbols (which may be textual or graphical). Documents that
are syntactically invalid are said to have a syntax error.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:00:40.817",
"Id": "37839",
"Score": "0",
"Tags": null,
"Title": null
}
|
37839
|
In computer science, the syntax of a programming language is the set of rules that define the combinations of symbols that are considered to be correctly structured programs in that language.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:00:40.817",
"Id": "37840",
"Score": "0",
"Tags": null,
"Title": null
}
|
37840
|
Microsoft Access, also known as Microsoft Office Access, is a database management system from Microsoft that combines the relational Microsoft Jet Database Engine with a graphical user interface and software-development tools.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:19:39.460",
"Id": "37842",
"Score": "0",
"Tags": null,
"Title": null
}
|
37842
|
Portable code can be run with little to no modification in multiple environments. Portable applications can be run from, for example, a USB drive without modifying a computer's environment.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:21:38.630",
"Id": "37844",
"Score": "0",
"Tags": null,
"Title": null
}
|
37844
|
A formal grammar is a set of production rules that describe how to form strings of valid syntax. Formal grammars are most often used to specify the syntax of a programming language.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:26:15.093",
"Id": "37847",
"Score": "0",
"Tags": null,
"Title": null
}
|
37847
|
<p>I'm trying to make my code easier to understand by making it more correct and maintainable.</p>
<p>Here's the code I'm trying to simplify:</p>
<pre><code> $(document).ready(function(){
$('.opretbruger').on('click', function(){
if (opretbruger() === true){
}
});
});
var opretbruger = function(){
if($('#brugernavn').val() === ''){
alert('remember Email');
return false;
}
if($('#pass1').val() === ''){
alert('remember password');
return false;
}
if($('#pass2').val() === ''){
alert('remember password');
return false;
}
if($('#fornavn').val() === ''){
alert('remember your name');
return false;
}
if($('#efternavn').val() === ''){
alert('remember your last name');
return false;
}
return true;
};
</code></pre>
<p>Here's my attempt at simplifying it:</p>
<pre><code> $(function () {
var $login = $("#login"),
$pwd = $("#pass"),
$usr = $("#brugernavn");
$login.on("submit", function (event) {
var msg = "Husk ",
usr = ($usr.val().trim() !== ""),
pwd = ($pwd.val().trim() !== "");
msg += !usr ? " brugernavn" : "";
msg += !usr && !pwd ? " og " : "";
msg += !pwd ? " kodeord" : "";
(pwd && usr) || alert(msg);
return (pwd && usr);
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T22:06:20.983",
"Id": "62975",
"Score": "0",
"body": "What does `overskulig` mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T22:07:37.753",
"Id": "62976",
"Score": "0",
"body": "@Nobody its foreseeable. :)"
}
] |
[
{
"body": "<p>Let me make sure I understand the problem. You have a number of fields on the page where a value is required; when the user submits the page, and any of the fields are blank, you'd like the page to display a Javascript alert instead of submitting the form. Yes?</p>\n\n<p>I'd suggest you use an unobtrusive technique as follows:</p>\n\n<ol>\n<li>If a field is required, it is marked with a \"required\" css class. This can be a dummy class if you like.</li>\n<li>Each field that is required is associated with a data attribute which specifies its human-readable name in the appropriate language</li>\n<li>The submit button inspects all fields that are marked with the style and displays the names.</li>\n</ol>\n\n<p>So to mark up a required field, use this pattern:</p>\n\n<pre><code><input ID=\"login\" class=\"required\" data-name=\"login\"/>\n</code></pre>\n\n<p>Then include this bit of code in your common script. There's nothing page- or field- specific in it, so you can include it in every page if you want (e.g. in \"common.js\" or whatever):</p>\n\n<pre><code>$(document).ready(function(){\n var validate = function(e){\n var emptyFields = [];\n $(\".required\").each(function(){\n if ($(this).val().trim() == \"\") emptyFields.push($(this).data(\"name\")); \n }\n if (emptyFields.length != 0) {\n e.preventDefault();\n var message = \"You forgot these fields: \" + emptyFields.join(\",\"); \n alert(message);\n }\n }\n\n $(\":submit\").click(validate);\n})\n</code></pre>\n\n<p>This ought to cover any additional fields or really any additional pages that require this sort of validation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T23:05:06.563",
"Id": "62977",
"Score": "0",
"body": "its not work for me, It does not come up with some errors or similar"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T23:42:16.447",
"Id": "62980",
"Score": "0",
"body": "I fixed a minor syntax error (missing a right paren), please try again. If you still have trouble, please let me know what kind of error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T23:52:31.143",
"Id": "62981",
"Score": "0",
"body": "it works is still not, and have not error.."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T22:30:26.800",
"Id": "37853",
"ParentId": "37852",
"Score": "2"
}
},
{
"body": "<h1>Solution 1</h1>\n<ol>\n<li><p>I suggest you place your inputs inside a <code><form></code>, that way, you won't be listening for a button <code>click</code> or ID each input. Instead, you'd be listening for a form <code>submit</code>. You can easily do that this way:</p>\n</li>\n<li><p>On the HTML side of things, the inputs in the forms need <code>name</code> attributes like they should. This will come handy later in the code</p>\n</li>\n<li><p>Next is to get <a href=\"https://stackoverflow.com/a/1186309/575527\">this very handy snippet</a>. This turns your form into an object, with keys as the names of the form inputs, and values as their values. I have to note that this snippet has issues when names have dashes, so avoid them.</p>\n</li>\n<li><p>Now, for the messages, you should make a map for the names to messages. Then in your validation code, loop through the messages and look at the value of the same key in <code>formValues</code>. If it the value is blank, then alert the message.</p>\n</li>\n</ol>\n<p>The code should look like this all in all. All you need to do is add names and messages for the things you want to check to <code>messages</code>.</p>\n<pre><code>var messages = {\n brugeravn : 'You forgot brugeravn',\n pass1 : 'You forgot pass1',\n ...\n}\n\n$('#TheFormID').on('submit',function(event){\n event.preventDefault();\n var formValues = $(this).serializeObject();\n\n $.each(messages,function(key,message){\n if(formValues.hasOwnProperty(key) && formValues[key] === ''){\n alert(message);\n }\n });\n});\n</code></pre>\n<h1>Solution 2</h1>\n<p>This would be similar to John Wu's answer, but a bit refined. I usually do this when developing with backend guys who don't like to write JS. So I give them config capability through <code>data-*</code> attributes.</p>\n<ol>\n<li><p>Same as solution 1, put everything in a form for ease of handling.</p>\n</li>\n<li><p>On the HTML, add in a few parameters. <code>name</code> isn't required this time.</p>\n<pre><code> <input type="text" data-required="true" data-message="You forgot brugeravn" />\n</code></pre>\n<p>As you can see, we set the input to "required" and set in a message, both via <code>data-*</code> attributes.</p>\n</li>\n</ol>\n<p>The only JS code you'll need for this solution is the following. What it does is listen for the form, gather all inputs marked "required" and check their values. If it's blank, alert their supplied message.</p>\n<pre><code> $('#TheFormID').on('submit',function(event){\n event.preventDefault();\n\n $(this).find('[data-required=true]').each(function(){\n if(this.value === '') alert(this.getAttribute('data-message'));\n });\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T01:38:37.520",
"Id": "37858",
"ParentId": "37852",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T21:58:22.313",
"Id": "37852",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"validation"
],
"Title": "Displaying alerts for blank fields"
}
|
37852
|
<p>The question is explained well by examples in the comments below. Also I request verifying complexity: O( n * n!), where n is the number of words in the subsets. Review my code for optimizations, best practices etc.</p>
<pre><code>/**
* Question is better explained by examples:
* 1. given
* i/p subsets - ["un", "xy", "te", "i", "d"]
* and i/p string is : united should result in true.
* and i/p string of : union should result in false.
*
* 2. i/p subsets - ["tonyl", "pqr", "pqrbri",]
* and i/p string of : briton should be true.
* and i/p string of : japan should result in false.
*
* Complexity: O( n * n!) where n is numnber of subset words.
*
*/
public final class StringFromSubSets {
private StringFromSubSets() {}
private static int getFactorial (int length) {
int factorial = 1;
for (int i = 1; i <= length; i++) {
factorial = factorial * i;
}
return factorial;
}
private static void swapWithNext (List<String> subStrings, int i) {
assert subStrings != null;
assert i >= 0 && i < subStrings.size() - 1;
String str = subStrings.get(i);
subStrings.set(i, subStrings.get(i + 1));
subStrings.set(i + 1, str);
}
private static String join (List<String> list) {
assert list != null;
final StringBuffer sb = new StringBuffer();
for (String str : list) {
sb.append(str);
}
return sb.toString();
}
private static Set<String> getPermutations(List<String> subStrings) {
assert subStrings != null;
final Set<String> set = new HashSet<String>();
int factorial = getFactorial(subStrings.size());
int counter = 0;
while (counter < factorial) {
for (int i = 0; i < subStrings.size() - 1; i++) {
swapWithNext (subStrings, i); // O(1)
String joinedString = join (subStrings); // O(n)
set.add(joinedString);
counter++;
}
}
return set;
}
public static boolean stringGotFromSubSets(List<String> subStrings, String wordToFind) {
if (subStrings == null) {
throw new NullPointerException("The substring provided is null.");
}
final Set<String> joinedStrings = getPermutations(subStrings);
for (String joinedString : joinedStrings) {
if (joinedString.contains(wordToFind)) return true;
}
return false;
}
public static void main(String[] args) {
List<String> listOfString = new ArrayList<String>();
listOfString.add("sachin");
listOfString.add("tendulkar");
listOfString.add("rahul");
listOfString.add("dravid");
System.out.println("Expected true, Actual " + stringGotFromSubSets(listOfString, "int"));
System.out.println("Expected true, Actual " + stringGotFromSubSets(listOfString, "idsa"));
System.out.println("Expected true, Actual " + stringGotFromSubSets(listOfString, "sachindravid"));
System.out.println("Expected false, Actual " + stringGotFromSubSets(listOfString, "sehwag"));
System.out.println("Expected false, Actual " + stringGotFromSubSets(listOfString, "ganguly"));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T11:55:55.570",
"Id": "63012",
"Score": "1",
"body": "I don't get it. What is your algorithm supposed to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T15:12:13.943",
"Id": "63080",
"Score": "0",
"body": "the original code isn't correct and doesn't do what it is supposed to do as pointed out by @200_succes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T02:25:08.783",
"Id": "63124",
"Score": "1",
"body": "Revised code here: http://codereview.stackexchange.com/q/37930"
}
] |
[
{
"body": "<p>Your <code>getPermutations()</code> fails to generate all permutations. Consider…</p>\n\n<pre><code>public static void main(String[] args) {\n List<String> list = Arrays.asList(args);\n for (String s : getPermutations(list)) {\n System.out.println(s);\n }\n}\n</code></pre>\n\n<p>If you run <code>java StringFromSubSets 0 1 2 3 | sort</code>, the result is:</p>\n\n<blockquote>\n<pre><code>0123\n0132\n0312\n1023\n1203\n1230\n2130\n2301\n2310\n3012\n3021\n3201\n</code></pre>\n</blockquote>\n\n<p>There should be 4! = 24 permutations, but you have produced only 12. For example, where is <code>0321</code>? In other words,</p>\n\n<pre><code>public static void main(String[] args) {\n // Simpler initialization than the original\n List<String> listOfString = Arrays.asList(new String[] {\n \"sachin\", \"tendulkar\", \"rahul\", \"dravid\"\n });\n System.out.println(\"Expected true, Actual \" +\n stringGotFromSubSets(listOfString, \"drahultendulkars\"));\n}\n</code></pre>\n\n<p>… prints <code>Expected true, Actual false</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T20:59:54.967",
"Id": "37889",
"ParentId": "37860",
"Score": "7"
}
},
{
"body": "<p>There are a number of things that are problematic.</p>\n\n<p>most fundamental is the algorithm you are choosing to run. It does indeed appear to be something like <code>O(n!)</code> complexity. This is unsustainable.... and needs to be resolved.What it means is that your solution will effectively be unusable for more than 13 members of the list. This is especially true because you store all combinations in a single set... which is 'insane'.</p>\n\n<p>What you are doing is searching for a needle in a haystack, and first you build the haystack ;-).</p>\n\n<p>Instead, you need to use a better algorithm (take a magnet to the haystack ...).</p>\n\n<p>But, dealing with your first issues first:</p>\n\n<ul>\n<li>there is almost never any reason (unless you use <code>java.util.regex.Matcher</code>) to use <code>StringBuffer</code>. use <code>StringBuilder</code> instead.</li>\n<li>your asserts are OK, but you need to also assert that the size of the list is less than 13, because <code>12!</code> is the largest factorial that fits in an <code>int</code>. Changing it to a long won't help because you can't have a set with more than <code>Integer.MAX_VALUE</code> members anyway.</li>\n<li>the other issues I have with your code stem from the fact you are using the wrong algorithm.....</li>\n</ul>\n\n<p>Now, if this was my problem, I would restructure it entirely.</p>\n\n<p>I would have one method that loops through all the members of the input set, and checks to see whether there's an overlap at the 'end' of the String, then I would split that matching value and keep the unused prefix, and then recursively search the remaining values.... let's explain that with pseudo code:</p>\n\n<pre><code>function: searchSequence(target, values)\n foreach (value : values)\n if (lastPartOfValueStarts(value, target)\n String matchingsuffix = matchingPartOf(value);\n String notmatchingprefix = restOf(value);\n Set candidates = values\n candidates.remove(value)\n candidates.add(nonmatchingprefix)\n if (recursiveSearch(target, lengthOf(matchingsuffix)))\n return true;\n\nfunction: recursiveSearch(target, fromindex, candidates)\n String remainder = target.substring(fromindex)\n foreach (candidate : candidates)\n if (candidate.startsWith(remainder))\n return true;\n if (remainder.startsWith(candidate))\n Set others = candidates.duplicate()\n others.remove(candidate)\n if (recursiveSearch(target, fromindex + lengthOf(candidate), others))\n return true\n return false\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T21:55:26.323",
"Id": "37894",
"ParentId": "37860",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37894",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T02:57:49.800",
"Id": "37860",
"Score": "2",
"Tags": [
"java",
"algorithm",
"strings",
"combinatorics"
],
"Title": "Determine if a word can be constructed from list of subsets"
}
|
37860
|
<p>I'm doing a website in CodeIgniter and I'm loading the content page via jQuery, but I don't know if this is a good practice or not. Could I improve it?</p>
<p><strong>jQuery:</strong> </p>
<pre><code>// Another question here: how can I group the repeated code in a function:
$(function() {
var control = '../Indoamericana/Intranet/index/Proceso/';
var loadPage = function(page){
$(".page-content").load(page);
};
$("#gestion_directiva").click(function(event) {
var process = 1;
loadPage(control + process);
});
$("#gestion_calidad").click(function(event) {
var process = 2;
loadPage(control + process);
});
$("#gestion_academica").click(function(event) {
var process = 3;
loadPage(control + process);
});
</code></pre>
<p><strong>Controller:</strong></p>
<pre><code>/**
* index();
*
* funcion que carga la información del proceso en la intranet
* @param String $process Identificador del proceso a cargar
* @return Vista del proceso indicado
*/
public function index($process, $idProcess){
$data['data'] = $this->intranet_model->getProcessInfo($idProcess);
$data['member'] = $this->intranet_model->getMembers($idProcess);
$data['proceso'] = 'GI7';
$route = '/Modules/Intranet/';
$route .= $process;
$this->load->view($route, $data);
}
</code></pre>
<p><strong>View:</strong> </p>
<pre><code><div class="row">
<div class="col-md-12">
<h3 class="page-title">
<?php foreach ($data as $row): ?>
<?php echo $row->name ?>
<?php endforeach ?>
</h3>
<ul class="page-breadcrumb breadcrumb">
<li>
<i class="icon-home"></i>
<a href="index.html">Página Principal</a>
<i class="icon-angle-right"></i>
</li>
<li>
<a href="#">Intranet</a>
<i class="icon-angle-right"></i>
</li>
<li>
<a href="#">
<?php foreach ($data as $row): ?>
<?php echo $row->name ?>
<?php endforeach ?>
</a>
</li>
</ul>
</div>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>You might already know this but you can add a library class called 'template' it allows you to make a kind of a masterpage where you can load all different php files, for example your header - content - footer or anything else, seperately into one page.</p>\n\n<p>Your controller will look like this for example:</p>\n\n<pre><code> public function example() {\n $partials = array('header' => 'header', 'navigation' => 'navigation', 'content' => 'content');\n $this->template->load('masterpage.php', $partials);\n }\n</code></pre>\n\n<p>Read more at <a href=\"http://ellislab.com/codeigniter%20/user-guide/libraries/parser.html\" rel=\"nofollow\">http://ellislab.com/codeigniter%20/user-guide/libraries/parser.html</a></p>\n\n<p>It's really use to use once you know how it's done.</p>\n\n<p>For example you could use for every page the same navigation but another index and header.</p>\n\n<p>The masterpage looks like this:</p>\n\n<pre><code><!DOCTYPE html>\n<html lang=\"en\">\n <head>\n </head>\n <body>\n<?php echo $navigation; ?>\n<?php echo $header; ?>\n<?php echo $content; ?>\n <div id=\"footer\">\n <div class=\"container\">\n </div>\n </div>\n </body>\n</html>\n</code></pre>\n\n<p>The last thing you need to do is search for the library file on the net upload it and autoload the library in your configs, file: autoload or just in the constructor of your controller. I recommend autoloading the template library because you normally use it at every end of a controller to make the full view.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T22:26:16.560",
"Id": "62985",
"Score": "0",
"body": "Which will give for this example the same footer on every page but you can choose which php file is shown at the controller for navigation, header and content."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T22:23:32.923",
"Id": "37862",
"ParentId": "37861",
"Score": "2"
}
},
{
"body": "<p>Only addressing the jQuery part - </p>\n\n<p>One way to simplify the code is by using the <code>Function.prototype.bind()</code> method.</p>\n\n<pre><code>$(function () {\n\n var control = '../Indoamericana/Intranet/index/Proceso/';\n\n var loadPage = function (process) {\n var page = control + process;\n $(\".page-content\").load(page);\n };\n\n $(\"#gestion_directiva\").click(loadPage.bind(this, 1));\n\n $(\"#gestion_calidad\").click(loadPage.bind(this, 2));\n\n $(\"#gestion_academica\").click(loadPage.bind(this, 3));\n});\n</code></pre>\n\n<p>You could also derive the process from the JavaScript event, but that might be a bit more clumsy.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T15:22:05.497",
"Id": "40969",
"ParentId": "37861",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "37862",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T22:12:46.807",
"Id": "37861",
"Score": "3",
"Tags": [
"javascript",
"php",
"jquery",
"controller",
"codeigniter"
],
"Title": "Loading content in page via jQuery"
}
|
37861
|
<p>I'm trying to write a neural network that only requires the user to specify the dimensionality of the network. Concretely, the user might define a network like this:</p>
<pre><code>nn = NN([2, 10, 20, 15, 2]) # 2 input, 2 output, 10 in hidden 1, 20 in hidden 2...
</code></pre>
<p>To do this, I'm trying to adapt some <a href="http://arctrix.com/nas/python/bpnn.py" rel="nofollow">basic code</a>. Please let me know what improvements can be made to improve readability (for example, I've considered cleaning up the distinction between <code>wDims</code> (weight dimensions) and layer <code>dims</code> because these variables seem redundant).</p>
<p>I would also appreciate any tips on how to implement a neural network as a graph. I've tried this but can't agree on what classes need to be defined or even how the graph would be stored (as a python dictionary?). Basically, some suggestions relating to good <strong>representation</strong> would be much appreciated.</p>
<p>First, auxiliary methods the network uses:</p>
<pre><code>import random, math
random.seed(0)
def r_matrix(m, n, a = -0.5, b = 0.5):
return [[random.uniform(a,b) for j in range(n)] for i in range(m)]
def sigmoid(x):
return 1.0/ (1.0 + math.exp(-x))
def d_sigmoid(y):
return y * (1.0 - y)
</code></pre>
<p>Definition and construction of the network:</p>
<pre><code>class NN:
def __init__(self, dims):
self.dims = dims
self.nO = self.dims[-1]
self.nI = self.dims[0]
self.nLayers = len(self.dims)
self.wDims = [ (self.dims[i-1], self.dims[i])\
for i in range(1, self.nLayers) ]
self.nWeights = len(self.wDims)
self.__initNeurons()
self.__initWeights()
def __initWeights(self):
self.weights = [0.0] * self.nWeights
for i in range(self.nWeights):
n_in, n_out = self.wDims[i]
self.weights[i] = r_matrix(n_in, n_out)
def __initNeurons(self):
self.layers = [0.0] * self.nLayers
for i in range(self.nLayers):
self.layers[i] = [0.0] * self.dims[i]
</code></pre>
<p>Implementation of back propagation and forward propagation:</p>
<pre><code> def __activateLayer(self, i):
prev = self.layers[i-1]
n_in, n_out = self.dims[i-1], self.dims[i]
for j in range(n_out):
total = 0.0
for k in range(n_in):
total += prev[k] * self.weights[i-1][k][j] # num weights is always one less than num layers
self.layers[i][j] = sigmoid(total)
def __backProp(self, i, delta):
n_out, n_in = self.dims[i], self.dims[i+1]
next_delta = [0.0] * n_out
for j in range(n_out):
error = 0.0
for k in range(n_in):
error += delta[k] * self.weights[i][j][k]
pred = self.layers[i][j]
next_delta[j] = d_sigmoid(pred) * error
return next_delta
def __updateWeights(self, i, delta, alpha = .7):
n_in, n_out = self.wDims[i]
for j in range(n_in):
for k in range(n_out):
change = delta[k] * self.layers[i][j]
self.weights[i][j][k] += alpha * change
def feedForward(self, x):
if len(x) != self.nI:
raise ValueError('length of x must be same as num input units')
for i in range(self.nI):
self.layers[0][i] = x[i]
for i in range(1, self.nLayers):
self.__activateLayer(i)
def backPropLearn(self, y):
if len(y) != self.nO:
raise ValueError('length of y must be same as num output units')
delta_list = []
delta = [0.0] * self.nO
for k in range(self.nO):
pred = self.layers[-1][k]
error = y[k] - pred
delta[k] = d_sigmoid(pred) * error
delta_list.append(delta)
for i in reversed(range(1, self.nLayers-1)):
next_delta = self.__backProp(i, delta)
delta = next_delta
delta_list = [delta] + delta_list
# now perform the update
for i in range(self.nWeights):
self.__updateWeights(i, delta_list[i])
</code></pre>
<p>Predict and train methods. Yes I'm planning on improving <code>train</code> to allow the user to specify the maximum number of iterations and alpha:</p>
<pre><code> def predict(self, x):
self.feedForward(x)
return self.layers[-1]
def train(self, T):
i, MAX = 0, 5000
while i < MAX:
for t in T:
x, y = t
self.feedForward(x)
self.backPropLearn(y)
i += 1
</code></pre>
<p>Sample data. Teach the network the numbers 0 through 4:</p>
<pre><code># no. 0
t0 = [ 0,1,1,1,0,\
0,1,0,1,0,\
0,1,0,1,0,\
0,1,0,1,0,\
0,1,1,1,0 ]
# no. 1
t1 = [ 0,1,1,0,0,\
0,0,1,0,0,\
0,0,1,0,0,\
0,0,1,0,0,\
1,1,1,1,1 ]
# no. 2
t2 = [ 0,1,1,1,0,\
0,0,0,1,0,\
0,1,1,1,0,\
0,1,0,0,0,\
0,1,1,1,0 ]
# no. 3
t3 = [ 0,1,1,1,0,\
0,0,0,1,0,\
0,1,1,1,0,\
0,0,0,1,0,\
0,1,1,1,0 ]
# no. 4
t4 = [ 0,1,0,1,0,\
0,1,0,1,0,\
0,1,1,1,0,\
0,0,0,1,0,\
0,0,0,1,0 ]
T = [(t0, [1,0,0,0,0]), (t1, [0,1,0,0,0]), (t2, [0,0,1,0,0]), (t3, [0,0,0,1,0]), (t4, [0,0,0,0,1])]
nn = NN([25, 50, 50, 20, 5])
nn.train(T)
</code></pre>
|
[] |
[
{
"body": "<p>Here are a bunch of relatively minor comments:</p>\n\n<ul>\n<li>put your imports on separate lines.</li>\n<li>call <code>random.seed</code> in an <code>if __name__ == '__main__':</code> section, not in the global section.</li>\n<li><code>r_matrix</code> is not a very obvious name; <code>random_matrix</code> seems better; the parameters of that function also have pretty non-obvious names; <code>rows</code>, <code>cols</code>, <code>min</code>, <code>max</code> seem to be more descriptive.</li>\n<li><code>self.layers = [0.0] * self.nLayers</code> is odd when <code>self.layers</code> is a list of lists. Actually, this is a perfect case to use a list comprehension: <code>self.layers = [[0.0] * dim for dim in self.dims]</code>. Similarly for <code>weights</code>.</li>\n<li>In <code>__activateLayer</code>: <code>self.layers[i][j] = sigmoid(sum(prev[k] * self.weights[i-1][k][j] for k in xrange(n_in)))</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T14:02:17.200",
"Id": "63013",
"Score": "0",
"body": "Thanks ruds. Are any of the ideas in the code really unclear? Could you please also offer some ideas about how I might use Neuron and Weight objects, to make the implementation cleaner?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:27:59.857",
"Id": "37874",
"ParentId": "37864",
"Score": "2"
}
},
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>There's no documentation! What do these functions do? How do I call them? If someone has to maintain this code in a couple of years' time, how will they know what to do?</p></li>\n<li><p><code>alpha</code> should be a property of the class (and thus an optional argument to the constructor), not an optional argument to the <code>__updateWeights</code> method (where the user has no way to adjust it).</p></li>\n<li><p>You don't need to write <code>\\</code> at the end of a line if you're in the middle of a parenthesis (because the statement can't end until the parenthesis is closed). So there's no need for the <code>\\</code> here:</p>\n\n<pre><code>self.wDims = [ (self.dims[i-1], self.dims[i])\\\n for i in range(1, self.nLayers) ]\n</code></pre>\n\n<p>nor in the definitions of <code>t0</code> and so on.</p></li>\n<li><p>The names could use a lot of work. <code>NN</code> should be <code>NeuralNetwork</code>. <code>MAX</code> should be something like <code>rounds</code>. <code>dims</code> should be something like <code>layer_sizes</code>.</p></li>\n<li><p>You use lots of <a href=\"http://docs.python.org/3/tutorial/classes.html#private-variables\">private method names</a> (starting with <code>__</code>). Why do you do that? The purpose of private names in Python is to \"avoid name clashes of names with names defined by subclasses\" but that's obviously not necessary here. All that the private names achieve here is to make your code a bit harder to debug:</p>\n\n<pre><code>>>> network = NN((1,1))\n>>> network.__backProp(0, [0.5])\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'NN' object has no attribute '__backProp'\n>>> network._NN__backProp(0, [0.5])\n[0.0]\n</code></pre>\n\n<p>If you want to indicate that a method is for internal use by a class, then the convention is to prefix it with a single underscore.</p></li>\n<li><p>Generally in Python you should prefer iterating over sequences rather than over indexes. So instead of:</p>\n\n<pre><code>self.wDims = [ (self.dims[i-1], self.dims[i])\\\n for i in range(1, self.nLayers) ]\n</code></pre>\n\n<p>you should write something like:</p>\n\n<pre><code>self.wDims = list(zip(self.dims[:-1], self.dims[1:]))\n</code></pre>\n\n<p>But in practice you'd do better just to drop <code>wDims</code> array altogether, since it just contains the same information as the <code>dims</code> aray. Whenever you write:</p>\n\n<pre><code>n_in, n_out = self.wDims[i]\n</code></pre>\n\n<p>you could write instead:</p>\n\n<pre><code>n_in, n_out = self.dims[i:i+2]\n</code></pre>\n\n<p>which seems clearer to me.</p></li>\n<li><p>In the <code>train</code> method, surely you should pass in <code>MAX</code> as a parameter?</p></li>\n<li><p>Instead of looping using <code>while</code>:</p>\n\n<pre><code>i = 0\nwhile i < MAX:\n # ...\n i += 1\n</code></pre>\n\n<p>prefer looping using <code>for</code>:</p>\n\n<pre><code>for i in range(MAX):\n # ...\n</code></pre>\n\n<p>(But actually here you don't use <code>i</code> in the loop body, so it would be conventional to write <code>_</code> instead.)</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>for t in T:\n x, y = t\n # ...\n</code></pre>\n\n<p>write:</p>\n\n<pre><code>for x, y in T:\n # ...\n</code></pre></li>\n<li><p>The array <code>layers</code> is not actually a permanent property of the neural networks. It's only used temporarily in <code>feedForward</code> and <code>backPropLearn</code>. And in fact only one layer is really used at a time. It would be better for <code>layer</code> to be a local variable in these methods.</p></li>\n<li><p>The random seed used to initialize the weights should surely be something that you choose each time you create an instance, not just once.</p></li>\n</ol>\n\n<h3>2. Rewriting using NumPy</h3>\n\n<p>This code would benefit enormously from using <a href=\"http://www.numpy.org/\">NumPy</a>, a library for fast numerical array operations.</p>\n\n<ol>\n<li><p>Your function <code>r_matrix</code> could be replaced with <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform\"><code>numpy.random.uniform</code></a>. Here I create a 4×4 array of random numbers chosen uniformly in the half-open range [2, 3):</p>\n\n<pre><code>>>> numpy.random.uniform(2, 3, (4, 4))\narray([[ 2.95552338, 2.75158213, 2.22088904, 2.95417241],\n [ 2.59129035, 2.29089095, 2.16007186, 2.64646486],\n [ 2.39729966, 2.96208642, 2.12305994, 2.68911969],\n [ 2.64394815, 2.21609217, 2.69556204, 2.35376118]])\n</code></pre>\n\n<p>so the whole of your <code>__initWeights</code> function could become:</p>\n\n<pre><code>self.weights = [numpy.random.uniform(-0.5, 0.5, size)\n for size in zip(self.dims[:-1], self.dims[1:])]\n</code></pre></li>\n<li><p>Similarly, the whole of your <code>__initNeurons</code> function could become:</p>\n\n<pre><code>self.layers = [numpy.zeros((size,)) for size in self.dims]\n</code></pre>\n\n<p>But as explained in §1.9 above, we don't actually want <code>self.layers</code>, so <code>__initNeurons</code> can simply be omitted.</p></li>\n<li><p>The <code>_activateLayer</code> method multiplies the vector in <code>self.layers[i-1]</code> by the matrix <code>self.weights[i-1]</code> and then applies the <code>sigmoid</code> function to each element in the result. So in NumPy, <code>_activateLayer</code> becomes:</p>\n\n<pre><code>def _activateLayer(self, i):\n self.layers[i] = sigmoid(numpy.dot(self.layers[i-1], self.weights[i-1]))\n</code></pre>\n\n<p>We don't even need the check on the length of the input any more, because if we pass in an input array of the wrong length, we'll get:</p>\n\n<pre><code>ValueError: matrices are not aligned\n</code></pre></li>\n<li><p>Similarly, the <code>_backProp</code> method multiplies the vector <code>delta</code> by the transpose of the matrix <code>self.weights[i]</code>, and then applies the <code>d_sigmoid</code> function to each element. So in Numpy this becomes:</p>\n\n<pre><code>def _backprop2(self, i, delta):\n return d_sigmoid(self.layers[i]) * numpy.dot(delta, self.weights[i].T)\n</code></pre>\n\n<p>Similarly, the <code>_updateWeights</code> method becomes:</p>\n\n<pre><code>def _updateWeights(self, i, delta, alpha = .7):\n self.weights[i] += alpha * numpy.outer(self.layers[i], delta)\n</code></pre>\n\n<p>And so on. See the revised code below for more improvements.</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<p>This answer was getting quite long, so you'll need to add the documentation yourself.</p>\n\n<pre><code>from itertools import product\nimport numpy\n\ndef sigmoid(x):\n return 1 / (1 + numpy.exp(-x))\n\ndef d_sigmoid(y):\n return y * (1 - y)\n\nclass NeuralNetwork(object):\n def __init__(self, layer_sizes, alpha=0.7, seed=None):\n self.alpha = alpha\n state = numpy.random.RandomState(seed)\n self.weights = [state.uniform(-0.5, 0.5, size)\n for size in zip(layer_sizes[:-1], layer_sizes[1:])]\n\n def _feed_forward(self, x):\n yield x\n for w in self.weights:\n x = sigmoid(numpy.dot(x, w))\n yield x\n\n def _deltas(self, layers, output):\n delta = d_sigmoid(layers[-1]) * (output - layers[-1])\n for layer, w in zip(layers[-2::-1], self.weights[::-1]):\n yield delta\n delta = d_sigmoid(layer) * numpy.dot(delta, w.T)\n\n def _learn(self, layers, output):\n deltas = reversed(list(self._deltas(layers, output)))\n return [w + self.alpha * numpy.outer(layer, delta)\n for w, layer, delta in zip(self.weights, layers, deltas)]\n\n def train(self, training_data, rounds=5000):\n for _, (input, output) in product(range(rounds), training_data):\n layers = self._feed_forward(numpy.array(input))\n self.weights = self._learn(list(layers), numpy.array(output))\n\n def predict(self, input):\n for layer in self._feed_forward(input): pass\n return layer\n</code></pre>\n\n<h3>4. Finally</h3>\n\n<p>Have you considered using <a href=\"https://code.google.com/p/neurolab/\"><code>neurolab</code></a> instead of writing your own?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T14:40:13.627",
"Id": "63014",
"Score": "0",
"body": "I think my code could be improved further (there's a bit too much fiddling about with list slices) but I ran out of time; maybe some other reviewer here can clean it up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T07:44:59.493",
"Id": "63054",
"Score": "0",
"body": "Thank you Gareth! I wrote this code mainly to figure out how neural networks work. I have considered using numpy (having installation issues for python 3) and in any professional application I would surely use a more stable implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T14:21:10.703",
"Id": "37881",
"ParentId": "37864",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37881",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T05:33:40.050",
"Id": "37864",
"Score": "8",
"Tags": [
"python",
"ai",
"machine-learning",
"neural-network"
],
"Title": "Python neural network: arbitrary number of hidden nodes"
}
|
37864
|
<p><a href="https://codereview.meta.stackexchange.com/a/1281/23788">This week's challenge</a> is essentially about fetching Json data from the Web, and deserializing it into objects. I don't have much time to devote to this one, so what I have is very basic: it displays the names of all pokemons in a WPF ListView:</p>
<p><img src="https://i.stack.imgur.com/XZond.png" alt="there's pikachu!"></p>
<p>Here's the code for the window:</p>
<pre><code>public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var service = new PokemonApp.Web.Pokedex();
var pokemons = service.SelectAllPokemonReferences().OrderBy(pokemon => pokemon.Name);
DataContext = new MainWindowViewModel { References = pokemons };
}
}
</code></pre>
<p>As you've guessed, the interesting code is in the <code>Pokedex</code> class:</p>
<pre><code>public class Pokedex
{
public IEnumerable<ResourceReference> SelectAllPokemonReferences()
{
string jsonResult = GetJsonResult(PokeDexResultBase.BaseUrl + "pokedex/1/");
dynamic pokemonRefs = JsonConvert.DeserializeObject(jsonResult);
ICollection<ResourceReference> references = new List<ResourceReference>();
foreach (var pokeRef in pokemonRefs.pokemon)
{
string uri = PokeDexResultBase.BaseUrl + pokeRef.resource_uri.ToString();
references.Add(new ResourceReference
{
Name = pokeRef.name,
ResourceUri = new Uri(uri)
});
}
return references;
}
private static string GetJsonResult(string url)
{
string result;
WebRequest request = HttpWebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";
try
{
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
catch (Exception exception)
{
result = string.Empty;
// throw?
}
return result;
}
}
</code></pre>
<p>The <code>ResourceReference</code> class has nothing special:</p>
<pre><code>public class ResourceReference
{
public string Name { get; set; }
public Uri ResourceUri { get; set; }
}
</code></pre>
<hr>
<p>This quite basic code makes a foundation for the more complex objects:</p>
<pre><code>public abstract class PokeDexResultBase : IPokeDexUri
{
private readonly string _controller;
protected PokeDexResultBase(string controller)
{
_controller = string.IsNullOrEmpty(controller) ? BaseUrl : controller;
}
public static string BaseUrl { get { return "http://pokeapi.co/api/v1/"; } }
public int Id { get; set; }
public Uri ResourceUri { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public virtual string Url { get { return BaseUrl + _controller + (Id == 0 ? string.Empty : Id.ToString()); } }
}
</code></pre>
<p>That base class is inherited by everything that has an <code>Id</code> in the API:</p>
<pre><code>public class Pokemon : PokeDexResultBase
{
public Pokemon() : base("pokemon/") { }
public string Name { get; set; }
public ICollection<ResourceReference> Abilities { get; set; }
public ICollection<ResourceReference> EggGroups { get; set; }
public ICollection<PokemonEvolution> Evolutions { get; set; }
public ICollection<PokemonMove> Moves { get; set; }
public ICollection<PokemonType> Types { get; set; }
public int Attack { get; set; }
public int CatchRate { get; set; }
public int Defense { get; set; }
public int EggCycles { get; set; }
public string EvolutionYield { get; set; }
public int ExperienceYield { get; set; }
public string GrowthRate { get; set; }
public int Happiness { get; set; }
public string Height { get; set; }
public int HitPoints { get; set; }
public string MaleFemaleRatio { get; set; }
public int SpecialAttack { get; set; }
public int SpecialDefense { get; set; }
public string Species { get; set; }
public int Speed { get; set; }
public int Total { get; set; }
public string Weight { get; set; }
}
public class PokemonEvolution
{
public int Level { get; set; }
public string Method { get; set; }
public Uri ResourceUri { get; set; }
public string ToPokemonName { get; set; }
}
</code></pre>
<p>There are other classes involved, but there's nothing much to review about them, they're very similar to the <code>Pokemon</code> class.</p>
<p>As I extend my code I'll add more methods to the <code>Pokedex</code> class, which will use the <code>GetJsonResult</code> method.</p>
<p>Have I well analyzed the API - I mean, is this code a solid foundation for deserializing pokemons and eventually getting them to fight against each other? What could be done better? Any nitpicks?</p>
|
[] |
[
{
"body": "<p>If a class such as <code>ResourceReference</code> makes sense as far as wrapping the API is concerned, from a UI standpoint, it's like using POCO's in the UI layer: If the data came from a database through Entity Framework, this code would be displaying the entities. This is a basic implementation, but if the goal is to make it an extensible \"skeleton\" implementation, there should be a <em>ViewModel</em> class for the UI to display, independently of the WebAPI-provided objects; the <em>ViewModel</em> doesn't care about <code>ResourceUri</code> - this property isn't meant to be displayed, it's plumbing for querying the API, doesn't belong in the UI.</p>\n\n<p>As far as the <code>Pokedex</code> service class goes, it looks like it could work, however it should be returning <em>ViewModel</em> objects for the UI to consume, and the static <code>GetJsonResult</code> method could be encapsulated in its own class, which would be an HTTP-based implementation of a helper object whose role is to fetch the data - there could be a SqlServer-based implementation that would do the same thing off a database, idea being to decouple the <em>data</em> from its <em>data source</em>... but it could be overkill.</p>\n\n<p>Usage of <code>Uri</code> in the POCO classes adds unnecessary complexity: they could just as well be kept as normal strings, so this code:</p>\n\n<blockquote>\n<pre><code>string uri = PokeDexResultBase.BaseUrl + pokeRef.resource_uri.ToString();\n</code></pre>\n</blockquote>\n\n<p>Could then look like this, skipping the useless <code>.ToString()</code> call:</p>\n\n<pre><code> string uri = PokeDexResultBase.BaseUrl + pokeRef.resource_uri;\n</code></pre>\n\n<p>The <code>PokeDexResultBase.BaseUrl</code> static string property would probably be better off as a static property of the <code>Pokedex</code> class, and then it would make <code>PokeDexResultBase</code> tightly coupled with <code>Pokedex</code>, which somehow makes sense.</p>\n\n<p>Also, class <code>PokeDexResultBase</code> should be called <code>PokedexResultBase</code>, for consistency.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T23:00:41.213",
"Id": "63028",
"Score": "1",
"body": "No need for Primitive Obsession. You can stick with `Uri`. You just need to use it consistently. `new Uri(Uri, Uri)` and `WebRequest.Create(Uri)` should do the trick."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T18:06:46.620",
"Id": "37886",
"ParentId": "37866",
"Score": "3"
}
},
{
"body": "<p>Actually, i ended up with this approach in deserializing</p>\n\n<pre><code>// Pocos for deserializing\npublic class PocoAnswer\n{ \n PocoItem item {get; set;}\n}\n\npublic class PocoItem\n{\n String name {get; set; }\n DateTime birthday {get; set; }\n}\n\n// Model for binding\npublic ItemModel\n{ \n public readonly PocoItem item; // I wish this to stay private, but json serializer cant get it then\n public ItemModel(PocoItem _item)\n { \n item = _item;\n }\n\n [JsonIgnore] // No need to store runtime generated data\n public FormattedInfoString // This is used for binding \n {\n get \n {\n return String.Format(\"My amazing custom string contains name {0} and birth {1}, item.Name, item.Birthday.ToString(\"yy-mm\");\n }\n }\n}\n</code></pre>\n\n<p>And when i'm getting answer from the server, i'm pushing it into binded item</p>\n\n<pre><code>var result = JsonConvert.DeserializeObject<PocoAnswer>(resultString);\nBindableModel = new ItemModel(result.answer.item);\n</code></pre>\n\n<p>and then in xaml</p>\n\n<pre><code><TextBlock Text={Binding BindableModel.FormattedInfoString} \\>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T23:59:58.857",
"Id": "47937",
"ParentId": "37866",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T06:34:37.260",
"Id": "37866",
"Score": "15",
"Tags": [
"c#",
"json",
"community-challenge",
"pokemon"
],
"Title": "Gotta catch 'em all!"
}
|
37866
|
<p>I have written this InsertSort program in F#. It works, but I am not very happy with it.</p>
<pre><code>let rec SubArrayBegin list n =
list |> Seq.ofList |> Seq.take n |> List.ofSeq
let SubArrayEnd list n =
List.rev (SubArrayBegin (List.rev list) ((List.length list) - n - 1))
let InsertSort list =
let rec innerInsertSort list n =
if n = (List.length list) then
list
else
let key = List.nth list n
let firstList = SubArrayBegin list n
let (firstListA, firstListB) = List.partition (fun x -> x < key) firstList
let remList = SubArrayEnd list n
innerInsertSort (firstListA @ [key] @ firstListB @ remList) (n + 1)
innerInsertSort list 1
[<EntryPoint>]
let main args =
let a = [10; 2; 9; 1; 4; 5; -1]
let b = InsertSort a
List.iter (fun x -> printfn "%i" x) b
0
</code></pre>
<p>List of annoyances:</p>
<ol>
<li>@ symbol for joining the lists back.</li>
<li>If Condition being used instead of pattern matching. </li>
</ol>
<p>I wonder if there is a better way of writing this.</p>
<p>Can you please review this and help me improve this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T11:50:05.087",
"Id": "63011",
"Score": "0",
"body": "What's wrong with `@` and `if`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T01:55:46.257",
"Id": "63040",
"Score": "0",
"body": "@ makes copy of the entire list when it joins the arrays. :: is better but I was not able to use it.\n\nfunctional programmers can write lot of stuff without using if. they tend to use pattern matching for conditionals rather than if."
}
] |
[
{
"body": "<ol>\n<li>Function names in F# are usually written in <code>camelCase</code>. (Though members that are not private should use <code>PascalCase</code>, to adhere to general .Net naming conventions.)</li>\n<li><code>SubArrayBegin</code> is not recursive, so it doesn't need to be <code>rec</code>.</li>\n<li><code>List</code> implements <code>Seq</code>, so you don't need that <code>Seq.ofList</code>.</li>\n<li>Collection manipulation functions usually have that collection as the last parameter, so that you can use them with <code>|></code>.</li>\n<li><p>Your implementation of <code>SubArrayEnd</code> is pretty complicated and inefficient. Instead, you could write it for example like this:</p>\n\n<pre><code>let rec subArrayEnd n list =\n match (n, list) with\n | 0, _ | _, [] -> list\n | _ -> subArrayEnd (n-1) (List.tail list)\n</code></pre></li>\n<li>There is no reason why your <code>innerInsertSort</code> has to follow the normal imperative version of insert sort so closely and operate on a single list (and use <code>List.nth</code>). Instead, you could have two collections: one where you take from using pattern matching and one where you insert using <code>List.partition</code> and <code>@</code>.</li>\n<li>Alternatively, you could use <code>ImmutableList</code> from <a href=\"https://www.nuget.org/packages/Microsoft.Bcl.Immutable\" rel=\"nofollow\">Microsoft.Bcl.Immutable</a> instead of <code>List</code> for the collection you're inserting into. With that, you can insert into the middle in O(log n) and you can also find the index to insert to in O(log n) using binary search. So it will make your code simpler and also much faster.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T16:27:19.707",
"Id": "37883",
"ParentId": "37868",
"Score": "1"
}
},
{
"body": "<p>Thank you so much Svick .... Based on your inputs I changed my code to </p>\n\n<pre><code>let insertSorted n list = \n let (a, b) = List.partition (fun x -> x < n) (n :: list) \n List.append a b\n\nlet insertSort list =\n let rec innerInsertSort sorted = function\n | [] -> sorted\n | hd :: tl -> \n innerInsertSort (insertSorted hd sorted) tl \n innerInsertSort [List.head list] (List.tail list)\n\n[<EntryPoint>]\nlet main args = \n printfn \"%s\" (List.fold (fun acc elem -> acc + \" \" + elem.ToString()) \"\" (insertSort [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3]))\n 0\n</code></pre>\n\n<p>Now I don't need List.nth or SubArrayBegin or SubArrayEnd.</p>\n\n<p>I use the two lists input which you gave me in point 6.</p>\n\n<p>Let me know your thoughts... but I am very happy with this code above because it is quite concise and is not so imperative as my first version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T11:43:55.290",
"Id": "63068",
"Score": "0",
"body": "This code won't work if `list` is empty."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T05:55:11.357",
"Id": "37899",
"ParentId": "37868",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37883",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T07:05:13.863",
"Id": "37868",
"Score": "4",
"Tags": [
"sorting",
"f#"
],
"Title": "InsertSort F# program"
}
|
37868
|
<p>This is my .cs part code where I am calling <code>storeprocedure</code> in LINQ to SQL:</p>
<pre><code>var rr_j_cat = db.allcategories().ToList();//its store procedure calling thousands of rows
if (rr_j_cat.Count() != 0)
{
DataTable dt = new DataTable();//making dynamic datatable
dt.Columns.Add("sub_id"); //dynamic columns
dt.Columns.Add("sibheadername"); //dynamic columns
foreach (var it in rr_j_cat) // will rotate thousands time which makes process talking more time
{
DataRow dr = dt.NewRow(); // dyanamic rows
var rr_sel_cat = db.selcategories(Convert.ToInt32(it.sub_id)).ToList(); //another storeprocedure to check a count of data present in another data or table
int count = Convert.ToInt32(rr_sel_cat.First().Column1);
if (count != 0)
{
dr["sub_id"] = it.sub_id;
dr["sibheadername"] = it.sibheadername + " (" + count + ")"; // adding count besides subheader name which you can see in below image on dance
count =0;
}
else
{
dr["sub_id"] = it.sub_id;
dr["sibheadername"] = it.sibheadername;
}
dt.Rows.Add(dr);
}
dd_j_area.DataSource = dt; // binding with dropdownlist
dd_j_area.DataTextField = "sibheadername";
dd_j_area.DataValueField = "sub_id";
dd_j_area.DataBind();
dd_j_area.Items.Insert(0, "");
}
</code></pre>
<p>It's working fine, but taking more time.</p>
<p>It will show as </p>
<p><img src="https://i.stack.imgur.com/Bg14o.jpg" alt="here"></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T09:15:22.187",
"Id": "63003",
"Score": "1",
"body": "Can you not have one stored procedure return you the results rather than having to call two?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T03:01:52.207",
"Id": "63041",
"Score": "0",
"body": "Have you thought about writing it in assembly? Bad and overused joke... sorry."
}
] |
[
{
"body": "<p>You asked two things, </p>\n\n<ol>\n<li>Clearer code</li>\n<li>Better performance</li>\n</ol>\n\n<p>I'll try to cover both.</p>\n\n<p>First of all it's unnecessary to convert <code>rr_j_cat</code> and <code>rr_sel_cat</code> to list again!\nSo <code>rr_j</code> and <code>rr_list</code> variables are both useless.</p>\n\n<p>Second, instead of converting <code>rr_sel_cat.First().Column1</code> to string, which in your case will instantiate a string variable (<code>count</code>) over and over, convert it to and <code>int</code> or if it's already an <code>int</code> or a value type, use it instead and avoid unnecessary boxing which is a performance issue.</p>\n\n<p>Third, instead of string concatenating in <code>dr[\"sibheadername\"] = it.sibheadername + \" (\" + count + \")\";</code>, use <code>StringBuilder</code> class which will be a good performance improvement in your case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T07:47:16.947",
"Id": "62990",
"Score": "0",
"body": "how to make use stringbuilder in this case?..please will u give some demo based on my question??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:25:18.620",
"Id": "62994",
"Score": "0",
"body": "as you suggested other things are being changed....but string builder is good to use ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:38:52.710",
"Id": "62997",
"Score": "0",
"body": "Actually StringBuilder is more efficient in case of using memory, but the fastest way will be using string.Format()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T09:37:41.220",
"Id": "63005",
"Score": "0",
"body": "Umhh, nope. First, the `ToList()` prevents the stored procedure from being executed more than once. Second, using StringBuilder is actually slower in this concrete case, because the compiler will optimize the statement `\" (\" + count + \")\"`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T07:42:56.190",
"Id": "37871",
"ParentId": "37869",
"Score": "0"
}
},
{
"body": "<p>This is how it should be using <code>StringBuilder</code>:</p>\n\n<pre><code> System.Text.StringBuilder sibHeaderNameBuilder = new StringBuilder();\n sibHeaderNameBuilder.Append(it.sibheadername);\n sibHeaderNameBuilder.Append(\"(\");\n sibHeaderNameBuilder.Append(count);\n sibHeaderNameBuilder.Append(\")\");\n dr[\"sibheadername\"] = sibHeaderNameBuilder.ToString();\n</code></pre>\n\n<p>Note that using the <code>stringBuilder.Append(int value)</code> method, you don't have to convert use the string representation of <code>count</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:16:35.997",
"Id": "62993",
"Score": "0",
"body": "its adding one more class of using System.Text; ....and on every loop it call this....i think it will make more load on page of name space and this code?????think so..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:31:15.580",
"Id": "62995",
"Score": "0",
"body": "OK, but you should instantiate the stringBuilder object outside of your loop. Also instead of using string concatenation you can use String.Format(), which will be more faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T09:35:59.757",
"Id": "63004",
"Score": "0",
"body": "Umhh, nope. Using StringBuilder is actually slower in this concrete case, because the compiler will optimize the statement `\" (\" + count + \")\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T10:12:35.407",
"Id": "63006",
"Score": "0",
"body": "You are right Thomas about the StringBuilder, but I think StringBuilder is a little bit more efficient (in case of memory management) than using string concatenation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T10:28:06.673",
"Id": "63007",
"Score": "0",
"body": "Generally speaking yes. Actually a **lot** more efficient (I've seen cases where this was around 1000 times faster). The only case where direct concatenation is faster is the `\"x\" + <somevar> + \"y\"` scenario."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:01:00.037",
"Id": "37872",
"ParentId": "37869",
"Score": "1"
}
},
{
"body": "<p>The principal performance issues are on the database side (or maybe you could do some kind of caching or pre-loading), but your code could be made much clearer and shorter (there should be also some minor performance improvements):</p>\n\n<pre><code>string[] columnNames = new[] { \"sub_id\", \"sibheadername\" };\n\nvar categories = db.allcategories().ToList(); \n\nif (categories.Count == 0)\n{\n return;\n}\n\nvar dt = new DataTable();\ndt.Columns.Add(columnNames[0]);\ndt.Columns.Add(columnNames[1]);\n\nforeach (var category in categories)\n{\n var selectedCategories = db.selcategories(Convert.ToInt32(category.sub_id)).ToList();\n int count = Convert.ToInt32(selectedCategories.First().Column1);\n\n DataRow dr = dt.NewRow();\n dr[0] = category.sub_id;\n dr[1] = count != 0\n ? category.sibheadername + \" (\" + count + \")\" // btw. this is FASTER (in this case) than a StringBuilder!\n : category.sibheadername;\n\n dt.Rows.Add(dr);\n}\n\nareaDropdown.DataSource = dt;\nareaDropdown.DataTextField = columnNames[1];\nareaDropdown.DataValueField = columnNames[0];\nareaDropdown.DataBind();\nareaDropdown.Items.Insert(0, \"\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:35:00.517",
"Id": "62996",
"Score": "0",
"body": "dr is missing.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:39:12.393",
"Id": "62998",
"Score": "0",
"body": "You're right. Simply overseen it. Will edit the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:45:06.337",
"Id": "63000",
"Score": "0",
"body": "hey its working faster"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:53:39.217",
"Id": "63001",
"Score": "0",
"body": "Nice to hear! You're welcome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:40:27.007",
"Id": "63228",
"Score": "0",
"body": "As i am using storeprocedure is there any necessary of using precompiling??"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:25:42.873",
"Id": "37873",
"ParentId": "37869",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37873",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T07:08:10.347",
"Id": "37869",
"Score": "2",
"Tags": [
"c#",
"asp.net",
"sql-server",
"linq-to-sql"
],
"Title": "How to make my code faster and easier?"
}
|
37869
|
<p>I would like to ask you for a code review of my c++11 Thread Pool implementation. Your constructive criticism is welcome! Could you give me some ideas how to extend it?</p>
<p>The main idea is to synchronise access to tasks with condition variable.</p>
<h2>ThreadPoolExecutor.cpp</h2>
<pre><code>#include "ThreadPoolExecutor.h"
#include <algorithm>
#include <iostream>
namespace ThreadPool
{
ThreadPoolExecutor::ThreadPoolExecutor(int maxWorkers)
{
this->maxWorkers = maxWorkers;
}
ThreadPoolExecutor::~ThreadPoolExecutor()
{
this->poolManager.join();
}
void ThreadPoolExecutor::ScheduleTask(std::function<void()> task)
{
std::unique_lock<std::mutex> lock(taskQueueMutex);
bool wasEmpty = this->taskQueue.empty();
this->taskQueue.push(task);
if (wasEmpty)
{
this->notEmptyTaskQueue.notify_one();
}
lock.unlock();
}
void ThreadPoolExecutor::Run()
{
this->poolManager = std::thread(&ThreadPoolExecutor::ManagePool, this);
}
void ThreadPoolExecutor::ManagePool()
{
for (int i = 0; i < this->maxWorkers; i++)
{
this->workers.push_back(std::thread(&ThreadPoolExecutor::Worker, this));
}
for (auto &thread : this->workers)
{
thread.join();
}
}
void ThreadPoolExecutor::Worker()
{
#ifdef _DEBUG
std::cout << "Hello from thread: " << std::this_thread::get_id() << std::endl;
#endif
while (1)
{
std::unique_lock<std::mutex> lock(taskQueueMutex);
if (this->taskQueue.empty())
{
this->notEmptyTaskQueue.wait(lock);
}
auto task = this->taskQueue.front();
this->taskQueue.pop();
lock.unlock();
task();
}
}
}
</code></pre>
<h2>ThreadPoolExecutor.h</h2>
<pre><code>#ifndef THREADPOOLEXECUTOR_H_
#define THREADPOOLEXECUTOR_H_
#include <functional>
#include <queue>
#include <thread>
#include <memory>
#include "Task.h"
#include <condition_variable>
namespace ThreadPool
{
class ThreadPoolExecutor
{
public:
ThreadPoolExecutor(int maxWorkers);
~ThreadPoolExecutor();
void ScheduleTask(std::function<void()> task);
void Run();
private:
int maxWorkers;
std::vector<std::thread> workers;
std::thread poolManager;
std::queue<std::function<void()>> taskQueue;
std::condition_variable notEmptyTaskQueue;
void ManagePool();
std::mutex taskQueueMutex;
void Worker();
};
}
#endif
</code></pre>
<p>And finally usage.</p>
<h2>Program.cs</h2>
<pre><code>#include "ThreadPoolExecutor.h"
#include "ExampleTask.h"
#include <iostream>
using namespace ThreadPool;
int main()
{
ThreadPoolExecutor executor = ThreadPoolExecutor(4);
for (int i = 0; i < 10; i++)
{
int random = std::rand() % 6;
std::chrono::seconds timeout(random);
executor.ScheduleTask([i, timeout](){
std::cout << "no " << i << std::endl;
std::this_thread::sleep_for(timeout);
});
}
executor.Run();
ExampleTask task;
executor.ScheduleTask(task);
std::this_thread::sleep_for(std::chrono::seconds(15));
for (int i = 0; i < 10; i++)
{
int random = std::rand() % 6;
std::chrono::seconds timeout(random);
executor.ScheduleTask([i, timeout](){
std::cout << "no " << i << std::endl;
std::this_thread::sleep_for(timeout);
});
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>ThreadManager.h</h1>\n\n<p>What is Task.h? Why are you including it? I see no names that aren't covered by the standard headers you include.</p>\n\n<p>There's no apparent order to your private members. You mix methods and data members; it looks like the members are added in the order they were written, as opposed to some logical order. I recommend putting your methods before your data members (my recommendation matches the <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Declaration_Order\" rel=\"nofollow\">Google C++ Style Guide</a>), and determining a logical order within each set.</p>\n\n<p>In general, the header is the place to document your interface. What are the semantics of <code>ScheduleTask</code>? Can it be called from multiple threads without mutual exclusion? Will <code>Run</code> return? Does <code>ThreadPoolExecutor</code> reuse threads after there work is complete? If so, will <code>ThreadPoolExecutor</code> ever destroy threads after creating them? Does the destructor block?</p>\n\n<p><code>Worker</code> is an odd name for a method. It is the usual practice that function names should be some sort of verb phrase; <code>Worker</code> is a noun, and it doesn't give a lot of insight into what it does.</p>\n\n<p><code>maxWorkers</code> should probably be declared <code>const</code>; it shouldn't change after construction.</p>\n\n<p>Comments on the private data members should clearly indicate which members are guarded by the mutex.</p>\n\n<h1>ThreadManager.cpp</h1>\n\n<p>Constructors should use initializers wherever possible:</p>\n\n<pre><code>ThreadPoolExecutor::ThreadPoolExecutor(int maxWorkers) : maxWorkers(maxWorkers) {}\n</code></pre>\n\n<p>This will allow the member to be declared <code>const</code>.</p>\n\n<p>Your destructor throws if <code>Run</code> has never been called: A default constructed <code>thread</code> is not joinable. That's not the biggest problem: Your destructor never returns if <code>maxWorkers > 0</code> because none of your calls to <code>join</code> ever complete.</p>\n\n<p>It is distracting (and unidiomatic!) to see unnecessary <code>this-></code> warts prepended to each member access. If you must have a visual indicator that you are accessing members rather than local variables, adopt a naming convention for your data members (common ones I've seen: maxWorkers_, m_maxWorkers).</p>\n\n<p>In <code>ScheduleTask</code>, it is unnecessary to call <code>lock.unlock();</code>. <code>std::unique_lock</code> unlocks its owned mutex in its destructor; when I see explicit unlocking, I expect that it's because of complicated locking semantics (e.g. conditional unlocking, or unlocking before <code>lock</code> goes out of scope, as in <code>Worker</code>) and look around for the complication; there's no such complication here.</p>\n\n<p><code>maxWorkers</code> appears to be a misnomer as you never have fewer workers. Maybe <code>numWorkers</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T23:49:41.447",
"Id": "63031",
"Score": "1",
"body": "I agree with your recomendations. But I don't think quoting google c++ style guide is good. The google C++ style guide is designed for google (and to support there legacy C++ systems). It is not considered a generically good C++ style guide."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T06:10:43.983",
"Id": "63052",
"Score": "0",
"body": "@LokiAstari The Google C++ style guide has its plusses and minuses, but I don't think it's clearly bad; certainly its advice on how to organize code is fine, even if it is a bit old-fashioned when it comes to exceptions and functional style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T10:11:11.863",
"Id": "63061",
"Score": "1",
"body": "I disagree. There are so many bad things in there (I did notice that it has been updated). But just a quick glance [Doing Work in Constructors](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Doing_Work_in_Constructors#Doing_Work_in_Constructors). Advice: don't do it because if things go wrong you have no object to check error codes from. So basically that is suggesting two phase initialization. I am sure I could find lots more. I consider this a travesty of style guide for modern C++. It is absolutely fine for internal google projects because they have a specific goal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T12:08:33.687",
"Id": "63071",
"Score": "0",
"body": "Yep, there is unnecessary \"Task.h\" include in ThreadPoolExecutor.h. Thank you for google c++ style, I'll familiarize with it. I agree, that the order is the order of writing code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T12:15:45.570",
"Id": "63072",
"Score": "0",
"body": "What do you mean by \"In general, the header is the place to document your interface\"? Should I place documentation there? And I agree that Worker is odd name, maybe \"RunWorker\" is better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T12:27:02.780",
"Id": "63074",
"Score": "0",
"body": "**ThreadPoolExecutor.cpp** You are right, my main thread is not joinable when I do not call Run. I could initialize it in constructor. But I can't figure out how to fix \"maxWorkers>0\"situation. Do you have any suggestions how to fix that? But I disagree with \"this->\", isn't it that just a styling convention? I am not cpp developer, but for me it is just question of taste? m_maxWorkers looks like hungarian notation for me. And many many thanks for your code review! That's great to have a feedback for my work!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:29:38.393",
"Id": "63092",
"Score": "0",
"body": "@LokiAstari 2-phase initialization is bad, and they should remove the `Init` recommendation from that section, but using factory functions is certainly a reasonable solution. It is generally bad style to have an operation that could fail (and thereby leave the object partially constructed) in constructors. However, I take your point. Do you have an alternative style guide to suggest?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:31:58.620",
"Id": "63093",
"Score": "0",
"body": "@klouch Yes, you should document the class as a whole and each of the public functions so that users can use it correctly. I mentioned in the answer some of the questions that documentation should answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:35:35.023",
"Id": "63095",
"Score": "0",
"body": "@klouch This answer on StackOverflow (http://stackoverflow.com/a/1229360/66509) addresses your Hungarian notation concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:38:20.157",
"Id": "63096",
"Score": "1",
"body": "@klouch `maxWorkers>0` problem can be addressed in a number of ways. One way would be to have a state variable (boolean or preferably an enum) as a class member. Your `Worker` function, on waking up, could check whether the state is `SHUTDOWN`, and stop checking the queue in that case. In your destructor, you could set the state and call `notify_all` on your condition variable before joining with the manager thread."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T18:52:07.283",
"Id": "37888",
"ParentId": "37878",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37888",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T12:17:22.623",
"Id": "37878",
"Score": "4",
"Tags": [
"c++",
"multithreading",
"c++11",
"thread-safety",
"asynchronous"
],
"Title": "simple ThreadPool implementations"
}
|
37878
|
<p>I'm looking for code review of part of my replacement of timeout() project. Namely, feedback on SleeperNotifier class:
<a href="https://github.com/ledestin/frugal_timeout/blob/master/lib/frugal_timeout.rb#L125" rel="nofollow">https://github.com/ledestin/frugal_timeout/blob/master/lib/frugal_timeout.rb#L125</a></p>
<p>If you would like to give feedback on the whole project, by all means do.</p>
<pre><code> # {{{1 SleeperNotifier
# Executes callback when a request expires.
# 1. Set callback to execute with #onExpiry=.
# 2. Set expiry time with #expireAt.
# 3. After the expiry time comes, execute the callback.
#
# It's possible to set a new expiry time before the time set previously
# expires. In this case, processing of the old request stops and the new
# request processing starts.
class SleeperNotifier # :nodoc:
include MonitorMixin
def initialize
super()
@condVar, @expireAt, @onExpiry = new_cond, nil, proc {}
@thread = Thread.new {
loop {
@onExpiry.call if synchronize {
# Sleep forever until a request comes in.
wait unless @expireAt
timeLeft = calcTimeLeft
disposeOfRequest
elapsedTime = MonotonicTime.measure { wait timeLeft }
elapsedTime >= timeLeft
}
}
}
ObjectSpace.define_finalizer self, proc { @thread.kill }
end
def onExpiry &b
@onExpiry = b
end
def expireAt time
synchronize {
@expireAt = time
signalThread
}
end
private
def calcTimeLeft
synchronize {
delay = @expireAt - MonotonicTime.now
delay < 0 ? 0 : delay
}
end
def disposeOfRequest
@expireAt = nil
end
def signalThread
@condVar.signal
end
def wait sec=nil
@condVar.wait sec
end
end
</code></pre>
|
[] |
[
{
"body": "<p>How do you cancel a sleep once it starts? I would expect that calling <code>.expireAt(nil)</code> might accomplish that. However, if <code>@expireAt</code> is nil, <code>calcTimeLeft()</code> crashes.</p>\n\n<p>Alternatively, one might try to call <code>.onExpiry(nil)</code>, but you don't handle <code>@onExpiry</code> being nil either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T07:22:30.663",
"Id": "63471",
"Score": "0",
"body": "There indeed wasn't a way to do it. I've just added it, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T07:40:54.773",
"Id": "63473",
"Score": "0",
"body": "Please remember to upvote any useful answers. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T07:49:51.947",
"Id": "63624",
"Score": "0",
"body": "Awww, I can't, my reputation won't permit me."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T17:59:27.473",
"Id": "37975",
"ParentId": "37879",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T13:08:37.990",
"Id": "37879",
"Score": "2",
"Tags": [
"ruby",
"multithreading"
],
"Title": "Sleep and background wakeup system"
}
|
37879
|
<p>I believe any data structure can be converted to RDF, and I wrote the
subroutine below which sort of does this, at least for arbitrarily
complex hashes. </p>
<p>However, I'm unhappy with it because: </p>
<ul>
<li><p><code>$hash2rdf_count</code> should not be global. I don't see an easy fix for this. </p></li>
<li><p>Where I comment "hopefully it's referring to a scalar at this
point!", I'm not actually convinced. Are there better ways to check? </p></li>
<li><p><code>@triplets</code> should not be global. I think I can fix this by passing
it as a parameter, but is there an easier way? </p></li>
</ul>
<p>Other notes: </p>
<ul>
<li><p>In my specific use case, I'm using <code>JSON::from_json($data)</code> to
convert JSON data to a hash, which I then feed to the subroutine
below. I then print out <code>@triplets</code> and create an SQLite3 DB out of it. So it's really: JSON2hash, hash2rdf, rdf2sql. The entire program: <a href="https://github.com/barrycarter/bcapps/blob/master/bc-get-discogs.pl" rel="nofollow">https://github.com/barrycarter/bcapps/blob/master/bc-get-discogs.pl</a></p></li>
<li><p><code>JSON::GRDDL</code> failed with an out-of-memory error on my data. My
subroutine doesn't. Is there another "prepackaged" solution I could
use? </p></li>
<li><p>I realize what I'm doing is a very minimal form of RDF.</p></li>
</ul>
<pre class="lang-perl prettyprint-override"><code>=item hash2rdf($ref,$name="")
Given a scalar/array/hash reference $ref, returns RDF triplets recursively.
If $name is given, assigns name $name to $ref. Otherwise, creates a name
Pretty much does what var_dump() does, only in RDF
=cut
sub hash2rdf {
my($ref,$name) = @_;
my($type) = ref($ref);
# if no type at all, just return self (after cleanup)
unless ($type) {
$ref=~s/\n/\r/isg;
$ref=~s/\"/\\"/isg;
return $ref;
}
# name I will give $ref if not given
unless ($name) {$name = "REF".++$hash2rdf_count;}
# TODO: making $hash2rdf_count global is bad
# TODO: making @triplets global is unacceptably bad (but just testing now)
# my(@triplets);
if ($type eq "ARRAY") {
# interim var
my(@l) = @{$ref};
# push triplets for my children
for $i (0..$#l) {push(@triplets, [$name, $i, hash2rdf($l[$i])]);}
# return the name I gave myself
return $name;
}
if ($type eq "HASH") {
# interim var
my(%h) = %$ref;
for $i (keys %h) {push(@triplets, [$name, $i, hash2rdf($h{$i})]);}
return $name;
}
# hopefully it's referring to a scalar at this point!
return $$ref;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T23:52:41.787",
"Id": "63032",
"Score": "0",
"body": "Could you provide an example of usage and expected output?"
}
] |
[
{
"body": "<p>I'm not sure what you're trying to do, so I'll just review the code itself, not what you're trying to do.</p>\n\n<p>I looked into the whole script on GitHub and was <em>shocked</em> to see that you didn't <code>use strict; use warnings</code>. This would usually abort any review, but let's continue for the sake of the argument.</p>\n\n<p>I think it's very nice that you've used POD documentation for your script.</p>\n\n<p>Let's look at this excerpt for a moment:</p>\n\n<pre><code>unless ($type) { \n $ref=~s/\\n/\\r/isg; \n $ref=~s/\\\"/\\\\\"/isg; \n return $ref; \n}\n</code></pre>\n\n<ol>\n<li><code>ref $foo</code> can be false, but a reference (consider <code>$foo = bless \\$bar, \"0\"</code>). Use either <code>length ref $foo</code> or <code>reftype $foo</code>, where <code>reftype</code> is imported from <code>Scalar::Util</code>.</li>\n<li><code>unless</code> is widely considered to be half a design error. <code>if (not ...)</code> is cleared most of the time.</li>\n<li>On each of your regexes you specify the flags <code>/isg</code>.\n<ul>\n<li>The <code>/i</code> does case insensitive matching but you don't match anything that has a case. As this flag reduces performance, you should use it sparingly.</li>\n<li>The <code>/s</code> flag causes the <code>.</code> to match any character including newlines. It is generally a good idea to use this flag (the default behavior of <code>.</code> is better written as <code>[^\\n]</code>). However, you do not use the <code>.</code> metacharacter, so <code>/s</code> is useless here.</li>\n</ul></li>\n<li>In the pattern, <code>\"</code> does not have to be escaped as it isn't a metacharacter.</li>\n<li>Use proper spacing around operators (usually a single space) to improve readability.</li>\n</ol>\n\n<p>Suggested refactoring:</p>\n\n<pre><code>if (not length $type) { \n $ref =~ s/\\n/\\r/g; \n $ref =~ s/\"/\\\\\"/g; \n return $ref; \n}\n</code></pre>\n\n<p>Now let's take a look at <code>unless ($name) {$name = \"REF\".++$hash2rdf_count;}</code>:</p>\n\n<ol>\n<li>As per <a href=\"http://perldoc.perl.org/perlstyle.html\" rel=\"nofollow\">Larry's style guide</a>, you shouldn't use a semicolon if the closing brace is on the same line.</li>\n<li><p>Never use the <code>conditional (...) {BLOCK}</code> form on a single line. Either put the statement on a line of its own, or use the statement modifier form:</p>\n\n<pre><code>$name = \"REF\" . ++$hash2rdf_count unless length $name;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (not length $name) {\n $name = \"REF\" . ++$hash2rdf_count;\n}\n</code></pre></li>\n<li><p>If you only want to overwrite <code>$name</code> if it is <code>undef</code>, you could either test for <code>defined</code>ness: <code>if (not defined $name)</code> or since perl 5.10, you can use the defined-or operator <code>//</code>:</p>\n\n<pre><code>$name //= \"REF\" . ++$hash2rdf_count;\n</code></pre></li>\n</ol>\n\n<p>What to do about the <code>$has2rdf_count</code>? The simplest solution that does not involve globals is to declare it outside of the subroutine:</p>\n\n<pre><code>my $hash2rdf_count = 0;\nsub hash2rdf {\n</code></pre>\n\n<p>A better solution (since perl 5.10) is to use state variables:</p>\n\n<pre><code>use feture 'state';\n...\nstate $hash2rdf_count = 0;\n$name //= \"REF\" . ++$hash2rdf_count;\n</code></pre>\n\n<p>A state variable belongs to a certain scope like <code>my</code> variables, but is initialized only at the first execution.</p>\n\n<p>However, it may be better to take this as another argument (will be discussed later).</p>\n\n<p><code>my(@l) = @{$ref}</code> there is no need to perform a copy of the array, and even if you feel the need to do that, please don't use a bad variable name like <code>@l</code>. Especially the charcterl <code>l</code> should be avoided on its own. Also, variable names don't <em>have</em> to be so short. Given an array reference, we can access an entry like <code>$ref->[$i]</code> and get the highest index like <code>$#$ref</code> (or with curlies: <code>$#{$ref}</code>).</p>\n\n<p>By now we know how a line like <code>for $i (0..$#l) {push(@triplets, [$name, $i, hash2rdf($l[$i])]);}</code> can be improved. But I would like you to call builtins like <code>push</code> without parens: They aren't subroutines, but operators.</p>\n\n<p>With a statement modifier:</p>\n\n<pre><code>push @triplets, [$name, $_, hash2rdf($ref->[$_])] for 0 .. $#$ref;\n</code></pre>\n\n<p>Without:</p>\n\n<pre><code>for my $i (0 .. $#ref) {\n push @triplets, [$name, $i, hash2rdf($ref->[$i])];\n}\n</code></pre>\n\n<p>And then there is a variant with <code>map</code>:</p>\n\n<pre><code>push @triplets, map { [$name, $_, hash2rdf($ref->[$_])] } 0 .. $#$ref;\n</code></pre>\n\n<p>The same holds for the <code>HASH</code>-reference case. Recommended refactoring there:</p>\n\n<pre><code>for my $key (keys %$ref) {\n push @triplets, [$name, $key, hash2rdf($ref->{$key})];\n}\n</code></pre>\n\n<p>Note that I'm not using <code>$i</code> here, as the hash key won't generally be an integer.</p>\n\n<p>How can we solve the problem that <code>@triplets</code> is a global? We take a reference to that array as another argument:</p>\n\n<pre><code>sub hash2rdf {\n my ($ref, $triplets, $name) = @_;\n ...\n push @$triplets, ...\n</code></pre>\n\n<p>This means that we have to change the way how we call ourselves when recursing:</p>\n\n<pre><code>hash2rdf($ref->[$i], $triplets)\n</code></pre>\n\n<p>On the outside, we call the subroutine like</p>\n\n<pre><code>hash2rdf(\\@releases, \\my @triplets, \"root\");\n</code></pre>\n\n<p>Eww, that is ugly (out-arguments always bother me). Let's rename <code>hash2rdf</code> to <code>hash2rdf_inner</code>, and create a wrapper. This is also a good opportunity to pass <code>$has2rdf_count</code> as an argument, and to rename the wrapper to something better.</p>\n\n<pre><code>sub ref2rdf {\n my ($data, $name) = @_;\n my $count = 0;\n my @triplets;\n ref2rdf_inner($data, \\@triplets, $name, \\$count);\n return @triplets;\n}\n\nsub ref2rdf_inner {\n my ($ref, $triplets, $name, $count_ref) = @_;\n ...\n $name //= \"REF\" . ++$$count_ref;\n ... \n ref2rdf_inner($ref->[$i], $triplets, undef, $count_ref)\n ...\n}\n</code></pre>\n\n<p>We could now dump a data structure like</p>\n\n<pre><code>use feature 'say'; # say is like print, but with newline\n\nfor my $triplet (ref2rdf(\\@releases, \"root\")) {\n say join \"\\t\", @$triplet;\n}\n</code></pre>\n\n<p>Happy refactoring!</p>\n\n<hr>\n\n<p>Edit: This code still has unresolved issues, e.g. hash keys can contain arbitrary strings which may include NUL, LF, tabs, spaces, or quotes. Those would have to be properly sanitized as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T16:02:35.893",
"Id": "63373",
"Score": "0",
"body": "Thank you! I didn't realize until just now that Perl had added static \nvariables and default assignments. I've been using Perl for ~20 years \nand have been waiting for those features!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T08:11:56.847",
"Id": "37903",
"ParentId": "37882",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37903",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T16:10:16.620",
"Id": "37882",
"Score": "4",
"Tags": [
"recursion",
"perl"
],
"Title": "Data structure to RDF"
}
|
37882
|
<p>Request for optimization, good practices, recommendations.</p>
<pre><code>class NodeMaxDepth {
private final NodeMaxDepth parent;
public NodeMaxDepth (NodeMaxDepth parent) {
this.parent = parent;
}
public NodeMaxDepth getParent() {
return parent;
}
}
/**
* Given a list of nodes with parent pointers,
* calculate the max depth of tree from the root.
*/
public final class MaxDepth {
private MaxDepth ( ) { }
public static int maxDepth (List<NodeMaxDepth> nodes) {
if (nodes.size() == 0) { throw new IllegalArgumentException("List of nodes is empty."); }
final Map<NodeMaxDepth, List<NodeMaxDepth>> parentChild = new HashMap<NodeMaxDepth, List<NodeMaxDepth>>();
NodeMaxDepth parent = null;
for (NodeMaxDepth node : nodes) {
if (node.getParent() == null) parent = node;
if (!parentChild.containsKey(node.getParent())) {
List<NodeMaxDepth> count = new ArrayList<NodeMaxDepth>();
parentChild.put(node.getParent(), count);
}
parentChild.get(node.getParent()).add(node);
}
if (parent == null) {
throw new IllegalArgumentException("The graph should be acyclic.");
}
return height (parentChild, parent);
}
private static int height (Map<NodeMaxDepth, List<NodeMaxDepth>> parentChild, NodeMaxDepth parent) {
assert parentChild != null;
assert parent != null;
final List<NodeMaxDepth> childList = parentChild.get(parent);
if (childList == null) return 0;
int maxCount = 0;
for (NodeMaxDepth child : childList) {
int height = height(parentChild, child);
if (height > maxCount) {
maxCount = height;
}
}
return maxCount + 1;
}
public static void main(String[] args) {
NodeMaxDepth root = new NodeMaxDepth(null);
NodeMaxDepth nodeLeft = new NodeMaxDepth(root);
NodeMaxDepth nodeRight = new NodeMaxDepth(root);
NodeMaxDepth nodeRightRight = new NodeMaxDepth(nodeRight);
NodeMaxDepth nodeRightRightRight = new NodeMaxDepth(nodeRightRight);
List<NodeMaxDepth> nodes = new ArrayList<NodeMaxDepth>();
nodes.add(root);
nodes.add(nodeLeft);
nodes.add(nodeRight);
nodes.add(nodeRightRight);
nodes.add(nodeRightRightRight);
System.out.println("Expected 3, Actual: " + maxDepth (nodes));
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>You shouldn't name your classes which form the data structure you operate on according to the problem you are trying to solve. The classes should be named according to their function in the data structure. Thus <code>NodeMaxDepth</code> should be simply <code>Node</code>. This also removes visual clutter when reading the code as the name is shorter yet conveys the same meaning.</p></li>\n<li><p>I'm not 100% sure why you build the list of children for each node in a separate data structure - it seems that this should be part of the <code>NodeMaxDepth</code> class. It would also make for a slightly cleaner implementation of building of the children lists as each node only has to add itself to the children collection of its parent.</p>\n\n<p>Something along these lines:</p>\n\n<pre><code>class Node {\n\n private final Node parent;\n private List<Node> children;\n\n public Node(Node parent) {\n this.parent = parent;\n children = new List<Node>();\n }\n\n public Node getParent() {\n return parent;\n }\n\n public void addChild(Node child) {\n children.add(child);\n }\n}\n\n\npublic static int maxDepth(List<Node> nodes) {\n if (nodes.size() == 0) { throw new IllegalArgumentException(\"List of nodes is empty.\"); }\n\n Node root = null;\n\n for (Node node : nodes) {\n if (node.getParent() == null) {\n if (root != null) {\n throw new IllegalArgumentException(\"Tree must not have multiple roots\");\n }\n root = node; \n }\n else {\n node.getParent().addChild(node);\n }\n }\n\n if (root == null) {\n throw new IllegalArgumentException(\"This does not seem to be a tree\");\n }\n\n return height (root);\n}\n</code></pre></li>\n<li><p>If you want to optimize for memory usage and code size you could resort to a simpler algorithm by simply walking up the tree from each node to the root and remember the longest path. Worst case this would result in <code>O(n^2)</code> runtime if I'm not mistaken but would not require any additional memory for building the children lists. The code would also be much simpler.</p>\n\n<p>As indicated by @200_success you could sacrifice a little bit more memory and find all leave nodes and just walk up from them:</p>\n\n<pre><code>// assume all nodes are leaves\nHashSet<Node> leaves = new HashSet<Node>(nodes);\n\nNode root = null;\n\n// remove all parents as they are not leaves\nfor (Node node : nodes) {\n if (node.getParent() == null) { \n root = node;\n }\n else {\n leaves.remove(node.getParent());\n }\n}\n\nif (root == null) {\n throw new IllegalArgumentException(\"The tree must have a root\");\n}\n\nint maxHeight = 0;\n\nfor (Node leaf : leaves) {\n int height = 1;\n Node current = leaf;\n while (current.getParent() != null) {\n current = current.getParent();\n height += 1;\n }\n if (maxHeight < height) {\n maxHeight = height;\n }\n}\n\nreturn maxHeight;\n</code></pre></li>\n<li><p>You don't really check for cycles - just that your tree has a root (you could have a normal tree and a disconnected cycle in the list).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T10:56:48.510",
"Id": "63063",
"Score": "0",
"body": "For (3), a shortcut is that you only have to consider the depths of the leaf nodes. Any node that has been mentioned as the parent of another node is of course not at maximum depth."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T20:36:03.053",
"Id": "63107",
"Score": "0",
"body": "As a minor optimization to part 3, you can compress the leaf list to the unique parents of the leaves - No need to traverse up from every leaf that shares a common parent especially if the branching factor is really high."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T23:57:32.003",
"Id": "63112",
"Score": "0",
"body": "The interviewer had given data structure of node that could not be modified. So addChild was not allowed, also he wanted strictly and O(n) answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T00:00:56.190",
"Id": "63114",
"Score": "0",
"body": "Your part 4 was excellent"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T10:28:48.507",
"Id": "37910",
"ParentId": "37890",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37910",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T21:04:53.437",
"Id": "37890",
"Score": "1",
"Tags": [
"java",
"algorithm",
"tree",
"hash-map"
],
"Title": "Max depth of tree when all parent pointers are provided"
}
|
37890
|
<p>I'm currently trying to improve my coding skills, so I'm trying to code a <em>Tic Tac Toe</em> game. At one point a "win check" is needed.<p>I'm using this code to check:</p>
<pre><code>public void CheckWin(States state)
{
if(fieldA1.GetState == state && fieldA2.GetState == state && fieldA3.GetState == state)
ReportWin(currentPlayer);
else if(fieldB1.GetState == state && fieldB2.GetState == state && fieldB3.GetState == state)
ReportWin(currentPlayer);
else if (fieldC1.GetState == state && fieldC2.GetState == state && fieldC3.GetState == state)
ReportWin(currentPlayer);
else if (fieldA1.GetState == state && fieldB1.GetState == state && fieldC1.GetState == state)
ReportWin(currentPlayer);
else if (fieldA2.GetState == state && fieldB2.GetState == state && fieldC2.GetState == state)
ReportWin(currentPlayer);
else if (fieldA2.GetState == state && fieldB2.GetState == state && fieldC2.GetState == state)
ReportWin(currentPlayer);
else if (fieldA3.GetState == state && fieldB3.GetState == state && fieldC3.GetState == state)
ReportWin(currentPlayer);
else if (fieldA1.GetState == state && fieldB2.GetState == state && fieldC3.GetState == state)
ReportWin(currentPlayer);
else if (fieldA3.GetState == state && fieldB2.GetState == state && fieldC1.GetState == state)
ReportWin(currentPlayer);
else
PlayerSwitch();
}
</code></pre>
<p>This code looks very unclean to me. Is there a better way to handle these <code>if</code> instructions?</p>
|
[] |
[
{
"body": "<p>There should only be eight ways to win; you have nine <code>ReportWin()</code>s. This one got listed twice:</p>\n\n<pre><code>fieldA2.GetState == state && fieldB2.GetState == state && fieldC2.GetState == state\n</code></pre>\n\n<p>Considering that you've named your squares as independent variables, there's not much you can do to generalize <code>CheckWin()</code>. Start by turning the board into an array or two-dimensional array, then read the advice in <a href=\"https://codereview.stackexchange.com/q/31769/9357\">Tic-Tac-Toe design</a> . Personally, I like the suggestion to <a href=\"https://codereview.stackexchange.com/a/31790/9357\">list all eight winning configurations</a>, as it results in the least code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T21:57:55.633",
"Id": "63025",
"Score": "1",
"body": "Yes, you're right! Thank you for bringing me in the right direction, this helped me alot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T21:50:44.783",
"Id": "37892",
"ParentId": "37891",
"Score": "8"
}
},
{
"body": "<p>I am too lazy to program it, but try programming tic tac toe instead of being in the \"bruteforce\" way, try making the winner the one who has at least 3 picks and the sum of his picks is 15(bad wording, I know). I'm going to save you on my blabbering and look at this: </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Magic_square\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Magic_square</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T01:13:34.867",
"Id": "63039",
"Score": "1",
"body": "Uhm I never heard of the real way to play this, I only knew the basic \"children game\". Looks like there is much more behind this game, thank you for showing me this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T00:40:26.020",
"Id": "37896",
"ParentId": "37891",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37892",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T21:09:28.430",
"Id": "37891",
"Score": "5",
"Tags": [
"c#",
"game"
],
"Title": "Simplifying `if` statements in Tic Tac Toe function"
}
|
37891
|
<p>I've just completed my first Ruby game. It's a modified BlackJack type game, called Hot 18.
I've used all methods for this Ruby game. It's a one-player game, but you can play with 1, 2, or 3 hands.</p>
<p>I would like to make it shorter and more efficient. I know it's kinda long, so I'm not asking you to go over everything. </p>
<p>If you notice any methods or <code>if</code> statements or something else I could shorten/improve on, that would be awesome.</p>
<p>Any other advice/opinions on how crappy or good my game is, is also welcome.</p>
<p>Lastly, since this is just a text version, where should I go from here? How can I make it visual? What program should I use? How to start that next step?</p>
<p>Here is a link where you can change the code/test the game/etc. <a href="http://labs.codecademy.com/BnL9#:workspace">http://labs.codecademy.com/BnL9#:workspace</a></p>
<pre><code>$deck = []
suits = ["spades", "diamonds", "clubs", "hearts"]
$hand1 = []
$hand2 = []
$hand3 = []
$handD = []
for x in suits
for y in 2..9
w = y.to_s
$deck.push(w+" of "+x)
end
end
def getnumberofhands
print "How many hands do you want to play? (1, 2, or 3) >>>"
num = gets.chomp.to_i
if num.between?(1,3)
startingchips(num)
$deck.shuffle!
puts "\n ...shuffling deck...\n\n"
cutdeck
newround(num)
else
getnumberofhands
end
end
def startingchips(num)
if num == 1
$h1c = 150_000
$h2c = nil
$h3c = nil
elsif num == 2
$h1c = 75_000
$h2c = 75_000
$h3c = nil
elsif num == 3
$h1c = 50_000
$h2c = 50_000
$h3c = 50_000
end
end
def placebets(chippers)
if chippers >= 1_000
print " Place your bet! (min: 1000, max: #{chippers}) >>>"
betamt = gets.chomp.to_i
if betamt.between?(1_000, chippers)
return betamt
else
placebets(chippers)
end
else
print " You don't have enough chips to place a bet.\n"
betamt = 0
end
end
def cutdeck
print " Cut the deck. (type a number between 1 and 32) >>>"
cut_the_deck_number = gets.chomp.to_i
if cut_the_deck_number.between?(1, 32)
puts "\n ...cutting the deck..."
bottomcut = $deck.pop(cut_the_deck_number)
topcut = $deck.pop($deck.length)
$deck = bottomcut + topcut
else
cutdeck
end
end
def newround(num)
if $deck.length > 14
if num > 0
puts "\nFirst Hand:"
$h1bet = placebets($h1c)
dealtwocards($hand1)
if num > 1
puts "\nSecond Hand:"
$h2bet = placebets($h2c)
dealtwocards($hand2)
if num > 2
puts "\nThird Hand:"
$h3bet = placebets($h3c)
dealtwocards($hand3)
end
end
puts "\n ...dealing cards..."
dealtwocards($handD)
puts "______________________________________________________________"
puts " \nDealer is showing the |#{$handD[1]}|"
puts "______________________________________________________________"
aroundtablechoices(num)
end
else
puts "______________________________________________________________"
puts " ____________________________________________________"
puts " _______________________________________"
puts "\n Game Over - Not enough cards left in deck to continue."
if num > 0
puts "\nFirst Hand:"
final(num, $h1c)
if num > 1
puts "\nSecond Hand:"
final(num, $h2c)
if num > 2
puts "\nThird Hand:"
final(num, $h3c)
end
end
totalscore(num)
end
end
end
def totalscore(num)
if num == 1
$h2c = 0
$h3c = 0
elsif num == 2
$h3c = 0
end
if $h1c + $h2c + $h3c < 150_000
xxx = 150_000 - $h1c - $h2c - $h3c
puts "\nYour total score is -#{xxx} (Which is not good at all)"
else
xxx = $h1c + $h2c + $h3c - 150_000
if xxx < 80_500
puts "\nYour total score is +#{xxx} (Which is okay)"
elsif xxx < 190_300 and xxx >= 80_500
puts "\nYour total score is +#{xxx} (Which is pretty decent)"
elsif xxx >= 190_300
puts "\nYour total score is +#{xxx} (Which is a great score!)"
end
end
end
def final(num, chipso)
if num == 1
abcd = 150_000
elsif num == 2
abcd = 75_000
elsif num == 3
abcd = 50_000
end
puts " Starting Chips: #{abcd}"
puts " Ending Chips: #{chipso}"
if chipso >= abcd
zyx = chipso - abcd
puts "\n You won #{zyx} play chips!"
else
zyx = abcd - chipso
puts "\n You lost #{zyx} play chips.."
end
end
def aroundtablechoices(num)
if num > 0
puts "\nFirst hand is |#{$hand1[0]}|#{$hand1[1]}|\n"
choices($hand1)
if num > 1
puts "_______________________________"
puts "\nSecond hand is |#{$hand2[0]}|#{$hand2[1]}|\n"
choices($hand2)
if num > 2
puts "_______________________________"
puts "\nThird hand is |#{$hand3[0]}|#{$hand3[1]}|\n"
choices($hand3)
end
end
puts "_______________________________"
puts "\nDealer flips over his second card which is the |#{$handD[0]}|"
dealerchoices($handD, num)
end
end
def dealonecard(hand)
hand.insert(-1, $deck.shift(1)).flatten!
end
def dealtwocards(hand)
hand.insert(0, $deck.shift(2)).flatten!
end
def choices(hand)
x = valueofcards(hand)
if x > 18
puts "\n ...you busted with #{x}..."
elsif x < 18
hitorstay(hand)
else
puts "\n ...you hit hot 18..."
end
end
def dealerchoices(hand, num)
x = valueofcards(hand)
if x > 18
puts "\n ...dealer busted with #{x}..."
prereview(num)
elsif x < 15
dealonecard(hand)
xxx = hand[-1]
puts "\n |#{xxx}|"
dealerchoices(hand, num)
else
puts "\n ...dealer stayed on #{x}..."
prereview(num)
end
end
def review(hand, chips, betamount)
abc = valueofcards(hand)
klm = valueofcards($handD)
if abc == klm and abc < 19
puts " You tied (you and dealer both had #{abc})"
puts " +0"
elsif abc > 18
puts " You lost (you went over 18 with #{abc})"
puts " -#{betamount}"
chips = chips - betamount
elsif abc < 19 and klm > 18
puts " You won (you had #{abc}, and dealer busted with #{klm})"
puts " +#{betamount}"
chips = chips + betamount
elsif abc < 19 and abc > klm
puts " You won (you had #{abc}, and dealer only had #{klm})"
puts " +#{betamount}"
chips = chips + betamount
elsif abc < 19 and klm < 19 and klm > abc
puts " You lost (you only had #{abc}, and dealer had #{klm})"
puts " -#{betamount}"
chips = chips - betamount
end
return chips
end
def prereview(num)
if num > 0
puts "_____________________________________________________________________"
puts "\n Recap of that round"
puts "\nFirst Hand:"
$h1c = review($hand1, $h1c, $h1bet)
if num > 1
puts "\nSecond Hand:"
$h2c = review($hand2, $h2c, $h2bet)
if num > 2
puts "\nThird Hand:"
$h3c = review($hand3, $h3c, $h3bet)
end
end
end
muckcards(num)
end
def muckcards(num)
if num > 0
$hand1.pop(10)
if num > 1
$hand2.pop(10)
if num > 2
$hand3.pop(10)
end
end
$handD.pop(10)
newround(num)
end
end
def hitorstay(hand)
x = valueofcards(hand)
print " You have #{x}, do you want to hit or stay? >>>"
y = gets.chomp.downcase
if y == "h" or y == "hit"
dealonecard(hand)
xxx = hand[-1]
puts "\n |#{xxx}|"
choices(hand)
elsif y == "s" or y == "stay"
puts "\n ...you stayed on #{x}..."
else
hitorstay(hand)
end
end
def valueofcards(hand)
total = 0
for x in hand
total += x[0..0].to_i
end
return total
end
getnumberofhands
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T04:53:38.280",
"Id": "63047",
"Score": "1",
"body": "*where should I go from here? How can I make it visual? What program should I use? How to start that next step?* These requests are off-topic, but the other review requests can still be fulfilled."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T01:55:19.830",
"Id": "63120",
"Score": "5",
"body": "**Hot18** sounds more like the name of a website I can't visit at work."
}
] |
[
{
"body": "<p>There is some awkward recursion and mutual recursion being used for flow control:</p>\n\n<ul>\n<li><code>getnumberofhands()</code> calls itself if the input fails validation.</li>\n<li><code>hitorstay()</code> calls itself if the input fails validation.</li>\n<li><code>newround()</code> calls <code>aroundtablechoices()</code>, which calls <code>dealerchoices()</code>, which calls <code>prereview()</code>, which calls <code>muckcards()</code>, which calls <code>newround()</code>.</li>\n</ul>\n\n<p>To begin it all, you call <code>getnumberofhands()</code>, which calls <code>newround()</code>. Who would have guessed that <code>getnumberofhands()</code> actually encompasses the entire game? You can't get an overview of the program unless you trace every line of code!</p>\n\n<p><strong>Basically, you are using function calls as <code>goto</code>, and it's not accepted programming practice.</strong> After a few rounds of play, with some invalid input, the call stack is going to be much deeper than it ought to be if you had structured your code properly. Instead, the outline of your code should be:</p>\n\n<pre><code>initialize_players\nwhile @deck.size > 14 do\n placebets!\n deal!\n\n @players.each do |player|\n player.play!(@deck)\n end\n @dealer.play!(@deck)\n review\nend\nfinal\n</code></pre>\n\n<p>With properly structured code, you can immediately get the big picture.</p>\n\n<hr>\n\n<p>Your code would benefit immensely with object-oriented programming. In particular, you have many if-conditions to support the one-, two-, or three-player cases. What you want to do is define a <code>Player</code> class:</p>\n\n<pre><code>class Player\n attr_reader :name\n attr_accessor :chips, :hand\n\n def initialize(name, chips)\n @name = name\n @chips = chips\n @hand = []\n end\n\n def hand_total\n # Functional code, like this, is more concise than for-loops\n @hand.collect { |card| card.value }.inject(:+)\n end\n\n def to_s\n '|' + hand.join('|') + '|'\n end\n\n def play!(deck)\n puts \"\\n#{self.name} is #{self}\"\n # Hit or stay loop\n ...\n end\n\n def new_hand!\n # Your muckcards() pops 10 cards off. Why not call clear() instead?\n hand.clear\n end\nend\n</code></pre>\n\n<p>The dealer would be a subclass of <code>Player</code>:</p>\n\n<pre><code>class Dealer < Player\n def initialize\n super('Dealer', 0)\n end\n\n def play!(deck)\n puts \"\\n#{self.name} flips over his second card which is the |#{hand[0]}|\"\n # Hit or stay code\n ...\nend\n</code></pre>\n\n<p>Then, elsewhere, you can initialize all of the players like this:</p>\n\n<pre><code>ordinals = ['First', 'Second', 'Third']\ninit_chips = 150_000\n\n# Initialize players\nn_players = _prompt_i(1, ordinals.size,\n \"How many hands do you want to play? (1, 2, or 3) >>> \")\n@players = (0...n_players).collect do |nth|\n Player.new(\"#{ordinals[nth]} Hand\", init_chips / n_players)\nend\n@dealer = Dealer.new\n</code></pre>\n\n<p>With all the players in an array, you can easily do <code>@players.each { |player| ... }</code> everywhere, without always having to worry about how many players there are.</p>\n\n<p>It's worthwhile to define a function to avoid code repetition:</p>\n\n<pre><code>def _prompt_i(min, max, prompt)\n begin\n print prompt\n num = gets.to_i\n end while ! num.between?(min, max)\n num\nend\n</code></pre>\n\n<p>Your cards are \"stringly typed\" — you store them as strings of the form <code>\"2 of spades\"</code>, then call <code>.to_i</code> when summing the hand. Better to define a proper class for them so that you can call <code>.value</code> instead:</p>\n\n<pre><code>class Card\n attr_reader :value, :suit\n\n def initialize(value, suit)\n @value = value\n @suit = suit\n end\n\n def to_s\n \"#{@value} of #{@suit}\"\n end\nend\n</code></pre>\n\n<p>You should also group your deck manipulation code into a class (and tighten up the code for <code>.initialize</code> and <code>.cut!</code>). </p>\n\n<pre><code>class Hot18Deck\n @@suits = [\"spades\", \"diamonds\", \"clubs\", \"hearts\"]\n\n def initialize\n @cards = @@suits.collect do |suit|\n (2..9).collect { |value| Card.new(value, suit) }\n end.flatten\n end\n\n def size\n @cards.size\n end\n\n def shuffle!\n @cards.shuffle!\n self\n end\n\n def cut!(position=nil)\n position = rand(@cards.size) if position.nil?\n @cards.rotate!(position)\n self\n end\n\n def deal!(player, n_cards=1)\n cards = (1..n_cards).collect { @cards.pop }\n player.hand.concat(cards)\n cards\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T07:19:22.213",
"Id": "63053",
"Score": "1",
"body": "LOL.. I was just writing an answer.. then read yours. You made all the points I was going to and more. I couldn't have said it better. Nice work"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T07:13:57.033",
"Id": "37900",
"ParentId": "37895",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "37900",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T23:54:10.187",
"Id": "37895",
"Score": "8",
"Tags": [
"optimization",
"ruby",
"beginner",
"game",
"playing-cards"
],
"Title": "Hot 18 game (modified Blackjack)"
}
|
37895
|
<p>In a question I answered I posted the following code:</p>
<pre><code>#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
int main()
{
fstream iFile("names.txt", ios::in);
// This does not work so replacing with code that does
// iFile >> file;
// This is not the best way.
// But the closest to the intention of the original post.
// Get size of file.
ifile.seekg(0,std::ios::end);
std::streampos length = ifile.tellg();
ifile.seekg(0,std::ios::beg);
// Copy file into string.
std::string file(length, '\0');
ifile.read(&buffer[0],length);
// Original code continues.
std::istringstream ss(file);
std::string token;
std::vector<std::string> names;
while(std::getline(ss, token, ',')) {
names.push_back(token);
}
for (unsigned int i = 0; i < names.size(); i++) {
auto it = std::remove_if(names[i].begin(), names[i].end(), [&] (char c) { return c == '"'; });
names[i] = std::string(names[i].begin(), it);
}
for (unsigned int i = 0; i < names.size(); i++) {
std::cout << "names["<<i<<"]: " << names[i] << std::endl;
}
}
</code></pre>
<p>Would this be inefficient for larger files? Would it be better if I read the file into one string, did all the manipulation on that, and then put it into a vector?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T10:00:42.273",
"Id": "63060",
"Score": "0",
"body": "Is the code all inside `main()`? You can't have free-floating code like that in C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:42:00.323",
"Id": "63196",
"Score": "0",
"body": "This code obviously does not work without main. So unless people have objects I will add main() around all the code so we are at least commenting on the code in the same way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:43:47.127",
"Id": "63197",
"Score": "0",
"body": "It still obviously does not work because `iFile >> file;` that is not doing very much. It reads a single space separated word. So I am going to change that to read the whole file into a string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:51:47.800",
"Id": "63198",
"Score": "0",
"body": "Now it works (as best it can)."
}
] |
[
{
"body": "<p>Instead of constructing an <code>fstream</code>, reading it all into a <code>string</code> (which is misleadingly named <code>file</code>, by the way), and creating an <code>istringstream</code> from that, why not just create an <code>ifstream</code> and call <code>getline</code> on it directly?</p>\n\n<p>You appear to be trying to parse a CSV file where the fields may be double quoted. If that is your intention, then simply deleting all <code>\"</code> characters is the wrong behaviour. See <a href=\"http://www.ietf.org/rfc/rfc4180.txt\" rel=\"nofollow\">RFC 4180</a> for commonly accepted quoting rules for CSV documents. Consider using a <a href=\"http://en.wikipedia.org/wiki/CSV_application_support\" rel=\"nofollow\">CSV parsing library</a> instead of rolling your own CSV parser.</p>\n\n<p>Your code would be clearer if you unquoted each <code>token</code> before adding it to <code>names</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:38:51.340",
"Id": "63195",
"Score": "1",
"body": "Totally agree on using CSV parsing library. CSV is one of those badly (not though through enough) defined formats that has a billion edge cases that you would never think about yourself. The simple case is trivial but doing it correctly for all cases is exceptionally hard."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T10:21:27.470",
"Id": "37909",
"ParentId": "37901",
"Score": "3"
}
},
{
"body": "<p>This code looks a little wild. I'd tame it like this:</p>\n\n<pre><code>#include <algorithm> // for std::remove\n#include <fstream> // for std::ifstream\n#include <string> // for std::string and std::getline\n#include <utility> // for std::move\n#include <vector> // for std::vector\n\nstd::ifstream infile(\"thefile.txt\"); // we don't really care where you got the name from\n\nstd::vector<std::string> names;\n\nfor (std::string line; std::getline(infile, line, ','); )\n{\n line.erase(std::remove(line.begin(), line.end(), '\"'), line.end());\n names.push_back(std::move(line));\n}\n\n// done\n</code></pre>\n\n<p>A few points to note:</p>\n\n<ul>\n<li><p>Keep it simple. Don't overthink.</p></li>\n<li><p>Use ready-made algorithms, don't reinvent wheels (<code>std::remove</code> removes values).</p></li>\n<li><p>Include what you use (<code>std::string</code>, <code>std::getline</code>).</p></li>\n<li><p>Use algorithms, don't hand-roll your own loops. (erase/remove)</p></li>\n<li><p>Understand what algorithms can do for you (don't hand-write your own \"erase\"). Get familiar with the standard library.</p></li>\n<li><p>Don't leak scopes. The <code>line</code> string is only needed within the loop, and no further.</p></li>\n<li><p>Efficiency tip: You can <em>move</em> from the <code>line</code> string that you no longer need and save yourself a copy. Also, we process everything in one step; no need to loop repeatedly.</p></li>\n</ul>\n\n<p>Furthermore, I suggest factoring this logic into a file:</p>\n\n<pre><code>std::vector<std::string> tokenize_file(std::string const & filename, char delimiter)\n{\n std::vector<std::string> result;\n\n // ...\n\n return result;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>std::vector<std::string> names = tokenize_file(\"thefile.txt\", ',');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T19:38:08.400",
"Id": "37919",
"ParentId": "37901",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37919",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T07:52:49.990",
"Id": "37901",
"Score": "3",
"Tags": [
"c++",
"strings",
"c++11",
"csv",
"io"
],
"Title": "Reading in a file and performing string manipulation"
}
|
37901
|
<p>I have written this code for BubbleSort in F#. Can you review and let me know how I can do this in most functional way.</p>
<pre><code>let rec getHighest list =
match list with
| [x] -> x
| [x; y] when x > y -> x
| [x; y] -> y
| hd1 :: hd2 :: tl when hd1 > hd2 -> getHighest (hd1 :: tl)
| hd1 :: tl -> getHighest tl
| _ -> failwith "unknown pattern"
let bubbleSort list =
let rec innerBubbleSort sorted = function
| [] -> sorted
| l ->
let x = getHighest l
let (a, b) = List.partition (fun i -> i = x) l
innerBubbleSort (a @ sorted) b
innerBubbleSort [] list
[<EntryPoint>]
let main args =
let input = [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3; 33; 34;]
let output = bubbleSort input
printfn "%s" (List.fold (fun acc x -> acc + " " + x.ToString()) "" output)
0
</code></pre>
|
[] |
[
{
"body": "<p>The first part could be rewritten as</p>\n\n<pre><code>match list with\n| hd1 :: hd2 :: tl when hd1 > hd2 -> getHighest (hd1 :: tl)\n| hd1 :: hd2 :: tl -> getHighest (hd2::t1)\n| hd1 :: [] -> hd1\n| _ -> failwith \"unknown pattern\"\n</code></pre>\n\n<p>which is significantly simpler</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:32:12.273",
"Id": "63725",
"Score": "0",
"body": "even simpler if you replace the first two patterns with a single one: `| hd1::hd2::tl -> let hd = if hd1 > hd2 then hd1 else hd2 in getHighest (hd::tl)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T08:56:27.387",
"Id": "37905",
"ParentId": "37902",
"Score": "1"
}
},
{
"body": "<p>I think a cleaner way to write <code>getHighest</code> would be to use accumulator:</p>\n\n<pre><code>let getHighest list =\n let rec getHighestImpl list highest =\n match list with\n | [] -> highest\n | head::tail -> getHighestImpl tail (max head highest)\n getHighestImpl (List.tail list) (List.head list)\n</code></pre>\n\n<p>You could also use the version of this function that already exists in the library: <a href=\"http://msdn.microsoft.com/en-us/library/ee370242.aspx\" rel=\"nofollow\"><code>List.max</code></a>.</p>\n\n<hr>\n\n<p>This is not bubble sort. In bubble sort, you compare neighboring items and swap them if they're in the wrong order. You do something similar in your <code>getHighest</code>, but you don't preserve the swaps. So, in the end, your algorithm is closer to <a href=\"https://en.wikipedia.org/wiki/Select_sort\" rel=\"nofollow\">selection sort</a>, than bubble sort.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T12:19:05.683",
"Id": "37912",
"ParentId": "37902",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T08:08:57.023",
"Id": "37902",
"Score": "1",
"Tags": [
"functional-programming",
"sorting",
"f#"
],
"Title": "Review my F# BubbleSort Program"
}
|
37902
|
<p>I have written the following program to implement merge sort in F#.</p>
<p>Can you please review this and let me know how can I write this in the most functional way (also most efficient and concise)?</p>
<p>In my recursion call, <code>mergeSort</code> is called again twice. I think it will be great if these two calls could be made on different threads.</p>
<p>Do I have to explicitly create separate threads or will F# automatically detect and execute on different cores (threads)? I have heard that functional languages are more multi-core friendly so I wonder what sort of optimization will be done by F# (or perhaps if this code was written in Haskell or pure functional language).</p>
<pre><code>let take n list =
List.ofSeq <| Seq.take n list
let rec takeRest n list =
match (n, list) with
| (0, l) -> l
| (n, _ :: tl) -> takeRest (n - 1) tl
| (_, _) -> failwith "unknown pattern"
let rec mergeList list1 list2 =
match (list1, list2) with
| [], [] -> []
| [], l -> l
| l, [] -> l
| hd1 :: tl1, (hd2 :: _ as tl2) when hd1 < hd2 -> hd1 :: mergeList tl1 tl2
| l1, hd2 :: tl2 -> hd2 :: mergeList l1 tl2
let rec mergeSort = function
| [] -> []
| [x] -> [x]
| l ->
let n = (int)(List.length l / 2)
let list1 = mergeSort (take n l)
let list2 = mergeSort (takeRest n l)
mergeList list1 list2
[<EntryPoint>]
let main args =
let input = [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3; 33; 34;];
List.iter (fun x -> printfn "%i" x) (mergeSort input)
0
</code></pre>
|
[] |
[
{
"body": "<p>A good start if you want to see a functional approach to a problem would be looking up a Haskell implementation. Poor guys are doomed to do things the functional way, so we might just as well use that - <a href=\"http://en.literateprograms.org/Merge_sort_%28Haskell%29\" rel=\"nofollow\">here's</a> a pretty in-depth description. It translates nicely to F# (minus one thing I'll talk about later).</p>\n\n<p>So without further ado:</p>\n\n<pre><code>let take n list = \n List.ofSeq <| Seq.take n list\n\nlet rec takeRest n list = \n match (n, list) with\n | (0, l) -> l\n | (n, _ :: tl) -> takeRest (n - 1) tl\n | (_, _) -> failwith \"unknown pattern\"\n</code></pre>\n\n<p>These are generally fine, however if you're already using Seq.take, there's also Seq.skip that does what your takeRest does, so you might use that.</p>\n\n<p>It's not the ideal way to split a list - look into the linked Haskell implementation for more of that.</p>\n\n<p>Also, going for a single split function is nicer in my opinion - let's say we have a function <code>split: a' list -> (a' list * a' list)</code> here. It can still use Seq.take/skip/length for now, can be switched for a better one transparently.</p>\n\n<pre><code>let rec mergeList list1 list2 =\n match (list1, list2) with\n | [], [] -> []\n | [], l -> l\n | l, [] -> l\n | hd1 :: tl1, (hd2 :: _ as tl2) when hd1 < hd2 -> hd1 :: mergeList tl1 tl2\n | l1, hd2 :: tl2 -> hd2 :: mergeList l1 tl2\n</code></pre>\n\n<p>Here, the first pattern is superfluous - the second and the third one cover the scenario already. The final two patterns seem clearer when you collapse them into a single one and move the when clause inside the pattern's body like this:</p>\n\n<pre><code>| x::xs, y::ys -> \n if x <= y \n then x :: (mergeList pred xs y::ys)\n else y :: (mergeList pred x::xs ys)\n</code></pre>\n\n<p>Also note the <code><=</code> there, so the order of elements is preserved.</p>\n\n<p>Your implementation however still has a problem that this doesn't fix - for large lists (around 100000 elements for me) you will get a StackOverflowException here, since the mergeList is not tail-recursive. In Haskell, a similar construct gives tail-recursive code due to optimization which F# doesn't have. You can make it tail-recursive in the usual way however, by using an accumulator instead of consing.</p>\n\n<pre><code>let rec mergeSort = function\n | [] -> [] \n | [x] -> [x]\n | l -> \n let n = (int)(List.length l / 2) \n let list1 = mergeSort (take n l)\n let list2 = mergeSort (takeRest n l)\n mergeList list1 list2\n</code></pre>\n\n<p>Assuming you have the split function defined as earlier, you can replace the third pattern's body like this:</p>\n\n<pre><code>let left, right = split l\nmergeList (mergeSort left) (mergeSort right)\n</code></pre>\n\n<p>Makes it more concise. </p>\n\n<pre><code>[<EntryPoint>]\nlet main args = \n let input = [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3; 33; 34;];\n List.iter (fun x -> printfn \"%i\" x) (mergeSort input)\n 0\n</code></pre>\n\n<p>So yeah, the code has a problem with larger inputs, which you obviously didn't test ;)\nSo as a bonus, a simple input generator I wrote for checking your code.</p>\n\n<pre><code>let generateInput rand min max len =\n Seq.unfold(fun (i, rand:Random) -> \n if i < len\n then Some <| (rand.Next(min, max), (i+1, rand))\n else None) (0, rand)\n\nlet input = generateInput (System.Random()) -1000 1000 10000 |> List.ofSeq\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong></p>\n\n<p>As for the other part of your question - F# will not do anything to make the code run in parallel by itself. You'd have to tell it to do it yourself. This would typically involve using async workflows. Another option would be parallel collection functions from F# PowerPack like Seq.pmap or the regular .NET mechanisms for parallelism like tasks. </p>\n\n<p>Anyway, asyncs are really cool if you have many long-running IO bound operations, but don't gain you much if all you're doing is sorting ints.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T16:36:51.340",
"Id": "38228",
"ParentId": "37904",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38228",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T08:53:53.757",
"Id": "37904",
"Score": "1",
"Tags": [
"recursion",
"functional-programming",
"sorting",
"f#",
"mergesort"
],
"Title": "Merge Sort Program"
}
|
37904
|
<p>I have been working on a javascript heavy project. There are sales, purchases, reports etc. What I've done is created a separate module for each i.e. a separate module for each i.e. a separate one for sale, one for purchase and so on. I am posting one of my modules, all the others have same structure. Can anyone please review it. Is there anything wrong with it or is everything okay. Any changes that I may want to consider to make it more better i.e. mantainable:</p>
<pre><code>var navigation = {
init : function (){
navigation.bindUI();
$('.ReportViews').addClass('active');
$('.stockNavReports').addClass('active');
},
bindUI : function () {
$("#btnReset").on('click', function (){
navigaiton.resetReport();
});
$("#btnShow").on('click', function (){
var fromEl = $('#txtStart');
var toEl = $('#txtEnd');
var groupBy = navigation.getGroupingCriteria();
if (navigation.validDateRange(fromEl.val(), toEl.val())) {
navigation.fetchReportData(fromEl.val(), toEl.val(), groupBy);
}
else{
fromEl.addClass('input-error');
toEl.addClass('input-error');
}
});
},
getGroupingCriteria : function () {
return $('input[name="grouping"]:checked').val().toLowerCase();
},
fetchReportData : function (startDate, endDate, groupBy) {
if (typeof navigation.dTable != 'undefined') {
navigation.dTable.fnDestroy();
$('#navigationRows').empty();
}
$.ajax({
url: base_url + "index.php/report/getNavigationReportData",
data: { startDate : startDate, endDate : endDate, groupBy : groupBy },
type: 'POST',
dataType: 'JSON',
beforeSend: function () {
// console.log(this.data);
},
complete: function () { },
success: function (result) {
if (result.length !== 0) {
$("#datatable_StockNavigationRows").fadeIn();
var prevDate = "";
var prevVrnoa = "";
var prevGodown_1 = "";
var prevGodown_2 = "";
if (result.length != 0) {
var navigationRows = $("#navigationRows");
$.each(result, function (index, elem) {
var obj = { };
obj.SERIAL = navigationRows.find('tr').length+1;
obj.VRNOA = elem.VRNOA;
obj.REMARKS = (elem.REMARKS) ? elem.REMARKS : "Not Available";
obj.QTY = (elem.QTY) ? elem.QTY : "Not Available";
obj.GODOWN_1 = (elem.GODOWN_1) ? elem.GODOWN_1 : "Not Available";
obj.GODOWN_2 = (elem.GODOWN_2) ? elem.GODOWN_2 : "Not Available";
obj.VRDATE = (elem.VRDATE) ? elem.VRDATE.substring(0,10) : "Not Available";
if (groupBy === 'date') {
if (prevDate != obj.VRDATE) {
// Create the heading for this new voucher.
var source = $("#report-dhead-template").html();
var template = Handlebars.compile(source);
var html = template(obj);
navigationRows.append(html);
// Reset the previous voucher to current voucher.
prevDate = obj.VRDATE;
}
}
else if (groupBy === 'vrnoa') {
if (prevVrnoa != obj.VRNOA) {
// Create the heading for this new voucher.
var source = $("#report-vhead-template").html();
var template = Handlebars.compile(source);
var html = template(obj);
navigationRows.append(html);
// Reset the previous voucher to current voucher.
prevVrnoa = obj.VRNOA;
}
}
else if (groupBy === 'godown_1') {
if (prevGodown_1 != obj.GODOWN_1) {
// Create the heading for this new voucher.
var source = $("#report-g1head-template").html();
var template = Handlebars.compile(source);
var html = template(obj);
navigationRows.append(html);
// Reset the previous voucher to current voucher.
prevGodown_1 = obj.GODOWN_1;
}
}
else if (groupBy === 'godown_2') {
if (prevGodown_2 != obj.GODOWN_2) {
// Create the heading for this new voucher.
var source = $("#report-g2head-template").html();
var template = Handlebars.compile(source);
var html = template(obj);
navigationRows.append(html);
// Reset the previous voucher to current voucher.
prevGodown_2 = obj.GODOWN_2;
}
}
// Add the item of the new voucher
var source = $("#report-item-template").html();
var template = Handlebars.compile(source);
var html = template(obj);
navigationRows.append(html);
});
}
}
navigation.bindGrid();
},
error: function (result) {
//$("*").css("cursor", "auto");
$("#loading").hide();
alert("Error:" + result);
}
});
},
bindGrid : function() {
// $("input[type=checkbox], input:radio, input:file").uniform();
var dontSort = [];
$('#datatable_StockNavigationRows thead th').each(function () {
if ($(this).hasClass('no_sort')) {
dontSort.push({ "bSortable": false });
} else {
dontSort.push(null);
}
});
navigation.dTable = $('#datatable_StockNavigationRows').dataTable({
// Uncomment, if datatable not working
// "sDom": "<'row-fluid table_top_bar'<'span12'<'to_hide_phone' f>>>t<'row-fluid control-group full top' <'span4 to_hide_tablet'l><'span8 pagination'p>>",
"sDom": "<'row-fluid table_top_bar'<'span12'<'to_hide_phone'<'row-fluid'<'span8' f>>>'<'pag_top' p> T>>t<'row-fluid control-group full top' <'span4 to_hide_tablet'l><'span8 pagination'p>>",
"aaSorting": [[0, "asc"]],
"bPaginate": true,
"sPaginationType": "full_numbers",
"bJQueryUI": false,
"aoColumns": dontSort,
"bSort": false,
"iDisplayLength" : 100,
"oTableTools": {
"sSwfPath": "js/copy_cvs_xls_pdf.swf",
"aButtons": [{ "sExtends": "print", "sButtonText": "Print Report", "sMessage" : "Stock Navigation Report" }]
}
});
$.extend($.fn.dataTableExt.oStdClasses, {
"s`": "dataTables_wrapper form-inline"
});
},
validDateRange : function (from, to){
if(Date.parse(from) > Date.parse(to)){
return false
}
else{
return true;
}
},
resetReport : function (){
$(".printBtn")
$("#datatable_navigationRows").hide();
}
}
navigation.init();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T09:29:30.940",
"Id": "63057",
"Score": "0",
"body": "Do you intend for each module to use it's own global namespace object, rather than just have one master namespace object that each module could plug its own object into?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T09:34:34.590",
"Id": "63058",
"Score": "0",
"body": "I have placed each of the object in a separate file and each page that intends to use that object, loads the file and uses it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T13:57:33.140",
"Id": "63077",
"Score": "2",
"body": "Your `$.ajax` success callback is **way** to big and cries out for refactoring."
}
] |
[
{
"body": "<p>In short,</p>\n\n<p>your code looks good until <code>$.ajax</code> where far to many things happen, more specifically too many things happen in <code>success</code>.</p>\n\n<p>The funny thing there is that it would look already a lot better if you took a generic approach to deal with the grouping.</p>\n\n<p>Maybe you can have a <code>groupingConfig</code> object : </p>\n\n<pre><code>var groupingConfigs = \n{\n date : { template : '#report-dhead-template' , fieldName : 'VRDATE' },\n vrnoa : { template : '#report-vhead-template' , fieldName : 'VRNOA' },\n godown_1 : { template : '#report-g1head-template' , fieldName : 'GODOWN_1' },\n godown_2 : { template : '#report-g1head-template' , fieldName : 'GODOWN_1' }\n}\n</code></pre>\n\n<p>then, before the <code>$.each(</code> you can get the groupingConfig</p>\n\n<pre><code>var groupingConfig = groupingConfigs[groupBy];\n</code></pre>\n\n<p>and within the <code>$.each(</code> you can simply</p>\n\n<pre><code>if (groupingConfig)\n{\n if (previousValue != obj[groupingConfig.fieldName])\n {\n // Create the heading for this new group. \n var source = $( groupingConfig.template ).html();\n var template = Handlebars.compile(source);\n var html = template(obj);\n\n navigationRows.append(html);\n //Reset the previous group value\n previousValue = obj[groupingConfig.fieldName];\n }\n}\n</code></pre>\n\n<p>Also, the below creation of the dataTable looks all kind of wrong:</p>\n\n<pre><code>navigation.dTable = $('#datatable_StockNavigationRows').dataTable({\n // Uncomment, if datatable not working\n // \"sDom\": \"<'row-fluid table_top_bar'<'span12'<'to_hide_phone' f>>>t<'row-fluid control-group full top' <'span4 to_hide_tablet'l><'span8 pagination'p>>\",\n \"sDom\": \"<'row-fluid table_top_bar'<'span12'<'to_hide_phone'<'row-fluid'<'span8' f>>>'<'pag_top' p> T>>t<'row-fluid control-group full top' <'span4 to_hide_tablet'l><'span8 pagination'p>>\",\n \"aaSorting\": [[0, \"asc\"]],\n \"bPaginate\": true,\n \"sPaginationType\": \"full_numbers\",\n \"bJQueryUI\": false,\n \"aoColumns\": dontSort,\n \"bSort\": false,\n \"iDisplayLength\" : 100,\n \"oTableTools\": {\n \"sSwfPath\": \"js/copy_cvs_xls_pdf.swf\",\n \"aButtons\": [{ \"sExtends\": \"print\", \"sButtonText\": \"Print Report\", \"sMessage\" : \"Stock Navigation Report\" }]\n }\n});\n</code></pre>\n\n<ul>\n<li>Hungarian notation, don't do that</li>\n<li>sDom is a super long string without any comment</li>\n<li>the commented sDom has a superfluous comment</li>\n<li>bJQueryUI ?</li>\n</ul>\n\n<p>Finally, </p>\n\n<pre><code>validDateRange : function (from, to){\n if(Date.parse(from) > Date.parse(to)){\n return false\n }\n else{\n return true;\n }\n}, \n</code></pre>\n\n<p>should really be </p>\n\n<pre><code>validDateRange : function (from, to)\n{\n return !(Date.parse(from) > Date.parse(to));\n}, \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T03:26:43.630",
"Id": "38006",
"ParentId": "37906",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38006",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T09:19:15.100",
"Id": "37906",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"design-patterns",
"modules"
],
"Title": "Javascript code pattern"
}
|
37906
|
<p>OK... last sort of the day and probably the most fun. F# is really awesome.</p>
<pre><code>let rec quickSort list =
match list with
| [] -> []
| [x] -> [x]
| hd :: _ ->
quickSort (List.filter (fun x -> x < hd) list) @ hd :: quickSort (List.filter (fun x -> x > hd) list)
[<EntryPoint>]
let main args =
printfn "%s" (List.fold (fun acc x -> acc + " " + x.ToString()) "" (quickSort [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3; 33; 34;]))
0
</code></pre>
<p>let me know How I can improve this code. I am trying to think functionally and want my program to be most efficient, concise and functional.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T10:41:51.133",
"Id": "63062",
"Score": "1",
"body": "This will probably drop any duplicate elements as `x !< hd` and `x !> hd`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T18:20:19.227",
"Id": "63097",
"Score": "0",
"body": "I do have a question though. since I make 2 calls to quickSort in the recursion... will these two calls be made parallelly? \n\nI have heard that functional languages are more multi-core friendly... but want to confirm if I have to do some thing explicilty to ensure that all the two sub quickSorts are executed on different threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T19:21:16.050",
"Id": "63102",
"Score": "0",
"body": "The calls will not run on separate threads. This is good as you could generate a lot of threads if itndid"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T19:26:07.427",
"Id": "63103",
"Score": "0",
"body": "OK... but they say that functional languages are more multi-core friendly as compared to imperative ones. so in the program above is there any multi-core benefit which I would not get in a traditional langugae.... also is there something I can do to be more multicore aware?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T16:16:12.797",
"Id": "63276",
"Score": "0",
"body": "@KnowsNotMuch Multi-core-frienly means that they are easy to parallelize. But easy doesn't mean mean it's done automatlically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T18:21:11.073",
"Id": "63285",
"Score": "0",
"body": "Fair enough. So how do I parallelize the code above. I am very sure that the subcalls to 2 methods can execute on their own threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T15:16:29.427",
"Id": "63371",
"Score": "1",
"body": "@KnowsNotMuch You can use normal .Net `Task`s for that. Something like `Task.Run(fun () -> quickSort ...)` to start two `Task`s and then call `Result` on both of them to get the results."
}
] |
[
{
"body": "<p>I'd:</p>\n\n<ul>\n<li>exclude unnecessary duplication (<code>List.filter</code> etc.)</li>\n<li>drop separate match rule for the list of one element</li>\n<li>rely on type inference</li>\n<li>use more succinct form of pattern matching</li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>let rec qsort = function\n | [] -> []\n | x::xs -> let lt, ge = List.partition ((>) x) xs\n qsort lt @ x :: qsort ge\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T20:52:17.943",
"Id": "37989",
"ParentId": "37907",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37989",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T09:58:24.340",
"Id": "37907",
"Score": "1",
"Tags": [
"functional-programming",
"sorting",
"f#",
"quick-sort"
],
"Title": "Review my F# QuickSort Program"
}
|
37907
|
<p>I am new to JavaScript, HTML and CSS, although not to programming.</p>
<p>I wanted to style 'select' dropdowns, so I wrote this:</p>
<p>What noob mistakes am I making? Is this a good or evil use of JS?</p>
<pre><code><head>
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<!--
<link href="./font-awesome-4.0.3/css/font-awesome.css" rel="stylesheet">
-->
<style>
body { font-family: sans-serif; }
.control { display: none; }
.dropdown > dl { margin: 4px; font-family: sans-serif; }
.dropdown > dl > dt { display:inline-block; width: auto; }
.dropdown .value { display: none; }
.dropdown > dl > dd { position: absolute; left: 0; top: 27px; display: none; }
.dropdown > dl { display:inline-block; width: auto; position: relative; cursor: pointer; }
.dropdown > dl > dt { border: 1px solid #ddd; background-color: #eee; color: black; padding: 3px 6px; font-weight: bold; }
.dropdown > dl > dd { border: 1px solid #ddd; background-color: white; margin:0;}
.dropdown > dl > dd > ul { padding:0; margin:0 }
.dropdown > dl > dd > ul > li { list-style: none; padding:5px 10px; padding-left: 28px; }
.dropdown > dl > dt:hover,
.dropdown > dl > dd > ul > li:hover { background-color: #333; color: white; }
.dropdown > dl > dd > ul > li { display: none; }
.dropdown li.selected:before { font-family: 'FontAwesome'; content: '\f00c'; margin: 0 5px 0 -22px; font-weight: normal; }
.dropdown li.selected { font-weight: bold; }
</style>
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<!--
<script src="jquery-2.0.3.js"></script>
-->
<script>
function Dropdown(name) {
this.name = name;
this.$root = $('#dropdown').clone().removeAttr('id').show();
this.$root.children('dl').css('z-index', Dropdown.zindex.next());
Controls.registerControl(this);
this.$selected = this.$root.find('dt');
this.$selectedContents = {
$text: this.$selected.children('span.text'),
$value: this.$selected.children('span.value') };
this.$popup = this.$root.find('dd');
this.$options = this.$popup.children('ul');
this.$option = this.$options.children('li');
this.$optionContents = {
$text: this.$option.children('span.text'),
$value: this.$option.children('span.value') };
var that = this;
this.$selected.click(function(event) {
if (!that.$popup.is(':visible')) {
Controls.blurAll();
}
that.$popup.toggle();
});
this.$options.click(function(event) {
that._selectOption($(event.target).is('li') ? $(event.target) : $(event.target).parent('li'));
that.$popup.hide();
});
}
Dropdown.prototype = {
constructor: Dropdown,
_makeOption: function(text, value) {
this.$optionContents.$text.text(text);
this.$optionContents.$value.text(value);
return this.$option.clone();
},
setOptions: function(optionsMap) {
for (var value in optionsMap) {
var text = optionsMap[value];
this._makeOption(text, value).appendTo(this.$options).show();
}
return this;
},
_selectOption: function($option) {
var text = $option.children('span.text').text();
var value = $option.children('span.value').text();
this.$selectedContents.$text.text(text);
this.$selectedContents.$value.text(value);
this.$options.children('.selected').removeClass('selected');
$option.addClass('selected');
this.$root.closest('form').find('[name="'+this.name+'"]').val(value);
},
selectOption: function(value) {
var that = this;
this.$options.find('li').each(function (idx, li) {
if ($(li).find('span.value').text() == value) {
that._selectOption($(li));
}
});
return this;
},
blur: function() {
this.$popup.hide();
}
};
Dropdown.replaceSelect = function($select) {
var options = {};
$select.children('option').each(function (idx, el) {
options[$(el).val()] = $(el).text();
});
$select.hide().before(
new Dropdown($select.prop('name'))
.setOptions(options)
.selectOption($select.children('option:selected').val())
.$root);
};
Dropdown.replaceSelectByName = function(name) {
Dropdown.replaceSelect($('select[name="' + name + '"]'));
};
Dropdown.replaceAllSelects = function() {
$('select').each(function (idx, el) {
Dropdown.replaceSelect($(el));
});
};
Dropdown.zindex = {
_idx: 100,
next: function() { return this._idx--; }
};
Controls = {
_controls: [],
registerControl: function (control) {
this._controls.push(control);
},
blurAll: function () {
$.each(this._controls, function (idx, control) {
control.blur();
});
}
}
</script>
</head>
<body>
<form method="POST" action="http://www.htmlcodetutorial.com/cgi-bin/mycgi.pl">
<p>Naci en el mes de <select name="month">
<option selected value=1>enero</option>
<option value=2>febrero</option>
<option value=3>marzo</option>
<option value=4>avril</option>
<option value=5>mayo</option>
<option value=6>junio</option>
<option value=7>julio</option>
<option value=8>agosto</option>
<option value=9>septiembre</option>
<option value=10>octubre</option>
<option value=11>noviembre</option>
<option value=12>diciembre</option></select></p>
<p>Me gusta las <select name="fruit">
<option value=1>manzanas</option>
<option selected value=2>peras</option>
<option value=3>naranjas</option></select></p>
<input type="submit" name="Submit" value="Submit">
</form>
<span class="control dropdown" id="dropdown">
<dl>
<dt><span class="text"></span><span class="value"></span>&nbsp;<i class="fa fa-caret-down"></i></dt>
<dd><ul>
<li><span class="text"></span><span class="value"></span></li>
</ul></dd>
</dl>
</span>
</body>
<script>
$(document).ready(function () {
Dropdown.replaceAllSelects();
});
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T12:30:12.117",
"Id": "63260",
"Score": "0",
"body": "Do I conclude that no-one knows if this is good or evil, or that it was so evil (or good) that it left everyone speechless?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T14:06:50.667",
"Id": "63496",
"Score": "1",
"body": "Be assured that we are quick to point out evil. However, if it is difficult to find constuctive criticism (i.e. what is posted is too good or too complex/specific) that can definitely silence the masses."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:53:55.527",
"Id": "63526",
"Score": "1",
"body": "For this kind of question, you should use http://jsfiddle.net/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:55:10.640",
"Id": "63529",
"Score": "1",
"body": "I use [jQuery-selectbox plugin](https://github.com/marcj/jquery-selectBox) to style `select` dropdowns, you may have a look at this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T09:34:34.207",
"Id": "67060",
"Score": "0",
"body": "Thanks for the tips and links. All useful and taken on board."
}
] |
[
{
"body": "<h1>Tip for your code:</h1>\n\n<ul>\n<li>Use <code>$name</code> for var names that represent a jQuery selection, nor for a member (it is the convention).</li>\n<li>Since you use jQuery, consider writing a plugin extending <code>jQuery.fn</code> instead of prototyping</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T14:04:17.310",
"Id": "63495",
"Score": "1",
"body": "You couldn't have his code working? Weird. http://jsfiddle.net/sciencepharaoh/JwXPc/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T14:28:16.557",
"Id": "63500",
"Score": "0",
"body": "How did you get it to work @DanielCook ???"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T14:43:52.727",
"Id": "63503",
"Score": "0",
"body": "@Malachi I put it in JSFiddle? Is it not working? I'm confused. It looks like it works to me. Though my linked fiddle removed some of the options but it worked with them in there as well. Actually, I did add 1 unnecessary semi-colon to make JSHint happy..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:41:20.233",
"Id": "63511",
"Score": "0",
"body": "@DanielCook, I tried to take the code from the original question post, and it was a plain drop down menu. I am probably making noob mistakes myself"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:04:30.067",
"Id": "63519",
"Score": "0",
"body": "@Sinsedrix, the `tip for your code` section is the only section that is actually a review in my opinion"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:37:11.347",
"Id": "63522",
"Score": "0",
"body": "@Malachi, should I remove the rest of recommandations to have an upvote instead of a downvote?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:39:29.167",
"Id": "63523",
"Score": "0",
"body": "the JSFiddle thing is a comment, the fact that you use a plugin is also a comment, your problem rendering the UTF-8 is sort of an off topic comment, and the OP has that link in their code. So I would say yes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T16:53:52.860",
"Id": "67523",
"Score": "0",
"body": "@sinsedrix - I _have_ used $name for variable names that represent a jQuery selection, check again. It's just that I store a number of them in member variables. Eg aDropdown.name is a string while aDropdown.$options references the <ul> of options."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T16:58:09.307",
"Id": "67524",
"Score": "0",
"body": "@Malachi yes the only thing was the reference to fontawesome css for the tick and down-caret symbols, which wants to go in the External Resources section on the left instead of in a <link> tag in the css section http://jsfiddle.net/JwXPc/2/ :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:44:34.403",
"Id": "67797",
"Score": "0",
"body": "@user2886246 `this.$xxx` are members not **variables** that represent a jQuery selection."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T11:22:13.317",
"Id": "38165",
"ParentId": "37908",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T10:02:14.717",
"Id": "37908",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "Styling <select> dropdowns with jQuery"
}
|
37908
|
<p>I'm looking for feedback (both general Java, and Twitter specific) on how I'm getting the Twitter handles of everyone who retweeted me over the last 200 Tweets. Comments welcome. </p>
<pre><code>package twitone;
import java.util.ArrayList;
import twitone.structure.BaseTwitterClass;
import twitone.structure.TwitApplicationFactory;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
public class getmyretweeters extends BaseTwitterClass {
public static void main(String[] args) throws TwitterException {
Twitter twitter = TwitApplicationFactory.getjoereddingtonTwitter();
String temp[] = getRetweeters(twitter);
for (String string : temp) {
System.out.println(string);
}
}
public static String[] getRetweeters(Twitter twitter) {
ArrayList<String> names = new ArrayList<String>();
try {
for (Status status : twitter.getUserTimeline(new Paging(1, 200))) {
System.out.println(status.getText());
if (status.getRetweetCount() > 0) {
Thread.sleep(120000);// Because I don't want to breach
// Twitter's rate limits
for (Status rt : twitter.getRetweets(status.getId())) {
names.add(rt.getUser().getScreenName());
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return names.toArray(new String[names.size()]);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>GOing through some general style issues first:</p>\n\n<ul>\n<li><code>getmyretweeters</code> is a class, and should have Camel-Case capitalization -> <code>GetMyRetweeters</code>. I would prefer <code>MyRetweeters</code> with a method <code>get()</code>.</li>\n<li>Your class should not have the static methods you have, but shouild rather have a constructor that takes a twitter name, and then initializes itself to that: <code>public MyRetweeters(Twitter account) {...}</code></li>\n<li>your <code>getRetweeters(...)</code> method is static, but should really be an instance method, and the name is implied by the class-name (Retweeters). <code>get()</code> is just fine. Since the class should have been constructed with a Twitter handle, there is no need for any arguments either...</li>\n</ul>\n\n<p>Note about the twitter-API rate limits. Sleeping for 2 minutes is a bad idea in your code. If you really have to be doing this sleeping, then you should change your code to do a background mechanism for accessing Twitter, and have a callback to your application with the results of your query. Also, you should have some sort of caching mechanism so that you do not need to re-query data you already have from Twitter. A limit of 1 query every 2 minutes is a really tight limit.</p>\n\n<p>You should also consider reading up on the <a href=\"https://dev.twitter.com/docs/rate-limiting/1.1#tips\" rel=\"nofollow\">Twitter API rate limits</a>... they are not as harsh as you have allowed for. Also, there are headers returned as part of tyour request that shows you how many requests are available in the current window, and when the window ends. Bottom line is that you should be smarter about your rate limiting.</p>\n\n<p>Finally, your factory that gets Twitter sessions should not have a method <code>TwitApplicationFactory.getjoereddingtonTwitter()</code> but should instead have something like: <code>TwitApplicationFactory.getTwitter(\"joereddington\")</code>;</p>\n\n<p>Your <code>main</code> method becomes:</p>\n\n<pre><code>public static void main(String[] args) throws TwitterException {\n Twitter twitter = TwitApplicationFactory.getTwitter(\"joereddington\");\n Retweeters retweets = new Retweeters(twitter);\n String temp[] = retweeters.get();\n for (String string : temp) {\n System.out.println(string);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T14:32:11.123",
"Id": "63078",
"Score": "0",
"body": "Lovely! thank you for all of that - very thorough! : )"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T13:16:16.673",
"Id": "37913",
"ParentId": "37911",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37913",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T12:17:40.010",
"Id": "37911",
"Score": "2",
"Tags": [
"java",
"twitter"
],
"Title": "Getting the list of people who RT'd a particular Twitter account (using Twitter4J)"
}
|
37911
|
<p>I'm making a Hangman game and it seems that my code doesn't provide me much freedom with using layouts. I added an image to my <code>JFrame</code> then I added a <code>JPanel</code> to my image which I'm using for all the <code>JLabel</code>s and <code>JTextField</code>s but it seems to me that it's inefficient because in order to change the layout of my <code>JTextField</code>s or <code>JLabel</code>s I have to change the layout of my image which messes up the entire looks of the game.</p>
<p>How can I make this code more efficient and give myself more freedom to change the layouts of my <code>JLabel</code>s and <code>JTextField</code>s without messing everything up?</p>
<pre><code>/*PACKAGE DECLARATION*/
package Game;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/************************
* GAME MECHANICS CLASS *
* **********************/
public class GameStructure {
/* INSTANCE DECLARATIONS */
private String []wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday"};
private int []length = new int [64];
private JTextField tf;//text field instance variable (used)
private JLabel jl2;//label instance variable (used)
private JLabel jl3;//label instance (working on)
private String letter;
/*****************
* LENGTH METHOD *
* ***************/
public void length(){
jl3 = new JLabel();
int j = 0;
for(j = 0; j<64; j++) {
length[j] = wordList[j].length();//gets length of words in wordList
}//end for
int l = 0;
String line = "";
//create line first then put into .setText
for(int m = 0; m<length[l]; m++) {
line += "__ ";
l++;
}//end for
jl3.setText(line);
}//end length method
/*****************
* WINDOW METHOD *
* ***************/
public void window() {
LoadImageApp i = new LoadImageApp();//calling image class
JFrame gameFrame = new JFrame();//declaration
JPanel jp = new JPanel();
//JPanel jp2 = new JPanel();//jpanel for blanks
JLabel jl = new JLabel("Enter a Letter:");//prompt with label
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));//set font
tf = new JTextField(1);//length of text field by character
jl2 = new JLabel("Letters Used: ");
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));//set font
jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));//set font
jp.add(jl);//add label to panel
jp.add(tf);//add text field to panel
jp.add(jl2);//add letters used
gameFrame.add(i); //adds background image to window
i.add(jp); // adds panel containing label to background image panel
gameFrame.setTitle("Hangman");//title of frame window
gameFrame.setSize(850, 600);//sets size of frame
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed
gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file
gameFrame.setLocationRelativeTo(null);//window centered
gameFrame.setResizable(false);//user can not resize window
gameFrame.setVisible(true);//display frame
}//end window method
/*********************
* USER INPUT METHOD *
* *******************/
public void userInput() {
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {//when enter key pressed
JTextField tf = (JTextField)e.getSource();
letter = tf.getText();
jl2.setText(jl2.getText() + letter + " ");//sets jlabel text to users entered letter
}//end actionPerformed method
});
}//end userInput method
}//end GameMechanics class
/*PACKAGE DECLARATION*/
package Game;
/***********************
* IMPORT DECLARATIONS *
* *********************/
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
/***************
* IMAGE CLASS *
* *************/
public class LoadImageApp extends JPanel {
private static final long serialVersionUID = 1L;
private ImageIcon image;
/***********************
* PAINT IMAGE METHOD *
* *********************/
public void paintComponent (Graphics g) {
//setLayout(new BorderLayout());
super.paintComponent(g);
image = new ImageIcon("hangman.png");//image name & type
image.paintIcon(this, g, 270, 20);
}//end paintComponent method
}//end LoadImageApp class
/*PACKAGE DECLARATION*/
package Game;
/*******************
* GAME MAIN CLASS *
* *****************/
public class GameMain {
/***************
* MAIN METHOD *
* *************/
public static void main (String []args) {
GameStructure game = new GameStructure();//declaration
game.length();
game.window();
game.userInput();
}//end main method
}//end GameMain class
</code></pre>
|
[] |
[
{
"body": "<p>You will need to do two things:</p>\n\n<ol>\n<li>Split your image into multiple pieces that will be loaded into different panels.</li>\n<li>Use appropriate layout managers when adding components so that you can control how components are arranged. <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html\" rel=\"nofollow\">Layout Manager Guide</a></li>\n</ol>\n\n<p>Since I can't see your image, I can't make specific suggestions, but remember that you can layer multiple Layout Managers together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T19:02:55.833",
"Id": "37918",
"ParentId": "37916",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37918",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T18:49:00.440",
"Id": "37916",
"Score": "3",
"Tags": [
"java",
"performance",
"functional-programming",
"homework",
"hangman"
],
"Title": "Hangman game background image possibly inefficient"
}
|
37916
|
<p>In C++11, it is en vogue to use small lambda expressions to produce ad-hoc predicates. However, sometimes it's fun to create predicates in a functional, "point-free" way. That way, no function bodies need to be inspected, the code is mildly self-documenting, and it's a great icebreaker at parties.</p>
<p>Suppose I have a <code>std::vector<std::vector<int>> v</code>, and I want to remove all the empty inner vectors. The lambda-style <code>remove_if</code> call might look like this:</p>
<pre><code>std::remove_if(v.begin(),
v.end(),
[](std::vector<int> const & w) -> bool { return w.empty(); });
</code></pre>
<p>This is verbose and redundant. The point-free approach uses <code>std::mem_fn</code>:</p>
<pre><code>std::remove_if(v.begin(),
v.end(),
std::mem_fn(&std::vector<int>::empty));
</code></pre>
<p>This works fine. But now the problem: Suppose I want to further compose this predicate, say by negating it. In the lambda this would be a trivial change. But for the functional notation, we <em>would</em> like to use the library function <code>std::not1</code> to produce a <code>unary_negate</code> wrapper.</p>
<p>However, the obvious <code>std::not1(std::mem_fn(&std::vector<int>::empty))</code> does not compile. The problem appears to be that the result type of <code>std::mem_fn</code> defines its <code>argument_type</code> member type as a <em>pointer</em> to the class, not a reference; cf. 20.8.10/2:</p>
<blockquote>
<p>The simple call wrapper shall define two nested types named <code>argument_type</code> and <code>result_type</code> as synonyms for <code>cv T*</code> and <code>Ret</code>, respectively, when <code>pm</code> is a pointer to member function with cv-qualifier <code>cv</code> and taking no arguments, where <code>Ret</code> is pm’s return type.</p>
</blockquote>
<p>This breaks the composability with <code>std::not1</code>.</p>
<p>I have written this type mangling work-around which strips the unwanted pointer:</p>
<pre><code>#include <type_traits>
template <typename T>
struct result_type_mangler : T
{
using argument_type = typename std::remove_pointer<typename T::argument_type>::type;
result_type_mangler(T t) : T(t) { }
};
template <typename T>
result_type_mangler<T> mangle(T t)
{
return result_type_mangler<T>(t);
}
</code></pre>
<p>Now I can compose the predicates:</p>
<pre><code>std::not1(mangle(std::mem_fn(&std::vector<int>::empty)))
</code></pre>
<p>Is this a legitimate work-around? Can member function predicates be composed in an easier way? And why is the member function wrapper's <code>argument_type</code> defined in such a weird way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T17:53:30.420",
"Id": "63168",
"Score": "0",
"body": "Note: `bind` also doesn't work: `std::not1(std::bind(&std::vector<int>::empty, std::placeholders::_1))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T08:58:04.450",
"Id": "63684",
"Score": "0",
"body": "Those parties sound fun!"
}
] |
[
{
"body": "<p>I think your way works, but there are other solutions:</p>\n\n<p>In C++98, there is actually an <code>std::mem_fun_ref</code> function.<br>\nIn C++11, there is the <code>std::ref</code> and <code>std::cref</code> functions. </p>\n\n<pre><code>// VS2012 doesn't have uniform initialization, so this is me being lazy\nint a1 [] = {1, 2, 3, 4, 5} ;\nint a2 [] = {6, 7, 8} ;\n\nstd::vector <int> v1 (std::begin (a1), std::end (a1)) ;\nstd::vector <int> v2 ;\nstd::vector <int> v3 (std::begin (a2), std::end (a2)) ;\n\nstd::vector <std::vector <int> > vv ;\nvv.push_back (v1) ;\nvv.push_back (v2) ;\nvv.push_back (v3) ;\n\nstd::cout << vv.size () << std::endl ;\n\nauto end = std::remove_if (std::begin (vv), std::end (vv), std::not1 (std::cref (&std::vector<int>::empty))) ;\nvv.erase (end, std::end (vv)) ;\n\nstd::cout << vv.size () << std::endl ;\n</code></pre>\n\n<p><strong>Update</strong><br>\nIt seems that using <code>std::cref</code> only works on Visual Studio. <code>std::mem_fun_ref</code> is a portable but deprecated solution. Therefore, I would say that your way is the best way out of these three solutions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T17:49:32.487",
"Id": "63167",
"Score": "0",
"body": "That sounded interesting, but I can't reproduce that. With gcc, `std::cref(&std::vector<int>::empty)` is an error, [e.g. see here](http://ideone.com/gRdrvw). Maybe a VS weirdness?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:04:51.273",
"Id": "63169",
"Score": "0",
"body": "I looked over the `reference_wrapper` class implementation is Visual Studio 2012. It uses, what I believe is a [universal reference](http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers) in its constructor. I don't own a copy of the standard, but I'm assuming you're correct and that this is VS weirdness. `std::mem_fun_ref` seems to work, but that's a deprecated solution."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T17:44:57.550",
"Id": "37972",
"ParentId": "37917",
"Score": "2"
}
},
{
"body": "<p>The verbosity of C++14 generic lambdas should be much lower than <code>std::mem_fun</code> </p>\n\n<pre><code>std::remove_if(v.begin(),\n v.end(),\n [](auto const & w) { return w.empty(); });\n</code></pre>\n\n<p>If you want to remove non-empty vectors, you can also do something like</p>\n\n<pre><code>std::function<bool(std::vector<int>)> is_empty = [](auto const & w) { return w.empty(); }; \nstd::remove_if(v.begin(),\n v.end(),\n std::not1(is_empty));\n</code></pre>\n\n<p>Oh and the <code>-> bool</code> in your question is already superfluous in C++11 for single-line lambdas. Generic lambdas are currently supported by Clang >= 3.4, GCC 4.9 and MSVC 2013 November CTP.</p>\n\n<p>I think Scott Meyers even has an Item \"Prefer lambdas over bind\" in his upcoming book Effective C++11/14.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T09:05:03.253",
"Id": "38265",
"ParentId": "37917",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T19:00:47.007",
"Id": "37917",
"Score": "8",
"Tags": [
"c++",
"c++11",
"template-meta-programming",
"higher-order-functions"
],
"Title": "Functional composition of member function predicates"
}
|
37917
|
<p>Given an array, find any three numbers which sum to zero. </p>
<p>This problem is a continuation of a code kata in <a href="https://codereview.stackexchange.com/questions/23996/given-an-array-find-any-three-numbers-which-sum-to-zero">Python</a> . I'm learning Scala and would like feedback on more efficient, cleaner, and functional ways of solving (and unit testing) this problem.</p>
<p><strong>SumToZero.scala</strong></p>
<pre><code>class SumToZeroNotFound(msg:String=null, cause:Throwable=null)
extends java.lang.Exception (msg, cause) {}
class SumToZero{
def process(arr: Array[Int], size: Int = 3): Array[Int] = {
for(combination <- arr.combinations(size))
if(combination.sum == 0) //note: can yield combinations here if we want to find all combinations that sum to zero
return combination
throw new SumToZeroNotFound()
}
}
</code></pre>
<p><strong>TestSumToZero.scala</strong></p>
<pre><code>import org.junit.runner.RunWith
import org.scalatest.junit._
import org.scalatest._
import scala.runtime.ScalaRunTime.stringOf
@RunWith(classOf[JUnitRunner])
class TestSumToZero extends FunSuite {
test("should return entire array that sums to zero") {
val stz = new SumToZero
val res = stz.process(Array(1,2,-3))
val str_res = stringOf(res)
assert( str_res == "Array(1, 2, -3)",
"res: " + str_res)
}
test("should raise NotFound exception if no combination sums to zero"){
val stz = new SumToZero
intercept[SumToZeroNotFound]{
stz.process(Array(1,2,3,4))
}
}
test("should return first set of nums that sum to zero"){
val stz = new SumToZero
val res = stz.process(Array(125, 124, -100, -25, 1, 2, -3, 10, 100))
val str_res = stringOf(res)
assert( str_res == "Array(125, -100, -25)",
"res: " + str_res)
}
}
</code></pre>
<p><strong>Updated SumToZero.scala</strong></p>
<pre><code>class SumToZeroNotFound(msg:String=null, cause:Throwable=null)
extends java.lang.Exception (msg, cause) {}
trait SumToZero{
@throws(classOf[SumToZeroNotFound])
def process(arr: Array[Int], size: Int = 3): Array[Int]
}
object SumToZeroBruteForce extends SumToZero{
//brute force process any size combination
override def process(arr: Array[Int], size: Int = 3): Array[Int] = {
arr.combinations(size).find(_.sum == 0).getOrElse(throw new SumToZeroNotFound)
}
}
object SumToZeroBinSearch extends SumToZero{
//optimized with sorting and binary search
//scala does not seem to have a native binary search routine
implicit private class Search(val arr: Array[Int]){
def binSearch(target: Int) = {
java.util.Arrays.binarySearch(arr.asInstanceOf[Array[Int]], target)
}
}
@throws(classOf[IllegalArgumentException])
override def process(arr: Array[Int], size: Int = 3): Array[Int] = size match {
case 3 =>
val sorted_arr = arr.sortWith(_<_)
val max_len = sorted_arr.length
for((i_val, i) <- sorted_arr.takeWhile(_ <= 0).zipWithIndex ){
val maxj = sorted_arr(max_len - 1) - i_val
for(j_val <- sorted_arr.slice(i+1, max_len).takeWhile(_ <= maxj)){
val temp_sum = i_val + j_val
val res_idx = sorted_arr.binSearch(-temp_sum)
if (res_idx > -1) {
return Array(i_val, j_val, sorted_arr(res_idx))
}
}
}
throw new SumToZeroNotFound
case _ => throw new IllegalArgumentException("only support size of three for now")
}
}
object SumToZero{
def apply(impl: String) = impl match{
case "with_bin_search" => SumToZeroBinSearch
case _ => SumToZeroBruteForce
}
}
</code></pre>
<p><strong>Updated TestSumToZero</strong></p>
<pre><code>import org.junit.runner.RunWith
import org.scalatest.junit._
import org.scalatest._
import scala.runtime.ScalaRunTime.stringOf
@RunWith(classOf[JUnitRunner])
class TestSumToZero extends FunSuite{
final val methods = Array("brute_force", "with_bin_search")
def testAllMethods(arr: Array[Int], expected_res: String = "",
methods: Array[String] = this.methods) = {
for (method <- methods){
println("testing: " + method)
val stz = SumToZero(method)
val res = stz.process(arr)
val str_res = stringOf(res.sortWith(_<_))
assert( str_res == expected_res,
"res: " + str_res)
}
}
test("should return entire array that sums to zero") {
testAllMethods(Array(1,2,-3), "Array(-3, 1, 2)")
}
test("should raise NotFound exception if no combination sums to zero"){
this.methods.foreach(method =>
intercept[SumToZeroNotFound]{
testAllMethods(Array(1,2,3), "", Array(method))
})
}
test("should return first set of nums that sum to zero"){
testAllMethods(Array(125, 124, -100, -25, 1, 2, -3, 10, 100), "Array(-100, -25, 125)")
}
}
</code></pre>
<p><a href="https://github.com/bcajes/katas/tree/master/jvm_langs" rel="nofollow noreferrer">GitHub link</a></p>
<p>I'd like to use Scala spec for unit testing, but was not able to get it working with Gradle. Please comment if you are able to build Scala projects with Gradle and produce JUnit-style output.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:44:53.123",
"Id": "63707",
"Score": "0",
"body": "Thanks for the feedback. I was not able to package functions outside an object or class. I also ended up playing around with Scala traits and pattern matching to test out multiple implementations of SumToZero. I've added the updated code above and in the repo. Maybe there's a more functional way to implement the optimized version... I'll have to tackle that another time."
}
] |
[
{
"body": "<p>If you only want to return the first such combination what about doing something like this instead of the for loop?</p>\n\n<pre><code>def process(arr: Array[Int], size: Int = 3): Array[Int] = {\n arr.combinations(size).find(_.sum == 0).getOrElse(throw new SumToZeroNotFound)\n}\n</code></pre>\n\n<p>I'd also suggest that if there's no reason to include it in a class that I personally would not. Unlike Java, not everything needs to be contained in a class and this seems like something which is in a class for the sake of being in a class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T01:36:41.867",
"Id": "38206",
"ParentId": "37922",
"Score": "3"
}
},
{
"body": "<p>Since this is tagged 'algorithm' I am going to review your algorithm....</p>\n\n<p>Your algorithm here is wrong. Looking for all combinations (<code>O(n!)</code>) is a very expensive way of doing it. I know very little about Scala, but, can assure you that a much better (the best?) algorithm would be something like:</p>\n\n<ol>\n<li>sort the data (<code>O(n log(n))</code>)</li>\n<li>'first' loop through all the values </li>\n<li>'nested' loop through all values <strong>after</strong> the value in the 'first' loop</li>\n<li>binary search for the value <code>- (first + nested)</code> in all the values <strong>after</strong> the nested value</li>\n</ol>\n\n<p>In Java it would be something like:</p>\n\n<pre><code>Arrays.sort(data);\nfor (int i = 0; i < data.length; i++) {\n for (int j = i + 1; j < data.length; j++) {\n int pos = Arrays.binarySearch(data, j + 1, data.length, - (data[i] + data[j]));\n if (pos >= 0) {\n System.out.printf(\"Zero-sum values are [%d,%d,%d]\\n\", data[i], data[j], data[pos]);\n }\n }\n}\n</code></pre>\n\n<p>This has a much better performance characteristic than checking every combination.</p>\n\n<p>You can also add some tricks / optimizations to the loops to quit when impossible combinations present themselves, like:</p>\n\n<pre><code>if (data[i] > 0) {\n // if the smallest value is positive then no possible combination exists....\n break;\n}\n</code></pre>\n\n<p>additionally, you can short-circuit the 'j' loop....</p>\n\n<pre><code>for (int i = 0; i < data.length; i++) {\n if (data[i] > 0) {\n break;\n }\n int maxj = data[data.length - 1] - data[i]; \n for (int j = i + 1; j < data.length && data[j] <= maxj; j++) {\n .......\n }\n}\n</code></pre>\n\n<p>how you do this in Scala is your problem .... ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-27T04:47:09.697",
"Id": "284172",
"Score": "1",
"body": "the algorithm is also named Leetcode 15 3 sum, I wrote the idea you presented, the time complexity is O(n*n*logn), n is the size of array. Leetcode online judge shows TLE - time limited exceeded. The optimal solution is not using binary search, using two pointers instead, the time complexity can be lowered to O(n*n)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T03:04:27.730",
"Id": "38208",
"ParentId": "37922",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38208",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T21:58:56.217",
"Id": "37922",
"Score": "3",
"Tags": [
"algorithm",
"scala"
],
"Title": "Given an array, find any three numbers which sum to zero"
}
|
37922
|
<p>I had a somewhat interesting issue. I had to take an array and turn it into a string with a set of delimiters; then later on take that string and turn it back into an array, splitting at the same delimiters. The twist was the string could be contain anything (including the delimiters).</p>
<p>I feel like I over-engineered the solution, and am wondering what you guys can come up with as alternatives.</p>
<p>Here is my solution. <code>escapedImplode</code> turns an array into a string, and <code>escapedExplode</code> turns that string back into its corresponding array. The <code>testEscapedIE</code> function is a little test scaffolding to see if your solution works.</p>
<pre><code>function escapedImplode ($glue, $array, $escapeChar = '\\')
{
$array = array_map(function ($item) use ($escapeChar, $glue) {
$item = str_replace($escapeChar, $escapeChar . $escapeChar, $item);
$item = str_replace($glue, $escapeChar . $glue, $item);
return $item;
}, $array);
return implode($glue, $array);
}
function escapedExplode ($delimiter, $string, $escapeChar = '\\')
{
$characters = str_split($string);
$isEscaped = false;
$parts = array();
$buffer = '';
for ($i = 0; $i < count($characters); $i++)
{
$char = $characters[$i];
// If is escaped, just add to the buffer and continue
if ($isEscaped)
{
$buffer .= $char;
$isEscaped = false;
continue;
}
// If is a delimiter, which isn't escaped, set state and continue
else if ($char == $escapeChar)
{
$isEscaped = true;
continue;
}
// If not escaped and is the delimiter, break here
if ($char == $delimiter)
{
$parts[] = $buffer;
$buffer = '';
continue;
}
// Doesn't match another special case, tack onto buffer
$buffer .= $char;
}
// Add whatever is in the buffer to end of parts
$parts[] = $buffer;
return $parts;
}
function testEscapedIE ()
{
$tests = array(
array('test', 'cool', 'awesome'),
array('some/thing', 'cool', '/isbrewing/'),
array('with\\/asdf', '//other//', '\\/collness\\/'),
array('////','//\\//','\\//\\//\\','\\\\'),
);
foreach ($tests as $test)
{
$imploded = escapedImplode('/', $test);
$exploded = escapedExplode('/', $imploded);
echo 'Testing: ' . implode(', ', $test) . ' -- ';
echo $imploded . ' -- ';
echo implode($exploded, ', ') . ': ';
echo $test === $exploded ? '<strong>Pass</strong>' : '<strong>Fail</strong>';
echo "<br/>\n";
}
}
testEscapedIE();
</code></pre>
|
[] |
[
{
"body": "<p>Not bad. I just have a few nitpicks.</p>\n\n<p>You can iterate over characters of a string directly without splitting it into an array first:</p>\n\n<pre><code>for ($i = 0; $i < strlen($string); $i++) {\n $char = $string[$i];\n ...\n}\n</code></pre>\n\n<p>I believe that the PHP interpreter isn't smart enough to recognize that <code>strlen($string)</code> is invariant, so you might get better performance with</p>\n\n<pre><code>$strlen = strlen($string);\nfor ($i = 0; $i < $strlen; $i++) {\n $char = $string[$i];\n ...\n}\n</code></pre>\n\n<p>I find the <code>else if</code> in <code>escapedExplode()</code> slightly jarring. Either use <code>if</code> and <code>continue</code> everywhere, or <code>if</code>, <code>else if</code>, <code>else if</code>, <code>else</code> without <code>continue</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T23:25:37.207",
"Id": "37928",
"ParentId": "37923",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37928",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T23:00:36.340",
"Id": "37923",
"Score": "3",
"Tags": [
"php",
"strings"
],
"Title": "Escaped explode/implode function"
}
|
37923
|
Programming questions involving digitally-represented playing cards. This includes representing cards and decks in data structures, user interfaces for manipulating cards in a virtual fashion, and implementing correct algorithmic shuffling.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T23:05:25.667",
"Id": "37925",
"Score": "0",
"Tags": null,
"Title": null
}
|
37925
|
The Fibonacci sequence is the sequence defined by F(0) = 0, F(1) = 1, F(n + 2) = F(n) + F(n + 1). The first few terms are 0, 1, 1, 2, 3, 5, 8.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T23:06:19.247",
"Id": "37927",
"Score": "0",
"Tags": null,
"Title": null
}
|
37927
|
<p>I have reworked my code as suggested from my previous question: <a href="https://codereview.stackexchange.com/questions/37860/determine-if-a-word-can-be-constructed-from-list-of-subsets/37894#37894">Determine if a word can be constructed from list of subsets</a>.</p>
<p>Please instruct me on the complexity along with a review feedback, as explained in the comments below.</p>
<pre><code>/**
* Question is better explained by examples:
* 1. given
* i/p subsets - ["un", "xy", "te", "i", "d"]
* and i/p string is : united should result in true.
* and i/p string of : union should result in false.
*
* 2. i/p subsets - ["tonyl", "pqr", "pqrbri",]
* and i/p string of : briton should be true.
* and i/p string of : japan should result in false.
*
*
* Complexity:
* O(n * m)
* - where n is number of characters in target
* - where m is number of subsets
*
*/
public final class StringFromSubSets {
private StringFromSubSets() {}
/**
* If a word ends with start of a target word, then return the common char count.
* Eg: for caterpillar and larva, the value returned should be 3 since,
* 'lar' is end of caterpillar which is common with 'lar' of larva.
*
* If there is no intersection then return 0.
*
* @param end The word, whose end chars should be considered to find intersection
* @param target The word, whose start chars should be considered to find intersection.
* @return The number of common chars at end of word end and start of word start.
*/
private static int subsetEndIntersectsWithTargetStart(String end, String target, int i) {
assert end != null;
assert target != null;
int j = 0;
while (i < end.length()) {
if (end.charAt(i) != target.charAt(j)) return 0;
i++;
j++;
}
return j;
}
private static final int anySubsetEndIntersectsWithTargetStart(List<String> stringSubsets, String target) {
assert stringSubsets != null;
assert target != null;
for (String string : stringSubsets) {
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == target.charAt(0)) {
int x = subsetEndIntersectsWithTargetStart (string, target, i);
if (x > 0) return x;
}
}
}
return 0;
}
/**
* Returns the number of common characters in target and and subset which are common from start
* Eg:
* "winner" and "wine" will result in return value of 3, since, "win" is the intersection from start.
*
*
* @param target : the target string
* @param subset : the subset string
* @return : the index which indicates the number of char's in common.
*/
private static int targetStartIntersectsWithSubsetStart(String target, String subset) {
assert target != null;
assert subset != null;
int i = 0;
while (i < target.length() && i < subset.length()) {
if (target.charAt(i) != subset.charAt(i)) return ++i;
++i;
}
return i;
}
private static boolean targetStartIntersectsWithAnySubsetStart(List<String> stringSubsets, String target) {
assert stringSubsets != null;
assert target != null;
if (target.length() == 0) return true;
for (String string : stringSubsets) {
int x = targetStartIntersectsWithSubsetStart(target, string);
if (x > 0) {
target = target.substring(x);
if (targetStartIntersectsWithAnySubsetStart(stringSubsets, target)) return true;
}
}
return false;
}
public static boolean targetFromSubSets(List<String> stringSubsets, String target) {
if (stringSubsets == null) throw new NullPointerException("The input subset should not be null");
if (target == null) throw new NullPointerException("The target cannot be null");
if (target.length() == 0) throw new IllegalArgumentException("The target should not be zero length");
// any ends with start ?
int x = anySubsetEndIntersectsWithTargetStart(stringSubsets, target);
if (x == 0) return false;
target = target.substring(x);
return targetStartIntersectsWithAnySubsetStart(stringSubsets, target);
}
public static void main(String[] args) {
List<String> listOfString = new ArrayList<String>();
listOfString.add("sachin");
listOfString.add("tendulkar");
listOfString.add("rahul");
listOfString.add("dravid");
System.out.println("Expected true, Actual " + targetFromSubSets(listOfString, "int"));
System.out.println("Expected true, Actual " + targetFromSubSets(listOfString, "idsa"));
System.out.println("Expected true, Actual " + targetFromSubSets(listOfString, "sachindravid"));
System.out.println("Expected true, Actual " + targetFromSubSets(listOfString, "drahultendulkars"));
System.out.println("Expected false, Actual " + targetFromSubSets(listOfString, "sehwag"));
System.out.println("Expected false, Actual " + targetFromSubSets(listOfString, "ganguly"));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T02:37:13.207",
"Id": "63125",
"Score": "1",
"body": "I believe you haven't thought this through. According to my interpretation, I would expect `targetFromSubSets(…, \"endul\")` to be `true`, but it would print `false`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T03:40:06.107",
"Id": "63130",
"Score": "0",
"body": "@200_success the question (and previous version) could be clearer, but, I believe `endul` should be false... since `end` is not attached to the beginning or end of an input 'subset' (but is in the middle)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T03:54:09.960",
"Id": "74672",
"Score": "1",
"body": "It is not clear whether SubStrings can be used multiple times."
}
] |
[
{
"body": "<ol>\n<li><p>After pressing <kbd>Ctrl</kbd>+<kbd>F</kbd> (code format) in Eclipse the javadoc will be this:</p>\n\n<pre><code>/**\n * Question is better explained by examples: 1. given i/p subsets - [\"un\", \"xy\",\n * \"te\", \"i\", \"d\"] and i/p string is : united should result in true. and i/p\n * string of : union should result in false.\n</code></pre>\n\n<p>I think Eclipse is right here because usually javadoc is ends up in HTML documentation which ignores whitespaces. Try to format your javadoc that remains readable in HTML too or use non-javadoc comments:</p>\n\n<pre><code>/*\n * Question is better explained by examples:\n * 1. given\n * i/p subsets - [\"un\", \"xy\", \"te\", \"i\", \"d\"]\n</code></pre>\n\n<p>(Note the only one <code>*</code> in the first line. Eclipse does not reformat this one.)</p></li>\n<li><p>It's confusing that the method name indicates a <code>boolean</code> return value but actually it's an integer.</p>\n\n<pre><code>private static final int anySubsetEndIntersectsWithTargetStart(List<String> stringSubsets, String target) {\n ...\n}\n</code></pre>\n\n<p>Inside the method the return variable is called <code>x</code> which still does not help. Name both of them to express their purpose.</p></li>\n<li><pre><code>private static int targetStartIntersectsWithSubsetStart(String target, String subset) {\n</code></pre>\n\n<p>The same issue is here. Actually, the javadoc is quite good:</p>\n\n<pre><code>/**\n * Returns the number of common characters in target and and subset which\n * are common from start Eg: \"winner\" and \"wine\" will result in return value\n * of 3, since, \"win\" is the intersection from start.\n</code></pre>\n\n<p>I'd call the method <code>getCommonStartCharacterCount</code> or <code>getCommonPrefixLength</code>. (The latter is better.) There is a similar method in <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#getCommonPrefix%28java.lang.String...%29\" rel=\"nofollow noreferrer\">Apache Commons Lang <code>StringUtils</code></a>:</p>\n\n<pre><code>String getCommonPrefix(String... strs)\n</code></pre>\n\n<p>One thing which does not trun out from the javadoc why the third one returns <code>4</code> here:</p>\n\n<pre><code>assertEquals(3, targetStartIntersectsWithSubsetStart(\"asdx\", \"asd\")); // OK\nassertEquals(3, targetStartIntersectsWithSubsetStart(\"asd\", \"asdx\")); // OK\nassertEquals(4, targetStartIntersectsWithSubsetStart(\"asdx\", \"asdY\")); // OK\n</code></pre>\n\n<p>Is it intentional? Why?</p>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><pre><code>for (String string: stringSubsets) {\n for (int i = 0; i < string.length(); i++) {\n if (string.charAt(i) == target.charAt(0)) {\n int x = subsetEndIntersectsWithTargetStart(string, target, i);\n if (x > 0)\n return x;\n }\n }\n}\n</code></pre>\n\n<p>I'd extract out a local variable here for better readability:</p>\n\n<pre><code>final char targetFirstChar = target.charAt(0);\n</code></pre></li>\n<li><pre><code>while (i < target.length() && i < subset.length()) {\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>while (i < Math.min(target.length(), subset.length())) {\n</code></pre>\n\n<p>I think it's easier to read since it reveals the intent.</p></li>\n<li><p>You could check first that the the subsets contains every required character for the <code>target</code>. If not you can fail early without too much effort.</p></li>\n<li><p>I'd go with something like that <a href=\"https://codereview.stackexchange.com/a/37894/7076\"><code>@rolfl</code> suggested in this former answer</a>. Using a higher level <code>Set</code> structures would improve readability and maintainability a lot.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T04:12:35.703",
"Id": "43272",
"ParentId": "37930",
"Score": "5"
}
},
{
"body": "<h2>General</h2>\n<p>This question still does not have a clear definition, despite the assurances at the top. For example should the following return true:</p>\n<blockquote>\n<pre><code>targetFromSubSetsX(listOfString, "raviddraviddraviddra")\n</code></pre>\n</blockquote>\n<p>This reuses the same word again, and again...</p>\n<p>The description does not give a clear indication whether that is valid or not.</p>\n<p>The code in the example says it is valid, but, am I to trust the code?</p>\n<h2>Your Solution</h2>\n<p>I considered how I would solve this problem, then looked at your code, and could not find that pattern.</p>\n<p>You do have extensive error checking (for nulls, empty, and otherwise broken input). This is good.</p>\n<p><strong>Bug1:</strong> - then I noticed that you have room for just a single matching start pattern... and that made me think there is a bug.... what if the wrong word matches, and there is not another word that can carry-through on the problem</p>\n<p><strong>Bug2:</strong> but, then I found this code:</p>\n<blockquote>\n<pre><code>private static int targetStartIntersectsWithSubsetStart(String target, String subset) {\n assert target != null;\n assert subset != null;\n\n int i = 0;\n while (i < target.length() && i < subset.length()) {\n if (target.charAt(i) != subset.charAt(i)) return ++i;\n ++i;\n }\n return i;\n}\n</code></pre>\n</blockquote>\n<p>And that code is obviously broken, it returns 1 when nothing matches....</p>\n<p>For the input <code>targetStartIntersectsWithSubsetStart("a", "b")</code> it returns 1... which is not what it is supposed to do.</p>\n<p>This second bug works to make the first bug disappear... because now anything matches!</p>\n<h2>Alternate Solution</h2>\n<p>Putting it together I figure the code is broken....</p>\n<p>This is how I would solve the problem... a set-up recursive method, and the actual recursion.</p>\n<p>The setup method does the work of identifying whether there is a prefix match on any of the words. If there is a match, it recursively matches the subset words with the target until there is just a 'tail' left.</p>\n<p>When I wrote it I assumed that a subset word could only be used once, but, then when I compared it to your results, I found that this is not the case. I have commented out the code that enforced the use-once rule on the subsets.....</p>\n<pre><code>public static boolean targetFromSubSets(List<String> stringSubsets, String target) {\n for (String word : stringSubsets) {\n Set<String> totry = new HashSet<>(stringSubsets);\n //totry.remove(word);\n \n // OK, we have a word, and a remaining set. Let's see what we can match.\n for (int i = 0; i < word.length(); i++) {\n String subword = word.substring(i);\n if (target.startsWith(subword)) {\n if (matchExactSubSets(totry, target.substring(subword.length()))) {\n return true;\n }\n }\n }\n \n }\n return false;\n}\n\n\nprivate static boolean matchExactSubSets(Set<String> totry, String substring) {\n if (substring.length() == 0) {\n return true;\n }\n String[] words = totry.toArray(new String[totry.size()]);\n for (String word : words) {\n if (substring.startsWith(word)) {\n //totry.remove(word);\n //try {\n if (matchExactSubSets(totry, substring.substring(word.length()))) {\n return true;\n }\n //} finally {\n //totry.add(word);\n //}\n } else if (substring.length() < word.length()) {\n if (word.startsWith(substring)) {\n return true;\n }\n }\n }\n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T04:20:36.347",
"Id": "43273",
"ParentId": "37930",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T23:42:04.730",
"Id": "37930",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings",
"combinatorics"
],
"Title": "Determine if a word can be constructed from list of subsets - follow-up"
}
|
37930
|
<p>I wrote a python model for the game "snake" that I'm not really satisfied with.</p>
<p>My intention was to separate the game logic from the drawing and input handling (which worked quite well) but I've got several points which I don't know how to solve better.</p>
<ol>
<li><p>To use this model one needs to initialize it with callbacks that fire when the score increases and when the game is over. They pass the score as an integer. I don't like this solution because it feels a lot like C, passing around function pointers.</p></li>
<li><p>For the drawing the user needs to access the head, tail and food variables in the model. Should I write explicit getters for that? I prefixed everything the user shouldn't directly access with an underscore. How can I make this interface more clear?</p></li>
<li><p>One needs to call _move_snake(dx, dy) with the direction dx, dy the snake should move although the model already has a variable that holds the snake's direction. But I guess this way it's easier for testing?</p></li>
</ol>
<hr>
<pre><code>import random
class SnakeModel(object):
"""
Model for a snake-like game.
"""
def __init__(self, width, height,
gameover_callback, atefood_callback):
"""
Initializes the game
gameover_callback and atefood_callback are callback functions. They
are passed the current player score (length of the snake's tail) as an
integer.
"""
self.width = width
self.height = height
self._gameover = gameover_callback
self._ateFood = atefood_callback
self.reset()
def reset(self):
"""
Starts a new game.
Sets the starting position, length and direction of the snake as well
as the position of the first food item.
"""
self._dir = (0, -1)
# You can read head, tail and food directly for drawing
self.head = (self.width / 2, self.height - 2)
self.tail = [(self.width / 2, self.height - 1)]
self.food = (self.width / 2, self.height / 3)
def step(self):
"""
Advances the game one step
"""
# check for collisions
if self.head in self.tail:
self._gameover(len(self.tail))
# eat food
if self.head == self.food:
self.tail.insert(0, self.head)
self.food = self._new_food_location()
self._ateFood(len(self.tail))
# move snake
self._move_snake(*self._dir)
def set_snake_direction(self, dx, dy):
"""
Sets the direction the snake will move on the next step
"""
self._dir = (dx, dy)
def _move_snake(self, dx, dy):
"""
Moves the snake one step in the given direction.
The snake can move through the game area's borders and comes out on the
other side.
"""
x, y = self.head
newX = (x + dx) % self.width
newY = (y + dy) % self.height
self.head = (newX, newY)
self.tail.insert(0, (x, y))
self.tail.pop()
def _new_food_location(self):
"""
Returns a new possible food position which is not in the snake.
"""
game_field = set([(x, y) for x in range(self.width)
for y in range(self.height)])
possible = game_field - set(self.tail) - set([self.head])
new_position = random.choice(list(possible))
return new_position
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T00:18:20.527",
"Id": "63116",
"Score": "0",
"body": "You might be interested in [this question](http://codereview.stackexchange.com/q/24267/11728) and its answer."
}
] |
[
{
"body": "<h3>1. Answers to your questions</h3>\n\n<ol>\n<li><p><strong>Callbacks</strong>. Why not use a <em>return value</em> intead?</p>\n\n<pre><code>def step(self):\n \"\"\"Advance the game one step.\n Return a pair of Booleans (game over, ate food).\n\n \"\"\"\n game_over = self.head in self.tail\n ate_food = self.head == self.food\n if ate_food:\n self.tail.insert(0, self.head)\n self.food = self._new_food_location()\n self._move_snake(*self._dir)\n return game_over, ate_food\n</code></pre>\n\n<p>(But see below for two bugs in this function.)</p></li>\n<li><p><strong>Getters</strong> are normally used in three scenarios. First, to provide a simple interface to a complex data structure. Second, to give the implementer freedom to change the implementation in future. Third, in combination with setters when writing a <em>public</em> API whose internal data structures have an <em>invariant</em> that needs to be preserved, so as to protect the internal data structures from corruption by a well-meaning but incompetent client.</p>\n\n<p>None of these scenarios applies here. The internal data structures are straightforward, so the first scenario does not apply. And this is all your own code (not a public API) so the second and third scenarios do not apply.</p></li>\n<li><p>Redundancy in <code>_move_snake</code>. It doesn't seem like a big deal either way. No opinion here.</p></li>\n</ol>\n\n<h3>2. Other comments on your code</h3>\n\n<ol>\n<li><p>There's a bug in <code>step</code>: you move the snake even if the game is over. Surely the snake should stop moving when it's dead?</p></li>\n<li><p>Another bug in <code>step</code>, this time in the \"eat food\" logic. You insert the head into the tail:</p>\n\n<pre><code>self.tail.insert(0, self.head)\n</code></pre>\n\n<p>but then you call <code>_move_snake</code> which does the same thing. So the snake ends up containing <em>two</em> copies of the head location.</p>\n\n<p>The usual way that \"snake\" games work is that when the snake eats some food, it does not grow a new tail segment immediately. Instead, it waits until the next time it moves and grows a new tail segment in the position where its old tail used to be. This is easily implemented by incrementing a counter each time the snake eats food:</p>\n\n<pre><code>self.growth_pending += 1\n</code></pre>\n\n<p>and then decrementing the counter instead of deleting the tail segment:</p>\n\n<pre><code>if self.growth_pending:\n self.growth_pending -= 1\nelse:\n self.tail.pop()\n</code></pre>\n\n<p>Note that these bugs would have been easy for you to spot had you actually finished writing the game and tried to run it.</p></li>\n<li><p>Inserting an item at the beginning of a list:</p>\n\n<pre><code>self.tail.insert(0, (x, y))\n</code></pre>\n\n<p>takes time proportional to the length of the list (see the <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow\">TimeComplexity page</a> on the Python wiki). It would be better to use a <a href=\"http://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow\"><code>collections.deque</code></a> and call the <a href=\"http://docs.python.org/3/library/collections.html#collections.deque.appendleft\" rel=\"nofollow\"><code>appendleft</code></a> method.</p></li>\n<li><p>This line of code:</p>\n\n<pre><code>game_field = set([(x, y) for x in range(self.width)\n for y in range(self.height)])\n</code></pre>\n\n<p>doesn't need the list comprehension, as you can pass a generator expression directly to <code>set</code>:</p>\n\n<pre><code>game_field = set((x, y) for x in range(self.width)\n for y in range(self.height))\n</code></pre>\n\n<p>This avoids constructing a list and then immediately throwing it away again.</p></li>\n<li><p>You can further simplify that line of code using <a href=\"http://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a>:</p>\n\n<pre><code>from itertools import product\ngame_field = set(product(range(self.width), range(self.height)))\n</code></pre></li>\n<li><p>In <code>_new_food_location</code> you convert <code>possible</code> into a list so that you can call <a href=\"http://docs.python.org/3/library/random.html#random.choice\" rel=\"nofollow\"><code>random.choice</code></a> on it. But if you used <a href=\"http://docs.python.org/3/library/random.html#random.sample\" rel=\"nofollow\"><code>random.sample</code></a> instead, you wouldn't have to do that.</p></li>\n<li><p>In <code>_new_food_location</code> you build a set containing every location in the game not occupied by the snake. It would be better to build this set just once per game, and keep it up to date as the snake moves.</p>\n\n<p>In detail, in <code>reset</code> you'd write something like:</p>\n\n<pre><code>self.growth_pending = 0\nself.empty = set(product(range(self.width), range(self.height)))\nself.empty.remove(self.head)\nself.empty.difference_update(self.tail)\n</code></pre>\n\n<p>(Note the use of <a href=\"http://docs.python.org/3/library/stdtypes.html#set.difference_update\" rel=\"nofollow\"><code>difference_update</code></a> to avoid having to convert <code>self.tail</code> to a set.)</p>\n\n<p>In <code>_move_snake</code> you'd write something like:</p>\n\n<pre><code>self.tail.appendleft(self.head)\nself.head = newX, newY\nself.empty.remove(self.head)\nif self.growth_pending:\n self.growth_pending -= 1\nelse:\n self.empty.add(self.tail.pop())\n</code></pre>\n\n<p>And finally, in <code>_new_food_location</code> you'd write:</p>\n\n<pre><code>new_position = random.sample(self.empty, 1)[0]\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:13:18.947",
"Id": "37981",
"ParentId": "37931",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37981",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T23:58:18.287",
"Id": "37931",
"Score": "6",
"Tags": [
"python",
"game",
"interface",
"callback"
],
"Title": "Python model for a \"snake\"-like game"
}
|
37931
|
<p>I am trying to solve a bioinformatics problems from a <a href="https://beta.stepic.org/Bioinformatics-Algorithms-2/An-Explosion-of-Hidden-Messages-4/#step-4" rel="nofollow">Stepic course</a>.</p>
<p><strong>The problem posed</strong>: find clumps of the same pattern within a longer genome.</p>
<p><strong>Motivation</strong>: Identifying 3 occurrences of the same pattern within a window of length 500 within a genome allows biologists to find the "replication origin" of a bacterial genome. This replication origin is required for the bacteria to clone itself, and it is therefore significant.</p>
<p>Using Python, I have written a solution that works effectively for small, test data sets, but which is not efficient for real-life genomes. Below I describe the method used.</p>
<p>I've used two core functions.</p>
<h3>patternOccurances</h3>
<p>This function finds all the starting locations of a short pattern in a longer string.</p>
<pre><code>def patternOccurances2(text="GATATATGCATATACTT", pattern="ATAT"):
occurances = []
position = -1
position = config.genome.find(pattern, position+1)
occurances.append(position)
while position != -1:
position = text.find(pattern, position+1)
occurances.append(position)
return occurances[:-1]
</code></pre>
<h3>frequentPatterns</h3>
<p>This second function finds all patterns of length <code>k</code> in a string that occur at least <code>t</code> times; or, if <code>t</code> is omitted, only the most frequent patterns of length <code>k</code>.</p>
<pre><code>def frequentPatterns(text="", k=2,numberOfOccurances=None):
#Frequent Words Problem: Find the frequent k-mers in a string.
# Input: A string text, and an integer k, number of occurances t
# Output: All most frequent k-mers in Text.
words = {}
frequentPatterns = []
#create a dictionary of all patterns of length k in text with their respective frequencies
for i in range(len(text)-k + 1): #iterate over the valid length of the string
a = text[i:i+k]
if a in words:
words[a] = words[a] + 1
else:
words[a] = 1
if numberOfOccurances == None: #gives only the most frequent strings of length k
largestValue=0
for k, v in words.iteritems():
if v > largestValue:
frequentPatterns = []
frequentPatterns.append(k)
largestValue = v
if v == largestValue:
frequentPatterns.append(k)
else: #gives all strings of length k that occur numberOfOccurances times
for k, v in words.iteritems():
if v >= numberOfOccurances:
frequentPatterns.append(k)
return frequentPatterns
</code></pre>
<h3>Main Code</h3>
<p>The main code calls the above functions as follows:</p>
<pre><code>#Clump Finding Problem: Find patterns forming clumps in a string.
# Input: A long string Genome, and integers k, L, and t.
# k is the length of the pattern we wish to match.
# t is the minimum number of times we wish to find this pattern in a portion of length L in the Genome.
# Output: All distinct k-mers forming (L, t)-clumps in Genome.
f = open("E-coli.txt",'r') #input from a large file, 4.2MB
genome = f.read()
k = 9
L = 500
t = 3
#find all patterns of length k in genome that occur at least t times
frequentPatterns = ex213.frequentPatterns(text=genome,k=k,numberOfOccurances=t)
#for each pattern in frequentPatterns, find the locations of the patterns in the genome
#then find if any 3 of these patterns are within distance L of each other
for pattern in frequentPatterns:
locations = ex322.patternOccurances("",pattern)
for location in range(len(locations) - 2):
if locations[location + 1] - locations[location] <= L:
if locations[location + 2] - locations[location] <= L:
print pattern #3 of the pattern are sufficiently close to each other
break
f.close()
</code></pre>
<h3>Main Code Performance</h3>
<p>Measurements show that the <code>frequentPatterns</code> call completes quickly. This call only occurs once, and therefore optimising it will not significantly improve the speed of the code.</p>
<p>However, the outer for loop takes a great deal of time to complete (in the order of several hours). In particular, the <code>patternOccurances</code> call is particularly slow. However, I am sure other inefficiencies exist in the code.</p>
<p>Other programmers have completed the same task within 40s.</p>
<ul>
<li>How can my coding be improved?</li>
<li>How can I optimise my algorithms performance?</li>
<li>Do more efficient algorithms exist?</li>
</ul>
<p>For those interested, the large dataset for which the above algorithms should efficiently work can be found <a href="https://beta.stepic.org/media/attachments/lessons/4/E-coli.txt" rel="nofollow">here</a> (4.2MB).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T03:26:53.373",
"Id": "63128",
"Score": "1",
"body": "Your `patternOccurances` function won't work properly: it doesn't check patterns beginning at the first character. And for the rest, you may want to take a look at [`Counter` from `collections`](http://docs.python.org/2/library/collections.html#collections.Counter)."
}
] |
[
{
"body": "<p>\"Occurrances\" should be spelled as \"occurrences\".</p>\n\n<p>The core of your strategy is this loop from <code>frequentPatterns()</code>:</p>\n\n<pre><code>for i in range(len(text)-k + 1): #iterate over the valid length of the string\n a = text[i:i+k]\n if a in words:\n words[a] = words[a] + 1\n else:\n words[a] = 1\n</code></pre>\n\n<p>I suggest using <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a> to keep track of the word count, as that is exactly what it is for.</p>\n\n<pre><code>words = collections.Counter([text[i:i+k] for i in range(len(text) - k + 1)])\n</code></pre>\n\n<p>Taking all those substrings might be a performance concern. Furthermore, you will have to find those substrings later in <code>patternOccurances()</code>. If <em>k</em> ≤ 16, you will likely improve performance by converting the words into numbers. Since there are four nucleobases, it should take only 2 bits to store each nucleobase. You should be able to store a 16-nucleobase string in a 32-bit number.</p>\n\n<p>Here's my attempt at it:</p>\n\n<pre><code>from array import array\nfrom collections import Counter\n\nDNA_NUCLEOBASES = 'ACTG'\n\ndef numerify(s, k):\n '''\n Summarizes consecutive k-length substrings of s as as list of numbers.\n s is a string consisting of letters from DNA_NUCLEOBASES.\n k is an integer, 1 <= k <= 16.\n '''\n TRANS = dict(map(lambda c: (c, DNA_NUCLEOBASES.index(c)), DNA_NUCLEOBASES))\n mask = 4 ** k - 1\n # Depending on k, we might need a byte, short, or long.\n array_type = '!BBBBHHHHLLLLLLLL'[k]\n result = array(array_type, [0] * (len(s) - (k - 1)))\n v = 0\n for i in range(len(s)):\n v = (v << 2 & mask) | TRANS[s[i]]\n result[i - (k - 1)] = v\n return result.tolist()\n\ndef stringify(n, k):\n '''\n Converts a number from numerify() back into a k-length string of\n DNA_NUCLEOBASES.\n '''\n result = [DNA_NUCLEOBASES[(n >> 2 * i) & 3] for i in range(k)][::-1]\n return ''.join(result)\n\ndef find_clumps(s, k):\n '''\n Lists all k-length substrings of s in descending frequency.\n Returns a list of tuples of the substring and a list of positions at which\n they occur.\n '''\n clumps = numerify(s, k)\n result = []\n for clump, occurrences in Counter(clumps).most_common():\n if occurrences <= 1:\n break\n positions = []\n i = -1\n for _ in range(occurrences):\n i = clumps.index(clump, i + 1)\n positions.append(i)\n result.append((stringify(clump, k), positions))\n return result\n\n\ns = 'CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA'\nk = 5\nfor clump, positions in find_clumps(s, k):\n print(\"%s occurs at %s\" % (clump, positions))\n</code></pre>\n\n<p>I'll leave it to you to implement the <em>L</em>-length windows.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T14:11:57.203",
"Id": "63156",
"Score": "0",
"body": "Interesting idea to use numbers to represent the pattern sequences. However, I think that the process to converting sequences to/from numbers is expensive. I've just tried your above algorithm on the [large data set](https://beta.stepic.org/media/attachments/lessons/4/E-coli.txt) and it is too long to complete efficiently (it has run for several minutes without returning any (s, k) clumps)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T04:44:01.367",
"Id": "37935",
"ParentId": "37932",
"Score": "2"
}
},
{
"body": "<p>Finding frequent occurring patterns in a string is a special case of the problem of finding all patterns that find more than a specified number of times in multiple strings. (Just set the specified number of times to your threshold for frequent and the number of strings to be searched to 1.)</p>\n\n<p>Finding all patterns that find more than a specified number of times in multiple strings is addressed <a href=\"http://bit.ly/MO7Rfd\" rel=\"nofollow\">here</a>. This link contains Python and C++ solutions of increasing complexity and speed that find all the repeated patterns that I need to find in the strings I work with. I think all these solutions can be easily adapted to your specific problem. Let me know if they can't</p>\n\n<p>I have heard that bioinformaticians use compressed suffix trees to solve this sort of problem. You may find some faster solutions by following that line of investigation. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:36:33.640",
"Id": "63138",
"Score": "1",
"body": "Link-only answers don't constitute a code review. Could you please elaborate on your answer — either provide specific advice, or at least summarize the generic advice? Alternatively, you could convert this answer into a comment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:21:20.503",
"Id": "37942",
"ParentId": "37932",
"Score": "0"
}
},
{
"body": "<h3>1. Introduction</h3>\n\n<p>This code has so many basic problems with documentation, layout, spelling, naming, and so on, that I didn't get around to looking at what it does. In a professional context we would say, \"this code is not remotely ready for review\" and send it back for you to fix!</p>\n\n<p>It's worth reading the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python style guide (PEP8)</a> and following the advice there. It's not compulsory, but it will make it easier for you to collaborate with other Python programmers and read each others' code. In particular, I'd use 4 spaces indentation, and <code>lowercase_words_with_underscores</code> for function and method names.</p>\n\n<h3>2. The function patternOccurances2</h3>\n\n<ol>\n<li><p>Your main code calls <code>patternOccurances</code> but when you define the function it's called <code>patternOccurances2</code>.</p></li>\n<li><p>There's no documentation for <code>patternOccurances2</code>. What does it do and how am I supposed to call it?</p></li>\n<li><p>This function takes default arguments <code>text=\"GATATATGCATATACTT\", pattern=\"ATAT\"</code>. These do not seem like suitable default arguments. Default arguments are normally used for common values, to save the caller having to specify them. If you want to provide test data, then write a test case separately. See below for one way to do it.</p></li>\n<li><p>This function takes its arguments in the order <code>(text, pattern)</code> but it would be better for it to take the arguments the other way round, for consistency with functions in the standard library like <a href=\"http://docs.python.org/3/library/re.html#re.search\" rel=\"nofollow noreferrer\"><code>re.search</code></a>.</p></li>\n<li><p>This function starts by calling:</p>\n\n<pre><code>position = config.genome.find(pattern, position+1)\n</code></pre>\n\n<p>What is <code>config.genome</code> and how is it relevant here? It looks as if it might be a mistake for <code>text</code>.</p></li>\n<li><p>It seems inelegant to append a <code>-1</code> to the list of occurrences, and then remove it again. It would be better to write the loop like this:</p>\n\n<pre><code>result = []\nposition = -1\nwhile True:\n position = text.find(pattern, position + 1)\n if position == -1:\n return result\n result.append(position)\n</code></pre></li>\n<li><p>Instead of returning a list, it's nearly always better in Python to <em>generate</em> the results using the <code>yield</code> instruction, explained <a href=\"https://stackoverflow.com/questions/231767/the-python-yield-keyword-explained\">here</a>. This means that you can process the results one by one without having to build up an intermediate list in memory. So I would write the function like this:</p>\n\n<pre><code>def pattern_occurrences(pattern, text):\n \"\"\"Generate the indices of the (possibly overlapping) occurrences of\n pattern in text. For example:\n\n >>> list(pattern_occurrences('ATAT', 'GATATATGCATATACTT'))\n [1, 3, 9]\n\n \"\"\"\n position = -1\n while True:\n position = text.find(pattern, position + 1)\n if position == -1:\n return\n yield position\n</code></pre>\n\n<p>Notice that the docstring includes an example test case. You can run this and check that the result is correct using the <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> module.</p></li>\n</ol>\n\n<h3>3. The function frequentPatterns</h3>\n\n<ol>\n<li><p>Something's gone wrong with the indentation in this function. A copy-paste error?</p></li>\n<li><p>The documentation says <code>Input ... number of occurances t</code>. But the actual argument is called <code>numberOfOccurances</code>, not <code>t</code>.</p></li>\n<li><p>The documentation for <code>frequentPatterns</code> says <code>Output: All most frequent k-mers in text.</code> But actually, only the k-mers that appear at least <code>t</code> times are output.</p></li>\n<li><p>There's no explanation in the documentation for the behaviour if you don't specify a value for <code>t</code>.</p></li>\n<li><p>The documentation for <code>frequentPatterns</code> is in a comment. But that means that I can't read it from the interactive interpreter:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> help(frequentPatterns)\nHelp on function frequentPatterns in module __main__:\n\nfrequentPatterns(text='', k=2, numberOfOccurances=None)\n</code></pre>\n\n<p>If you put this documentation into a docstring, like this:</p>\n\n<pre><code>def frequent_patterns(text=\"\", k=2, t=None):\n \"\"\"Return a list of the most frequent k-mers in a string.\n\n Input: A string text, an integer k, and a number of occurrences t.\n Output: All k-mers that appear at least t times in text.\n\n If t is omitted, return a list containing the k-mer that appears\n the most often (or the k-mers, if there is a tie).\n\n \"\"\"\n words = {}\n # ...\n</code></pre>\n\n<p>then you'd be able to read it from the interactive interpreter:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> help(frequent_patterns)\nHelp on function frequent_patterns in module __main__:\n\nfrequent_patterns(text='', k=2, t=None)\n Return a list of the most frequent k-mers in a string.\n\n Input: A string text, an integer k, and a number of occurrences t.\n Output: All k-mers that appear at least t times in text.\n\n If t is omitted, return a list containing the k-mer that appears\n the most often (or the k-mers, if there is a tie).\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T15:03:43.817",
"Id": "63271",
"Score": "1",
"body": "Thanks for these useful observations. Novice programmers can often miss out on including detail that would be particularly useful when showing their code to other programmers, since a novice will tend to write code that works in a way most easily understood by them.\n\nSo perhaps someone should create a PEP8-equivalent just for novice programmers, so that after learning the basics of Python they can learn how to improve the readability of their code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:00:50.410",
"Id": "37957",
"ParentId": "37932",
"Score": "5"
}
},
{
"body": "<p>Here is my version, which takes a little over 6 seconds to run in my tests. </p>\n\n<p>The main goal of this version is to avoid iterating over the same piece of text repeatedly. In more naive implementations you might start with the first 'L' window of the genome, and check all of its contents before moving on to the next 'L' size window. </p>\n\n<p>However, this window is only really changing by two characters - one is being removed from the front, and one added to the end. This means that we can keep the substring counts from the first window, decrement the counter for the first substring (as it's no longer there) and increment the counter for the new final string. This proves to be much faster that repeatedly iterating and counting.</p>\n\n<p>Further improvements might be to discard the idea of storing the L size window, in case a future analysis involves a very large window where storing an extra copy of it would be memory intensive. </p>\n\n<p>My initial version used a Counter, but this proved to be slower than a defaultdict, so I removed it. The list of relevant substrings is also more intuitively stored as a list, but the lookup of <code>... in list</code> proved to scale poorly when the size of relevant matches grew large, so that is stored as a dictionary for better performance. </p>\n\n<pre><code>#!/usr/bin/env python\n\nfrom collections import defaultdict\n\nwith open('E-coli.txt', 'r') as f:\n genome = f.read().rstrip()\n\n\nkmer = 9 # Length of the k-mer\nwindowsize = 500 # genome substring length to register clumps in\nmin_clumpsize = 3 # minimum number of repetitions of the k-mer\n\n\n# find substrings at least kmer long that occur at least min_clumpsize\n# times in a window of windowsize in genome\n\ndef get_substrings(g, k):\n \"\"\"\nTake the input genome window 'g', and produce a list of unique \nsubstrings of length 'k' contained within it. \n \"\"\"\n substrings = list()\n\n # Start from first character, split into 'k' size chunks\n # Move along one character and repeat. No sense carrying on beyond\n # a starting point of 'k' since that will be the first iteration again.\n for i in range(k):\n line = g[i:]\n substrings += [line[i:i + k]\n for i in range(0, len(line), k) if i + k <= len(line)]\n\n # Using collections.Counter increases the runtime by about 3 seconds,\n # during testing.\n results = defaultdict(int)\n for s in substrings:\n results[s] += 1\n return results\n\n\ndef find_clumps(genome, kmer, windowsize, clumpsize):\n \"\"\"\nIn a given genome, examines each windowsize section for strings of length kmer\nthat occur at least clumpsize times. \n\nInput: \ngenome: text string to search\nkmer: length of string to search for\nwindowsize: size of the genome section to consider for clumping\nclumpsize: the kmer length strings must occur at least this many times\n\nReturns: a list of the strings that clump\n \"\"\"\n window = genome[0:windowsize]\n\n # Initialise our counter, because the main algorithm can't start from\n # scratch.\n patterns = get_substrings(window, kmer)\n\n # Using a dictionary not a list because the lookups are faster once the\n # size of the object becomes large\n relevant = {p: 1 for p in patterns if patterns[p] >= clumpsize}\n\n starting_string = genome[0:kmer]\n\n for i in range(windowsize, len(genome)):\n # Move the window along one character\n window = window[1:]\n window += genome[i]\n\n # This is the only string that can decrease if we've moved one\n # character\n patterns[starting_string] -= 1\n starting_string = window[0:kmer]\n\n # This is the only string that can increase if we've moved one\n # character\n ending_string = window[-kmer:]\n patterns[ending_string] += 1\n\n # if there are enough matches of the string at the end, add it to\n # matches.\n if patterns[ending_string] >= clumpsize and ending_string not in relevant:\n relevant[ending_string] = 1\n\n return list(relevant)\n\n\nif __name__ == \"__main__\":\n clumps = find_clumps(genome, kmer, windowsize, min_clumpsize)\n print(\"Total: {}\".format(len(clumps)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-30T14:50:16.103",
"Id": "124764",
"Score": "0",
"body": "I apologise, I'm new on the site and saw other people had just submitted new code. I will explain further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-30T14:55:52.040",
"Id": "124766",
"Score": "0",
"body": "Hopefully the explanation is sufficient."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-30T14:26:27.953",
"Id": "68404",
"ParentId": "37932",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T00:54:57.180",
"Id": "37932",
"Score": "7",
"Tags": [
"python",
"performance",
"bioinformatics"
],
"Title": "Genome string clump finding problem"
}
|
37932
|
<p>Which one of these two is better?</p>
<p>This one:</p>
<pre><code>middleware.response_redirect = function(){
return function (req, res, next){
var redirect = function(){
if(req.form.redirect) return url.parse(req.form.redirect);
return {
protocol: "http",
hostname: config.domain,
pathname: "thanks",
}
}();
redirect.query = querystring.stringify({
"status": "success",
"message": req.form.message
});
return res.redirect(url.format(redirect);
}
}
</code></pre>
<p>Or this one:</p>
<pre><code>middleware.response_redirect = function(){
return function (req, res, next){
var redirect;
if(req.form.redirect){
redirect = url.parse(req.form.redirect);
}else{
redirect = {
protocol: "http",
hostname: config.domain,
pathname: "thanks",
}
}
redirect.query = querystring.stringify({
"status": "success",
"message": req.form.message
});
return res.redirect(url.format(redirect);
}
}
</code></pre>
<p>The function within function thing bothers me a little. But so does setting <code>redirect</code> in two places.</p>
|
[] |
[
{
"body": "<p>How about a ternary operator?</p>\n\n<pre><code>var redirect = req.from.redirect\n ? url.parse(req.from.redirect)\n : {\n protocol: 'http',\n hostname: config.domain,\n pathname: 'thanks'\n };\n</code></pre>\n\n<p>Looks cleaner in my opinion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T06:00:14.583",
"Id": "37937",
"ParentId": "37933",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T04:02:10.047",
"Id": "37933",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"comparative-review",
"express.js"
],
"Title": "I'm torn between conditionals and abrupt return functions"
}
|
37933
|
<p>Follow-up posted -> <a href="https://codereview.stackexchange.com/q/38016/18427">Follow up to Pay Rate Calculator</a></p>
<hr>
<p>This little bit of code is just some code that I wrote from a flowchart at the beginning of a programming and logic book that I have added some to. I tried to create it as an object.</p>
<p>I would like a review on what I am doing and if I am doing it right, and what I could do better. I want you to look at this like I am a novice to intermediate Programmer. I don't think that I learned as much as I should have while I was in school, and it probably shows.</p>
<p><strong>Main Method</strong></p>
<pre><code>public static void Main (string[] args)
{
var payCheck = new PayRateCalculator();
Console.Write ("Please provide the Employees Last Name >>");
payCheck.lastName = Console.ReadLine();
Console.Write ("How many hours has employee {0} worked? >>", payCheck.lastName);
payCheck.hours = Convert.ToInt32 (Console.ReadLine());
Console.Write ("What is employee {0}'s hourly wage? >>", payCheck.lastName);
payCheck.payrate = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine ("{0}'s Gross pay is ${1}", payCheck.lastName, payCheck.grossPay);
Console.WriteLine ("{0}'s Net pay is ${1}", payCheck.lastName, payCheck.netPay);
}
</code></pre>
<p><strong>Class</strong></p>
<pre><code>class PayRateCalculator
{
private float _payrate = 8.25f;
private float _withholdingRate = 0.20F;
public float hours { get; set; }
public float grossPay {
get {
return hours * _payrate;
}
}
public float netPay {
get {
return grossPay - (grossPay * _withholdingRate);
}
}
public float payrate {
get {
return _payrate;
}
set {
_payrate = value;
}
}
public string lastName { get; set; }
public PayRateCalculator (string lastName, float hours, float payRate)
{
this.hours = hours;
this.payrate = payrate;
this.lastName = lastName;
}
public PayRateCalculator ()
{
}
}
</code></pre>
<p>Just a simple console application. Help me to relearn coding the right way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T10:03:30.090",
"Id": "63142",
"Score": "1",
"body": "`payCheck = PayRateCalculator` should be enough to raise an eyebrow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T14:16:28.603",
"Id": "63157",
"Score": "0",
"body": "@abuzittingillifirca, it started off as one thing and turned into another. the flowchart from the book was set up for step by step, which I could have done without creating an object. that is the reason for the difference in naming. thank you for pointing that out though."
}
] |
[
{
"body": "<ol>\n<li><p>The standard naming convention for properties is <code>PascalCase</code> in C#.</p></li>\n<li><p>I try and give default \"magic constants\" a name. In this case I admit it's fairly obvious however you never really know what your code will turn into. It is also good to form habits so you wont forget these things.</p>\n\n<pre><code>private const float DefaultPayrate = 8.25f;\nprivate const float DefaultWithholdingRate = 0.2f;\n\nprivate float _Payrate = DefaultPayRate;\nprivate float _WithholdingRate = DefaultWithholdingRate;\n</code></pre></li>\n<li><p>You should use <code>decimal</code> as you are operating with currencies and pay rates. Floating point rounding can unexpectedly bite you.</p></li>\n<li><p>There is no way to change the <code>_withholdingRate</code>.</p></li>\n<li><p>As the <code>PayRateCalculator</code> only really makes sense once you have set the name, hours and payrate I'd consider removing the default constructor. Then you'd have to change the calling code to temporarily store these things before you can instantiate an instance. I'd also consider changing most of those properties to a <code>private set</code>. This way you can avoid getting a <code>PayRateCalculator</code> into an inconsistent state.</p>\n\n<p>Another programmer cannot easily figure out from just the class interface (ctor and public methods and properties) which he needs to populate in order to make sensible use of it. Taking the choice away (forcing to pass in the important properties through the ctor) makes that obvious.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T09:11:53.693",
"Id": "37947",
"ParentId": "37939",
"Score": "6"
}
},
{
"body": "<h1>From a design perspective</h1>\n\n<p>A domain consists of data and services and entities.\nOur minds should be clear where each class belongs in the above categories.</p>\n\n<h2>Data Objects</h2>\n\n<p>See:</p>\n\n<pre><code>var payCheck = ....\npayCheck.hours = someVal; // what?\npayCheck.hours = someOtherVal; // really?\n</code></pre>\n\n<p>This doesn't make sense because we know that IRL paychecks represent a fact: e.g. \"John Doe was paid $100.\" They do not change <strong>after the fact</strong>. This is true for any print documents: receipts, tickets, etc.</p>\n\n<p>Due to the fact that they are immutable, once they are created (i.e. composed) how did their components came to be is irrelevant. A data object should not have any creation logic, let alone the creation logic of it components. c.f. <code>netPay</code>, <code>grossPay</code> above.</p>\n\n<h2>Service Objects</h2>\n\n<p>Service objects are purely or heavily behavior focused components. Complementarily they have little state. When your use case is \"do X to Y\", X is <em>prior</em> to Y. When we try to \"Calculate payment amount for some work\". It is implied that there is a calculation method independent of the amount of work(DUH). More concisely: Service Objects [are|are like] a collection of functions. Enough philosophizing.</p>\n\n<p>Instead of :</p>\n\n<pre><code>var calculator = ....\n\ncalculator.hours = x;\nuse(calculator.grossPay);\n\ncalculator.hours = y;\nuse(calculator.grossPay);\n</code></pre>\n\n<p>We should see:</p>\n\n<pre><code>var calculator = ....\n\nuse(calculator.grossPay(x));\n\nuse(calculator.grossPay(y));\n</code></pre>\n\n<h2>Dividing <code>PayRateCalculator</code></h2>\n\n<p>Dividing <code>PayRateCalculator</code> along this line we get:</p>\n\n<pre><code>class PayRateCalculator\n{\n private decimal _withholdingRate;\n\n public PayRateCalculator (decimal withHoldingRate)\n {\n this._withholdingRate = withHoldingRate;\n }\n\n public PayCheck CreatePayCheck(string lastName, decimal hours, decimal payRate) {\n decimal grossPay = hours * payRate;\n decimal netPay = grossPay - (grossPay * _withholdingRate);\n return new PayCheck(lastName, netPay, grossPay);\n }\n}\n\nclass PayCheck {\n public decimal GrossPay {get; private set;}\n public decimal NetPay {get; private set;}\n public string LastName {get; private set;}\n\n public PayCheck(string lastName, decimal netPay, decimal grossPay) {\n this.LastName = lastName;\n this.GrossPay = grossPay;\n this.NetPay = netPay;\n }\n}\n</code></pre>\n\n<h2>Remaining problems</h2>\n\n<p>We observe that <code>PayRateCalculator</code> do not want to do anything with <code>lastName</code>. IRL too, the effect of your last name on your paycheck usually is already reflected in the pay rate.\nSimilarly, we can observe that any addition of more information to Pay Check would result in more inane modifications to <code>PayRateCalculator</code>.</p>\n\n<p>Names also still do not fit: Service class is called <code>PayRateCalculator</code> but the service method is called <code>CreatePaycheck</code>. </p>\n\n<p>These could be alleviated by further separation of concerns. Though it might seem too much for this small problem.</p>\n\n<pre><code>class Payment \n{\n decimal Gross;\n decimal Net;\n}\n\nclass PaymentCalculator\n{\n decimal _withholdingRate;\n Payment CalculatePayment(decimal hours, decimal payRate);\n}\n\nclass PayCheck \n{\n string LastName;\n Payment Payment;\n}\n\nclass PayCheckFactory {\n PaymentCalculator paymentCalculator;\n PayCheck CreatePayCheck(string lastName, decimal hours, decimal payRate);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T14:22:07.740",
"Id": "63159",
"Score": "0",
"body": "thank you for that insight, almost all of this completely makes sense to me. I shouldn't perform function operations inside of properties they should be functions, is the biggest thing that I took from this. and in the beginnning is what I meant to do, but I simplified and did it wrong as you pointed out, thank you again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T12:35:10.913",
"Id": "37956",
"ParentId": "37939",
"Score": "4"
}
},
{
"body": "<p>As a few people have pointed out, there is actually nothing really wrong with this code.</p>\n\n<p>I mean, there needs to be some naming standardization, most notably any public property should be capital.</p>\n\n<p>I would also advise a backing field for each property making the constructor a bit cleaner:</p>\n\n<pre><code>_hours = hours;\n_payrate = payrate;\n_lastName = lastName;\n</code></pre>\n\n<p>That being said from a design point of view, it is best to mirror your objects to real world objects.</p>\n\n<p>Is a <code>PayRateCalculator</code> actually a <code>PayCheck</code>? Would it not make more sense to have a paycheck of some kind, once you have your details assigned you can return the paycheck as a separate thing?</p>\n\n<p>The means with which you generate the paycheck should stand alone from the paycheck itself,\nallowing the possibility in future of having multiple calculation methods or doing something interesting with the paycheck object.</p>\n\n<p>Although again, these are just design considerations as your application scales.</p>\n\n<p>There is nothing inherently wrong with your code, which is well-written, decently-named and functional.</p>\n\n<p>Well done.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:56:03.523",
"Id": "37964",
"ParentId": "37939",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "37964",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T06:53:52.293",
"Id": "37939",
"Score": "8",
"Tags": [
"c#",
"beginner",
"console"
],
"Title": "Simple pay rate calculator"
}
|
37939
|
<p>I want to combine elements in different lists.
For example, here are 3 lists.</p>
<pre><code>list_a : [ 1,2,3 ]
list_b : [ 4,5,6 ]
list_c : [ 7,8 ]
</code></pre>
<p>Selecting elements from <code>list_b</code> and <code>list_c</code> is mutually exclusive. When including an element from <code>list_b</code>, I'd like to also include an element from <code>list_bb</code>; when including an element from <code>list_c</code>, I'd like to also include an element from <code>list_cc</code>.</p>
<pre><code>list_bb : [ 14,15,16 ]
list_cc : [ 17,18 ]
</code></pre>
<p>I wrote this code:</p>
<pre><code>global sum_list=[]
for a in list_a:
for b in list_b:
for bb in list_bb:
sum_list.append([a,b,bb])
for a in list_a:
for c in list_c:
for cc in list_cc:
sum_list.append([a,c,cc])
</code></pre>
<p>Is there any better way to get the same result?</p>
|
[] |
[
{
"body": "<p>The <code>itertools</code> library has a function called <a href=\"http://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>product</code></a>. You can rewrite your snippet as:</p>\n\n<pre><code>global sum_list=itertools.product(list_a, list_b, list_bb) + itertools.product(list_a, list_c, list_cc)\n</code></pre>\n\n<p>If you don't want to use <code>itertools</code> (e.g. because you're stuck on python 2.4), you can also use a list comprehension:</p>\n\n<pre><code>global sum_list=[]\nsum_list.extend([a,b,bb] for a in list_a for b in list_b for bb in list_bb)\nsum_list.extend([a,c,cc] for a in list_a for c in list_c for cc in list_cc)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:51:19.997",
"Id": "37945",
"ParentId": "37941",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T07:36:31.170",
"Id": "37941",
"Score": "2",
"Tags": [
"python",
"combinatorics",
"python-2.x"
],
"Title": "Produce product of lists"
}
|
37941
|
<p>I am constructing a binary tree. Let me know if this is a right way to do it. If not please tell me how to?? I could not find a proper link where constructing a general binary tree has been coded. Everywhere BST is coded.</p>
<pre><code> 3
/ \
1 4
/ \
2 5
</code></pre>
<p>This is the binary tree which i want to make.I should be able to do all the tree traversals.Simple stuff.</p>
<pre><code>public class Binarytreenode
{
public Binarytreenode left;
public Binarytreenode right;
public int data;
public Binarytreenode(int data)
{
this.data=data;
}
public void printNode()
{
System.out.println(data);
}
public static void main(String ar[])
{
Binarytreenode root = new Binarytreenode(3);
Binarytreenode n1 = new Binarytreenode(1);
Binarytreenode n2 = new Binarytreenode(4);
Binarytreenode n3 = new Binarytreenode(2);
Binarytreenode n4 = new Binarytreenode(5);
root.left = n1;
root.right = n2;
root.right.left = n3;
root.right.right = n4;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code does represent the tree that you drew. However, the code doesn't implement the logic for determining <em>where</em> to place nodes within a binary search tree; instead, you hard-coded that logic in your <code>main()</code> function. A useful implementation of <code>Binarytreenode</code> would let you write something like</p>\n\n<pre><code>BinaryTree t = new BinaryTree();\nt.add(3);\nt.add(1);\nt.add(4);\nt.add(2);\nt.add(5);\n</code></pre>\n\n<p>… to produce the same tree structure.</p>\n\n<hr>\n\n<p>You want to design the code as a class that maintains the tree in a self-consistent state, supporting operations such as <code>.add(int value)</code> and <code>.find(int value)</code>. The member fields <code>left</code>, <code>right</code>, and <code>data</code> should generally not be have <code>public</code> access, which would let other code modify the tree in an invalid way. It could be acceptable, however, to let <code>data</code> remain <code>public</code> if you also mark it as <code>final</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T09:18:32.190",
"Id": "63141",
"Score": "0",
"body": "I understand your point but I dont want a BST. I just want a binary tree , which does not have a logic for adding nodes. How to do that??"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:55:56.143",
"Id": "37946",
"ParentId": "37944",
"Score": "1"
}
},
{
"body": "<p>If you just want to be able to construct arbitrary trees, you could introduce some convenience functions:</p>\n\n<pre><code>public static Binarytreenode n(int datum) {\n return new Binarytreenode(datum);\n}\n\npublic static Binarytreenode n(Binarytreenode left, int datum, Binarytreenode right) {\n Binarytreenode root = n(datum);\n root.left = left;\n root.right = right;\n return root;\n}\n\npublic static void main(String[] args) {\n Binarytreenode root = n(n(1), 3, n(n(2), 4, n(5)));\n}\n</code></pre>\n\n<p>With the right imagination, you can visualize the tree in <code>main()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T09:33:30.910",
"Id": "37948",
"ParentId": "37944",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T08:29:08.277",
"Id": "37944",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"tree"
],
"Title": "Constructing a binary tree in java"
}
|
37944
|
<p>Single Instruction, Multiple Data describes CPU instructions that process many operands in parallel. Examples of SIMD instruction sets include AltiVec on PowerPC, SSE and MMX on Intel x86, and 3DNow! on AMD.</p>
<p>Related tag: <a href="/questions/tagged/gpgpu" class="post-tag" title="show questions tagged 'gpgpu'" rel="tag">gpgpu</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T10:02:44.490",
"Id": "37950",
"Score": "0",
"Tags": null,
"Title": null
}
|
37950
|
Single Instruction, Multiple Data describes CPU instructions that process many operands in parallel.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T10:02:44.490",
"Id": "37951",
"Score": "0",
"Tags": null,
"Title": null
}
|
37951
|
<p>Given the test code:</p>
<pre><code>import struct
buf = bytearray(b'\xef\xf8\t\xf2')
number = struct.unpack("<I", buf)[0]
</code></pre>
<p>How do I cleanly make it work both under Python 2.6 and Python 3.3? The problem is that struct.unpack in Python 2.6 seems to expect a str object (not unicode), so the only way I managed to come up with in order to get it working on both versions is:</p>
<pre><code>buf_raw = bytearray(b'\xef\xf8\t\xf2')
buf_decoded = buf_raw.decode('latin1')
buf_encoded = buf_decoded.encode('latin1')
number = struct.unpack("<I", buf_encoded)[0]
</code></pre>
<p>...though I'm abusing the fact that <code>latin1</code> translates every 0-255 ASCII character to itself. What's the better way?</p>
|
[] |
[
{
"body": "<p>Why not just call <code>bytes</code>?</p>\n\n<pre><code>number = struct.unpack('<I', bytes(buf))[0]\n</code></pre>\n\n<p>In Python 2.6:</p>\n\n<pre><code>Python 2.6.8 (unknown, Aug 13 2012, 22:19:05) \n...\n>>> import struct\n>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))\n(1145258561,)\n</code></pre>\n\n<p>In Python 3.3:</p>\n\n<pre><code>Python 3.3.2 (default, May 21 2013, 11:50:47) \n...\n>>> import struct\n>>> struct.unpack('<I', bytes(bytearray(b'ABCD')))\n(1145258561,)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T11:04:24.143",
"Id": "406537",
"Score": "0",
"body": "How to handle it while double back slash issue.. For example b'\\\\xef\\\\xf8\\\\t\\\\xf2'.."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:23:11.887",
"Id": "37961",
"ParentId": "37959",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37961",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:17:40.143",
"Id": "37959",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "struct.unpack on a bytearray that works under Python 2.6.6, 2.7 and 3.3?"
}
|
37959
|
<p>I've been writing a simple code just for fun:</p>
<p>This is a simple WinForms application with which you can measure your typing speed. There are three controls on it, doing the following:</p>
<ul>
<li><code>rtbResults</code> - The one where you need to be as quick as possible.</li>
<li><code>textBox1</code> - The one where you submit the reference text.</li>
<li><code>tbBestTime</code> - The one storing the best time of a "contestant".</li>
</ul>
<p>Fields:</p>
<pre><code>Stopwatch sw = new Stopwatch();
long bestTime = long.MaxValue;
</code></pre>
<p>One handler:</p>
<pre><code>private void rtbResults_TextChanged(object sender, EventArgs e)
{
if (rtbResults.Text.Length == 1)
{
sw.Restart();
}
else
{
if (rtbResults.Text == textBox1.Text)
{
sw.Stop();
if (sw.ElapsedMilliseconds < bestTime)
{
bestTime = sw.ElapsedMilliseconds;
tbBestTime.Text = (bestTime / 1000.0).ToString();
}
MessageBox.Show("Your time: " + sw.ElapsedMilliseconds / 1000.0 + "s.");
sw = null;
rtbResults.Text = "";
}
}
}
</code></pre>
<p>Another handler:</p>
<pre><code>private void textBox1_TextChanged(object sender, EventArgs e)
{
bestTime = long.MaxValue;
tbBestTime.Text = bestTime.ToString();
}
</code></pre>
<p>Now I'm looking for techniques to optimize the performance to get more precise results.
The point is not the memory consumption, but the length of the source code and the performance, and of course it must result the same as it does now (I mean the mentioned code).</p>
<p>I would like you to consider the following issues:</p>
<p>Is the...</p>
<ul>
<li>Stopwatch</li>
<li>TextChanged event</li>
<li>type long</li>
<li>if/else (instead of if/return)</li>
</ul>
<p>... the best way to do this?</p>
|
[] |
[
{
"body": "<p>Your code seems to me to be as efficient as reasonable for the application you are writing...</p>\n\n<p>... but what you want/intend to do with it is unreasonable.... but first:</p>\n\n<ul>\n<li><p>The method resetting the time is not very practical</p>\n\n<pre><code>private void textBox1_TextChanged(object sender, EventArgs e)\n{\n bestTime = long.MaxValue;\n tbBestTime.Text = bestTime.ToString();\n}\n</code></pre>\n\n<p>This method is setting the text to a value that the typical user will have no frame of reference for.... why is that 'big' number meaningful. Why not just set the <code>tbBestTime.Text</code> to be 'None yet' or something? This is especially significant since all other times the <code>tbBestTime</code> is set, you set it to a floating-point <code>time/1000.0</code> value.</p></li>\n<li><p>In your messageBox you do a simple <code>/1000.0</code> for your time display. This is not going to always be 'pretty' since not all floating point values have a neat representation in binary. You should be using a Number formatter to ensure that the presentation of the value is consistent.... consider <a href=\"http://msdn.microsoft.com/en-us/library/0c899ak8%28v=vs.110%29.aspx\">Custom Numeric Format Strings</a>.</p></li>\n</ul>\n\n<p>Finally, lets talk about accuracy and precision.... </p>\n\n<ul>\n<li>precision is reporting values to a large number of significant figures. In your case, reporting the time to (an intended) millisecond precision seems like a good idea, but, is that accurate?</li>\n</ul>\n\n<p>Your intention with this question is to improve the accuracy of the results by reducing the overhead of the code when compared to the typing.</p>\n\n<p>Unfortunately there is so much happening between your code and the keyboard that any attempt to increase the code performance will be outweighed by the simple operations happening on the system.... The following are things that may/will affect the accuracy of your timing:</p>\n\n<ol>\n<li><a href=\"http://en.wikipedia.org/wiki/Keyboard_technology#Debouncing\">Key debouncing</a></li>\n<li>Interrupt handling</li>\n<li>OS event notification</li>\n<li>OS Thread scheduling</li>\n<li>Clock granularity</li>\n<li>TextBox listener notification</li>\n</ol>\n\n<p>I would wager that each of these will be significantly more time than the per-cycle cost of your code.</p>\n\n<p>Optimizing your code will make no difference to the accuracy of your timing, and, as it is, your reported precision is probably far more than the actual accuracy. In fact, I would suggest that anything within 1/10th of a second (instead of 1/1000th) is a 'tie'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:01:09.240",
"Id": "63177",
"Score": "0",
"body": "Thank you rolfl for your detailed answer. It is very helpful for me!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:46:44.543",
"Id": "37963",
"ParentId": "37960",
"Score": "6"
}
},
{
"body": "<p>One way to get around system events interfering with the recording of the elapsed time, is to take a snapshot of the current time(<code>DateTime.Now</code>) when the typing starts and another when the typed text equals the source text. A timespan of the difference between the two will give you reasonable accuracy on the elapsed time. This way too, your output can easily be formatted as time instead of just a number.</p>\n\n<p>Another thing to consider is typing tests usually use words per minute for grading rather than total time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:01:36.603",
"Id": "63178",
"Score": "0",
"body": "This is a good idea I will implement into my program. Thank you very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:15:43.000",
"Id": "37977",
"ParentId": "37960",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37963",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:22:16.997",
"Id": "37960",
"Score": "8",
"Tags": [
"c#",
"performance",
"game"
],
"Title": "WinForms typing speed game"
}
|
37960
|
<p>As a student of C# right now, I am trying my best to get a grasp on many of the systems being taught. I just completed Week 1 of a C# 102 class and the class was assigned a bit of homework. I am curious, from a beginners point of view, how you might restructure this code to make it more readable and understandable.</p>
<p>For context, here is a word for word description of what the homework was supposed to be.</p>
<blockquote>
<p>Create an abstract Pet class that has abstract functionality (at least
3 methods). It must have a "string Name" read-only (he didnt mean
readonly keyword) that is filled by a parameter to the constructor. At
least one of the methods must take in parameters, and at least one of
the methods must return a value instead of printing things to the
console.</p>
<p>Create four implementations of the Pet class that all appropriately
implement the different methods.</p>
<p>Allow the user to enter 0 to many pets (can be any type) and store
them into a List object</p>
<p>After the user is done entering in pets allow the user to:</p>
<p>A: select a pet</p>
<p>B: perform an operation</p>
<p>C: allow the user to repeat everything</p>
</blockquote>
<p>Thanks for your time. And if you do find yourself answering, please keep in mind, we have not gone over Interfaces yet. That is the next class. The things we learned in this class had mostly to do with virtual, override, abstract members and classes.</p>
<pre><code>using System;
using System.Collections.Generic;
namespace Pet_Application
{
public enum PetMood
{
Furious,
Upset,
Bored,
Content,
Happy
};
public enum HungerLevel
{
Starving,
Hungry,
Content,
Full
}
public abstract class Pet
{
public string Name { get; private set; }
public string Breed { get; private set; }
//Happiness relates to playing with the pet
public PetMood Mood { get; private set; }
//Pet hunger level
public HungerLevel Hunger { get; private set; }
//Has the pet been vaccinated
public bool IsVaccinated { get; private set; }
//The pet class constructor
public Pet(string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated)
{
Name = name;
Breed = breed;
Mood = mood;
Hunger = hunger;
IsVaccinated = isVaccinated;
}
public void GivePetShot()
{
IsVaccinated = true;
}
public abstract PetMood PlayWithPet();
public abstract PetMood PunishPet();
public abstract HungerLevel FeedPet();
public abstract HungerLevel StarvePet();
public void UpdatePet(HungerLevel hunger)
{
if (hunger != Hunger)
{
Hunger = hunger;
}
}
public void UpdatePet(PetMood mood)
{
if (mood != Mood)
{
Mood = mood;
}
}
public void DisplayPetInformation()
{
Console.WriteLine("\n\nName: {0}\n" +
"Breed: {1}\n" +
"Mood: {2}\n" +
"Hunger Status: {3}\n" +
"Is Pet Vaccinated: {4}\n",
Name, Breed, Mood, Hunger, IsVaccinated);
}
}
public class Cat : Pet
{
private string _name;
private string _breed;
private PetMood _mood;
private HungerLevel _hunger;
private bool _isVaccinated;
public Cat(string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated) :
base(name, breed, mood, hunger, isVaccinated)
{
_name = name;
_breed = breed;
_mood = mood;
_hunger = hunger;
_isVaccinated = isVaccinated;
}
public override PetMood PlayWithPet()
{
if ((int)_mood < 4)
{
Console.WriteLine("You gave the cat a ball!");
return _mood += 1;
}
Console.WriteLine("You gave the cat a ball!");
return _mood;
}
public override PetMood PunishPet()
{
if ((int)_mood > 0)
{
Console.WriteLine("You slapped that kitty!");
return _mood -= 1;
}
Console.WriteLine("You slapped that kitty!");
return _mood;
}
public override HungerLevel FeedPet()
{
if ((int)_hunger < 3)
{
Console.WriteLine("You fed the cat!");
_hunger += 1;
return _hunger;
}
Console.WriteLine("You failed to feed the cat!");
return _hunger;
}
public override HungerLevel StarvePet()
{
if ((int)_hunger > 0)
{
Console.WriteLine("You starved the cat!");
_hunger -= 1;
return _hunger;
}
Console.WriteLine("You starved the cat!");
return _hunger;
}
}
public class Dog : Pet
{
private string _name;
private string _breed;
private PetMood _mood;
private HungerLevel _hunger;
private bool _isVaccinated;
public Dog(string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated) :
base(name, breed, mood, hunger, isVaccinated)
{
_name = name;
_breed = breed;
_mood = mood;
_hunger = hunger;
_isVaccinated = isVaccinated;
}
public override PetMood PlayWithPet()
{
if ((int)_mood < 4)
{
Console.WriteLine("You threw a frisby!");
return _mood += 1;
}
return _mood;
}
public override PetMood PunishPet()
{
if ((int)_mood > 0)
{
Console.WriteLine("You scolded to dog!");
return _mood -= 1;
}
return _mood;
}
public override HungerLevel FeedPet()
{
if ((int)_hunger < 3)
{
Console.WriteLine("You fed the dog!");
_hunger += 1;
return _hunger;
}
Console.WriteLine("You failed to feed the dog!");
return _hunger;
}
public override HungerLevel StarvePet()
{
if ((int)_hunger > 0)
{
Console.WriteLine("You starved the dog!");
_hunger -= 1;
return _hunger;
}
Console.WriteLine("You starved the dog!");
return _hunger;
}
}
public class Shark : Pet
{
private string _name;
private string _breed;
private PetMood _mood;
private HungerLevel _hunger;
private bool _isVaccinated;
public Shark(string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated) :
base(name, breed, mood, hunger, isVaccinated)
{
_name = name;
_breed = breed;
_mood = mood;
_hunger = hunger;
_isVaccinated = isVaccinated;
}
public override PetMood PlayWithPet()
{
if ((int)_mood < 4)
{
Console.WriteLine("You swam with! {0}", _name);
return _mood += 1;
}
return _mood;
}
public override PetMood PunishPet()
{
if ((int)_mood > 0)
{
Console.WriteLine("You hit your shark on the nose!");
return _mood -= 1;
}
return _mood;
}
public override HungerLevel FeedPet()
{
if ((int)_hunger < 3)
{
Console.WriteLine("You fed the shark!");
_hunger += 1;
return _hunger;
}
Console.WriteLine("You failed to feed the shark!");
return _hunger;
}
public override HungerLevel StarvePet()
{
if ((int)_hunger > 0)
{
Console.WriteLine("You starved the shark!");
_hunger -= 1;
return _hunger;
}
Console.WriteLine("You starved the shark!");
return _hunger;
}
}
public class Bird : Pet
{
private string _name;
private string _breed;
private PetMood _mood;
private HungerLevel _hunger;
private bool _isVaccinated;
public Bird(string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated) :
base(name, breed, mood, hunger, isVaccinated)
{
_name = name;
_breed = breed;
_mood = mood;
_hunger = hunger;
_isVaccinated = isVaccinated;
}
public override PetMood PlayWithPet()
{
if ((int)_mood < 4)
{
Console.WriteLine("You petted the bird!");
return _mood += 1;
}
return _mood;
}
public override PetMood PunishPet()
{
if ((int)_mood > 0)
{
Console.WriteLine("You clipped the birds wings!");
return _mood -= 1;
}
return _mood;
}
public override HungerLevel FeedPet()
{
if ((int)_hunger < 3)
{
Console.WriteLine("You fed the bird!");
_hunger += 1;
return _hunger;
}
Console.WriteLine("You failed to feed the bird!");
return _hunger;
}
public override HungerLevel StarvePet()
{
if ((int)_hunger > 0)
{
Console.WriteLine("You starved the bird!");
_hunger -= 1;
return _hunger;
}
Console.WriteLine("You starved the bird!");
return _hunger;
}
}
public class PetDataHandler
{
private List<Pet> pets = new List<Pet>();
public void AddPet(Pet pet)
{
pets.Add(pet);
}
public void RemovePet(int i)
{
pets.RemoveAt(i);
}
public int PetCount()
{
return pets.Count;
}
public void Feed(int index)
{
pets[index].UpdatePet(pets[index].FeedPet());
}
public void Starve(int index)
{
pets[index].UpdatePet(pets[index].StarvePet());
}
public void PlayWith(int index)
{
pets[index].UpdatePet(pets[index].PlayWithPet());
}
public void Punish(int index)
{
pets[index].UpdatePet(pets[index].PunishPet());
}
public void GiveShot(int index)
{
pets[index].GivePetShot();
}
public void ShowData(int index)
{
pets[index].DisplayPetInformation();
}
//Creates an indexer for the pets list
public string this[int i]
{
get { return pets[i].Name; }
}
}
public class Menu
{
Input input = new Input();
PetDataHandler petList = new PetDataHandler();
public void DisplayMainMenu()
{
DisplayTitle();
Console.WriteLine("[1] Add a pet\n" +
"[2] Remove a pet\n" +
"[3] Inspect a pet\n" +
"[4] Quit application\n");
MenuChoice(input.GetChoice("Enter choice"));
}
public void DisplayPetTypeMenu()
{
DisplayTitle();
Console.WriteLine("[1] Cat\n" +
"[2] Dog\n" +
"[3] Shark\n" +
"[4] Bird\n" +
"[5] Exit\n");
PetTypeChoice(input.GetChoice("Enter choice"));
}
public void DisplayPetActionMenu(int petIndex)
{
Console.WriteLine("[1] Feed Pet\n" +
"[2] Starve Pet\n" +
"[3] Play With Pet\n" +
"[4] Punish Pet\n" +
"[5] Vaccinate Pet\n" +
"[6] Main Menu");
PetActionChoice(input.GetChoice("Enter choice"), petIndex);
}
public void DisplayPetRemovalMenu()
{
DisplayTitle();
for (int i = 0; i < petList.PetCount(); i++)
{
Console.WriteLine("[{0}]{1}", (i + 1), petList[i]);
}
int choice = input.GetChoice("Enter choice");
if (choice > 0 && choice <= petList.PetCount())
{
petList.RemovePet(choice - 1);
}
DisplayMainMenu();
}
public void DisplayPetInspectionMenu()
{
DisplayTitle();
for (int i = 0; i < petList.PetCount(); i++)
{
Console.WriteLine("[{0}]{1}", (i + 1), petList[i]);
}
int choice = input.GetChoice("Enter number for pet");
if (choice > 0 && choice <= petList.PetCount())
{
petList.ShowData(choice - 1);
}
DisplayPetActionMenu(choice - 1);
Console.ReadKey(true);
DisplayMainMenu();
}
private void DisplayTitle()
{
Console.Clear();
Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n" +
" Pet Application 1.0\n" +
"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
}
public void MenuChoice(int choice)
{
switch (choice)
{
case 1:
DisplayPetTypeMenu();
PetTypeChoice(input.GetChoice("Enter choice"));
break;
case 2:
DisplayPetRemovalMenu();
break;
case 3:
DisplayPetInspectionMenu();
break;
case 4:
Environment.Exit(0);
break;
default:
Console.Write("\n\nNot a valid selection. Press any key to return");
Console.ReadKey(true);
DisplayMainMenu();
break;
}
}
public void PetTypeChoice(int choice)
{
switch (choice)
{
case 1:
petList.AddPet(new Cat(input.GetString("\n\nName"), input.GetString("Breed"), PetMood.Content, HungerLevel.Content, false));
DisplayMainMenu();
break;
case 2:
petList.AddPet(new Dog(input.GetString("\n\nName"), input.GetString("Breed"), PetMood.Content, HungerLevel.Content, false));
DisplayMainMenu();
break;
case 3:
petList.AddPet(new Shark(input.GetString("\n\nName"), input.GetString("Breed"), PetMood.Content, HungerLevel.Content, false));
DisplayMainMenu();
break;
case 4:
petList.AddPet(new Bird(input.GetString("\n\nName"), input.GetString("Breed"), PetMood.Content, HungerLevel.Content, false));
DisplayMainMenu();
break;
case 5:
DisplayMainMenu();
break;
default:
Console.Write("\n\nNot a valid selection. Press any key to return>");
Console.ReadKey(true);
DisplayPetTypeMenu();
break;
}
}
public void PetActionChoice(int choice, int petIndex)
{
switch (choice)
{
case 1:
petList.Feed(petIndex);
DisplayPetInspectionMenu();
break;
case 2:
petList.Starve(petIndex);
DisplayPetInspectionMenu();
break;
case 3:
petList.PlayWith(petIndex);
DisplayPetInspectionMenu();
break;
case 4:
petList.Punish(petIndex);
DisplayPetInspectionMenu();
break;
case 5:
petList.GiveShot(petIndex);
DisplayPetInspectionMenu();
break;
case 6:
DisplayMainMenu();
break;
default:
Console.Write("\n\nNot a valid selection. Press any key to return>");
Console.ReadKey(true);
DisplayPetTypeMenu();
break;
}
}
}
public class Input
{
public string GetString(string prompt)
{
Console.Write("{0}> ", prompt);
return Console.ReadLine();
}
public int GetInt(string prompt)
{
Console.Write("{0}> ", prompt);
return int.Parse(Console.ReadLine());
}
public int GetChoice(string prompt)
{
Console.Write("{0}> ", prompt);
return int.Parse(Console.ReadKey().KeyChar.ToString());
}
}
class Program
{
static void Main(string[] args)
{
Menu menu = new Menu();
menu.DisplayMainMenu();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A huge amount of that code is 'garbage', afraid to say.</p>\n\n<p>You already have all the basic pet data stored in the <code>Pet</code> class... so there is no need to duplicate it all in each pet type class (Dog/Cat, etc.).</p>\n\n<p>For example, your <code>Cat</code> class should remove all the duplication in then simply be:</p>\n\n<pre><code>public class Cat : Pet\n{\n public Cat(string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated) : \n base(name, breed, mood, hunger, isVaccinated)\n {\n // base constructor takes care of everything.\n }\n\n ......\n\n}\n</code></pre>\n\n<p>Then, in your other methods you should reference the 'public' base variables <code>Name</code> instead of <code>_name</code>, etc.</p>\n\n<p>Finally, you should add values to the <code>Pet</code> class that indicate thresholds for things like <code>mood</code> and <code>hunger</code>. All the currently 'abstract' methods on the <code>Pet</code> should instead be full methods, but should be parameterized. For example, the method on <code>Dog</code>:</p>\n\n<pre><code> public override PetMood PlayWithPet()\n {\n if ((int)_mood < 4)\n {\n Console.WriteLine(\"You threw a frisby!\");\n return _mood += 1;\n }\n return _mood;\n }\n</code></pre>\n\n<p>Should instead be on <code>Pet</code>, and would look like:</p>\n\n<pre><code> public PetMood PlayWithPet()\n {\n if ((int)Mood < MoodThreshold)\n {\n Console.WriteLine(PlayMessage);\n return Mood += 1;\n }\n return Mood;\n }\n</code></pre>\n\n<p>Then, when you construct <code>Dog</code> you should also add all the thresholds and messages that are needed in the <code>Pet</code> class.</p>\n\n<p>By doing this, the actual implementations ( <code>Dog</code>, <code>Cat</code>, etc.) become simple classes with just a constructor and no methods at all. The <code>Pet</code> Base class does all the heavy-lifting, and the code is in one place only.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:46:46.393",
"Id": "63184",
"Score": "0",
"body": "I definitely see where you are coming from, but if I'm not mistaken, your solution appears to not meet the parameters of what the homework was designed to be. Three of the methods in the base class Pet had to be abstract so that you could define the functionality. The idea, even if it is more complicated then it needs to be, is to just get us to understand how things like abstract, override and virtual work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:49:36.980",
"Id": "63186",
"Score": "2",
"body": "In which case, have abstract methods that return: getMoodThreshold(), getHungryThreshold(), getFeedMessage(), etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T16:14:45.843",
"Id": "37967",
"ParentId": "37962",
"Score": "10"
}
},
{
"body": "<p>There is a lot of repetition here; although @rolfl already explained that very well.</p>\n\n<p>Aside from moving all of the base variables into the Pet class I would add one more piece of advice: Writing code is like writing a book. Try to make it read like one. </p>\n\n<p>For example:</p>\n\n<pre><code>public override PetMood PlayWithPet()\n{\n if (inABadMood)\n {\n Console.WriteLine(\"You threw a frisby!\");\n IncreaseMood();\n }\n return Mood;\n}\n</code></pre>\n\n<p>These are simple to implement and are nice and easy to read. Once you go over Interfaces there will be a lot more power to this but right now it improves readability.</p>\n\n<p>Those extra parts can be made like:</p>\n\n<pre><code>protected int _goodMoodAmount = 4;\nprotected int _badMoodAmount = 0; \n\npublic Boolean InABadMood\n{\n get\n {\n return (int)_mood > _goodMoodAmount;\n }\n}\n</code></pre>\n\n<p>Now, if this was someone else's code and you were trying to figure out what it was doing, which would you prefer? Because that is the situation your lecturer will be in!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T16:40:25.393",
"Id": "37969",
"ParentId": "37962",
"Score": "8"
}
},
{
"body": "<p>Another thing to consider. Instead of sending the output of your methods directly to the console, make them return a string. This way a person using your class can output it to a console or a form or a webpage whatever.</p>\n\n<p>You might want to consider having the menu display and the switch block, that processes the input, in the same method. If you decide to change a menu item all your code for that is in one place.</p>\n\n<p>If you want the ability to use a foreach loop with your petlist you'll have to implement an enumerator as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:49:23.763",
"Id": "63185",
"Score": "0",
"body": "Good points. Haven't come to enumerators yet which is why I did it the way I did. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:29:54.587",
"Id": "37978",
"ParentId": "37962",
"Score": "4"
}
},
{
"body": "<ol>\n<li>Remove fields which we already have as properties in base class.</li>\n<li>Change everything to use base properties</li>\n<li>Change setter scope of base properties to protected</li>\n</ol>\n\n<p>Let's start with <code>PlayWithPet</code>. This is doing the same thing in all subclasses except displaying a different message for each one of them. </p>\n\n<p>Let's move this code into Base and implement a method <code>GetPlayWithPetMessage</code> in all child classes which will return that different message.</p>\n\n<p>Change <code>PlayWithPet</code> from abstract to virtual and add a new abstract method instead which is <code>GetPlayWithPetMessage</code> and then <code>PlayWithPet</code> will call this new method.</p>\n\n<p>Now do the same thing for <code>PunishPet</code> which is to change it to a virtual method and a new abstract method <code>GetPunishPetMessage</code>, and so on for <code>FeedPet</code> and <code>StarvePet</code>.</p>\n\n<p>Have a look at the modified source code. For you info, this code still has some duplication which can be removed by using C# lambda Actions or interfaces but probably too early for you. After writing few lines of code, always try to refactory (basically you should refactor after passing your test but I guess its again too early for you). And the primary factor when doing refactoring is to look for duplication in your code and try to remove it. BTW I only looked into Pet and subclasses but I am pretty sure others classes functionality can be moved into base pet classes as well and then each sub class display its own information.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace Pet_Application\n{\n public enum PetMood\n {\n Furious,\n Upset,\n Bored,\n Content,\n Happy\n };\n\n public enum HungerLevel\n {\n Starving,\n Hungry,\n Content,\n Full\n }\n\n public abstract class Pet\n {\n public Pet( string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated )\n {\n Name = name;\n Breed = breed;\n Mood = mood;\n Hunger = hunger;\n IsVaccinated = isVaccinated;\n }\n\n public string Name { get; private set; }\n public string Breed { get; private set; }\n\n //Happiness relates to playing with the pet\n public PetMood Mood { get; protected set; }\n\n //Pet hunger level\n public HungerLevel Hunger { get; protected set; }\n\n //Has the pet been vaccinated\n public bool IsVaccinated { get; private set; }\n\n //The pet class constructor\n\n public void GivePetShot()\n {\n IsVaccinated = true;\n }\n\n public virtual PetMood PlayWithPet()\n {\n var message = GetPlayWithPetMessage();\n if ( (int)this.Mood < 4 )\n {\n Console.WriteLine( message );\n return this.Mood += 1;\n }\n Console.WriteLine( message );\n return this.Mood; \n }\n\n public abstract string GetPlayWithPetMessage();\n\n\n public virtual PetMood PunishPet()\n {\n string message = GetPunishPetMessage();\n if ( (int) this.Mood > 0 )\n {\n Console.WriteLine( message );\n return this.Mood -= 1;\n }\n Console.WriteLine( message );\n return this.Mood; \n }\n\n public abstract string GetPunishPetMessage();\n\n public virtual HungerLevel FeedPet()\n {\n if ( (int)this.Hunger < 3 )\n {\n Console.WriteLine( GetFeedPetSuccessMessage() );\n this.Hunger += 1;\n return this.Hunger;\n }\n\n Console.WriteLine( GetFeedPetFailedMessage() );\n return this.Hunger; \n }\n\n public abstract string GetFeedPetSuccessMessage();\n public abstract string GetFeedPetFailedMessage();\n\n\n public HungerLevel StarvePet()\n {\n string message = GetStarvePetMessage();\n if ( (int)this.Hunger > 0 )\n {\n Console.WriteLine( message );\n this.Hunger -= 1;\n return this.Hunger;\n }\n\n Console.WriteLine( message );\n return this.Hunger; \n }\n public abstract string GetStarvePetMessage();\n\n public void UpdatePet( HungerLevel hunger )\n {\n if ( hunger != Hunger )\n {\n Hunger = hunger;\n }\n }\n\n public void UpdatePet( PetMood mood )\n {\n if ( mood != Mood )\n {\n Mood = mood;\n }\n }\n\n public void DisplayPetInformation()\n {\n Console.WriteLine( \"\\n\\nName: {0}\\n\" +\n \"Breed: {1}\\n\" +\n \"Mood: {2}\\n\" +\n \"Hunger Status: {3}\\n\" +\n \"Is Pet Vaccinated: {4}\\n\",\n Name, Breed, Mood, Hunger, IsVaccinated );\n }\n }\n\n public class Cat : Pet\n {\n public Cat( string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated ) :\n base( name, breed, mood, hunger, isVaccinated )\n {\n }\n\n\n public override string GetPlayWithPetMessage()\n {\n const string result = @\"You gave the cat a ball!\";\n return result;\n }\n\n public override string GetPunishPetMessage()\n {\n return \"You slapped that kitty!\";\n }\n\n public override string GetFeedPetSuccessMessage()\n {\n return \"You fed the cat!\";\n }\n\n public override string GetFeedPetFailedMessage()\n {\n return \"You failed to feed the cat!\";\n }\n\n public override string GetStarvePetMessage()\n {\n return \"You starved the cat!\";\n }\n }\n\n public class Dog : Pet\n {\n public Dog( string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated ) :\n base( name, breed, mood, hunger, isVaccinated )\n {\n }\n\n public override string GetPlayWithPetMessage()\n {\n return @\"You threw a frisby!\";\n }\n\n public override string GetPunishPetMessage()\n {\n return \"You scolded to dog!\";\n }\n\n public override string GetFeedPetSuccessMessage()\n {\n return \"You fed the dog!\";\n }\n\n public override string GetFeedPetFailedMessage()\n {\n return \"You failed to feed the dog!\";\n }\n\n public override string GetStarvePetMessage()\n {\n return \"You starved the dog!\";\n }\n }\n\n public class Shark : Pet\n {\n public Shark( string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated ) :\n base( name, breed, mood, hunger, isVaccinated )\n {\n }\n\n public override string GetPlayWithPetMessage()\n {\n return \"You swam with! \" + this.Name;\n }\n\n public override string GetPunishPetMessage()\n {\n return \"You hit your shark on the nose!\";\n }\n\n public override string GetFeedPetSuccessMessage()\n {\n return \"You fed the shark!\";\n }\n\n public override string GetFeedPetFailedMessage()\n {\n return \"You failed to feed the shark!\";\n }\n\n public override string GetStarvePetMessage()\n {\n return \"You starved the shark!\";\n }\n }\n\n public class Bird : Pet\n {\n public Bird( string name, string breed, PetMood mood, HungerLevel hunger, bool isVaccinated ) :\n base( name, breed, mood, hunger, isVaccinated )\n {\n }\n\n public override string GetPlayWithPetMessage()\n {\n return \"You petted the bird!\";\n }\n\n public override string GetPunishPetMessage()\n {\n return \"You clipped the birds wings!\";\n }\n\n public override string GetFeedPetSuccessMessage()\n {\n return \"You fed the bird!\";\n }\n\n public override string GetFeedPetFailedMessage()\n {\n return \"You failed to feed the bird!\";\n }\n\n public override string GetStarvePetMessage()\n {\n return \"You starved the bird!\";\n }\n }\n\n public class PetDataHandler\n {\n private readonly List<Pet> pets = new List<Pet>();\n\n public string this[ int i ]\n {\n get { return pets[i].Name; }\n }\n\n public void AddPet( Pet pet )\n {\n pets.Add( pet );\n }\n\n public void RemovePet( int i )\n {\n pets.RemoveAt( i );\n }\n\n public int PetCount()\n {\n return pets.Count;\n }\n\n public void Feed( int index )\n {\n pets[index].UpdatePet( pets[index].FeedPet() );\n }\n\n public void Starve( int index )\n {\n pets[index].UpdatePet( pets[index].StarvePet() );\n }\n\n public void PlayWith( int index )\n {\n pets[index].UpdatePet( pets[index].PlayWithPet() );\n }\n\n public void Punish( int index )\n {\n pets[index].UpdatePet( pets[index].PunishPet() );\n }\n\n public void GiveShot( int index )\n {\n pets[index].GivePetShot();\n }\n\n public void ShowData( int index )\n {\n pets[index].DisplayPetInformation();\n }\n\n //Creates an indexer for the pets list\n }\n\n public class Menu\n {\n readonly Input input = new Input();\n readonly PetDataHandler petList = new PetDataHandler();\n\n public void DisplayMainMenu()\n {\n DisplayTitle();\n Console.WriteLine( \"[1] Add a pet\\n\" +\n \"[2] Remove a pet\\n\" +\n \"[3] Inspect a pet\\n\" +\n \"[4] Quit application\\n\" );\n\n MenuChoice( input.GetChoice( \"Enter choice\" ) );\n }\n\n public void DisplayPetTypeMenu()\n {\n DisplayTitle();\n Console.WriteLine( \"[1] Cat\\n\" +\n \"[2] Dog\\n\" +\n \"[3] Shark\\n\" +\n \"[4] Bird\\n\" +\n \"[5] Exit\\n\" );\n\n PetTypeChoice( input.GetChoice( \"Enter choice\" ) );\n }\n\n public void DisplayPetActionMenu( int petIndex )\n {\n Console.WriteLine( \"[1] Feed Pet\\n\" +\n \"[2] Starve Pet\\n\" +\n \"[3] Play With Pet\\n\" +\n \"[4] Punish Pet\\n\" +\n \"[5] Vaccinate Pet\\n\" +\n \"[6] Main Menu\" );\n\n PetActionChoice( input.GetChoice( \"Enter choice\" ), petIndex );\n }\n\n public void DisplayPetRemovalMenu()\n {\n DisplayTitle();\n for ( int i = 0; i < petList.PetCount(); i++ )\n {\n Console.WriteLine( \"[{0}]{1}\", ( i + 1 ), petList[i] );\n }\n\n int choice = input.GetChoice( \"Enter choice\" );\n\n if ( choice > 0 && choice <= petList.PetCount() )\n {\n petList.RemovePet( choice - 1 );\n }\n\n DisplayMainMenu();\n }\n\n public void DisplayPetInspectionMenu()\n {\n DisplayTitle();\n for ( int i = 0; i < petList.PetCount(); i++ )\n {\n Console.WriteLine( \"[{0}]{1}\", ( i + 1 ), petList[i] );\n }\n\n int choice = input.GetChoice( \"Enter number for pet\" );\n\n if ( choice > 0 && choice <= petList.PetCount() )\n {\n petList.ShowData( choice - 1 );\n }\n\n DisplayPetActionMenu( choice - 1 );\n\n Console.ReadKey( true );\n\n DisplayMainMenu();\n }\n\n private void DisplayTitle()\n {\n Console.Clear();\n Console.WriteLine( \"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\n\" +\n \" Pet Application 1.0\\n\" +\n \"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\" );\n }\n\n public void MenuChoice( int choice )\n {\n switch ( choice )\n {\n case 1:\n DisplayPetTypeMenu();\n PetTypeChoice( input.GetChoice( \"Enter choice\" ) );\n break;\n\n case 2:\n DisplayPetRemovalMenu();\n break;\n\n case 3:\n DisplayPetInspectionMenu();\n break;\n\n case 4:\n Environment.Exit( 0 );\n break;\n\n default:\n Console.Write( \"\\n\\nNot a valid selection. Press any key to return\" );\n Console.ReadKey( true );\n DisplayMainMenu();\n break;\n }\n }\n\n public void PetTypeChoice( int choice )\n {\n switch ( choice )\n {\n case 1:\n petList.AddPet( new Cat( input.GetString( \"\\n\\nName\" ), input.GetString( \"Breed\" ), PetMood.Content,\n HungerLevel.Content, false ) );\n DisplayMainMenu();\n break;\n\n case 2:\n petList.AddPet( new Dog( input.GetString( \"\\n\\nName\" ), input.GetString( \"Breed\" ), PetMood.Content,\n HungerLevel.Content, false ) );\n DisplayMainMenu();\n break;\n\n case 3:\n petList.AddPet( new Shark( input.GetString( \"\\n\\nName\" ), input.GetString( \"Breed\" ), PetMood.Content,\n HungerLevel.Content, false ) );\n DisplayMainMenu();\n break;\n\n case 4:\n petList.AddPet( new Bird( input.GetString( \"\\n\\nName\" ), input.GetString( \"Breed\" ), PetMood.Content,\n HungerLevel.Content, false ) );\n DisplayMainMenu();\n break;\n\n case 5:\n DisplayMainMenu();\n break;\n\n default:\n Console.Write( \"\\n\\nNot a valid selection. Press any key to return>\" );\n Console.ReadKey( true );\n DisplayPetTypeMenu();\n break;\n }\n }\n\n public void PetActionChoice( int choice, int petIndex )\n {\n switch ( choice )\n {\n case 1:\n petList.Feed( petIndex );\n DisplayPetInspectionMenu();\n break;\n\n case 2:\n petList.Starve( petIndex );\n DisplayPetInspectionMenu();\n break;\n\n case 3:\n petList.PlayWith( petIndex );\n DisplayPetInspectionMenu();\n break;\n\n case 4:\n petList.Punish( petIndex );\n DisplayPetInspectionMenu();\n break;\n\n case 5:\n petList.GiveShot( petIndex );\n DisplayPetInspectionMenu();\n break;\n\n case 6:\n DisplayMainMenu();\n break;\n\n default:\n Console.Write( \"\\n\\nNot a valid selection. Press any key to return>\" );\n Console.ReadKey( true );\n DisplayPetTypeMenu();\n break;\n }\n }\n }\n\n public class Input\n {\n public string GetString( string prompt )\n {\n Console.Write( \"{0}> \", prompt );\n return Console.ReadLine();\n }\n\n public int GetInt( string prompt )\n {\n Console.Write( \"{0}> \", prompt );\n return int.Parse( Console.ReadLine() );\n }\n\n public int GetChoice( string prompt )\n {\n Console.Write( \"{0}> \", prompt );\n return int.Parse( Console.ReadKey().KeyChar.ToString() );\n }\n }\n\n class Program\n {\n static void Main( string[] args )\n {\n var menu = new Menu();\n\n menu.DisplayMainMenu();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:57:07.740",
"Id": "63250",
"Score": "0",
"body": "Excellent advise and good refactoring of the stuff you did. I've learned a lot!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:25:44.940",
"Id": "63573",
"Score": "1",
"body": "`DisplayPetInformation()` - take the guts out and override `ToString()`. Then DisplayPetInformation() will simply be: `Console Writeline(this)`. Typically where a string is expected `ToString()` is implicitly called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:33:13.770",
"Id": "63574",
"Score": "0",
"body": "`(int) this.Mood > 0` defeats the purpose of `enum`s don't you think? The default value of `enum` in C# is zero, but let's roll that into every enum: `Undefined = 0`. Then you can test like this `if(! Mood.Undefined) …`. Finally, if we ever add values to the `enum`s, we probably just broke the code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:46:41.500",
"Id": "37991",
"ParentId": "37962",
"Score": "6"
}
},
{
"body": "<pre><code>(int)_mood < 4\n</code></pre>\n\n<p>If you want to compare <code>enum</code> values with numbers, then you should specify them explicitly in the definition of the <code>enum</code>. But even better option would be to compare the <code>enum</code> values directly:</p>\n\n<pre><code>_mood < PetMood.Happy\n</code></pre>\n\n<hr>\n\n<pre><code>if ((int)_mood < 4)\n{\n Console.WriteLine(\"You gave the cat a ball!\");\n return _mood += 1;\n}\nConsole.WriteLine(\"You gave the cat a ball!\");\nreturn _mood;\n</code></pre>\n\n<p>You should try to avoid repetition in your code (this is called <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">Don't Repeat Yourself</a>, or DRY). The problem with repeating is that when you want to modify the code, you will need to modify all instances. And you are going to forget that sooner or later, which leads to unnecessary bugs.</p>\n\n<p>So, you could write this code instead like this:</p>\n\n<pre><code>if ((int)_mood < 4)\n _mood += 1;\n\nConsole.WriteLine(\"You gave the cat a ball!\");\nreturn _mood;\n</code></pre>\n\n<hr>\n\n<p>Your menu code also contains lots of repetition. What you could do is to create a type that represents a menu entry and the associated action and then work with collections of these.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T23:57:02.233",
"Id": "38000",
"ParentId": "37962",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:26:27.663",
"Id": "37962",
"Score": "8",
"Tags": [
"c#",
"design-patterns",
"beginner",
"classes"
],
"Title": "Abstract Pet class"
}
|
37962
|
<p>I am writing up a class to handle various templates to be used in a web application. Each template contains various placeholders which will need to be replaced at the time of the build. I am wondering if the method I am using is the best solution, or if I should consider something else. At the moment I have two separate functions <code>addPlaceholder()</code> and <code>addMultiplePlaceholders()</code>. Each performs as their names suggest.</p>
<p>The function <code>addPlaceholder()</code> has two parameters one, the key <code>$k</code>, must be a string while the other, the value <code>$v</code>, can be anything. These get stored in the classes placeholder array. </p>
<p>The function <code>addMultiplePlaceholders()</code> has only one parameter, <code>$array</code>, and it should be an associative array. This function calls <code>addPlaceholder()</code> for each index of <code>$array</code> to store the corresponding values. The reason for the call to an existing function is to help alleviate duplicitous code, and when only a single placeholder is in use to bypass the <code>foreach</code> loop.</p>
<p>Is this the best method to accomplish this? Would it be better to forgo <code>addPlaceholder()</code> and just use <code>addMultiplePlaceholders()</code> for everything? Perhaps, overloading <code>addPlaceholder()</code> would be a better solution having one version which accepts the two parameters, and another which accepted the array. However, I would be in the same situation as now having to decide whether to duplicate the code for adding the placeholder to the class property, or calling the other function.</p>
<pre><code>public function addPlaceholder($k,$v){
if(empty($k)){
throw new Exception('Class Template->addPlaceholder() '.'The placeholder string cannot be empty.');
}
if(isset($this->placeholders[$k])){
throw new Exception('Class Template->addPlaceholder() '.'['.$k.'] is a duplicate entry');
}
$this->placeholders[$k] = $v;
}
public function addMultiplePlaceholders($array){
if(!is_associative($array)){ // if `$array` is not an associative array throw exception
throw new Exception("The supplied parameter value is not an associative array");
}
foreach($array as $key => $value){
try{
addPlaceholder($key,$value);
}catch(Exception $e){
$msg = $e->getMessage();
preg_replace(preg_quote('Class Template->'), '', $msg);
throw new Exception("Class Template->addMultiplePlacerholders()->".$msg);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:51:12.627",
"Id": "63175",
"Score": "2",
"body": "Your solution sounds fine. By the way, \"duplicitous\" means \"treacherous\" and has nothing to do with duplicates :)"
}
] |
[
{
"body": "<p>To answer just the question in the title;\nYour solution seems fine to me; <code>addMultiplePlaceholders()</code> is a utility method that acts as a wrapper for <code>addPlaceholder()</code></p>\n\n<p><strong>Note</strong> there's a bug in your code; <code>addMultiplePlaceholders()</code> calls <code>addPlaceholder()</code> without <code>$this-></code> 'prefix', so your code won't work</p>\n\n<p>However, there <em>is</em> room for improvement. I'll try to summarize what I'd do differently.</p>\n\n<h2>Remove redundant information from your Exception messages</h2>\n\n<p>Exceptions are 'smart' messages in that they already contain all the meta-information you need to find <em>where</em> they occurred (e.g. line number, file etc). Don't clutter your messages with that information, It'll only complicate your code (for example the <code>preg_replace</code>). Just include the bare error-message. See the documentation on <a href=\"http://www.php.net/manual/en/class.exception.php\" rel=\"nofollow\">Exceptions</a>.</p>\n\n<p>If your going to output a message, make sure they cannot be mis-interpreted. Being consistent in your messages will prevent confusion and make it easier to debug your code later on, for example:</p>\n\n<pre><code>throw new Exception('The placeholder string cannot be empty');\n</code></pre>\n\n<p>Is confusing; <em>What is the placeholder string</em>? The name (<code>$k</code>)? Value (<code>$v</code>)? </p>\n\n<p>Outputting the meta-information can be done when <em>printing</em> the exception, for example;</p>\n\n<p>Just use this to throw your exception;</p>\n\n<pre><code>throw new Exception('Placeholder name cannot be empty');\n</code></pre>\n\n<p>And output it in your Exception-handler with this;</p>\n\n<pre><code>printf(\n \"An Exception has occurred: '%s' in file '%s' on line '%s',\n $e->getMessage(),\n $e->getFile(),\n $e->getLine()\n);\n\n// --> An Exception has occurred: 'The placeholder string cannot be empty' in file 'Template.php' on line '52'\n</code></pre>\n\n<p>Since you're no longer including the name of the Class/Method in your messages, you can completely remove the 'try/catch' from your 'addMultiplePlaceholders'.</p>\n\n<h2>Use the right 'type' of Exception</h2>\n\n<p>To be more expressive/specific when throwing Exceptions, consider using special Exceptions for a situation, for example, the <a href=\"http://www.php.net/manual/en/spl.exceptions.php\" rel=\"nofollow\">SPL Exceptions</a>. In this case an <a href=\"http://www.php.net/manual/en/class.invalidargumentexception.php\" rel=\"nofollow\">InvalidArgumentException</a> will be appropriate</p>\n\n<h2>Consider what <em>really</em> is an exception</h2>\n\n<p>Inside <code>addPlaceholder</code>, you're throwing an exception if a key is already set. Personally, I wouldn't do this (it does feel like 'business logic'). Technically, overwriting the value of a placeholder that was already set won't cause any problem. Disallowing overwriting existing placeholders may limit you in situations that you <em>want</em> to overwrite a placeholder.</p>\n\n<p>However, renaming <code>addPlaceholder</code> to <code>setPlaceholder</code> may be more appropriate, to indicate that you can both 'add' or 'update/replace' a placeholder.</p>\n\n<h2>Use descriptive variable/argument-names</h2>\n\n<p>The arguments for <code>addPlaceholder</code> are not very descriptive. Additionally, the variable names you're using seem to be picked based on the the 'inner workings' of the method (key/value pairs), which should be of no interest when using that method. I'd suggest something more describing the <em>purpose</em> of the arguments, for example:</p>\n\n<pre><code>public function addPlaceholder($name, $value)\n{\n //...\n}\n</code></pre>\n\n<p>Likewise, replace '$array' to something more describing its <em>purpose</em>, for example</p>\n\n<pre><code>public function addMultiplePlaceholders($nameValuePairs)\n{\n //...\n}\n\n// or..\n\npublic function addMultiplePlaceholders($placeholders)\n{\n //...\n}\n</code></pre>\n\n<p>If you want to explicitly indicate you're expecting an array (and have PHP check this for you), you can add a type-hint, like this:</p>\n\n<pre><code>public function addMultiplePlaceholders(array $placeholders)\n{\n //...\n}\n</code></pre>\n\n<p>Finally, naming this method <code>addMultiplePlaceholders</code> may be a bit verbose. Since the method is plural, it's probably already clear that it is used to add <em>multiple</em> placeholders, so simply calling it <code>addPlaceholders</code> may be clear enough.</p>\n\n<h2>Remove 'comment' clutter. Add PhpDoc in stead</h2>\n\n<p>Do not describe code that is self-explanatory. In general, try to omit inline comments in all cases, unless a piece of code <em>really</em> is confusing.</p>\n\n<p>In most cases, don't describe the <em>code</em>, but describe the <em>purpose</em> / <em>intent</em> of a function/method inside a PhpDoc comment.</p>\n\n<p>For example:</p>\n\n<pre><code>if(!is_associative($array)){ // if `$array` is not an associative array throw exception\n throw new Exception(\"The supplied parameter value is not an associative array\");\n}\n</code></pre>\n\n<p><strong>This comment is just repeating the code!</strong> Also, inline code is not used by IDE's and will not be included in automatically generated documentation (e.g. <a href=\"http://phpdoc.org\" rel=\"nofollow\">phpdocumentor</a>). It's best to move relevant information to a <a href=\"http://www.phpdoc.org/docs/latest/references/phpdoc/index.html\" rel=\"nofollow\">PhpDoc block</a></p>\n\n<p>For example:</p>\n\n<pre><code>/**\n * Adds placeholder(s) passed as an associative array ('name' => value)\n *\n * Name should be a string, value can be any type of value\n *\n * This method is a wrapper for @see addPlaceholder()\n *\n * @param array $nameValuePairs\n *\n * @throws InvalidArgumentException if $nameValuePairs is not an associative array \n * or an empty name is used for a placeholder\n * @return void\n */\npublic function addMultiplePlaceholders(array $nameValuePairs)\n{\n //...\n}\n</code></pre>\n\n<h2>Modified code</h2>\n\n<p>This is the code after applying my suggestions</p>\n\n<pre><code>/**\n * Adds or updates a placeholder\n *\n * @param string $name Name of the placeholder. Cannot be empty\n * @param mixed $value Value of the placeholder\n *\n * @throws InvalidArgumentException if $name is invalid (empty)\n *\n * @return void\n */\npublic function setPlaceholder($name, $value)\n{\n if (empty($name)) {\n throw new InvalidArgumentException('Placeholder $name cannot be empty.');\n }\n\n $this->placeholders[$name] = $value;\n}\n\n/**\n * Adds or updates placeholder(s), passed as an associative array ('name' => value)\n *\n * Name should be a string, value can be any type of value\n *\n * This method is a wrapper for @see addPlaceholder()\n *\n * @param array $placeholders placeholder(s), passed as an associative array ('name' => value)\n *\n * @throws InvalidArgumentException if $placeholders is not an associative array \n * or an empty name is used for a placeholder\n * @return void\n */\npublic function setPlaceholders(array $placeholders)\n{\n if (!is_associative($nameValuePairs)) { \n throw new InvalidArgumentException('Parameter $placeholders is not an associative array');\n }\n\n foreach (placeholders as $name => $value) {\n $this->addPlaceholder($name, $value);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T05:25:59.873",
"Id": "63607",
"Score": "0",
"body": "Wow, and thank you!! This response is far more than I had expected. I have been doing some research on the how to properly use exceptions this is my first attempt. Again, thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T16:33:27.653",
"Id": "63636",
"Score": "0",
"body": "@BrookJulias you are welcome. My description of Exception handling is nowhere near complete, but it might give you some ideas. Be sure to check out the source code of some popular frameworks (e.g. Symphony, CakePHP). It's a good source to obtain ideas and learn."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T23:06:36.507",
"Id": "38139",
"ParentId": "37966",
"Score": "3"
}
},
{
"body": "<p>Two remarks:</p>\n\n<p>I share your \"feeling\" that this is somehow a \"code duplication\": Writing</p>\n\n<pre><code>addPlaceHolder(array(\"key\" => someValue))\n</code></pre>\n\n<p>is equally understandable and not that much more effort to write than</p>\n\n<pre><code>addPlaceHolder(\"key\", someValue\")\n</code></pre>\n\n<p>Also providing only the version with multiple key/value pairs will encourage \"clients\" to pass values \"in a single step\" which I consinder to be a good thing (otherwise, filling the template might be unnecessarily cluttered and thus seeing which values go into the template might be more difficult).</p>\n\n<p>Therefore I'd probably go with only one function.</p>\n\n<p>Also the <code>addMultiplePlaceholders</code> function can be easily implemented using PHP's <code>array_merge</code> builtin. Detecting duplicate keys can be done using <code>array_intersect_keys</code>, and you can also simply check for the \"empty\" key in the argument array. So the function could look like</p>\n\n<pre><code>public function addPlaceholders($placeholders){\n if(!is_associative($array)){ \n throw new Exception(\"The supplied parameter value is not an associative array\");\n }\n if (array_key_exists(\"\", $placeholders)) {\n throw new Exception('The placeholder string cannot be empty.');\n }\n $intersect = array_intersect_key($placeholders, $this->placeholders);\n if (count($intersect) > 0) {\n throw new Exception('Duplicate entries: ' . implode(', ', array_keys($intersect)));\n }\n $this->placeholders = array_merge($this->placeholders, $placeholders);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:34:06.470",
"Id": "38280",
"ParentId": "37966",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38139",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T16:05:17.987",
"Id": "37966",
"Score": "1",
"Tags": [
"php"
],
"Title": "Handling templates for a web application"
}
|
37966
|
<p>Basically, this code takes a keyword and an array of strings, then sorts them based on two things: the number of characters shared with the key, and the distance between them.(As a side note, would this properly be called a sort, not a search?)</p>
<pre><code>def search(key, list)
# Format for everything pushed to out:
# Should this be a class?
# {
# val: the string in question,
# shared_chars: [{char: shared char of key list elem,
# index: index of shared char,
# kindex: index of shared char in key
# distance: how close the shared chars are}]
# }
out = []
key = key.downcase
list.each { |l|
l.downcase!
shared_chars = []
keyi = 0
key.each_char { |c|
index = /#{c}/ =~ l
if index != nil
shared_chars.push char: c, index: index, kindex: keyi
end
# Inelegant?
keyi += 1
}
# Calulate total distance between shared_chars
distance = 0
odistance = 0
shared_chars.each_index { |i|
unless i == shared_chars.length-1
distance += (shared_chars[i+1][:index] - shared_chars[i][:index]).abs
odistance += (shared_chars[i+1][:kindex] - shared_chars[i][:kindex]).abs
end
}
distance -= odistance
distance = distance.abs
out.push val: l, shared_chars: shared_chars, distance: distance
}
out.sort_by! { |e|
# 100 is arbitrary
100 + e[:distance] - e[:shared_chars].length*3
}
out
end
</code></pre>
<p>Specifically I would like to know if any part of it could be made more efficient and/or elegant, but general critique is of course welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:40:04.490",
"Id": "63182",
"Score": "1",
"body": "You appear to be trying to do fuzzy text matching. Consider using an [existing solution](https://github.com/seamusabshere/fuzzy_match), [another existing solution](https://github.com/makaroni4/amatch), or an [alternative metric](http://stackoverflow.com/a/653165/1157100) for string similarity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:42:27.257",
"Id": "63183",
"Score": "0",
"body": "@200_success I mostly did this for fun and as an exercise."
}
] |
[
{
"body": "<ul>\n<li>Blocks longer than one line are conventionally written using <code>do</code>…<code>end</code> rather than braces.</li>\n<li><p>Code of the form</p>\n\n<pre><code>out = []\nlist.each { |l| ... out.push(something) }\n</code></pre>\n\n<p>… would be better expressed as</p>\n\n<pre><code>out = list.collect { |l| something }\n</code></pre>\n\n<p>Besides being slightly more compact, there is a subtle difference in thinking: the former feels like \"do this, then this, then this to build a result\"; the latter says \"transform each element like this\", and it's easier to see that there is a one-to-one correspondence between input elements and output elements.</p></li>\n<li><p>Within that block,</p>\n\n<pre><code>out = list.collect do |l|\n # Calling l.downcase! would have the side-effect of modifying\n # strings in the original list, which is impolite.\n l = l.downcase\n\n shared_chars = []\n key.split.each_with_index do |c, keyi|\n index = l.index(c)\n # Actually, char:c is never used and could be eliminated\n shared_chars.push(char: c, index: index, kindex: keyi) if index\n end\n\n distance, kdistance = 0, 0\n shared_chars.each_cons(2) do |a, b|\n distance += (b[:index] - a[:index]).abs\n kdistance += (b[:kindex] - a[:kindex]).abs\n end\n\n { val: l, shared_chars: shared_chars, distance: (distance - odistance).abs }\nend\n</code></pre></li>\n<li><p>Furthermore,</p>\n\n<pre><code>out.sort_by! { |e| ... }\nout\n</code></pre>\n\n<p>could just be</p>\n\n<pre><code>out.sort_by { |e| ... }\n</code></pre>\n\n<p>(<code>.sort_by</code> is defined because an <code>Array</code> is an <code>Enumerable</code>.)</p></li>\n<li><p>I think that the whole function would be better as one chained expression:</p>\n\n<pre><code>def search(key, list)\n key = key.downcase\n\n list.collect do |l|\n ...\n end.sort_by do |e|\n # There's no point in adding 100 to each element\n e[:distance] - 3 * e[:shared_chars].length\n end\nend\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:16:11.657",
"Id": "63180",
"Score": "0",
"body": "Excellent answer. Note that the bad indentation only happened when I pasted to stackexchange"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T12:05:55.840",
"Id": "63259",
"Score": "0",
"body": "`do ... end` can make problems because of operator precedence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T09:48:01.000",
"Id": "65013",
"Score": "0",
"body": "@Nakilon As can `{....}`. The difference in precedence between `do...end` and `{...}` matters mostly in internal DSLs, where parentheses are, by convention, frequently omitted from method calls. As used in this answer, it's not an issue."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:10:07.927",
"Id": "37980",
"ParentId": "37971",
"Score": "6"
}
},
{
"body": "<p>Here's one way to modify your code:</p>\n\n<pre><code>def sort_list_by_key(key, list)\n key_arr = key.downcase.chars.each_with_index.to_a\n metric = list.each_with_object([]) do |l, m|\n w = l.downcase\n ndx = key_arr.each_with_object({w: [], k: []}) do |(c, i), h|\n if (j = w.index(c))\n h[:w] << j\n h[:k] << i\n end\n end \n m << (distance(ndx[:w]) - distance(ndx[:k])).abs - 3 * ndx[:w].size\n end\n list.zip(metric).sort_by(&:last).map(&:first)\nend\n\ndef distance(ndx)\n ndx.each_cons(2).to_a.reduce(0) {|d, (i,j)| d + (i-j).abs}\nend\n</code></pre>\n\n<p>Let's look at an example:</p>\n\n<pre><code>key = \"match\"\nlist = %w[The cat had kittens] # => [\"the\", \"cat\", \"had\", \"kittens\"]\n</code></pre>\n\n<p>We know we will need the index of each character of <code>key</code> for each word in <code>list</code>, so we first construct <code>key_arr</code>:</p>\n\n<pre><code>key_arr # => [[\"m\", 0], [\"a\", 1], [\"t\", 2], [\"c\", 3], [\"h\", 4]] \n</code></pre>\n\n<p>We now ask <a href=\"http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-each_with_object\" rel=\"nofollow\">Enumerable#each_with_object</a> (available since Ruby 1.9) to iterate a block for each element of <code>list</code>, and return the results in an array, denoted by the block variable <code>m</code>. This array will be captured by the variable <code>metric</code>. <code>each_with_object</code> creates this (initially empty) array. Each element is the ordering metric for the corresponding member of <code>list</code>.</p>\n\n<p>Consider the first element of <code>list</code>: <code>l => \"The\"</code>. We use String#downcase to change \"The\" to \"the\" (not <code>downcase!</code>, because we don't want to change <code>list</code>). We again use <code>each_with_object</code>, this time to create a hash that will contain two arrays that are needed to calculate the ordering metric. These arrays contain indices of matching characters, for \"the\" (<code>ndx[:w]</code>) and \"match\" (<code>ndx[:k]</code>), respectively. The calculation <code>key_arr.each...</code> proceeds as follows:</p>\n\n<pre><code>w => \"the\"\n [c, i] j=index(c) ndx[:w] ndx[:k]\n ['m', 0] nil [] [] \n ('a', 1] nil [] [] \n ['t', 2] 0 [0] [2]\n ['c', 3] nil [0] [2]\n ['h', 4] 1 [0,1] [2,4]\n</code></pre>\n\n<p>A similar calculation is done for \"cat\", \"had\" and \"kittens\". The results are as follows:</p>\n\n<pre><code> distance\n w ndx[:w] ndx[:k] list key |diff| 3*size metric \n'the' [0,1] [2,4] 1 2 1 6 -5\n'cat' [1, 2, 0] [1, 2, 3] 3 2 1 9 -8\n'had' [1, 0] [1, 4] 1 3 2 6 -4\n'kittens' [2] [2] 0 0 0 3 -3\n\nmetric # => [-5, -8, -4, -3]\n</code></pre>\n\n<p>These index arrays provide the information needed to calculate the ordering metric for each word, shown in the last column of this table. For <code>w => \"cat\"</code>, the ordering metric is:</p>\n\n<pre><code>(distance([1,2,0]) - distance[1,2,3]).abs - 3 * [1,2,0].size\n</code></pre>\n\n<p>For <code>distance([1,2,0])</code></p>\n\n<pre><code>[1,2,0].each_cons(2).to_a # => [[1, 2], [2, 0]]\n[[1, 2], [2, 0]].reduce(0) {|d, (i,j)| d + (i-j).abs} # => 3\n</code></pre>\n\n<p>(Recall that <code>reduce</code> and <code>inject</code> are synonyms.)</p>\n\n<p>Similarly, <code>distance([[1, 2, 3]]) => 2</code> and <code>3 * [1,2,0].size => 9</code>, so</p>\n\n<pre><code>(distance([1,2,0]) - distance[1,2,3]).abs - 3 * [1,2,0].size => |3 - 2| - 9 => -8\n</code></pre>\n\n<p>We can now construct</p>\n\n<pre><code>list.zip(metric) # => [[\"The\", -5], [\"cat\", -8], [\"had\", -4], [\"kittens\", -3]]\n</code></pre>\n\n<p>which we sort on the second (last) value of each array to obtain:</p>\n\n<pre><code>=> [[\"cat\", -8], [\"The\", -5], [\"had\", -4], [\"kittens\", -3]]\n</code></pre>\n\n<p>Lastly, we return the first element of each array:</p>\n\n<pre><code> => [\"cat\", \"The\", \"had\", \"kittens\"] \n</code></pre>\n\n<p>I invite corrections and suggestions for improvements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T05:33:40.590",
"Id": "38731",
"ParentId": "37971",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37980",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T17:36:55.487",
"Id": "37971",
"Score": "4",
"Tags": [
"algorithm",
"ruby",
"beginner",
"search",
"edit-distance"
],
"Title": "Simple fuzzy text search algorithm"
}
|
37971
|
<p>I created a weather widget in JavaScript that requests the current weather from Yahoo. The weather request returns a code which corresponds with a current weather image. I don't like Yahoo's images, so I use my own CSS classes that correspond with my own images. Consequently, the following code returns the correct CSS class which I then deal with later: </p>
<pre><code>function returnClass(c) {
if (c === "0" || c === "19" || c === "23" || c === "24") {
return ["basecloud", "wind"];
} else if (c === "1" || c === "2") {
return ["basecloud", "rain"];
} else if (c === "3" || c === "4" || c === "37" || c === "38" || c === "39" || c === "45" || c === "47") {
return ["basecloud", "thunder"];
} else if (c === "5" || c === "6" || c === "7" || c === "8" || c === "10" || c === "18") {
return ["basecloud", "sleet"];
} else if (c === "9") {
return ["basecloud", "drizzle"];
} else if (c === "11" || c === "12" || c === "40") {
return ["basecloud", "rain"];
} else if (c === "13" || c === "14" || c === "15" || c === "16" || c === "41" || c === "42" || c === "43" || c === "46") {
return ["basecloud", "snow"];
} else if (c === "17" || c === "35") {
return ["basecloud", "hail"];
} else if (c === "20" || c === "21" || c === "22") {
return ["mist"];
} else if (c === "25") {
return ["basecloud", "frost"];
} else if (c === "26" || c === "27" || c === "29" || c === "33" || c === "28" || c === "30" || c === "34" || c === "44") {
return ["cloud"];
} else if (c === "31") {
return ["moon"];
} else if (c === "32" || c === "36") {
return ["sun"];
} else if (c === "3200") {
return ["none"];
}
}
</code></pre>
<p>Is there any way to simplify the above code? As you can tell, multiple codes can represent the same CSS class, which is why I have so many <code>or</code> operators. The only requirement is that it returns the correct array depending on the code.</p>
|
[] |
[
{
"body": "<p>This sort of thing, with a finite set of coditions, is typically done using an array:</p>\n\n<pre><code>var codeIcons=[\n [\"basecloud\", \"wind\"],\n [\"basecloud\", \"rain\"],\n [\"basecloud\", \"rain\"],\n [\"basecloud\", \"thunder\"],\n [\"basecloud\", \"thunder\"],\n ....\n ];\n</code></pre>\n\n<p>Then your method simply becomes:</p>\n\n<pre><code>function returnClass(c) {\n c = parseInt(c);\n return (c < codeIcons.length) ? codeIcons[c] : [\"none\"];\n}\n</code></pre>\n\n<p>Just adding to a set of advantages this method has:</p>\n\n<ul>\n<li>sure, it is hard-coding logic, but, the presentation is better than multiple if-statements.</li>\n<li>it is more managable - you can easily add conditions</li>\n<li>you know exactly what conditions lead to certain output (you do not need to scan pages of code to find the right conditions</li>\n<li>you cannot have bugs where multiple conditions lead to the same result (these types of bugs tend to creep in after maintaining the code - you have multiple or-conditions where <code>c == xxx</code>.</li>\n<li>if, further down the road, you want to migrate the logic for what classes/icons to use, and when, you can easily just change where the array-of-values is configured (i.e. it can become a configuration value, not hard-coded.)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:11:47.917",
"Id": "63170",
"Score": "0",
"body": "So I will have an array with 36 subarrays?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:22:13.363",
"Id": "63171",
"Score": "0",
"body": "@Charlie exactly, and handle the 3200 independently. This will reduce your code substantially. You can choose whether to handle 3200 and everything else as `[\"none\"]` or whether to have some error condition for non-3200 values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T02:09:48.230",
"Id": "63225",
"Score": "3",
"body": "I think the re-formatted code is not very readable. As array literals don't have index numbers, it's difficult to see which classes correspond to a given number."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:05:03.743",
"Id": "37976",
"ParentId": "37974",
"Score": "16"
}
},
{
"body": "<p>I like @rolfl's answer. Here's another way to do it that's superficially different, but sort of (but not really) similar. First, create the following function:</p>\n\n<pre><code>var addIcons = function(icons, c) {\n return function(push, values) {\n if (values.indexOf(c) !== -1) {\n icons.push(push);\n }\n return icons;\n }\n}\n</code></pre>\n\n<p>This function constructs a new function that is specifically built to check its inputs for the existence of <code>c</code> and to push a new value into the <code>icons</code> array when it's found. This function closes over both <code>c</code> and <code>icons</code> so the results are accumulated, as expected. Here's an example:</p>\n\n<pre><code>var add = addIcons([], 2);\nadd(\"basecloud\", [0, 19, 23, 24, 1, 2, 3, 4, 37, 38, 39, \n 45, 47, 5, 6, 7, 8, 10, 18, 9, 11, 12, \n 40, 13, 14, 15, 16, 41, 42, 43, 46, 17, \n 35, 25]);\nadd(\"rain\", [1, 2]);\nadd(\"thunder\", [3, 4, 37, 38, 39, 45, 47]);\n\n// ...and so on\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[\"basecloud\", \"rain\"]\n</code></pre>\n\n<p>Of course, you can (and probably should) create a lookup table (sort of the inverse of @rolfl's table) and further abstract the code needed to get the final result:</p>\n\n<pre><code>var icons = {\n \"basecloud\": [0, 19, 23, 24, 1, 2, 3, 4, 37, 38, 39, \n 45, 47, 5, 6, 7, 8, 10, 18, 9, 11, 12, \n 40, 13, 14, 15, 16, 41, 42, 43, 46, 17, \n 35, 25],\n\n \"rain\": [1, 2],\n \"thunder\": [3, 4, 37, 38, 39, 45, 47]\n};\n\nfunction getAllIcons(c) {\n var res = [];\n var add = addIcons([], c);\n for (var icon in icons) {\n res = add(icon, icons[icon]);\n }\n return res;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>getAllIcons(2);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[\"basecloud\", \"rain\"]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T20:52:06.897",
"Id": "63193",
"Score": "0",
"body": "This is how I usually do it, sparse arrays like that scale better for more spread out values and translate seamlessly to arbitrary objects instead of just integers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:34:48.180",
"Id": "63268",
"Score": "0",
"body": "I like the second implementation. That way I would only need 15 subarrays instead of 36. Is the return speed negligible between the previously accepted answer and this one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T16:13:01.950",
"Id": "63275",
"Score": "0",
"body": "This is also way more manageable for future maintenance than rolfl's answer, which doesn't list the indexes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:18:17.587",
"Id": "63308",
"Score": "0",
"body": "@charlie - Array lookup by index is done in constant time, but this needs to loop over each icon type and search its array to see if the value is present, so mine is definitely slower (`n * m` operations versus a single array lookup). But I think we're talking about a micro-optimization for structures of the size presented. I would go for readability and maintainability first."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:37:33.730",
"Id": "37979",
"ParentId": "37974",
"Score": "14"
}
},
{
"body": "<p>Why not use the <code>switch-case</code> construct for this?</p>\n\n<p>You could condense your <code>if-else</code> structure into the following:</p>\n\n<pre><code>switch(c)\n{\n case '0':\n case '19':\n case '23':\n case '24':\n return [\"basecloud\", \"wind\"];\n\n case '1':\n case '2':\n return [\"basecloud\", \"rain\"];\n\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:58:02.387",
"Id": "63190",
"Score": "0",
"body": "That's not really saving any lines of code though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T20:45:51.250",
"Id": "63192",
"Score": "0",
"body": "Yeah, it's fine, but it's going to be looooong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T08:00:54.457",
"Id": "63251",
"Score": "4",
"body": "It may be longer, but it will be a lot clearer and _that_ is what matters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T08:01:27.117",
"Id": "63252",
"Score": "3",
"body": "Not longer than the accepted answer, which is also harder to maintain than the original if-else setup should he wish to change any of the css classes, or the original mapping from the Yahoo feed changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:27:03.430",
"Id": "63266",
"Score": "0",
"body": "@HaykoKoryun Good point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:12:18.673",
"Id": "63307",
"Score": "0",
"body": "That's no longer the accepted answer :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:47:07.310",
"Id": "37985",
"ParentId": "37974",
"Score": "10"
}
},
{
"body": "<p>If you don't mind using the 'JSON strings as index' trick, you can do the following:</p>\n\n<pre><code>var classMap = \n{\n '[\"basecloud\", \"wind\"]' : [0,19,23,24],\n '[\"basecloud\", \"rain\"]' : [1,2],\n '[\"basecloud\", \"thunder\"]' : [3,4,37,38,39,45,47],\n etc. etc \n} \n\n\nfunction returnClass(c)\n{\n var n = +c, key;\n for( key in classMap )\n if( ~classMap[key].indexOf( n ) )\n return JSON.parse( key );\n return [\"none\"];\n}\n</code></pre>\n\n<p>This implies of course that you run on a modern browser, or that you shim in the indexOf ( you can use the code from <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility\" rel=\"nofollow\">here</a> ).</p>\n\n<p>A more old skool version of the returnClass function would be</p>\n\n<pre><code>function returnClass(c)\n{\n var n = parseInt(c,10), key;\n for( key in classMap )\n if( classMap[key].indexOf( n ) != -1 )\n return JSON.parse( key );\n return [\"none\"];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:30:30.520",
"Id": "63267",
"Score": "0",
"body": "This one seems the cleanest. Thankfully I have the luxury of developing for a specific browser on a specific platform. I also like @lwburk's example as well, and his has the advantage of being more readable. For instance, are you setting `n` to `+c` so that it increments each time? And what does the tilde (`~`) operator accomplish?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:37:26.470",
"Id": "63269",
"Score": "3",
"body": "`n = +c` converts a string to a number ( '20' to 20 ). `~` ( Bitwise NOT ) effectively converts -1 to 0 and all other values to not-zero. It is an answer as to why indexOf returns -1 when not found. So `~'abc'.indexOf('a')` is true, `~'abc'.indexOf('d')` is false."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T17:03:35.943",
"Id": "63278",
"Score": "0",
"body": "Ah. Thanks for updating the answer with your recent explanation. I like this method the most."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:20:25.973",
"Id": "37990",
"ParentId": "37974",
"Score": "9"
}
},
{
"body": "<pre><code>// Programmer-friendly representation\nvar WEATHER = [\n { class: [\"basecloud\", \"wind\"], codes: [0, 19, 23, 24] },\n { class: [\"basecloud\", \"rain\"], codes: [1, 2] },\n { class: [\"basecloud\", \"thunder\"], codes: [3, 4, 37, 38, 39, 45, 47] },\n { class: [\"basecloud\", \"sleet\"], codes: [5, 6, 7, 8, 10, 18] },\n { class: [\"basecloud\", \"drizzle\"], codes: [9] },\n { class: [\"basecloud\", \"rain\"], codes: [11, 12, 40] },\n { class: [\"basecloud\", \"snow\"], codes: [13, 14, 15, 16, 41, 42, 43, 46] },\n { class: [\"basecloud\", \"hail\"], codes: [17, 35] },\n { class: [\"mist\"], codes: [20, 21, 22] },\n { class: [\"basecloud\", \"frost\"], codes: [25] },\n { class: [\"cloud\"], codes: [26, 27, 29, 33, 28, 30, 34, 44] },\n { class: [\"moon\"], codes: [31] },\n { class: [\"sun\"], codes: [32, 36] },\n // { class: [\"none\"], codes: [3200] },\n];\n\n// Transform into a lookup table\nvar WEATHER_CODES = [];\nfor (var i = 0; i < WEATHER.length; i++) {\n WEATHER[i].codes.forEach(function(code) {\n WEATHER_CODES[code] = WEATHER[i].class;\n });\n}\n\n// The original function interface, for compatibility\nfunction returnClass(c) {\n return WEATHER_CODES[c] || [\"none\"];\n}\n</code></pre>\n\n<p>This is a variant of @tomdemuyt's solution, with two differences:</p>\n\n<ul>\n<li>No reliance on JSON hack.</li>\n<li><code>returnClass(c)</code> is a simple lookup, for possibly better performance.</li>\n</ul>\n\n<hr>\n\n<p>If you care about namespace pollution, then you could hide <code>WEATHER</code> and <code>WEATHER_CODES</code> inside a function scope:</p>\n\n<pre><code>var returnClass = (function() {\n var WEATHER = [\n { class: [\"basecloud\", \"wind\"], codes: [0, 19, 23, 24] },\n // etc.\n ];\n\n var WEATHER_CODES = [];\n for (var i = 0; i < WEATHER.length; i++) {\n WEATHER[i].codes.forEach(function(code) {\n WEATHER_CODES[code] = WEATHER[i].class;\n });\n }\n\n return function returnClass(c) {\n return WEATHER_CODES[c] || [\"none\"];\n };\n})();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T09:58:29.727",
"Id": "38160",
"ParentId": "37974",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37990",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-12-23T17:55:58.667",
"Id": "37974",
"Score": "15",
"Tags": [
"javascript"
],
"Title": "Mapping Yahoo weather codes to CSS classes"
}
|
37974
|
<p>I am/have been building a game for a long time now. The game is a web browser based system, and data is stored using <code>JSON</code> stored in <code>RavenDB</code>.</p>
<p>One thing I am very constantly running into as a problem is the notion of <code>Requirements</code>. Anyone who has played a game, particularly an RPG, is probably familiar with this. Requirements such as <code>Requires Level 10 to use</code> or <code>Requires [Race] to use</code>.</p>
<p>This has been a constant struggle for me, and I have finally worked out what I feel is a solution; But I wanted to see if there were other people who have overcome this issue and could offer any advice.</p>
<p>The way it works is that all of the various things in the game that can have requirements have a field...</p>
<pre><code>List<Conditional> Conditions { get; set; }
</code></pre>
<p>Conditional is defined like this; </p>
<pre><code>public class Conditionals {
public Condition<bool> Named { get; set; }
public Condition<double> Minimum { get; set; }
public Condition<double> Maximum { get; set; }
public Condition<double> Exactly { get; set; }
}
</code></pre>
<p>And then each of those is a type of <code>Condition<T></code>, which is declared like this;</p>
<pre><code>public class Condition<T> {
public string Id { get; set; }
public string Name { get; set; }
public string Adjective { get; set; }
public string Label { get; set; }
public T Value { get; set; }
}
</code></pre>
<p>So then the <code>JSON</code> would, if I am right, look like this... assume an item that requires level 10.</p>
<pre><code>var Conditionals = new List<Conditionals>{
new Conditionals {
Minimum = new Condition<double>{
Id = "clue/level",
Name = "Level",
Adjective = ">=",
Label = "Level is greater than or equal to 10",
Value = 10
}
}
};
</code></pre>
<p>These will be resolved when the character is retrieved from the database using <code>Clues</code>. Clues are simple <code>key/value</code> pairs, like a dictionary. A clue has an identity and a value only.</p>
<pre><code>var character = new Character {
Level = 11,
Clues = new List<Clue> () // clues will contain key/value pairs
};
// on database save
character.Clues.Add(new Clue {
Id = "clue/level",
Value = character.Level
});
</code></pre>
<p>This means I will have to do <code>some</code> hard coding, but only by coding in clues that we know the game is going to expect. This allows us to be a little more specific (I feel) and still have some freedom.</p>
<pre><code>foreach (var condition in Conditionals) {
// attempt to see if the condition can be satisfied. This code would
// execute for all four propertyes (named, minimum, maximum, equals)
var currentClue = character.Clues.FirstOrDefault(y => y.Id == condition.Minimum.Id);
// attempt to resolve. this is the minimum section, so we always use >=
var outcome = currentClue.Value >= condition.Value;
}
</code></pre>
<p>I am basically trying to ask if anyone else who has more experience has ever encountered this kind of issue in their own projects, and if my solution compares to any that are known to work. This has frustrated me for a long time.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T20:00:40.783",
"Id": "63191",
"Score": "1",
"body": "Have you seen [Specification Pattern](http://en.wikipedia.org/wiki/Specification_pattern)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T00:02:57.697",
"Id": "63222",
"Score": "2",
"body": "Why is `Adjective` a `string`? It should be an `enum`, or something like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:05:51.557",
"Id": "76256",
"Score": "0",
"body": "I actually really wanted to use `enum`, but JSON only deserializes them to integers and not to strings. Even storing them as strings makes it difficult. I eventually gave up and used different objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:53:22.617",
"Id": "77629",
"Score": "0",
"body": "How about decoupling your data/Json model from your domain model? The domain model shouldn't be bothered with the constraints of Json serialization..."
}
] |
[
{
"body": "<p>I have never written code against a RavenDB, and very seldom use Json (actually, \"never\" is almost accurate). The way I see it, the classes that end up Json-serialized and persisted to the database, are analoguous to <em>Entities</em> (Entity Framework), or <em>POCO</em>'s.</p>\n\n<p>They are part of your <em>data model</em>.</p>\n\n<p>It might seem (/be) code duplication, but if you had a <em>domain model</em> (which might mirror your <em>data model</em>... or not) and a way to \"translate\" a <em>domain entity</em> to a <em>data entity</em> (and vice-versa), you could very well use an <code>enum</code> in your <em>domain model</em>, and have it serialized as a <code>string</code>.</p>\n\n<p>Basically: the shape of the data shouldn't drive, nor define, the shape of the objects your application is going to work with.</p>\n\n<p>Your <em>business logic</em> (well, the actual game!) should work with the <em>domain model</em> objects, and then you'll have a <em>data access layer</em> that will do its job with RavenDB and Json - the <em>business logic</em> shouldn't be bothered with these concerns.</p>\n\n<p>The <code>Label</code> is a good example of why presentation concerns and data concerns need to be separated: serializing and storing it is a waste, you already have all the necessary information in the other fields.</p>\n\n<p>If you had a <em>domain model</em> <code>Condition</code>, it could have a <code>Label</code> property, with logic to build the string out of the other values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T17:20:26.137",
"Id": "44681",
"ParentId": "37982",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:29:02.590",
"Id": "37982",
"Score": "8",
"Tags": [
"c#",
"json"
],
"Title": "\"Game\" Engine Requirements System"
}
|
37982
|
<p>I feel like I don't understand how polymorphism works in Python. Here is something I put together.</p>
<pre><code>class _Tag(object):
def __init__(self):
#DisjointedTag and JoinedTag will bypass __init__.
#Also, self will not be defined within this class.
#Bottom line, this class is just for inheritance.
raise NotImplementedError;
def join_attributes(self):
self.joined_pieces=''.join(self.funct_pieces);
self.__class__=JoinedTag;
def to_disjointed(self):
self.__class__=DisjointedTag;
def add_attribute(self, attribute, value):
self.funct_pieces.insert(
-1, ' {}="{}"'.format(attribute, value)
);
self.to_disjointed();
class Tag(_Tag):
def __init__(self, name):
self.funct_pieces=[
i.format(name) for i in ['<{0}', '>{{}}</{0}>']
];
self.joined_pieces='';
def __call__(self, contents):
self.join_attributes();
return self(contents);
class JoinedTag(_Tag):
def __call__(self, contents):
return self.joined_pieces.format(contents);
class DisjointedTag(_Tag):
#JoinedTag.__call__ has 1 mandatory parameter so this also needs one.
def __call__(self, place_holder):
raise TypeError(
'{} is disjointed because attributes were added to it.'.\
format(self)
);
</code></pre>
<p>Here is an example:</p>
<pre><code>>>> p=Tag('p')
>>> p('hi')
'<p>hi</p>'
>>> p.add_attributes('align', 'left')
>>> p.join_attributes();
>>> p('hi')
'<p align="left">hi</p>'
</code></pre>
<p>I could have joined the attributes on every call but that would waste time. The code I made has no <code>if</code> statements, so it should be more readable according to the philosophy of polymorphism. However, it is very hard to read. I figure I've done something wrong or I'm not used to reading polymorphic code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:34:39.203",
"Id": "63194",
"Score": "0",
"body": "I get `SyntaxError: invalid syntax` when I try to run your code. At Code Review we review *working* code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:56:24.290",
"Id": "63200",
"Score": "0",
"body": "The `add_attribute` method definition is missing a `def` keyword."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:58:31.690",
"Id": "63201",
"Score": "0",
"body": "Sorry, I fixed the errors I made typing the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:59:32.950",
"Id": "63202",
"Score": "2",
"body": "I think what you're doing is overkill. Although it is possible to modify `self.__class__` that way lies dragons. Do you really need separate classes for `JoinedTag` and `DisjointededTag`? A flag would seem fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T22:00:33.527",
"Id": "63203",
"Score": "0",
"body": "I'm trying to avoid flags because I heard that is the polymorphic way. But, I agree it does look like overkill."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T22:30:20.850",
"Id": "63206",
"Score": "0",
"body": "Oh, yeah. Polymorphism avoids boolean flags but other types are fine. This is my shaky understanding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T22:34:37.513",
"Id": "63209",
"Score": "0",
"body": "Well, you can. But there's no reason to use this sort of polymorphism for such a simple task."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T22:38:49.810",
"Id": "63210",
"Score": "0",
"body": "That's fair enough."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T23:11:41.433",
"Id": "63214",
"Score": "1",
"body": "If you have problems with understanding polymorphism in python it seems to me that CR is the wrong place to ask. Maybe you should have a try at StackOverflow or programmers.SE?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:34:19.477",
"Id": "63242",
"Score": "0",
"body": "what version of python are you using?"
}
] |
[
{
"body": "<p>I'm a bear of very little brain, so I don't really understand what you are trying to achieve, or why you think polymorphism will help you achieve it.</p>\n\n<p>But I did notice some problems with your code:</p>\n\n<ol>\n<li><p>There's no documentation.</p></li>\n<li><p>There are no test cases.</p></li>\n<li><p>Python doesn't need semicolons at the end of lines.</p></li>\n<li><p>You don't need a <code>\\</code> at the end of a line if the statement cannot end at that point because of an unclosed parenthesis.</p></li>\n<li><p>There are no checks on the validity of entity and attribute names.</p></li>\n<li><p>Values aren't escaped.</p></li>\n<li><p>There's no check to stop the caller adding multiple attributes with the same name.</p></li>\n<li><p>You shouldn't raise an exception class, you should raise an instance of that class (passing a suitable error message to the constructor).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T23:05:09.227",
"Id": "63213",
"Score": "0",
"body": "The semicolons are just my personal preference. Polymorphism was a challenge I imposed on myself but it was not suitable for the task. What do you mean test cases?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T23:12:25.807",
"Id": "63215",
"Score": "3",
"body": "Very few Python programmers use semicolons like that (it's a sign that someone is not fluent in the language), so if you insist on using them you'll find it a barrier to collaboration. As for test cases, [see Wikipedia](https://en.wikipedia.org/wiki/Test_case)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T22:44:34.617",
"Id": "37997",
"ParentId": "37987",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37997",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T20:10:25.510",
"Id": "37987",
"Score": "0",
"Tags": [
"python",
"polymorphism"
],
"Title": "Understanding polymorphism in Python"
}
|
37987
|
<p>I have attached two scripts which calculate the most popular songs according to zipf's law from the following standard input:</p>
<pre><code>6 3
100 one
50 two
10 three
30 four
5 five
10 six
</code></pre>
<p>The first line details the number of songs to be input followed by the number of songs to return. Each line that follows holds the play counts and respective song titles. In the case of a tie, the algorithm must give precedence to the song that appeared earlier on the album.</p>
<p>Both of my attempts to solve are currently not efficient enough. Any help in optimizing one or both of these would be greatly appreciated.</p>
<p>Attempt 1:</p>
<pre><code>import sys
from operator import itemgetter
def main():
line1 = sys.stdin.readline().split()
x = int(line1[0])-1
z = int(line1[1])
data = ""
for line in sys.stdin:
data+=line
data = data.split()
while(x >= 0):
data[2*x]= float(data[2*x]) * (x+1)
x-=1
answers = [(data[a+1], data[a]) for a in range(0,len(data),2)]
answers.sort(key=itemgetter(1), reverse=True)
p=0
while(p<z):
print answers[p][0]
p+=1
main()
</code></pre>
<p>Attempt 2:</p>
<pre><code>import sys
from operator import itemgetter
def main():
line1 = sys.stdin.readline().split()
x = int(line1[0])-1
p = x
z = int(line1[1])
data = ""
for line in sys.stdin:
data+=line
data = data.split()
while(x >= 0):
data[2*x]= float(data[2*x]) * (x+1)
x-=1
y=0
list_of_lists = []
while(y<=p):
list_of_lists.append([data[2*y+1], data[2*y]])
y+=1
list_of_lists = sorted(list_of_lists, key=itemgetter(1), reverse=True)
n=0
while(n<z):
print list_of_lists[n][0]
n+=1
main()
</code></pre>
<p>Currently Cprofile reports are indicating that the first script is faster. Thanks!</p>
|
[] |
[
{
"body": "<p>I must confess that I do not understand what you're trying to achieve and how Zipf's law come into play !\nBut I've some suggestions about the code itself :</p>\n\n<ul>\n<li>Use meaningful variable names.</li>\n<li>Concatenating strings only to split the result afterward is terribly costly, for no advantage.</li>\n<li>Instead, use meaningful data structures. You deal with a sequence of <code>(count, title)</code> pairs. Flattening that and playing with index parity is confusing.</li>\n</ul>\n\n<p>So, here is my take on it :</p>\n\n<pre><code>import sys\nfrom operator import itemgetter\n\ndef main(source = sys.stdin):\n\n nb_in, nb_out = (int(x) for x in source.readline().split())\n\n #(lazely) collect Count and Title.\n data = ( source.readline().split() for i in range(nb_in) )\n\n #multiply each count by rank.\n answers = [ (title, int(count)*(rank+1)) for (rank, (count, title)) in enumerate(data) ]\n answers.sort(key = itemgetter(1), reverse = True)\n\n for title, _ in answers[:nb_out]:\n print title\n\nmain()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T13:08:06.377",
"Id": "38030",
"ParentId": "38001",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T00:17:34.330",
"Id": "38001",
"Score": "1",
"Tags": [
"python",
"algorithm",
"performance"
],
"Title": "Optimizing/Cleaning up Python Script for Zipf's Law"
}
|
38001
|
<p>Any suggestions on how to shorten this would be greatly appreciated. This code takes three parameters through the URL and displays a page with targeted ads. I especially need help on how to cut down the three sections where I replace <code>%20</code> with spaces. Also, here is the URL with sample parameters - <a href="http://timtechsoftware.com/ad.html?file_url=URL?file_name=FILE?keyword=KEY" rel="nofollow">http://timtechsoftware.com/ad.html?file_url=URL?file_name=FILE?keyword=KEY</a></p>
<p>This is the code of <code>ad.html</code>:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Download File</title>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41582851-1', 'timtechsoftware.com');
ga('send', 'pageview');
</script>
</head>
<body><div align="center">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-1582371570610820";
/* Page Link Medium */
google_ad_slot = "3981698399";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<script>
function getParam(paramName){ //Look for parameters
var prmstr = window.location.search.substr(1);
var prmarr = prmstr.split ("?");
var params = {};
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params[paramName]; //Return the requested parameter
}
var keyword = getParam('keyword');
var intIndexOfMatch = keyword.indexOf( "%20" );
while (intIndexOfMatch != -1){ // Loop over the string value replacing out each matching substring.
keyword = keyword.replace( "%20", " " ) // Relace out the current instance.
intIndexOfMatch = keyword.indexOf( "%20" );} // Get the index of any next matching substring.
var file_name = getParam('file_name');
var intIndexOfMatch = file_name.indexOf( "%20" );
while (intIndexOfMatch != -1){ // Loop over the string value replacing out each matching substring.
file_name = file_name.replace( "%20", " " ) // Relace out the current instance.
intIndexOfMatch = file_name.indexOf( "%20" );} // Get the index of any next matching substring.
var file_url = getParam('file_url');
var intIndexOfMatch = file_url.indexOf( "%20" );
while (intIndexOfMatch != -1){ // Loop over the string value replacing out each matching substring.
file_url = file_url.replace( "%20", " " ) // Relace out the current instance.
intIndexOfMatch = file_url.indexOf( "%20" );} // Get the index of any next matching substring.
document.write('<p style="text-align: center;"><a href="' + file_url + '">Download ' + file_name + '</a>' +
'<br/><br/>Tagged: ' + keyword + '</p>'); //Write the page
</script>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-1582371570610820";
/* Rectangle Large */
google_ad_slot = "9662168393";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Your getParam code has a bug and cannot possibly work..</p>\n\n<pre><code>function getParam(paramName){ //Look for parameters\n var prmstr = window.location.search.substr(1);\n var prmarr = prmstr.split (\"?\"); //This has to be ampersand!!\n var params = {};\n\n for ( var i = 0; i < prmarr.length; i++) {\n var tmparr = prmarr[i].split(\"=\");\n params[tmparr[0]] = tmparr[1];\n }\n return params[paramName]; //Return the requested parameter\n}\n</code></pre>\n\n<p>This function could be shorter if you skipped a few intermediary and some unnecessary steps:</p>\n\n<ul>\n<li>There is no need to assign anything to an object, and hence to create that object</li>\n<li>You only split out prmstr, no need to put that in a var</li>\n<li>You could return early out of the for loop</li>\n</ul>\n\n<p>That would give something more like</p>\n\n<pre><code>//Look for parameters\nfunction getParam( s )\n{ \n var a = window.location.search.substr(1).split(\"&\"), i = a.length, pair;\n while(i--)\n {\n pair = a[i].split(\"=\");\n if( pair[0] == s )\n return pair[1];\n }\n}\n</code></pre>\n\n<p>or, more Golfic</p>\n\n<pre><code>function getParam( s )\n{ \n return location.search.substr(1).split(s+\"=\")[1].split(\"&\")[0]\n}\n</code></pre>\n\n<p>Then, someone clearly copy pasted 3 times the same piece of code and made minor changes.\nYou should have 1 generic function, called 3 time instead. Or, realize that this code is a bad replacement of <code>unescape</code> and just call that. The reason the replacement is bad is that there are lot more characters out there than just <code>%20</code>.</p>\n\n<pre><code>var keyword = unescape( getParam( 'keyword' ) ),\n file_name = unescape( getParam( 'file_name' ) ), \n file_url = unescape( getParam( 'file_url' ) );\n</code></pre>\n\n<p>Furthermore, you assign <code>google_ad_client = \"ca-pub-1582371570610820\";</code> and <code>google_ad_slot = \"9662168393\";</code> twice.</p>\n\n<p>Be aware , <code>document.write</code>, I have been told by reliable sources, should only be used when standing inside a protective summoning circle, lest greater demons devour you. Instead you should have the link tag in your HTML and then find the link in your js and fill in the anchor and caption.</p>\n\n<p>Finally, this is not very good code, I hope the server side code that downloads the file is of higher quality and will not allow path manipulation or path traversal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T13:15:08.783",
"Id": "63261",
"Score": "0",
"body": "I don't get what you mean by this code being dangerous, but everything else is great. Especially unescape!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T13:47:41.587",
"Id": "63262",
"Score": "0",
"body": "You are writing out URL parameters, think about what happens if a malicious person puts a closing link tag and then javascript, that javascript could navigate around your site and do who knows what ( For more info, see https://www.owasp.org/index.php/DOM_Based_XSS )"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T02:19:49.323",
"Id": "38005",
"ParentId": "38002",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T00:19:37.233",
"Id": "38002",
"Score": "4",
"Tags": [
"javascript",
"optimization",
"html",
"url"
],
"Title": "Ad page optimization?"
}
|
38002
|
<p>I have below Java code to compare two list values with some condition:</p>
<pre><code> public boolean compareLists(List<SortData> prevList, List<SortData> modelList) {
if (prevList != null && modelList != null && prevList.size() == modelList.size()) {
boolean indicator = false;
for (SortData modelListdata : modelList) {
if (prevList.size() > 1 && modelList.size() > 1 && prevList.size() == modelList.size()) {
for (SortData prevListdata : prevList) {
if (modelListdata.getListBoxHeaderName().equals(prevListdata.getListBoxHeaderName())) {
indicator = false;
break;
}
else{
indicator = true;
}
}
}
for (SortData prevListdata : prevList) {
if (prevListdata.getListBoxHeaderName() != null && modelListdata.getListBoxHeaderName() != null) {
if (prevList.size() == 1 && modelList.size() == 1
&& !prevListdata.getListBoxHeaderName().equals(modelListdata.getListBoxHeaderName())) {
return true;
} else if (prevListdata.getListBoxHeaderName().equals(modelListdata.getListBoxHeaderName())
&& prevListdata.isSortAscending() != modelListdata.isSortAscending()) {
return true;
} else if (modelListdata.getListBoxHeaderName().equals(prevListdata.getListBoxHeaderName())
&& modelListdata.getPosition() != prevListdata.getPosition()) {
return true;
}
}
}
}
if (indicator) {
return true;
}
} else {
return true;
}
return false;
}
</code></pre>
<p>But I do not think this code is optimized.</p>
<p>The condition I am checking:</p>
<pre><code>Both List not null
If both List size 1 & Name not null return true
If header Names equals but sortAcscending boolean variable not same return true.
If header Names equals but position a integer value not same return true
If both List size > 1 and bth list size equals then check same header name exist in both the List if not then return true.
</code></pre>
<p>I don't think the above code is optimized and I have to write two <code>for</code> loops which look ugly. What can I do to optimize this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T06:32:13.127",
"Id": "63238",
"Score": "1",
"body": "If you could, please state more concretely what this method is intended to do. Rather than just restating your program logic with words, explain what its purpose is. Right now it just looks like a hodgepodge of things you're checking and the code itself is pretty unclear (and, I think, has a bug for what is right now condition #5 in the OP corresponding to inner loop #1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:47:09.963",
"Id": "63247",
"Score": "0",
"body": "That i changed please see edited question"
}
] |
[
{
"body": "<p>Some comments:</p>\n\n<pre><code>&& modelList.size() > 1\n</code></pre>\n\n<p>this check is redundant, in fact</p>\n\n<pre><code>if (prevList.size() > 1 && modelList.size() > 1 && prevList.size() == modelList.size()) {\n</code></pre>\n\n<p>this whole check doesn't depend on the for variable, and can be hoisted outside the for.</p>\n\n<p>The big <code>if</code> that starts at the first line can be inverted to reduce nesting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T23:27:59.060",
"Id": "38141",
"ParentId": "38007",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38141",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T04:56:19.553",
"Id": "38007",
"Score": "5",
"Tags": [
"java",
"optimization"
],
"Title": "Optimize list comparison method?"
}
|
38007
|
<blockquote>
<p>Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. <em>More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42.</em> All
numbers at input are integers of one or two digits.</p>
</blockquote>
<p>I submitted the code for the above problem on spoj and it says wrong answer even when writing the correct output.</p>
<p>The first solution I submitted was:</p>
<pre><code>#include <stdio.h>
int main(void)
{
int i;
while (1) {
scanf("%d", &i);
if (i == 42)
break;
printf("%d", i);
}
return 0;
}
</code></pre>
<p>The above solution doesn't check whether the input is two digit or not so I wrote another one:</p>
<pre><code>#include <stdio.h>
int main(void)
{
int i;
while (1) {
scanf("%d", &i);
if (i > 99)
continue;
if (i == 42)
break;
printf("%d", i);
}
return 0;
}
</code></pre>
<blockquote>
<p>... <strong>rewrite small numbers</strong> from input to output. All numbers at input ... one or two digits.</p>
</blockquote>
<p>However, both of the above solutions don't work on spoj.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:45:41.790",
"Id": "63230",
"Score": "3",
"body": "Try adding a newline after each echo'd integer. I suspect that SPOJ is like most judges and likes line breaks between outputs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-06T16:39:01.937",
"Id": "126152",
"Score": "0",
"body": "If your solution doesn't work, then it is not a working piece of code. So it does not belong here."
}
] |
[
{
"body": "<p><strong>Disclaimer:</strong> I'm not sure if this code will be the solution for <a href=\"http://www.spoj.com/\" rel=\"nofollow\">SPOJ</a>.</p>\n\n<p>You don't check if the input number is an <code>int</code>.</p>\n\n<pre><code>if (scanf(\"%d\", &i) == 1)\n{\n printf(\"OK\\n\");\n} \nelse\n{\n printf(\"Not an integer.\\n\");\n}\n</code></pre>\n\n<hr>\n\n<p>You don't ever tell the user what to enter.</p>\n\n<pre><code>printf(\"%s\\n\", \"Enter what you think the answer is to life, the universe, and everything (hint: it's a number).\");\n</code></pre>\n\n<hr>\n\n<p>This is more of a nitpick, but the <code>while</code> loop could be created in a better fashion instead of <code>break</code>ing.</p>\n\n<pre><code>while (i != 42)\n</code></pre>\n\n<hr>\n\n<p>Another nitpick, you don't add a newline after printing the <code>int</code>.</p>\n\n<pre><code>printf(\"%d\\n\", i);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:45:22.583",
"Id": "63229",
"Score": "1",
"body": "Your printf makes sense in the context of a normal program, but in this context, I think it could be harmful. Code challenge websites typically do not have user interaction of any kind. They tend to be extremely picky about having the *exact* same output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:47:58.907",
"Id": "63231",
"Score": "0",
"body": "@Corbin I agree, and that is why I don't really like code challenge websites because they are usually very nit-picky and can promote bad coding habits. Keep in mind I didn't review the program so it would pass the spoj code challenge."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:59:56.170",
"Id": "63233",
"Score": "0",
"body": "True, I just worry that it could have been misleading given that this was asked in the context of an online judge :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:10:15.610",
"Id": "38009",
"ParentId": "38008",
"Score": "4"
}
},
{
"body": "<p>Assuming SPOJ is like other online judges, you need to work on a line basis. If you just output undelimited integers, how can the judge tell if <code>111</code> is <code>1</code>, <code>11</code>, <code>11</code>, <code>1</code> or <code>111</code>?</p>\n\n<p>This is meant to just be an introduction to SPOJ's system. You're overcomplicating it a bit. It's as simple as:</p>\n\n<pre><code>#include <stdio.h>\n\nint main() {\n int i = 0;\n while (scanf(\"%d\\n\", &i) > 0 && i != 42) {\n printf(\"%d\\n\", i);\n }\n return 0;\n}\n</code></pre>\n\n<p>Anyway, on to a few review points:</p>\n\n<ul>\n<li>Your loop is way overcomplicated. <code>scanf</code> returns the number of tokens extracted. The idiomatic way to use scanf (and fscanf) is to use it as the loop control \n<ul>\n<li>note that it's typically a good idea to do <code>scanf() > 0</code> rather than <code>scanf()</code> implicitly since <code>scanf</code> can return <code>EOF</code> which typically evaluates to true</li>\n<li>Really you should do <code>scanf() == n</code> where <code>n</code> is the expected number of tokens. For simple IO like this though, that's likely overkill. In more complicated cases though, you might need to be aware of how many tokens scanf read.</li>\n</ul></li>\n<li>The instructions never specified that a small number if 2 digits. That's a dangerous assumption. It likely meant small to mean \"fits in an int.\" That's their fault for not being more specific.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T06:02:49.010",
"Id": "63235",
"Score": "0",
"body": "I tried while((i = getchar()) != 42) but that caused file size limit exceed error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T06:05:50.190",
"Id": "63236",
"Score": "3",
"body": "@yesboy That's not how getchar works. It returns an character for the next character in the input buffer. In other words \"42\" is interpreted as the character \"4\" and the character \"2\". Character code 42 is the asterisk character (`*`)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:59:02.747",
"Id": "38012",
"ParentId": "38008",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38012",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T04:58:14.280",
"Id": "38008",
"Score": "5",
"Tags": [
"c",
"io"
],
"Title": "Life, the Universe, and Everything"
}
|
38008
|
<p>I've run my code through Valgrind and managed to not get any memory leaks based on the test code in main. I'm looking for things that I may not have thought to check for, and ways to improve my code in general.</p>
<p><strong>Header file:</strong></p>
<pre><code>#ifndef DLL_H
#define DLL_H
struct node{
void *data;
struct node *next;
struct node *prev;
};
struct dl_list{
struct node *head;
struct node *tail;
int size;
};
struct node *create_empty_node();
struct node *create_node(void *);
void destroy_node(struct node *);
struct dl_list *create_empty_list();
struct node *search(struct dl_list *, void *, int (*comp)(void *,void *));
void insert_el_head(struct dl_list **, void *);
void insert_el_tail(struct dl_list **, void *);
void insert_node_head(struct dl_list **, struct node *);
void insert_node_tail(struct dl_list **, struct node *);
void insert_el_at(struct dl_list **, void *, int);
void insert_node_at(struct dl_list **, struct node *, int);
void delete_all(struct dl_list **, void *, int(*com)(void*,void*));
struct node *delete_el(struct dl_list **, void *, int (*comp)(void *, void *));
struct node *delete_head(struct dl_list **);
struct node *delete_tail(struct dl_list **);
struct node *delete_at(struct dl_list **, int);
struct node *delete_node(struct dl_list **, struct node *);
//uses delete_el, assuming comp == numcmp
struct node *delete_int(struct dl_list **, int);
void print_list(struct dl_list *);
int is_empty(struct dl_list *);
void clear_list(struct dl_list *);
void free_list(struct dl_list *);
int size(struct dl_list *);
//comparison functions
int numcmp(int *x, int *y);
#endif
</code></pre>
<p><strong>Implementation:</strong></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stddef.h>
#include "double_linked_list.h"
struct node *create_empty_node(){
struct node *temp = (struct node *) malloc(sizeof(struct node));
temp->next = temp->prev = NULL;
temp->data = NULL;
return temp;
}
struct node *create_node(void *key){
void *copy = malloc(sizeof(void *));
memcpy(copy, key, sizeof(key));
struct node *temp = create_empty_node();
temp->data = copy;
temp->next = temp->prev = NULL;
return temp;
}
void destroy_node(struct node *to_die){
free(to_die->data);
free(to_die);
}
struct dl_list *create_empty_list(){
struct dl_list *temp = (struct dl_list *)malloc(sizeof(struct dl_list));
temp->head = temp->tail = NULL;
temp->size = 0;
return temp;
}
struct node *search(struct dl_list *list,
void *key, int (*comp)(void *,void *)){
struct node *cur = list->head;
while(cur && !(*comp)(cur->data, key)){
cur = cur->next;
}
return cur;
}
void insert_el_head(struct dl_list **list, void *key){
struct node *temp = create_node(key);
insert_node_head(list, temp);
}
void insert_el_tail(struct dl_list **list, void *key){
struct node *temp = create_node(key);
insert_node_tail(list, temp);
}
void insert_node_head(struct dl_list **list, struct node *temp){
//is the list empty?
if(is_empty(*list)){
(*list)->head = (*list)->tail = temp;
++(*list)->size;
return;
}
temp->next = (*list)->head;
((*list)->head)->prev = temp;
(*list)->head = temp;
++(*list)->size;
}
void insert_node_tail(struct dl_list **list, struct node *temp){
//is the list empty?
if(is_empty(*list)){
(*list)->head = (*list)->tail = temp;
++(*list)->size;
return;
}
(*list)->tail->next = temp;
temp->prev = (*list)->tail;
(*list)->tail = temp;
++(*list)->size;
}
//if z>list->size, insert at tail;
void insert_el_at(struct dl_list **list, void *key, int z){
struct node *temp = create_node(key);
insert_node_at(list, temp, z);
}
//insert in the z+1 position
void insert_node_at(struct dl_list **list, struct node *dat, int z){
if(is_empty(*list) || z == 0){
insert_node_head(list, dat);
return;
}
if(z >= (*list)->size){
insert_node_tail(list, dat);
return;
}
//0<z<list->size
struct node *cur = (*list)->head;
while(z-- > 0){
cur = cur->next;
}
dat->next = cur->next;
cur->next = dat;
dat->next->prev = dat;
dat->prev = cur;
++(*list)->size;
}
void delete_all(struct dl_list **list, void *key, int (*comp)(void*,void*)){
//nothing to delete
if(is_empty(*list)){
return;
}
//list not empty
struct node *cur;
struct node *temp;
for(cur = (*list)->head; cur != NULL; ){
//if first element is key, remove it
if((*comp)((*list)->head->data, key)){
cur = cur->next;
destroy_node(delete_head(list));
}
//if tail is key, remove it
if((*comp)((*list)->tail->data, key)){
cur = cur->next;
destroy_node(delete_tail(list));
}
//key found in cur->data
else if((*comp)(cur->data, key)){
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
temp = cur;
cur = (cur->next ? cur->next : NULL);
destroy_node(temp);
--(*list)->size;
}
//key not found
else{
cur = cur->next;
}
}
}
struct node *delete_el(struct dl_list **list, void *key, int (*comp)(void*,void*)){
if(is_empty(*list)){
return NULL;
}
struct node *cur;
//key not found
if(!(cur=search(*list, key, comp))){ return NULL; }
//delete found key
return delete_node(list, cur);
}
struct node *delete_head(struct dl_list **list){
//empty list
if(is_empty(*list)){
return NULL;
}
//singleton list
if((*list)->size == 1){
struct node *to_die = (*list)->head;
(*list)->head = (*list)->tail = NULL;
--(*list)->size;
return to_die;
}
//(*list)->size > 1
struct node *to_die = (*list)->head;
(*list)->head = (*list)->head->next;
(*list)->head->prev = NULL;
--(*list)->size;
return to_die;
}
struct node *delete_tail(struct dl_list **list){
//empty list
if(is_empty(*list)){
return NULL;
}
//singleton list
if((*list)->size == 1){
struct node *to_die = (*list)->head;
(*list)->head = (*list)->tail = NULL;
--(*list)->size;
return to_die;
}
//(*list)->size > 1
struct node *to_die = (*list)->tail;
(*list)->tail = (*list)->tail->prev;
(*list)->tail->next = NULL;
--(*list)->size;
return to_die;
}
//delete tail if input is larger than list size
//delete the element immediately after the zth node
struct node *delete_at(struct dl_list **list, int z){
if(is_empty(*list)){
//nothing to delete
return NULL;
}
else if(z == 0){
return delete_head(list);
}
else if(z >= (*list)->size){
return delete_tail(list);
}
else{
struct node *temp = (*list)->head;
while(z-- > 0){
temp = temp->next;
}
return delete_node(list, temp);
}
}
struct node *delete_node(struct dl_list **list, struct node *to_die){
if(!to_die->next){
//data == (*list)->tail
return delete_tail(list);
}
else if(!to_die->prev){
//data == (*list)->head
return delete_head(list);
}
else{
to_die->prev->next = to_die->next;
to_die->next->prev = to_die->prev;
--(*list)->size;
to_die->next = to_die->prev = NULL;
return to_die;
}
}
struct node *delete_int(struct dl_list **list, int z){
return delete_el(list, (void *)&z, (int(*)(void*,void*))numcmp);
}
void print_list(struct dl_list *list){
if(list->size == 0){
return;
}
int i = 0;
struct node *cur = list->head;
while(i++ < list->size){
printf("%d ", *((int *)cur->data));
cur = cur->next;
}
printf("\n");
}
int is_empty(struct dl_list *list){ return list == NULL || list->size == 0; }
void clear_list(struct dl_list *list){
list->size = 0;
struct node *cur;
struct node *temp;
for(cur = list->head; cur != NULL; cur = temp){
temp = cur->next;
destroy_node(cur);
}
}
int size(struct dl_list *list){
return list->size;
}
void free_list(struct dl_list *list){
clear_list(list);
free(list);
}
int numcmp(int *x, int *y){
return *x == *y;
}
/*
int main(){
int *p = (int *)malloc(sizeof(int *));
int x = 1, y=2, z=5, a=7, m = 100;
*p = m;
struct dl_list *head = create_empty_list();
insert_el_head(&head, (void *)p);
insert_el_head(&head, (void *)&x);
insert_el_head(&head, (void *)&y);
print_list(head);
insert_el_head(&head, (void *)&z);
insert_el_head(&head, (void *)&a);
insert_el_head(&head, (void *)&z);
insert_el_head(&head, (void *)&a);
print_list(head);
insert_el_tail(&head, (void *)&z);
insert_el_tail(&head, (void *)&a);
insert_el_tail(&head, (void *)&z);
insert_el_tail(&head, (void *)&a);
insert_el_tail(&head, (void *)&y);
insert_el_tail(&head, (void *)&y);
insert_el_tail(&head, (void *)&y);
insert_el_tail(&head, (void *)&y);
print_list(head);
destroy_node(delete_int(&head, x));
print_list(head);
delete_all(&head, (void *)&a, (int(*)(void*,void*))numcmp);
print_list(head);
struct node *temp = search(head, (void *)&z,
(int (*)(void *,void *))numcmp);
printf("is it found? %d\n", (temp == NULL) ? 0 : *((int *)temp->data));
temp = search(head, (void *)&m, (int (*)(void *,void *))numcmp);
printf("Is it found? %d\n", (temp == NULL) ? 0 : *((int *)temp->data));
print_list(head);
print_list(head);
printf("Deleting head\n");
destroy_node(delete_head(&head));
print_list(head);
printf("Deleting tail\n");
destroy_node(delete_tail(&head));
print_list(head);
printf("Deleting: %d\n", *((int *)&x));
printf("Null? %d\n", delete_el(&head, (void *)&x, (int(*)(void*,void*))numcmp)==NULL);
print_list(head);
printf("Freeing p\n");
free(p);
print_list(head);
printf("Inserting %d at position %d\n", *((int *)&y), 5);
insert_el_at(&head, (void *)&y, 4);
print_list(head);
destroy_node(delete_at(&head, 10000));
print_list(head);
printf("Size: %d\n", size(head));
free_list(head);
return 0;
}
*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:50:42.953",
"Id": "63232",
"Score": "3",
"body": "Hmm, that's a lot of code. Sounds like a job for tomorrow :P"
}
] |
[
{
"body": "<p><code>typedef</code> means you no longer have to write <code>struct</code> all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction. There are some places I wouldn't use it in your code, but the <code>struct</code>s in your header file can use them.</p>\n\n<pre><code>typedef struct {\n void *data;\n struct node *next;\n struct node *prev;\n} Node;\n</code></pre>\n\n<hr>\n\n<p>Some of your <code>if</code> conditions only have one statement in them. <strong>This is completely optional</strong>, but I like to remove the braces and move the statement up to the same line as the condition.</p>\n\n<pre><code>if(is_empty(*list)) return;\n</code></pre>\n\n<hr>\n\n<p>I find the space between the name and the asterisks a bit hard to read. You also don't include a space sometimes. You can choose to keep the space or not, but consistency is important.</p>\n\n<pre><code>void delete_all(struct dl_list **, void *, int(*com)(void*,void*)); // inconsistent\n\nvoid delete_all(struct dl_list**, void*, int(*com)(void*,void*)); // consistent\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T06:47:38.327",
"Id": "63337",
"Score": "0",
"body": "Thank you for taking the time to read the code and give input. I'm curious about the use of typedef, I see in the [Linux kernel guidelines](https://www.kernel.org/doc/Documentation/CodingStyle) under the typedef section that it is not suggested to typdef structures and pointers. Is there a general consensus on when, and when not to use typedefs? I'm much more experienced with Java and I mainly keep the statements such as if(is_empty(*list)){ return; } for a consistency reason (otherwise I'd spend a long time on a stupid error where I forgot brackets after a conditional). Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T16:25:08.427",
"Id": "63376",
"Score": "0",
"body": "@Sunde Here is a [`typedef` question on SO](http://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c). It's fine if you keep the `if(is_empty(*list)){ return; }`, as long as you are consistent with them (that's what really matters)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T18:02:54.897",
"Id": "38037",
"ParentId": "38010",
"Score": "3"
}
},
{
"body": "<p>I don't see any memory leaks <em>per se</em>. However, poor naming of your <code>delete_*()</code> functions could mislead a user into thinking that those functions free the memory. After all, <code>delete</code> in C++ frees memory. Your <code>delete_all()</code> function frees memory.</p>\n\n<p>To prevent confusion, I suggest renaming the <code>delete_*()</code> functions (except <code>delete_all()</code>) to something like <code>remove_*()</code>, or better yet, <code>detach_*()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T06:44:08.717",
"Id": "63336",
"Score": "0",
"body": "Thanks you for that input, as I am fairly new to C, I wasn't aware of the convention to have delete free memory. Originally the methods did free the method, but it seemed easier to implement stacks and queues using a doubly linked list, and so not freeing the data became more helpful. I appreciate the advice, this is my first attempt at C and really want to make sure I am doing everything I can to produce good code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T00:34:39.270",
"Id": "38053",
"ParentId": "38010",
"Score": "2"
}
},
{
"body": "<p>There are multiple issues with your code. The most obviously wrong is the use of double-pointers everywhere.</p>\n\n<p>For example:</p>\n\n<pre><code>void insert_node_head(struct dl_list **list, struct node *temp){\n if(is_empty(*list)){\n (*list)->head = (*list)->tail = temp;\n ++(*list)->size;\n return;\n }\n</code></pre>\n\n<p>The double pointers result in the need to de-reference before use, as\nin <code>(*list)->head</code>. This is totally unnecessary. This and all other\nfunctions should be written with single pointers:</p>\n\n<pre><code>void insert_node_head(struct dl_list *list, struct node *temp){\n if(is_empty(list)){\n list->head = list->tail = temp;\n ++list->size;\n return;\n }\n</code></pre>\n\n<p>Double pointers are necessary only when you need to change a pointer\n(as opposed to what the pointer locates) in the calling function.</p>\n\n<hr>\n\n<p>Your idea of data storage is odd. In your <code>key</code> parameters you seem\nto want to store just an integer value (as all of the data you store\nin your tests is smaller or equal to a <code>void*</code>). In <code>create_node</code>\nyou make a copy of the <code>key</code>.</p>\n\n<pre><code>struct node *create_node(void *key){\n void *copy = malloc(sizeof(void *));\n memcpy(copy, key, sizeof(key));\n</code></pre>\n\n<p>This might be what you intended but all the same it looks wrong. Your\n<code>node</code> structure contains a <code>void *data</code> field and you are allocating\nanother <code>void*</code> to hang off that, so at a minimum the allocation is\nredundant. But more to the point if you wanted to store only data up\nto the size of a pointer, you should just declare <code>data</code> differently.\nIt would be much simpler just to store an <code>int</code> or <code>long</code> and cast integer types to that, but if you really want to store varying data types, you might use a union (although unions are not widely used):</p>\n\n<pre><code>union node_data {\n int i;\n long l;\n char ch;\n};\n\nstruct node{\n union node_data data; // not a pointer\n ...\n\nstruct node *create_node(union node_data *data)\n{\n struct node *n = create_empty_node();\n n->data = *data;\n</code></pre>\n\n<p>This also makes it clearer to the caller the nature of the data that\ncan be stored. Your existing functions <em>appear</em> to offer the ability\nto store data of any size. As I said, storing a single scalar type is much simpler.</p>\n\n<p>With variable data types, the comparator functions need to know what data they are comparing, so your existing comparisons and any based upon a union as above are unlikely to be reliable without some extra information to identify the type of data (a discriminator for the union). If any given list contains only one data type, the problem is lessened, but you have no way to enforce that.</p>\n\n<p><hr>\nYou have many functions taking a callback and you have many function\ncalls that cast a function parameter to be suitable for these functions:</p>\n\n<pre><code>struct node *search(struct dl_list *, void *, int (*comp)(void *,void *));\n...\ntemp = search(head, (void *)&m, (int (*)(void *,void *))numcmp);\n</code></pre>\n\n<p>These are ugly and make reading slower than it need be. It is better\nto define a comparator type:</p>\n\n<pre><code>typedef int(*Comparator)(const void*,const void*);\n...\nstruct node *search(struct dl_list *, void *, Comparator);\n...\ntemp = search(head, (void *)&m, (Comparator) numcmp);\n</code></pre>\n\n<p>Note also the <code>const</code> in the Comparator definition.</p>\n\n<hr>\n\n<p>The loop in your <code>delete_all</code> function is odd:</p>\n\n<pre><code>struct node *cur;\nstruct node *temp;\nfor(cur = (*list)->head; cur != NULL; ){\n //if first element is key, remove it\n if((*comp)((*list)->head->data, key)){\n cur = cur->next;\n destroy_node(delete_head(list));\n }\n //if tail is key, remove it\n if((*comp)((*list)->tail->data, key)){\n cur = cur->next;\n destroy_node(delete_tail(list));\n }\n //key found in cur->data\n else if((*comp)(cur->data, key)){\n</code></pre>\n\n<p>You call <code>comp</code> three times, when one should suffice, and you have a\nloop variable <code>cur</code> which traverses each entry in the list but is\nunused until the third call of <code>comp</code>. It would be more normal to\nexamine each <code>cur</code> using <code>comp</code> and then if there is a match, adjust\nthe list according to whether <code>cur</code> is the head/tail or other:</p>\n\n<pre><code>for (struct node *cur = list->head; cur != NULL; ...) {\n if (comp(cur->data, key)){\n /* do all the work in here !! */\n if (cur is head) {\n ...\n }\n else if (cur is tail) {\n ...\n }\n else {\n ...\n }\n }\n}\n</code></pre>\n\n<p>Note that I defined <code>cur</code> within the for-loop and assumed removal of\nthe <code>list</code> double-pointer</p>\n\n<p><hr>\nI think that is enough for really, but a few minor points occur to me:</p>\n\n<ul>\n<li><p>use <code>const</code> everywhere you can. Functions that don't change a\npointer parameter should define that parameter <code>const</code>. For example:</p>\n\n<pre><code>void insert_el_head(struct dl_list *, const void *);\nint size(const struct dl_list *);\n</code></pre></li>\n<li><p>don't cast the return from <code>malloc</code>. This is not needed in C and\ncan be harmful.</p></li>\n<li><p>functions (and their prototypes) that take no parameters should\ndeclare a <code>void</code> parameter list.</p></li>\n<li><p>function pointers can be used as if they were functions, so instead\nof writing</p>\n\n<pre><code>(*comp)(cur->data, key)\n</code></pre>\n\n<p>you can write the more understandable</p>\n\n<pre><code>comp(cur->data, key)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T18:11:39.987",
"Id": "63389",
"Score": "0",
"body": "My oh my, you really went all out. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T04:31:55.860",
"Id": "63404",
"Score": "0",
"body": "Thank you very much for this well thought out answer. Many of the concerns were on my mind, but I was unaware of how to do them (for example typedeffing the function pointer). My use of a void pointer as the data type is to gain some form of generic data type for the list, I only tested with ints for ease. Is there a better way to get a generic type effect?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:54:37.237",
"Id": "38081",
"ParentId": "38010",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "38081",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:28:23.780",
"Id": "38010",
"Score": "12",
"Tags": [
"c",
"linked-list",
"memory-management"
],
"Title": "Doubly linked list with no apparent memory leaks"
}
|
38010
|
<p>Below is the python code to compress js and css files.</p>
<pre><code>import sys
import os
import glob
import shutil
import fnmatch
import os.path
import re
import argparse
import time
#Store the time the script starts
start_time = time.time()
total_files_compressed = 0
total_js_files_compressed = 0
total_css_files_compressed = 0
jsMinPath = 'min/js'
jsDevPath = 'js'
cssDevPath = 'css'
cssMinPath = 'min/css'
yuicompressorPath = 'yuicompressor.jar'
enable_log = False
retval = os.getcwd()
total_warnings = 0
total_errors = 0
print ("Minification script started")
def logErrorWarning(filepath):
global total_warnings
global total_errors
logf = open(filepath)
warning_count = 0
error_count = 0
for line in logf:
if "[ERROR]" in line:
error_count = error_count + 1
total_errors = total_errors + 1
if "[WARNING]" in line:
warning_count = warning_count + 1
total_warnings = total_warnings + 1
logf.close()
logOutput("Errors " + str(error_count) + " Total Warnings " + str(warning_count))
def logOutput(text):
print (text)
def incrementCompressedFileCount():
global total_files_compressed
total_files_compressed = total_files_compressed + 1
def incrementCompressedJSFileCount():
global total_js_files_compressed
total_js_files_compressed = total_js_files_compressed + 1
def incrementCompressedCSSFileCount():
global total_css_files_compressed
total_css_files_compressed = total_css_files_compressed + 1
def minifyJs():
if not os.path.exists(jsMinPath + "/log"):
os.makedirs(jsMinPath + "/log")
else:
shutil.rmtree(jsMinPath + "/log")
os.makedirs(jsMinPath + "/log")
logfile = open(jsMinPath + "/log/fulllog.txt", 'w')
logfile.write('Minify script started for internal js files\n')
os.chdir(jsMinPath)
jsmincontents = glob.glob("*.js")
logfile.write("Removing existing minified files..\n")
logfile.write("Total "+ str(len(jsmincontents)) + " min files exist\n")
for j in jsmincontents:
os.remove(j)
logfile.write("Removed file " + j + "..\n")
os.chdir(retval)
os.chdir(jsMinPath)
jsmincontents = glob.glob("*.js")
os.chdir(retval)
jscontents = os.listdir(jsDevPath)
logfile.write("Compressing internal js files ")
logOutput("Compressing internal js files ")
for i in jscontents:
if i.lower().endswith('.js'):
command = "java -jar " + yuicompressorPath + " -v " + jsDevPath + "/" + i + " -o " + jsMinPath + "/" + i[0:-3] + ".min.js 2> " + jsMinPath + "/log/" + i[0:-3] + ".log.txt"
#print command
logfile.write("Compressing file "+ i + "\n")
logOutput("Compressing file "+ i + "..")
logfile.write(command + "..\n\n")
os.system(command)
incrementCompressedFileCount()
incrementCompressedJSFileCount()
logErrorWarning(jsMinPath + "/log/" + i[0:-3] + ".log.txt")
logfile.close()
logOutput("All internal js files minified")
def minifyCss():
if not os.path.exists(cssMinPath + "/log"):
os.makedirs(cssMinPath + "/log")
else:
shutil.rmtree(cssMinPath + "/log")
os.makedirs(cssMinPath + "/log")
logfile = open(cssMinPath + "/log/fulllog.txt", 'w')
logfile.write('Minify script started\n')
os.chdir(cssMinPath)
cssmincontents = glob.glob("*.css")
logfile.write("Removing existing minified files..\n")
logfile.write("Total "+ str(len(cssmincontents)) + " min files exist\n")
for j in cssmincontents:
os.remove(j)
logfile.write("Removed file " + j + "..\n")
os.chdir(retval)
os.chdir(cssMinPath)
cssmincontents = glob.glob("*.css")
os.chdir(retval)
csscontents = os.listdir(cssDevPath)
logfile.write("Compressing files ")
for i in csscontents:
if i.lower().endswith('.css'):
command = "java -jar " + yuicompressorPath + " -v " + cssDevPath + "/" + i + " -o " + cssMinPath + "/" + i[0:-4] + ".min.css 2> " + cssMinPath + "/log/" + i[0:-4] + ".log.txt"
#print command
logfile.write("Compressing file "+ i + "\n")
logOutput("Compressing file "+ i + "..")
logfile.write(command + "..\n\n")
os.system(command)
incrementCompressedFileCount()
incrementCompressedCSSFileCount()
logErrorWarning(cssMinPath + "/log/" + i[0:-4] + ".log.txt")
logfile.close()
def contains(list, element):
flag = False
for x in list:
if x == element:
flag = True
return flag
def minifyAll():
minifyJs()
minifyCss()
def logoutput(text):
if enable_log:
print (text)
def printsummary():
global total_files_compressed
global total_js_files_compressed
global total_css_files_compressed
print ("----------------------Summary--------------------")
print '%6s %10s' % ("Total", str(total_files_compressed))
print '%6s %10s' % ("JS", str(total_js_files_compressed))
print '%6s %10s' % ("CSS", str(total_css_files_compressed))
print ("-------------------------------------------------")
parser = argparse.ArgumentParser()
group1 = parser.add_mutually_exclusive_group()
group1.add_argument("--all",help="Minify all files",action="store_true")
group1.add_argument("--js",help="Minify all js files",action="store_true")
group1.add_argument("--css",help="Minify all css files",action="store_true")
group1.add_argument("--clear",help="Clear existing files in min",action="store_true")
args = parser.parse_args()
if args.all:
minifyAll()
elif args.js:
minifyJs()
elif args.css:
minifyCss()
elif args.clear:
print "Clear files"
if not len(sys.argv) > 1:
minifyAll()
end_time = time.time()
printsummary()
if total_warnings:
print "Total warnings " + "\033[1;38m"+ str(total_warnings)+"\033[1;m"
else:
print "Total warnings " + str(total_warnings)
if total_warnings:
print "Total errors " + "\033[1;31m"+ str(total_errors)+"\033[1;m"
else:
print "Total errors " + str(total_errors)
print "Time taken for execution(seconds)"
print abs(start_time - end_time)
</code></pre>
<p>The repo link is <a href="https://github.com/hkasera/minify" rel="nofollow">this</a>.</p>
<p>The code stores logs and compresses js and css files. Please suggest any possible optimization or improvement.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:20:22.787",
"Id": "63265",
"Score": "0",
"body": "I removed the javascript tag, that tag is meant for the language of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:55:06.280",
"Id": "63270",
"Score": "0",
"body": "Same for the css tag."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T14:31:23.227",
"Id": "66915",
"Score": "3",
"body": "I disagree with both of you. this has everything to do with CSS and JS. you have to know the syntax to minify the language."
}
] |
[
{
"body": "<pre><code> if not os.path.exists(jsMinPath + \"/log\"):\n os.makedirs(jsMinPath + \"/log\")\n else:\n shutil.rmtree(jsMinPath + \"/log\")\n os.makedirs(jsMinPath + \"/log\")\n</code></pre>\n\n<p>could be</p>\n\n<pre><code> if os.path.exists(jsMinPath + \"/log\"):\n shutil.rmtree(jsMinPath + \"/log\")\n os.makedirs(jsMinPath + \"/log\")\n</code></pre>\n\n<p>Also</p>\n\n<pre><code>def contains(list, element):\n flag = False\n for x in list:\n if x == element:\n flag = True\n return flag\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>def contains(list, element):\n return element in list\n</code></pre>\n\n<p>and for that reason is probably not required (it doesn't seem to be used anyway).</p>\n\n<p>No time to go further at the moment. I might edit my answer later on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T15:19:33.710",
"Id": "38033",
"ParentId": "38011",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T05:55:59.757",
"Id": "38011",
"Score": "3",
"Tags": [
"javascript",
"python",
"performance",
"css"
],
"Title": "Python code to minify JS and CSS on the fly"
}
|
38011
|
<p>I wrote some code for linked lists and would like to know what things could/should be done differently.</p>
<p>I'm using an index to keep track of the most important information and have 2 sets of functions, one to use the list just to point to data and the other to store the data in the list.</p>
<p>Here's the code so far:</p>
<pre><code>#include <stdlib.h>
#include <string.h>
//Basic structure
typedef struct nNode Node;
struct nNode {
void *content;
Node *next;
Node *previous;
};
//An index will make everything simpler
typedef struct {
Node *first;
Node *last;
size_t node_count;
} List;
//Initialize list index with default values
void init_list(List *root)
{
root->first = NULL;
root->last = NULL;
root->node_count = 0;
}
//Link new element and return pointer to it if successful or NULL
Node *add_node(List *root, void *content)
{
Node *temp = malloc(sizeof(Node));
if(temp == NULL){
return NULL;
}
//Fill node
temp->content = content;
temp->next = NULL;
temp->previous = root->last; //NULL if first node
//Handle first element insertion
if(root->first == NULL){
root->first = temp;
}
//Or update previous element
else {
root->last->next = temp;
}
//Update index
root->last = temp;
++root->node_count;
return temp;
}
//Unlink element, always successful
void delete_node(List *root, Node *node)
{
//If it's the first, update index reference
if(node->previous == NULL){
root->first = node->next;
}
//Or it's safe to update previous node
else {
node->previous->next = node->next;
}
//If it's the last, update index reference
if(node->next == NULL){
root->last = node->previous;
}
//Not the last? Safe to update next node
else {
node->next->previous = node->previous;
}
//Update count and free memory
free(node);
--root->node_count;
}
//Iterate through all nodes and call a function on every iteration
void iterate(const List *root, void(*function)(Node*))
{
Node *next; //store in case the node changes
for(Node *ite = root->first; ite != NULL; ite = next){
next = ite->next;
(*function)(ite);
}
}
//Iterate through all nodes backwards and call a function on every iteration
void iterate_backwards(const List *root, void(*function)(Node*))
{
Node *previous; //store in case the node changes
for(Node *ite = root->last; ite != NULL; ite = previous){
previous = ite->previous;
(*function)(ite);
}
}
//Delete all elements in the list
void delete_list(List *root)
{
iterate(root, (void(*)(Node*))free);
init_list(root);
}
////////////////
////// The following functions also store the content in the list
///// instead of just pointing to it. They should be used together
//// in order to avoid memory leaks.
/////////////
//Add node and store a copy of content
Node *add_node_store(List *root, const void *content, size_t content_size)
{
//Allocate space
void *copy = malloc(content_size);
if(copy == NULL){
return NULL;
}
//Copy content
memcpy(copy, content, content_size);
//Check if node insertion succeeded
void *response = add_node(root, copy);
if(response == NULL){
free(copy);
}
return response;
}
//Unlink node and free stored content
void delete_node_store(List *root, Node *node)
{
free(node->content);
delete_node(root, node);
}
//Free node and its content
static void free_node_store(Node *node)
{
free(node->content);
free(node);
}
//Delete all nodes on the list, free them and their contents
void delete_list_store(List *root)
{
iterate(root, free_node_store);
init_list(root);
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>You use <code>root</code> as parameter name when you pass the list around but I think a better name would just be <code>list</code>. <code>root</code> implies that you pass the first node of the list around rather than the container.</p></li>\n<li><p><code>++root->node_count</code> is correct but <code>root->node_count += 1</code> reads nicer (imho).</p></li>\n<li><p>I would consider changing the interface slightly:</p>\n\n<ol>\n<li>Have a <code>List* new_list()</code> method which creates the list (and initializes the object).</li>\n<li><code>delete_list</code> should also delete the list object (probably needs signature change to <code>delete_list(List **list)</code>)</li>\n<li>Add a method <code>clear_list</code> which just clears the contents of the list.</li>\n</ol></li>\n<li><p>Right now the programmer has to remember whether a node was added via <code>add_node</code> or <code>add_node_store</code> in order to call the proper delete function. However this could be solved by having a flag in <code>nNode</code> which indicates whether the node owns the content or not. Delete could then automatically do the right thing.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T10:47:06.707",
"Id": "63258",
"Score": "0",
"body": "+1 thank you very much. Really useful insight, I'll definitely follow most suggestions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T10:41:43.757",
"Id": "38027",
"ParentId": "38013",
"Score": "6"
}
},
{
"body": "<p>Your code is nicely written. A few minor points:</p>\n\n<ol>\n<li>Sometimes you are over-commenting (comments that add nothing). </li>\n<li><p>When calling through a function pointer, instead of writing this:</p>\n\n<pre><code>(*function)(ite);\n</code></pre>\n\n<p>you can just write the much clearer</p>\n\n<pre><code>function(ite);\n</code></pre></li>\n<li><p>I would call <code>nNode</code> just <code>node</code></p></li>\n</ol>\n\n<p>A more significant point is that your iterations can <strong>break the list</strong>. During\niteration you allow list nodes to be deleted (or added I guess). But the\ncallback has no access to the list's node-count, as it has no access to the\nlist itself. One solution would be to pass the list to the iteration function\nas well as the node.</p>\n\n<p>I'd also prefer to see your uses of iteration (<code>delete_list</code>,\n<code>delete_list_store</code>) use the list manipulation functions (eg <code>delete_node</code>) as\ncallbacks.</p>\n\n<p>Finally, I also think that having separate methods of adding to the list (one\nthat copies the data and one that doesn't) is confusing. I think I would\nstick to one public <code>add_node</code> function and make the list itself (rather than each\nnode) either a copying list or a non-copying list via an extra field in <code>List</code> and \na call parameter in <code>new_list</code> (a function suggested by @ChrisWue).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T08:49:18.690",
"Id": "63342",
"Score": "0",
"body": "+1 Thanks for your feedback, I didn't know it was possible to call function pointers like that and didn't really think about the struct name, I already changed those. Your other points also look right. But why use the functions `delete_list` and `delete_list_store` instead of `free()` if the memory will be free'd anyway and the entire list deleted?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T11:22:44.423",
"Id": "63345",
"Score": "0",
"body": "Just that the way you currently do it breaks the list (wrong node count) for the duration of the iteration. And I think it is best of only one function needs to know how to delete an entry from the list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-22T04:07:21.700",
"Id": "135370",
"Score": "0",
"body": "Can you give an example of where in this code, the author is \"over-commenting\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-22T13:18:24.660",
"Id": "135422",
"Score": "0",
"body": "@franklin How many comments can you find that tell you something you didn't already know (from the code that follows)? Some are worse than others - saying \"allocate memory\" before a `malloc` call clearly adds something only for a reader who doesn't recognize `malloc`. For everyone else it is just noise."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T17:22:17.437",
"Id": "38036",
"ParentId": "38013",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38027",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T06:32:13.567",
"Id": "38013",
"Score": "7",
"Tags": [
"c",
"linked-list"
],
"Title": "Linked list implementation"
}
|
38013
|
<p>Request for review, optimization, best practice recommendations etc.</p>
<pre><code>/**
* Find the smallest positive number whose individual digits adds to the input number.
* eg: consider the input 14,
* The smallest number whose digit add to the given number is 59 ie 5 + 9 = 14.
*
* Complexity: O(n), where n is the input number
*
*/
public class SmallestNumber {
private SmallestNumber() {}
private static int getIntNum(int x, int y) {
String number = new StringBuilder().append(x).append(y).toString();
return Integer.parseInt(number);
}
/**
* Given an integer, returns the smallest positive number whose digits adds up to that number.
*
* @param x the number used to find another number whose digits add up to itself
* @returns the smallest positive number whose digits adds up to input number.
*/
public static int getVal(int x) {
x = Math.abs(x);
int min = Integer.MAX_VALUE;
for (int i = 1; i <= x / 2; i++) {
int diff = x - i;
int p1 = getIntNum(i, diff);
int p2 = getIntNum(diff, i);
/**
* http://stackoverflow.com/questions/9576557/most-efficient-way-to-
* find-smallest-of-3-numbers-java
*/
if (p1 < min) min = p1;
if (p2 < min) min = p2;
}
return min;
}
/**
* http://stackoverflow.com/questions/2674707/how-to-concatenate-int-values-
* in-java
*
* @param args
*/
public static void main(String[] args) {
int x1 = getVal(14);
System.out.println("Expected 59, Actual: " + x1);
int x2 = getVal(16);
System.out.println("Expected 79, Actual: " + x2);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:20:52.793",
"Id": "63239",
"Score": "1",
"body": "`getVal(50)` returns 149, which is wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T08:33:03.370",
"Id": "63253",
"Score": "2",
"body": "When someone asks *\"Find x such that phi(x)\"*, they do not mean *\"Make a brute force search of the solution space\"*. I bet there is a thousand digit number in the test cases. Analyze the question first."
}
] |
[
{
"body": "<p>I am struggling to understand your algorithm. I don't fathom why you have to go through all that work of adding digits to values when the math behind this problem is so much simpler.</p>\n\n<p>The smallest value will always be a digit followed by nines. The number of nines is the number of whole times 9 divides in to the value, and the first digit is the remainder.</p>\n\n<p>Mathematically this translates to like:</p>\n\n<pre><code>public static int getVal(int val) {\n val = Math.abs(val);\n int ninecount = val / 9;\n int remainder = val % 9;\n int scale = (int)Math.pow(10, ninecount);\n int result = remainder * scale + (scale - 1);\n return result;\n}\n</code></pre>\n\n<p>Which is an <code>O(1)</code> operation (or, as has been pointed out by James, the complexity of this function is dependent on the complexity of <code>Math.pow(...,...)</code>). If you want to keep <code>O(1)</code> complexity you can precompute the scale for valid ranges of <code>ninecount</code>. The largest possible <code>ninecount</code> for an int result is 9, and for a <code>long</code> result it is 19. This is a small data set to keep in an indexed array accessed with <code>int scale = scales[ninecount];</code> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T16:22:34.017",
"Id": "63277",
"Score": "0",
"body": "I'm fairly certain its actually a O(log(n)) Because the Math.pow is a O(n) operation where n in this case is log base 9 of val. Still within the maximum of O(N) required by the problem statement but worth noting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T12:55:42.453",
"Id": "38029",
"ParentId": "38014",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38029",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T06:35:51.277",
"Id": "38014",
"Score": "2",
"Tags": [
"java",
"mathematics"
],
"Title": "Find the smallest number whose sum of digits add to a number"
}
|
38014
|
<p>This is a Follow-up to <a href="https://codereview.stackexchange.com/q/37939/18427">Simple pay rate calculator</a></p>
<hr>
<p>Here is what I came up with. Hopefully if I have missed something that was said in answers on the previous question, we can still get those things pointed out. I am hoping that I made the code cleaner.</p>
<p><strong>Main Method</strong></p>
<pre><code>class MainClass
{
public static void Main (string[] args)
{
//var payCheck = new PayRateCalculator("Hart",40,23);
var payCheck = new PayCalculator();
Console.Write ("Please provide the Employees Last Name >>");
payCheck.lastName = Console.ReadLine();
Console.Write ("How many hours has employee {0} worked? >>", payCheck.lastName);
payCheck.hours = Convert.ToInt32 (Console.ReadLine());
Console.Write ("What is employee {0}'s hourly wage? >>", payCheck.lastName);
payCheck.payrate = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine ("{0}'s Gross pay is ${1}", payCheck.lastName, payCheck.GrossTotal());
Console.WriteLine ("{0}'s Net pay is ${1}", payCheck.lastName, payCheck.NetTotal());
}
}
</code></pre>
<p><strong>PayCalculator Class</strong></p>
<pre><code>class PayCalculator
{
private const decimal _PayRateDefault = 8.25m;
private decimal _payrate = _PayRateDefault;
private decimal _withholdingRate = 0.20m;
private decimal _hours;
public decimal hours {
get {
if (hours < 1) {
return 40;
} else {
return _hours;
}
}
set {
_hours = value;
}
}
public decimal grossPay { get;set; }
public decimal netPay { get; private set; }
public decimal payrate {
get {
return _payrate;
}
set {
if (value < 8.25){
_payrate = 8.25m;
} else {
_payrate = value;
}
}
}
public decimal WithholdingRate{ get; set; }
public string lastName { get; set; }
public decimal GrossTotal ()
{
grossPay = hours * payrate;
return grossPay;
}
public decimal NetTotal ()
{
grossPay = GrossTotal();
netPay = grossPay - (grossPay * _withholdingRate);
return netPay;
}
public PayCalculator (string lastName, decimal hours, decimal payRate)
{
this.hours = hours;
this.payrate = payrate;
this.lastName = lastName;
}
public PayCalculator ()
{
}
}
</code></pre>
<p>I am going to put the <a href="/questions/tagged/beginner" class="post-tag" title="show questions tagged 'beginner'" rel="tag">beginner</a> tag on this again because I know that my coding skills are still not very good. </p>
<p>This will be the last review for this little bit of code. I am going to see what else catches my eye in this book while I am working through it.</p>
|
[] |
[
{
"body": "<p>Some enhancements I'd make is making employee a separate class with name, payrate, and a list of another class,workday that holds days and hours worked in the current pay period. If you make the PayRate class static and have only methods that take an object of class employee you simplify the class quite a bit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:23:15.183",
"Id": "63240",
"Score": "0",
"body": "I was thinking about something similar to what I think you are saying, but I was thinking that should be more of a SQL/database stuff, I figure that is going to be the next step."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:24:27.460",
"Id": "63241",
"Score": "2",
"body": "Having your code already like that will help when you implement storing the data."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:21:08.003",
"Id": "38017",
"ParentId": "38016",
"Score": "5"
}
},
{
"body": "<p>Well, you have started to use <code>decimal</code> instead of <code>float</code> and introduced a couple of named constants but pretty much every other point I stated in my answer to the other question still stands.</p>\n\n<ol>\n<li>Naming conventions (<code>PascalCase</code> for properties)</li>\n<li>You now have introduced a <code>WithholdingRate</code> property but that doesn't affect anything (the property is not used anywhere in the class)</li>\n<li>Although you have introduced a named constant <code>_PayRateDefault</code> you are still using magic numbers in various places.</li>\n<li>You have added some rules but they are implemented inconsistently - in <code>hours</code> you enforce the rule in the <code>get</code> while in <code>payrate</code> you do it in the <code>set</code>.</li>\n<li><p>The way you have added the rules is simply bad - you silently coerce the values and the user of your class won't have a clue what's going on. </p>\n\n<p>Assume this calculator is used to process the payroll in a company with lots of employees. Further assume that some of those are contractors which have not worked in the last week for whatever reason. Now you read in the work hours for each employee and everyone who hasn't worked at all (<code>hours == 0</code>) will get a full week payed - ouch.</p>\n\n<p>If properties have restrictions on what range of values they should be in then enforce them in the <code>set</code> method by throwing an <code>ArgumentException</code> stating what was violated. It's better for your program to crash with an exception than to spit out bad data.</p>\n\n<p>One of the few places where coercion of values makes sense is in user controls which force out of range values back into the range and then feed that back to the user (e.g. numeric up/down controls which a given min and max) but in most other cases it will do more harm than good.</p></li>\n</ol>\n\n<p>Unfortunately your code has become somewhat more convoluted than the original.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T23:43:28.507",
"Id": "63314",
"Score": "0",
"body": "the `WithholdingRate` is used to figure out the net total. I had a reason for putting rules on Setting the `payrate` but I am thinking of going a different way with it, in that I would produce a message for trying to set the rate less than a minimum, which would be kind of like the exceptions that you are talking about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T00:45:12.717",
"Id": "63318",
"Score": "1",
"body": "@Malachi: The property `WithholdingRate` is not used at all. You use the private field `_withholdingRate` but that has no relationship with the public property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T02:06:50.750",
"Id": "63403",
"Score": "0",
"body": "I am going to have to look into the Private field/public property thing, because I might be operating under a false impression."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T10:21:45.513",
"Id": "38025",
"ParentId": "38016",
"Score": "7"
}
},
{
"body": "<p>There are several things to address here:</p>\n\n<p><strong>Naming Conventions:</strong> only fields, method parameters, and local variables should be camelCase, everything else should be PascalCase. This doesn't make your programs run better, but it does make you a more likable programmer in the workplace. Being able to produce code that is consistent with your co-workers will help you stay employeed. No one likes a rogue programmer.</p>\n\n<p><strong>Validate all external input:</strong> in your application the external input is coming from the info provide by the user of your program. It could be a text box in a windows application or data provided to a web service that you have written. In all cases you need to validate the input before processing so that you can provide the user with an appropriate message. In your case there are places where valid values cannot be less than zero. Check for that and alert the user of their mistake. Here is an example that verifies the pay rate and ensures that it is at least the minimum pay rate.</p>\n\n<pre><code>decimal GetRate(string lastName)\n{\n decimal rate = -1m;\n string tmp = string.Empty;\n do\n {\n Console.Write(\"What is employee {0}'s hourly wage? >>\", lastName);\n tmp = Console.ReadLine();\n if (!decimal.TryParse(tmp, out rate) || rate < Paycheck.MinimumHourlyRate)\n {\n Console.WriteLine(\"hourly wages must be a valid number greater than {0:#######.00}\", Paycheck.MinimumHourlyRate);\n rate = -1m; // set the rate to an out of bounds value because the TryParse call may have returned false\n }\n } while (rate < Paycheck.MinimumHourlyRate);\n return rate;\n}\n</code></pre>\n\n<p><strong>Do not let objects be created in an invalid state:</strong> This is not always possible to achieve, but you have total control over this code. Your <code>PayCalculator</code> class has computed values for both gross and net pay. Neither of these values make sense with out an appropriate pay rate and number of hours. Therefore all constructors should take, at a minimum, these two values. This ensures that your <code>PayCalculator</code> does not get created in an invalid state.</p>\n\n<p><strong>Do not let objects become invalid:</strong> You should be checking that values are in range when being assigned. This is different than the validation mentioned earlier. For example negative hours make no sense in this program. You should throw an appropriate exception if someone tries to set the number of hours worked to a negative value:</p>\n\n<pre><code>decimal _numberOfHours;\npublic decimal NumberOfHours\n{\n get\n {\n return _numberOfHours;\n }\n set\n {\n if (value < 0)\n throw new ArgumentOutOfRangeException(\"NumberOfHours\", value, \"value cannot be less than zero\");\n }\n}\n</code></pre>\n\n<p>If you perform proper validation as discussed earlier, this exception should never be thrown. However, the whole point of exceptions is for exceptional situations that are not supposed to occur.</p>\n\n<p><strong>Principle of least astonishment:</strong> You have places in your code that assume a default value when the supplied value is out of range. For example, in the property setter of <code>payrate</code>:</p>\n\n<pre><code>if (value < 8.25)\n _payrate = 8.25m;\n</code></pre>\n\n<p>A user of your code that tries to assign 1.0m to the <code>payrate</code> property is not expecting that value to magically change to 8.25m. If you refer back to the example for the <code>NumberOfHours</code> property you will see that I am not defaulting a negative value to zero. I am throwing an exception. It is the user's responsibility to provide your <code>PayCalculator</code> class with valid values. In order to facilitate this you should be documenting your code. The <code>NumberOfHours</code> example property should clearly document that it will throw an exception if someone tries to assign a negative value to that property.</p>\n\n<p><strong>Conclusion</strong>\nThe items explained above should be carried beyond this program and taken into consideration for all programs that you write. They will make you a better programmer in the long run if you adopt them now.</p>\n\n<p>There are also a few other things in your code that are incorrect. Those are simply bugs in your code</p>\n\n<ul>\n<li><code>WithholdingRate</code> does not use its backing field</li>\n<li>You are using <code>Convert.ToInt32</code> for a <code>decimal</code> value</li>\n<li>using <code>Convert.ToInt32</code> or the correct <code>Convert.ToDecimal</code> function can throw exceptions if text is entered. You should code for that. I recommend using <code>decimal.TryParse</code> instead.</li>\n<li>the <code>payrate</code> property setter checks value < 8.25, 8.25 is going to be a double. <code>double</code> values can lose precision. It won't lose precision in the case of 8.25 but you should be doing 8.25m so that this problem does not arise</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T03:47:20.970",
"Id": "64108",
"Score": "1",
"body": "Very nice organization, and some great points. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T22:23:00.623",
"Id": "38138",
"ParentId": "38016",
"Score": "7"
}
},
{
"body": "<p>Not to detract from all the above useful posts but I don't think your code is going to work. Recommend you fix it (<strong>replace</strong> hours <strong>with _hours</strong> in the line indicated) so that it conforms to the \"code must work!\" guidelines in CodeReview</p>\n\n<pre><code>public decimal hours { \n get {\n if (hours < 1) { // <------------ Recursion?\n return 40;\n } else {\n return _hours;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:01:33.767",
"Id": "64089",
"Score": "0",
"body": "it does work, I tested it before I posted it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:11:08.627",
"Id": "64090",
"Score": "0",
"body": "Please explain how the recursive call to hours is going to make your code work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T00:13:51.713",
"Id": "64095",
"Score": "0",
"body": "it functions the way that I anticipated it would function, if the hours variable was less than 1 it would return 40 hours. otherwise it will return the value held in the hours variable. as pointed out by @ChrisWue it is a design flaw and not a functionality flaw. it will function but the design is bad, so it should be changed, and will be, but the code still works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T00:16:01.033",
"Id": "64096",
"Score": "0",
"body": "what I was intending on doing with this was to make sure that the edge cases were caught, so it should really be `if (hours < 0)` which would make total sense I think"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T01:51:06.910",
"Id": "64101",
"Score": "1",
"body": "PLEASE (I'm going to resort to begging now) pay attention to my comment in the code-snippet copied from your code. Your property is recursively calling itself. Stack overflow!!! You've evidently made changes to this posted code after you tested it as a simple copy-paste into my VS2012 IDE reveals this \"code will fail\" problem rather loudly.\nThis might help you understand what I'm getting at.\nhttp://stackoverflow.com/questions/12044505/how-to-make-a-property-set-itself-using-instead-of"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T03:53:58.157",
"Id": "64109",
"Score": "1",
"body": "I see what you are saying, it should be `_hours` instead of `hours`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:41:01.163",
"Id": "38456",
"ParentId": "38016",
"Score": "3"
}
},
{
"body": "<p>I made a small mistake in my Code that causes an issue when trying to edge test</p>\n\n<p>this code</p>\n\n<pre><code>public decimal hours { \n get {\n if (hours < 1) {\n return 40;\n } else {\n return _hours;\n }\n }\n set {\n _hours = value;\n }\n}\n</code></pre>\n\n<p>was changed to this</p>\n\n<pre><code>public decimal hours { \n get {\n if (_hours < 0) {\n return 40;\n } else {\n return _hours;\n }\n }\n set {\n _hours = value;\n }\n}\n</code></pre>\n\n<p>so that it doesn't crash when entering 0, and if something less than 0 is entered it automatically gives a default value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-05T20:55:34.837",
"Id": "62083",
"ParentId": "38016",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38138",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T06:50:20.523",
"Id": "38016",
"Score": "7",
"Tags": [
"c#",
"beginner"
],
"Title": "Follow up to Pay Rate Calculator"
}
|
38016
|
<p>I wanted to consolidate solutions to disparate problems into a single program. I am worried that there is a interface, command pattern, or dictionary solution to what will become a massive switch statement here. However, the main in this program is essentially a meta-program which would switch between the miniature programs that it links to.</p>
<pre><code>static void Main(string[] args)
{
int eulerNumber;
Console.WriteLine("Please enter the number of the Problem you want to solve.");
while (!int.TryParse(Console.ReadLine(), out eulerNumber))
{
Console.WriteLine("Please enter a valid number.");
Console.WriteLine();
Console.WriteLine("Please enter the number of the Problem you want to solve.");
}
switch (eulerNumber)
{
case 1:
//solve problem 1.
break;
case 2:
//solve problem 2.
break;
case 3:
//solve problem 3.
break;
etc. etc. etc.
}
}
</code></pre>
<p>This is not an elegant solution, but it seems to mirror the situation quite well, as I see it.</p>
<p>Should I scratch this approach? It seems to me to violate OCP but at the same time, it isn't chaotic, and isn't that much to keep track of, - just tack one more case onto the end, create a new class, and another problem is functional. Should I look into some other structure to make it easier to modify?</p>
|
[] |
[
{
"body": "<p>Instead of making one big program to solve all the problems, I would just make one program per problem. There is no logical connection between the Euler problems, so it's best to keep the solutions separate, too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:40:41.060",
"Id": "38021",
"ParentId": "38019",
"Score": "8"
}
},
{
"body": "<p>If I were to solve this, adding the new code to the switch seems to me like overkill.</p>\n\n<p>I would try writing an application that uses plugins in a searchable directory.\nThen you solve each problem in its own plugin and the main program just consists of the logic to find and execute the plugins.</p>\n\n<p>Of course to enhance finding the plugins there some possible designs:</p>\n\n<h2>Naming the plugin after the solved problem</h2>\n\n<p>Name the plugin file by a given structure so it is obvious which problem is solved:</p>\n\n<pre><code>ep-001.dll\nep-002.dll\n...\n</code></pre>\n\n<p>That has the problem of forbidding user defined names, however it offers efficiency in that you can directly load only the needed plugin if you know the number.</p>\n\n<h2>Give the plugin class a problemNumber function</h2>\n\n<p>The other solution is to give the plugin class (that you will need anyway for a common interface to query for the solution) a function that returns the problem number.\nThis allows for arbitrarily named plugins, but also for duplicates and has the disadvantage of loading all plugins that are there to see if the one containing the requested solution is there.</p>\n\n<p>Since you are not that much efficiency bound on this problem I would suggest the second alternative because it has a much nicer OO interface (IMHO).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T16:03:09.273",
"Id": "63274",
"Score": "0",
"body": "+1 this is definitively a great example where a plugin architecture works best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T06:29:53.633",
"Id": "63938",
"Score": "0",
"body": "Supposed to avoid thanks, but this is my first post so... I'll just revel in the interwebs. Yeah, it's overkill but student practicing for rl here. The thing that pulls these disparate problems together is the desire for accessibility."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T10:03:42.430",
"Id": "38024",
"ParentId": "38019",
"Score": "10"
}
},
{
"body": "<p>Not sure how to do it in C#, but if you don't want to change the names of the individual functions, I would recommend putting them in an indexed table. </p>\n\n<p>If you don't want to create individual functions for each problem, your current solution is probably the way to go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:05:23.110",
"Id": "38031",
"ParentId": "38019",
"Score": "0"
}
},
{
"body": "<p>I think a plugin architecture would be a little overkill unless you're interested in versioning or deploying the sub-modules separately. You haven't shown the sub-modules (the actual solvers) but I'd probably define an interface for them and then use a <code>Dictionary</code> instead of the <code>switch</code> statement. Really, it's pretty minor, but I see a couple of advantages of the <code>Dictionary</code>:</p>\n\n<ul>\n<li>You go from three lines for a new definition to a single line; this will start to make a difference after 10 or so sub-modules since you'll fit on the same screen</li>\n<li>It makes explicit that this main method is solely for determining the sub-module; the switch statement leaves room for other code, so it needs to be scanned when reading the code</li>\n<li>Since the dictionary is explicitly data, it'd be easier to abstract out later if you wanted</li>\n<li>You may want to inject other components into your sub-modules (such as a logger, or an abstracted input/output routine) and having a single init routine will make that easier.</li>\n</ul>\n\n<p>So, a quick implementation would be something like:</p>\n\n<pre><code>interface ISolver {\n void Solve();\n}\n\nclass EulerOne : ISolver {\n}\n\n\nstatic void Main(string[] args)\n{\n // Using a Func to allow a new copy and/or some custom init if needed\n Dictionary<int, Func<ISolver>> solvers = new Dictionary<int, Func<ISolver>>() {\n { 1, () => new EulerOne() },\n { 2, () => new EulerTwo() },\n { 3, () => new EulerThree() }\n };\n\n int eulerNumber;\n\n Console.WriteLine(\"Please enter the number of the Problem you want to solve.\");\n\n while (!int.TryParse(Console.ReadLine(), out eulerNumber))\n {\n Console.WriteLine(\"Please enter a valid number.\");\n Console.WriteLine();\n Console.WriteLine(\"Please enter the number of the Problem you want to solve.\");\n }\n\n var solverBuilder = solvers[eulerNumber];\n var solver = solverBuilder();\n solver.Solve();\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T11:55:37.403",
"Id": "63693",
"Score": "0",
"body": "`solvers` would be `solverBuilders` then, and the lost and lonely `_solver`, too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:36:48.237",
"Id": "38195",
"ParentId": "38019",
"Score": "3"
}
},
{
"body": "<p>I took advantage of the partial keyword.</p>\n\n<p>For example, Problem 21 would go into Question021.cs.</p>\n\n<pre><code> namespace ProjectEuler\n {\n partial class Questions\n {\n public void Question021()\n {\n Console.WriteLine(\"Question021: 42\");\n }\n }\n }\n</code></pre>\n\n<p>This way all your answers can go into their own file. I also started .cs file called Common that has all of my helper functions in it (generating primes, triangle numbers, Fibonacci sequence, etc) that all the questions can take advantage of.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-14T19:05:43.983",
"Id": "100963",
"ParentId": "38019",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:34:13.990",
"Id": "38019",
"Score": "5",
"Tags": [
"c#",
"beginner",
"programming-challenge"
],
"Title": "Solving Project Euler challenge"
}
|
38019
|
<p>Review this code for code quality.</p>
<pre><code><!DOCTYPE html>
<title>Email obfuscator</title>
<style>.email { unicode-bidi: bidi-override; direction: rtl; }</style>
<h1>Email obfuscator</h1>
<p>A kick-ass email obfuscator, inspired by <a href="http://mathiasbynens.be/demo/email-obfuscator#code">Mathias Bynens's <code>obfuscate_email()</code> PHP function</a>. This tool will encode (HTML) and/or reverse (CSS) any email address you enter, making it less vulnerable to spammers who use email harvesting software aka spambots.</p>
<h2>The output</h2>
<p id="preview">(preview will be shown here)</p>
<p><textarea id="output" rows="6" cols="60" onclick="this.select()"></textarea></p>
<h2>The input</h2>
<form name="OBFUSCATOR">
<p><label for="email">Email: <small>(enter the email address to be obfuscated)</small></label> <input type="text" id="email" size="28" autofocus></p>
<p><input id="encode" type="checkbox" checked> <label for="encode">Convert into HTML entities ("encode")</label></p>
<p><input id="reverse" type="checkbox"> <label for="reverse">Reverse using CSS</label></p>
<p><input id="link" type="checkbox"> <label for="link">Create HTML link</label></p>
<p><input type="button" value="Obfuscate This!" onclick="obfuscate_email()"></p>
</form>
<script>
function obfuscate_email() {
var email = document.OBFUSCATOR.email.value,
encodedEmail = "",
output = "";
if (!email) {
alert("Please enter an email address.");
} else {
if (document.OBFUSCATOR.reverse.checked) {
email = email.split("").reverse().join("");
output = "<span class=\"email\">";
}
if (document.OBFUSCATOR.encode.checked) {
for (var i = 0; i < email.length; i++) {
encodedEmail += "&#" + email.charCodeAt(i) + ";";
}
output += encodedEmail;
} else {
output += email;
}
if (document.OBFUSCATOR.reverse.checked) {
output += "</span>";
}
document.getElementById("output").value = document.OBFUSCATOR.link.checked ? "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;" + (document.OBFUSCATOR.encode.checked ? encodedEmail : email) + "\">" + output + "</a>" : output;
document.getElementById("preview").innerHTML = document.getElementById("output").value;
}
}
</script>
</code></pre>
|
[] |
[
{
"body": "<p>Your code has room for improvement,</p>\n\n<p>in top-bottom order:</p>\n\n<ul>\n<li>Your code is littered with DOM queries, I would suggest to group them all on top, they reduce comprehension speed</li>\n<li>Access elements through the form is considered old skool, always use getElementByID</li>\n<li>Adding a span around the email should be done in 1 go, it would be much cleaner</li>\n<li>You can determine the output in one shot, from the email address</li>\n<li>If continuing does not makes sense ( when email is blank ), return early, this will reduce <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">arrow coding</a></li>\n</ul>\n\n<p>If you apply all this you should end up with something like this:</p>\n\n<pre><code>function obfuscateEmail( )\n{\n var email = document.getElementById( 'email' ).value,\n encode = document.getElementById( 'encode' ).checked,\n reverse = document.getElementById( 'reverse' ).checked,\n link = document.getElementById( 'link' ).checked,\n output = document.getElementById( 'output' ),\n preview = document.getElementById('preview'),\n html = '',\n encodeEmail = '';\n\n if( !email ) {\n return alert('Please enter an email address.');\n }\n\n if( reverse ) {\n email = email.split('').reverse().join('');\n }\n if( encode ){\n for (var i = 0; i < email.length; i++) {\n encodeEmail += '&#' + email.charCodeAt(i) + ';';\n } \n email = encodeEmail;\n }\n\n html = reverse?( '<span class=\"email\">' + email + '</span>' ):email;\n\n output.value = link ? \"<a href=\\\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;\" + email + \"\\\">\" + html + \"</a>\" : html;\n preview.innerHTML = output.value; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T17:56:14.777",
"Id": "63283",
"Score": "0",
"body": "thanks for the answer. but I think you forget to replace `output` with `html` here - `link ? \"<a href=\\\"mailto:\" + email + \"\\\">\" + output + \"</a>\" : output`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T14:48:21.030",
"Id": "38032",
"ParentId": "38020",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T07:36:32.830",
"Id": "38020",
"Score": "4",
"Tags": [
"javascript",
"email"
],
"Title": "Email obfuscator"
}
|
38020
|
<p>Below is my first attempt at programming a Celsius to Fahrenheit converter in C# winforms. I'm looking for tips and advice on improving my style and what I can do to make the code more efficent/proper, or is it good as is? I apologize ahead of time if i've forgotten any details and would be happy to provide more upon request.</p>
<pre><code>namespace TemperatureConverter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Initalize the handler to allow use of only control/number characters.
this.txtCelsius.KeyPress += new KeyPressEventHandler(txtCelsius_KeyPress);
// Limits user's inpute to 5 characters max.
txtCelsius.MaxLength = 5;
// Prevents the user from resizing window.
this.FormBorderStyle = FormBorderStyle.FixedDialog;
}
// Main function. Converts the input into Fahrenheit and outputs to the targeted label.
private void btnConvert_Click(object sender, EventArgs e)
{
double C;
double F;
C = double.Parse(txtCelsius.Text);
F = C * 9 / 5 + 32;
lblFahrenheit.Text = F.ToString();
}
// Prevents user from entering anything other than Number and Control characters.
private void txtCelsius_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsControl(e.KeyChar) && !Char.IsNumber(e.KeyChar))
{
e.Handled = true;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T09:57:54.860",
"Id": "63256",
"Score": "3",
"body": "In this piece of code it does not really matter because it it so short, but if it were longer you should start avoiding one letter variables and given them proper names like `celciusValue`, `fahrenheitValue` and `eventArgs`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T17:22:15.343",
"Id": "63281",
"Score": "4",
"body": "`e` is a pretty typical name for the `eventArgs` argument. I think .NET may even default to it under some circumstances. Doesn't mean it isn't worth changing, but it *is* a convention."
}
] |
[
{
"body": "<p>The main change is separation of logic and User Interface. Firstly the calculation methods should ideally not reside in UI methods like event handlers.</p>\n\n<p>Secondly the calculations should really be in it's own class, (but this application is just small enough that it is not ENTIRELY necessary).</p>\n\n<hr>\n\n<p>in programming we hate <a href=\"http://www.techrepublic.com/article/avoid-using-magic-numbers-and-string-literals-in-your-code/\">Magic Numbers</a>. If you can, move any numbers littered around your code and name them something useful. </p>\n\n<p>so:</p>\n\n<p>As <code>9/5 + 32</code> is equal to <strong>1.8 (+32)</strong> and that number represents the scale difference, if we declare that at the top of our code like</p>\n\n<pre><code>double FAHRENEHEIT_SCALE_DIFFERENCE = 1.8; \ndouble FREEZING_POINT_OF_WATER = 32;\n</code></pre>\n\n<p>Depending on how much you have covered thus far you should then move the actual conversion to it's own method. </p>\n\n<p>(because if you come back to this code in 12-18months will you be able to remember what it does? What if it quadruples in size with more features?</p>\n\n<p>So:</p>\n\n<p>I would suggest something along the lines of</p>\n\n<pre><code>public double convertCelsiusToFahrenheit(double celsius)\n{\n return celsius * FAHRENEHEIT_SCALE_DIFFERENCE + FREEZING_POINT_OF_WATER;\n}\n</code></pre>\n\n<p>Next, \nyou can tidy the button click.</p>\n\n<pre><code>private void btnConvert_Click(object sender, EventArgs e)\n{\n double celsius = double.Parse(txtCelsius.Text);\n lblFahrenheit.Text = convertCelsiusToFahrenheit(celsius);\n}\n</code></pre>\n\n<hr>\n\n<p>Finally the golden change is the separation of the logic from the interface.</p>\n\n<p>Now that you have a simple method that is separate from the actual screen; you could move it, and all similar methods into it's own <code>TemperatureConverter</code> class, or something similar.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T09:52:31.587",
"Id": "63255",
"Score": "5",
"body": "Your refactoring is broken - check the conversion in the original code (hint: `a * b + c` is not the same as `a * (b + c)`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T15:29:07.157",
"Id": "63272",
"Score": "1",
"body": "I think your constants have unfortunate names, though. `FAHRENEHEIT_SCALE_DIFFERENCE` should be `CELSIUS_TO_FAHRENHEIT_FACTOR` (remove the typo in Fahrenheit, include Celsius, and it’s not a difference, but a factor), and `FREEZING_POINT_OF_WATER` – in most of the world, a constant of that name would be either 0 or 273.15. I think I’d use `CELSIUS_TO_FAHRENHEIT_OFFSET`. Just my 2 cents, of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T17:24:11.310",
"Id": "63282",
"Score": "1",
"body": "You should use `decimal.TryParse()` instead. What if the user asks to convert `five` or `50C`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T17:58:56.723",
"Id": "63284",
"Score": "1",
"body": "SCREAMING_CAPS is not in favor as constant naming convention for C#. They should be PascalCased, e.g. `FahrenheitScaleDifference` and `FreezingPointOfWater`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T03:49:35.143",
"Id": "64296",
"Score": "0",
"body": "@JesseC.Slicer I disagree, SCREAMING_CAPS is to my eye's considerably cleaner given the propensity to PascalCase Public properties. Consts are rather a separate concept and should be marked as such."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T03:53:28.027",
"Id": "64297",
"Score": "0",
"body": "@Bobson most definitely but that borders on premature optimization. There are many other changes I would also make regarding input sanitization but I felt they were out of scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T04:49:43.820",
"Id": "64298",
"Score": "0",
"body": "@apieceoffruit to each their own, of course, but it's not current convention. See this answer: http://stackoverflow.com/a/242549/3312"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T05:03:36.403",
"Id": "64299",
"Score": "0",
"body": "@JesseC.Slicer yeah, for this very reason I have taken stylecop off my VS required app list and instead use custom Resharper settings. I also remove the preceding I in front facing interfaces. \n\nIf you haven't I suggest reading bob martin's clean code.\n\nIt's not gospel or anything but it makes you think of the point/relevance of standards.\n\n(although I still love my occasional closing brace comment...)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T09:32:10.877",
"Id": "38023",
"ParentId": "38022",
"Score": "14"
}
},
{
"body": "<p>Here's how I would encapsulate the logic:</p>\n\n<pre><code>public interface ITemperature\n{\n double Temperature\n {\n get;\n }\n}\n\npublic interface ITemperatureConverter<in T, out U> where T: ITemperature where U: ITemperature\n{\n U Convert(T temperature);\n}\n\npublic abstract class TemperatureBase : ITemperature\n{\n private readonly double temperature;\n\n protected TemperatureBase(double temperature)\n {\n this.temperature = temperature;\n }\n\n public double Temperature\n {\n get\n {\n return this.temperature;\n }\n }\n}\n\npublic sealed class Fahrenheit : TemperatureBase\n{\n public Fahrenheit(double temperature) : base(temperature)\n {\n }\n\n public static implicit operator Fahrenheit(double temperature)\n {\n return new Fahrenheit(temperature);\n }\n\n public override string ToString()\n {\n return this.Temperature + \"F\";\n }\n}\n\npublic sealed class Celsius : TemperatureBase\n{\n public Celsius(double temperature) : base(temperature)\n {\n }\n\n public static implicit operator Celsius(double temperature)\n {\n return new Celsius(temperature);\n }\n\n public override string ToString()\n {\n return this.Temperature + \"C\";\n }\n}\n\npublic sealed class FahrenheitToCelsiusConverter : ITemperatureConverter<Fahrenheit, Celsius>\n{\n public Celsius Convert(Fahrenheit temperature)\n {\n if (temperature == null)\n {\n throw new ArgumentNullException(\"temperature\");\n }\n\n return new Celsius((5f / 9f) * (temperature.Temperature - 32f));\n }\n}\n\npublic sealed class CelsiusToFahrenheitConverter : ITemperatureConverter<Celsius, Fahrenheit>\n{\n public Fahrenheit Convert(Celsius temperature)\n {\n if (temperature == null)\n {\n throw new ArgumentNullException(\"temperature\");\n }\n\n return new Fahrenheit(temperature.Temperature * (9f / 5f) + 32f);\n }\n}\n</code></pre>\n\n<p>Your UI code then becomes:</p>\n\n<pre><code>private readonly CelsiusToFahrenheitConverter celsiusToFahrenheitConverter = new CelsiusToFahrenheitConverter();\n\nprivate void btnConvert_Click(object sender, EventArgs e)\n{\n lblFahrenheit.Text = celsiusToFahrenheitConverter.Convert(double.Parse(txtCelsius.Text));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T20:40:40.183",
"Id": "63300",
"Score": "1",
"body": "This feels like serious overkill for the given problem-statement, but, if you are going to go this far, why not take it the full-monty, throw in a Kelvin converter, and then you only need to have a MyUnit-Kelvin converter, and you can then ue any unit you want. The Model you suggest here could be the basis of that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:26:12.320",
"Id": "63309",
"Score": "0",
"body": "Couldn't agree more! But the problem at hand only needed C -> F. More can be created pretty easily."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T18:45:54.953",
"Id": "38040",
"ParentId": "38022",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38023",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T08:03:19.393",
"Id": "38022",
"Score": "16",
"Tags": [
"c#",
"winforms",
"converting"
],
"Title": "Simple temperature converter"
}
|
38022
|
<p>I have started learning about SOLID principles yesterday. I've got a detailed explanation of SOLID principles <a href="http://cre8ivethought.com/blog/2011/08/23/software-development-is-not-a-jenga-game" rel="nofollow noreferrer">here</a>. After reading it, and a few other articles, I have tried to apply these principles in one of my projects.</p>
<p>This is a tool for importing data from another system. Requirements are as follows:</p>
<ol>
<li>Read some settings from SQL Server database.</li>
<li>Call an external system API with read settings.</li>
<li>API returns the result in Json format.</li>
<li>Returned results should be saved in SQL Server Database.</li>
</ol>
<p><strong>Following code sample is in C# with Asp.Net</strong></p>
<p>I have a form that initiates the import process on a button's click event.</p>
<pre><code>private void btnStart_Click(object sender, EventArgs e)
{
IReader _reader = new DBReader();
Interfaces.IWriter _writer = new Classes.DBWriter();
Interfaces.IExternalSystemInteraction _externalSystem = new Classes.JSonExternalSystem(_writer);
Classes.Client _client = new PxImportApplication.Classes.Client(_reader, _externalSystem);
_client.Invoke();
}
</code></pre>
<ul>
<li><p><code>DBReader</code> class inherits from <code>IReader</code> interface and does the job to read settings from SQL server database. We can create a new class if there is a requirement to read from MySQL database instead of SQLServer.</p>
</li>
<li><p>Similary <code>DBWriter</code> writes into SQL Server database and implements IWriter interface.</p>
</li>
<li><p><code>JSonExternalSystem</code> class hits the API and reads data into Json format. IWriter interface instance is passed to get the Json data so that it could write that data into the SQL Server DB.</p>
</li>
</ul>
<p>Client class has the following implementation:</p>
<pre><code>class Client
{
private IReader _reader;
private Interfaces.IExternalSystemInteraction _externalSystemInformation;
public Client(IReader reader, Interfaces.IExternalSystemInteraction externalSystem)
{
_reader = reader;
_externalSystemInformation = externalSystem;
}
public void Invoke()
{
List<IProperties> lstProperties = _reader.ReadData();
_externalSystemInformation.HitAPI(lstProperties);
}
}
</code></pre>
<p>JSONExternalSystem's implementation is as follows:</p>
<pre><code>class JSonExternalSystem : Interfaces.IExternalSystemInteraction
{
private Interfaces.IWriter _writer;
public JSonExternalSystem(Interfaces.IWriter writer)
{
_writer = writer;
}
#region IExternalSystemInteraction Members
public void HitAPI(List<IProperties> properties)
{
foreach (IProperties property in properties)
{
ReadJsonFormat(property.Xproperty);
_writer.ImportToDataBase();
}
}
}
</code></pre>
<p>My question is: By looking at this much code, do you think that I am on the right way to implement SOLID principles? I know that this doesn't show the whole implementation but most of the code for other classes goes more or less like the above given classes. I am sure I must be lacking somewhere as this is just my second day. Kindly correct me.</p>
|
[] |
[
{
"body": "<p>When you say <em>I have a form that initiates import process on a button's click event</em>, you've coupled your UI with some \"business logic\". Let's look at that <code>Click</code> handler:</p>\n\n<blockquote>\n<pre><code>private void btnStart_Click(object sender, EventArgs e)\n {\n IReader _reader = new DBReader();\n Interfaces.IWriter _writer = new Classes.DBWriter();\n\n Interfaces.IExternalSystemInteraction _externalSystem = new Classes.JSonExternalSystem(_writer);\n\n Classes.Client _client = new PxImportApplication.Classes.Client(_reader, _externalSystem);\n _client.Invoke();\n }\n</code></pre>\n</blockquote>\n\n<p><strong>Naming</strong></p>\n\n<p>This method handles the click of a button, I'd infer a button named <code>btnStart</code> and say that the naming convention you're using for control names is breaking the naming convention for method names - how about naming the button <code>StartButton</code> and handle the <code>Click</code> event in a <code>StartButton_Click</code>, or <code>OnStartButtonClick</code> method? In my opinion the reasons why <em>btnStart</em> is a bad name would be something like:</p>\n\n<ul>\n<li><em>Hungarian Notation</em> is used, \"btn\" being a short for <code>Button</code>, which is a type.</li>\n<li><em>Disemvoweling</em> turned \"button\" into \"btn\".</li>\n<li><em>camelCase</em> breaks the <em>PascalCase</em> convention for naming methods, because the convention for event handlers is <code>void [objectName]_[eventName](object sender, EventArgs e)</code>.</li>\n</ul>\n\n<p><strong>Type qualification</strong></p>\n\n<p>If, at the top of your code file, you added the following:</p>\n\n<pre><code>using PxImportApplication.Classes;\nusing PxImportApplication.Interfaces;\n</code></pre>\n\n<p>Your handler code could read like this:</p>\n\n<pre><code>private void btnStart_Click(object sender, EventArgs e)\n {\n var reader = new DBReader();\n var writer = new DBWriter();\n\n var externalSystem = new JSonExternalSystem(writer);\n\n var client = new Client(reader, externalSystem);\n client.Invoke();\n }\n</code></pre>\n\n<p>Fully-qualified types make the code harder to read. I noticed you used <code>_</code> in front of local variables; I prefer to use the underscore for private fields, if at all.</p>\n\n<p><strong>Dependencies</strong></p>\n\n<p>The problem with this approach, is that by instantiating that form you automatically get a <code>new DBReader</code> and a <code>new DBWriter</code>, with absolutely no way of swapping these two with a mock implementation - actually you don't really have another way of testing this piece of logic, other than <kbd>F5</kbd> and run the thing and click the button and see how it goes.</p>\n\n<p>In fact, the UI is <em>tightly coupled</em> with the <code>DBReader</code>, <code>DBWriter</code> (which should be <code>DbReader</code> and <code>DbWriter</code>), <code>Client</code> and <code>JSonExternalSystem</code>. Whenever you <code>new</code> up something, you've identified a <em>dependency</em>. Most classes of the .net framework are ok to instantiate on the fly like this, other dependencies should be clearly stated, in the form's constructor. Keep the parameterless default constructor so that you won't break the designer, but make another that takes all other dependencies. Too many (4? 5? 6? Your call!) constructor parameters (/dependencies) is a sign that your class is starting to break the <em>Single Responsibility Principle</em>.</p>\n\n<p>I think the form is doing much more than just <em>being a UI</em> here, and the dependencies really are, is dependencies of another type, namely <code>PxImportApplication.Classes.Client</code>.</p>\n\n<p>What the button really needs to do, is instantiate a <code>Client</code> and call the <code>Invoke()</code> method (a confusing name that breaks POLS, <code>Invoke</code> is .net lingo for synchroneously calling a delegate). All this <code>new</code>ing up is covering-up the real intent. How about having a click handler doing this:</p>\n\n<pre><code>private void btnStart_Click(object sender, EventArgs e)\n{\n var client = _clientFactory.Create();\n client.Invoke(); // todo: rename this method\n}\n</code></pre>\n\n<p>This code means the handler now only <em>depends</em> on a <code>_clientFactory</code> private field:</p>\n\n<pre><code>private readonly IFactory _clientFactory;\n</code></pre>\n\n<p>And this field can be instantiated from the form's parameterized constructor:</p>\n\n<pre><code>public Form1(IFactory clientFactory) : this()\n{\n _clientFactory = clientFactory;\n}\n</code></pre>\n\n<p>The factory class has its own dependencies:</p>\n\n<pre><code>private readonly IReader _reader;\nprivate readonly IExternalSystemInteraction _externalSystem;\n\npublic ClientFactory(IReader reader, IExternalSystemInteraction externalSystem)\n{\n _reader = reader;\n _externalSystem = externalSystem;\n}\n\npublic IClient Create()\n{\n return new Client(_reader, _externalSystem);\n}\n</code></pre>\n\n<p>The <code>ClientFactory</code> class <em>implements</em> the <code>IFactory</code> interface, which simply exposes a parameterless <code>Create()</code> method - and that's everything the form needs to know.</p>\n\n<hr>\n\n<p>Your constructor-injected private fields can be made <code>readonly</code> in both <code>Client</code> and <code>JSonExternalSystem</code> classes (should be <code>JsonExternalSystem</code>). You're doing it right in these classes - don't do DI halfway though, do it all the way. Creating instances of types is the role of factory/infrastructure classes and of the application's <em>composition root</em>. If you're using an IoC container you don't have to resolve the dependencies yourself. This means if the <code>IReader</code> that the factory class takes has dependencies of its own, you don't need to bother with them; by <em>letting go</em> of the control you have over the types that a type can instantiate, your code becomes very focused, <em>cohesive</em>. <em>High cohesion, low coupling</em> is what you want to achieve.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T03:48:03.410",
"Id": "63463",
"Score": "0",
"body": "Ooh, I should have double-checked the tags before answering. I took \"form\" as in `System.Windows.Forms`... DI is a bit different in this case (because the *page* is your *composition root*), I'll edit my post accordingly when I have a chance, but most of it still stands. Just don't bother with \"the form's constructor\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T14:09:42.393",
"Id": "63904",
"Score": "0",
"body": "I read the points you mentioned carefully. Your point about high cohesion and low coupling is very true. I have two questions here: 1) As a programmer, how can I reduce the chances of breaking SRP, as you said above, \"Too many (4? 5? 6? Your call!) constructor parameters (/dependencies) is a sign that your class is starting to break the Single Responsibility Principle.\" 2) At some point of time I will need to initialize IReader reader = new DbReader();, somewhere. What should be that point ? For eg; In a windows application should I initialize it in Main() method of program.cs ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T17:40:31.343",
"Id": "63915",
"Score": "0",
"body": "Regarding 1, many times multiple dependencies are related and can be regrouped into one; 2, that should be as close as possible to your *composition root*.. but in asp.net that entry point isn't exactly as clear-cut as a `Main()` method would be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T07:51:22.953",
"Id": "63942",
"Score": "0",
"body": "So I guess idea is to keep those points to minimum where we need to initialize objects of a particular type. Right ?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T03:08:24.730",
"Id": "38147",
"ParentId": "38035",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-12-24T16:10:11.300",
"Id": "38035",
"Score": "5",
"Tags": [
"c#",
"design-patterns",
"asp.net"
],
"Title": "Implementing SOLID Principles with C# Asp.net"
}
|
38035
|
<p>As a challenge to myself, I wrote a solution to <a href="https://stackoverflow.com/questions/20763678/convert-list-of-list-tree-to-dict">this Stack Overflow question</a>. For completeness, the bulk of the question is as follows:</p>
<h2>Problem</h2>
<p>Input:</p>
<pre><code>[
['key1', 'value1'],
['key2',
[
['key3', 'value3'],
['key4',
[
...
]
],
['key5', 'value5']
]
],
['key6', 'value6'],
]
</code></pre>
<p>Ouput:</p>
<pre><code>{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": ...,
"key5": "value5"
},
"key6": "value6"
}
</code></pre>
<h2>Solution</h2>
<p>Please note that this is my first attempt.</p>
<pre><code>import pprint
def main():
lt = [ \
['key1', 'value1'], \
['key2', \
[ \
['key3', 'value3'], \
['key4', \
['key7','value7'] \
], \
['key5', 'value5'] \
] \
], \
['key6', 'value6'] \
]
print('Input:')
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(lt)
dt = lists2dict(lt, pp)
print('-' * 80)
print('Output:')
pp.pprint(dt)
def lists2dict(lt, pp):
# form a dict from a list of lists,
# if a key's value is a single-element list, just add the element
dt = {l[0]: l[1:] if len(l[1:]) > 1 else l[1] for l in lt}
# print('-' * 70)
# pp.pprint(dt)
for k,v in dt.items(): # step through the dict, looking for places to recurse
# print('k=%r, v=%r' %(k,v))
if isinstance(v, list): # a value which is a list needs to be converted to a dict
if isinstance(v[1], list): # only recurse if a to-be-parsed value has a list
dt[k] = lists2dict(v, pp)
else: # just a single k/v pair to parse
dt[k] = {v[0]: v[1]}
return dt
if __name__ == '__main__':
main()
</code></pre>
<p>If anyone has improvements, or a more efficient and/or Pythonic implementation, please share it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T18:40:45.667",
"Id": "63289",
"Score": "2",
"body": "Argh! All the `\\ ` you are using when defining the input are *useless*. Also you should **never** us `\\ ` to continue a line since you can wrap whatever expression you are writing in parenthesis `(` and `)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:28:15.167",
"Id": "63443",
"Score": "0",
"body": "All brackets in Python (`(`, `[`, and `{`) begin implicit line continuation. There is no need to use `\\` to continue a line so long as it's enclosed in a pair of matching brackets."
}
] |
[
{
"body": "<p>You could simplify your function:</p>\n\n<pre><code>def nested_pairs2dict(pairs):\n d = {}\n for k, v in pairs:\n if isinstance(v, list): # assumes v is also list of pairs\n v = nested_pairs2dict(v)\n d[k] = v\n return d\n</code></pre>\n\n<p><a href=\"http://ideone.com/V0tVFN\">It seems to work</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T21:13:15.790",
"Id": "63302",
"Score": "0",
"body": "You could also shorten it further to [`def nested_pairs2dict(pairs):\n return dict((k, nested_pairs2dict(v) if isinstance(v, list) else v) for k, v in pairs)`](http://ideone.com/DHU1FM)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T21:14:24.213",
"Id": "63303",
"Score": "3",
"body": "@200_success: I find such one-liners less readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T21:41:02.383",
"Id": "63305",
"Score": "0",
"body": "Locally I get an error: `for k,v in pairs // ValueError: too many values to unpack`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:33:19.420",
"Id": "63310",
"Score": "0",
"body": "@kevlar1818 Then you are not passing a list of 2-element lists to the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T01:29:51.143",
"Id": "63322",
"Score": "0",
"body": "I'd also stick with the full version for long term maintenance. This example illustrates a great python principle: doing it right is usually shorter and cleaner than doing it wrong :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T20:26:32.270",
"Id": "38043",
"ParentId": "38038",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "38043",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T18:06:40.863",
"Id": "38038",
"Score": "4",
"Tags": [
"python",
"recursion",
"hash-map"
],
"Title": "Recursively convert a list of lists into a dict of dicts"
}
|
38038
|
<p>I don't like to post programming contest code in here, but I really like the question and want to share it with you all.</p>
<blockquote>
<p>It has been years since Superman started his enmity with the
super-genius Lex Luthor. After years of intense battle, Luthor finally
decides to end it all by going into the past and capturing Superman
the moment he lands on Earth. Using the time warp machine that he
built, Luthor goes back in time. Superman, wanting to thwart his evil
intentions, asks The Flash to push him back into time by breaking the
time barrier.</p>
<p>The Flash obliges and throws Superman back in time. But Superman
senses that something is fishy and the Earth doesn't feel the same.
After an hour of intense detective work (which he isn’t used to) he
finds out that he has been sent into a parallel anti-universe where
everything is reverse to that of our Universe. Looking at his watch,
Superman realizes that he'll first need to correct the time on his
watch in order to reach Kansas, the place where his ship landed, on
time.</p>
<p>Superman, not being as smart as you, asks for your help in fixing the
time on his watch. You know that the actual time on the other
anti-Universe is the mirror image of the time on Superman's watch,
considering the mirror to be a vertical line running from 12 to 6 on
the watch.</p>
<p><em>INPUT</em></p>
<p>The first line contains an integer <em>T</em>, denoting the number of test
cases. <em>T</em> lines follow with the time given in the 12-hour format: HH:MM
am/pm</p>
<p><em>OUTPUT</em></p>
<p>The output should consist of <em>T</em> lines with the mirrored time of each
test case in the 12-hour format: HH:MM am/pm</p>
<p><em>SAMPLE I/O</em></p>
<p><strong>Input</strong></p>
<pre><code>3
05:00 am
06:00 pm
03:15 pm
</code></pre>
<p><strong>Output</strong></p>
<pre><code>07:00 pm
06:00 am
08:45 am
</code></pre>
</blockquote>
<p><strong>TL;DR</strong></p>
<p>You will be given a time as <code>XX:XX am/pm</code> (12 hour format) and you have to print the time that you will see if you hold the analog clock beside the mirror.</p>
<p><em>A picture worth thousands words</em></p>
<p><img src="https://i.stack.imgur.com/MoXrT.gif" alt="enter image description here"></p>
<pre><code>package foo.competition;
import java.util.Scanner;
public class Parallel {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
// number of testcases
int t = input.nextInt();
// feeding newline
input.nextLine();
while(t-- > 0) {
String actualTime = input.nextLine();
String parallelUniverseTime = parallelUniverseTime(actualTime);
System.out.println(parallelUniverseTime);
}
}
}
/**
*
* @param actualTimeStamp - actual time. format XX.XX am/pm (12 hour clock)
* @return - a String formatted as "XX:XX am/pm" as the time in parallel universe
*/
public static String parallelUniverseTime(String actualTimeStamp) {
String []time = parseTimeAndReturnAsArray(actualTimeStamp);
String mirrorHour = mirroredHour(time[0], time[1]);
String mirrorMinute = mirroredMinute(time[1]);
String mirrorMedian = mirroredMedian(time[2]);
return formattedMirroredTime(mirrorHour, mirrorMinute, mirrorMedian);
}
/**
*
* @param timeStamp - actual time. format XX:XX am/pm (12 hour clock)
* @return - an array as {hour, minute, median}
*/
private static String[] parseTimeAndReturnAsArray(String timeStamp) {
// timeStamp example - "07:30 pm"
String hour = timeStamp.charAt(0) + "" + timeStamp.charAt(1);
String minute = timeStamp.charAt(3) + "" + timeStamp.charAt(4);
String median = timeStamp.charAt(6) + "" + timeStamp.charAt(7);
return new String[]{hour, minute, median};
}
private static String mirroredHour(final String hour, final String minute) {
String hourAndMinute = hour + ":" + minute;
if(hourAndMinute.equals("12:00") || hourAndMinute.equals("06:00")) {
return hour;
}
final int minuteAsInt = Integer.parseInt(minute);
final int hourAsInt = Integer.parseInt(hour);
// after 12 min the hour hand moves one place
// so before XX:12 the mirrored hour will be (12 - hour)
if(minuteAsInt < 12) {
return (12 - hourAsInt) + "";
}
// otherwise hour hand already moved so mirrored hour hand
// will near to 6.
else {
return (12 - hourAsInt - 1) + "";
}
}
private static String mirroredMinute(final String minute) {
if(minute.equals("00")) {
return minute;
}
final int minuteAsInt = Integer.parseInt(minute);
// return the mirrored minute hand
return (60 - minuteAsInt) + "";
}
private static String mirroredMedian(final String median) {
if(median.equals("am")) return "pm";
else return "am";
}
private static String formattedMirroredTime(String hour, String minute, String median) {
if(hour.length() == 1) { hour = "0" + hour; }
return (hour + ":" + minute + " " + median);
}
}
</code></pre>
<p>There are many pitfalls of the code:</p>
<ol>
<li>I didn't handle the user input error case. </li>
<li>All methods are static and in under one class.</li>
<li>Bad documentation.</li>
</ol>
<p>and many more...</p>
<p>But I wrote the <strong>whole</strong> code under 1 hour, so I'd like to get a review my code as I wrote the first time. All kind of reviewing and criticization are welcomed.</p>
<p>I didn't find any bugs in my code, but if you find any, please comment.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T21:39:24.907",
"Id": "63304",
"Score": "0",
"body": "One thing I found out : `median` should be `meridiem` or `period`."
}
] |
[
{
"body": "<p>For writing all of that in under an hour you should feel pretty good about yourself (with partial documentation to boot!). Here are some things I found though:</p>\n\n<hr>\n\n<p>You currently <a href=\"https://stackoverflow.com/a/2125337/1937270\">aren't following Java package naming standards</a>.</p>\n\n<pre><code>package com.foo.competition;\n</code></pre>\n\n<hr>\n\n<p>The <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29\" rel=\"nofollow noreferrer\"><code>Scanner.nextInt()</code></a> method does not read the <em>last newline</em> character of your input, and thus a <em>newline</em> could be consumed if you call <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29\" rel=\"nofollow noreferrer\"><code>Scanner.nextLine</code></a>. I prefer to use <code>Scanner.nextLine</code> since you can input any valid <code>String</code>, and then just parse it into the type you need (as long as it's a valid type to parse it to).</p>\n\n<p>I would be especially wary of this since you have multiple <code>.nextInt()</code> and <code>.nextLine()</code> method calls scattered throughout your code.</p>\n\n<pre><code>int t = Integer.parseInt(input.nextLine());\n</code></pre>\n\n<hr>\n\n<p>You aren't consistent in your <code>if</code> condition statements. You should choose a way to write with them and stick with it so you don't confuse yourself and other people reading your code.</p>\n\n<pre><code>if(minute.equals(\"00\")) {\n return minute;\n}\n...\nif(median.equals(\"am\")) return \"pm\";\n...\nif(hour.length() == 1) { hour = \"0\" + hour; }\n</code></pre>\n\n<hr>\n\n<p>There is an <code>if</code> condition statement that you have on one line, with braces. You don't really need those braces since if you added another statement to the condition, it would be pretty noticeable and you would add braces anyways. You already did this for one of your <code>if</code> condition statements anyways.</p>\n\n<pre><code>if(hour.length() == 1) { hour = \"0\" + hour; }\n\nif(median.equals(\"am\")) return \"pm\";\n</code></pre>\n\n<hr>\n\n<p>This is more of a nitpick, but I don't like how you are declaring arrays with a space in-between the object and and the brackets. It is a <code>String</code> array with the variable name <code>time</code>. But keeping it that way is up to you.</p>\n\n<pre><code>String []time = parseTimeAndReturnAsArray(actualTimeStamp);\n\nString[] time = parseTimeAndReturnAsArray(actualTimeStamp);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T21:49:52.447",
"Id": "63306",
"Score": "0",
"body": "Yes inconsistency of `if` blocks, I didn't notice that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T21:46:52.753",
"Id": "38046",
"ParentId": "38044",
"Score": "8"
}
},
{
"body": "<p>You're working too hard.</p>\n\n<p>Parsing is easier using a regular expression (<code>import java.util.regex.*</code>).</p>\n\n<p>Figuring out the mirrored time is easier if you convert everything into minutes first. Then the code would model how an analog clock works. You don't want your code to be littered with special cases.</p>\n\n<p>Formatting the output is easier using <code>String.format()</code>.</p>\n\n<pre><code>private static final int MINUTES_PER_HALF_DAY = 12 * 60;\n\nprivate static final Pattern TIME_FMT = Pattern.compile(\n \"(0?[1-9]|1[0-2])\" + // Group 1: Hour 01-12 (optional leading zero)\n \":\" + // colon\n \"([0-5]\\\\d)\" + // Group 2: Minute 00-59 (0-5 followed by any 2nd digit)\n \"\\\\s*\" + // optional whitespace\n \"([ap]m)\" // Group 3: am or pm\n , Pattern.CASE_INSENSITIVE);\n\npublic static String parallelUniverseTime(String time) {\n Matcher m = TIME_FMT.matcher(time);\n if (!m.matches()) {\n return null;\n }\n\n // Hour as an int, but mapping \"12\" to 0\n int hour = Integer.parseInt(m.group(1)) % 12;\n int minute = Integer.parseInt(m.group(2));\n String ampm = m.group(3).toLowerCase();\n\n int minutes = 60 * hour + minute;\n\n // ^^^ Normal universe ^^^\n // ** WARP! **\n // vvv Parallel universe vvv\n\n minutes = MINUTES_PER_HALF_DAY - minutes;\n\n // Likely 0 ≤ hour < 12, but possibly hour = 12 if minutes == 0.\n // We'll canonicalize hour = 0 and hour = 12 to \"12\" on output.\n hour = minutes / 60;\n minute = minutes % 60;\n ampm = (\"pm\".equals(ampm)) ? \"am\" : \"pm\";\n\n return String.format(\"%02d:%02d %s\", (hour == 0 ? 12 : hour), minute, ampm);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T00:04:42.980",
"Id": "63315",
"Score": "0",
"body": "Very nice (+1), but there is one exception I would point out with using regex for parsing; [don't do it with HTML](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-reg?lq=1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T07:21:37.850",
"Id": "63339",
"Score": "0",
"body": "Your `am`/`pm` is wrong for `12:00`. Noon and midnight should map to itself. You should always test for edge cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T08:46:18.977",
"Id": "63341",
"Score": "0",
"body": "@abuzittingillifirca I did consider noon and midnight. The challenge description was ambiguous on how they should be handled, so I opted to stay compatible with the OP's code. If you want noon and midnight to map to themselves, it's even easier: calculate minutes using a 24-hour clock, and subtract it from `MINUTES_PER_DAY` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T11:35:56.003",
"Id": "63346",
"Score": "1",
"body": "@200_success Well I don't like [regular expression](http://xkcd.com/1171/)! But can you explain *how* are you using regex? And what is the ambiguousness in the question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T11:36:56.633",
"Id": "63348",
"Score": "0",
"body": "@abuzittingillifirca Yes in a [12 hour clock] `12:00 am` mirrored time will be `12:00 pm` and vice versa."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T11:45:39.007",
"Id": "63351",
"Score": "0",
"body": "@200_success also I didn't get `int hour = Integer.parseInt(m.group(1)) % 12`, as the format is `12 hour` clock `hour` will be always between `0-12`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T12:35:27.540",
"Id": "63355",
"Score": "0",
"body": "@tintinmj No. And incidentally this is true for both 24h and 12h am/pm clock. But suit yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T12:44:33.387",
"Id": "63357",
"Score": "0",
"body": "@abuzittingillifirca see the table at right side http://en.wikipedia.org/wiki/24-hour_clock."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T08:14:32.053",
"Id": "63407",
"Score": "0",
"body": "@abuzittingillifirca I think you're right after all: noon and midnight should map to themselves. See my [revised answer](http://codereview.stackexchange.com/a/38103/9357)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:43:35.423",
"Id": "38051",
"ParentId": "38044",
"Score": "6"
}
},
{
"body": "<p>I found some <strong>major</strong> bugs in my code <strike> and also in <a href=\"https://codereview.stackexchange.com/a/38051/26200\">200_success's code</a></strike>. Since bug-determining and killing also a part of <em>code-review</em> I want to post this as an answer not as a comment. I think it's OK? right?</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code> Input Correct output My output 200_success's output [No bugs found]\n\n 12:01 am 11:59 pm 00:59 pm x 11:59 pm \n 11:32 am 12:28 pm 00:28 pm x 12:28 pm\n 12:34 am 11:26 pm -1:26 pm x 11:26 pm\n 06:01 am 05:59 pm 06:59 pm x 05:59 pm \n 11:02 am 12:58 pm 01:58 pm x 12:58 pm\n 12:59 am 11:01 pm -1:1 pm x 11:01 pm\n</code></pre>\n</blockquote>\n\n<p><code>x</code> is marked as wrong output.</p>\n\n\n\n<p>So in my code the line</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> if(minuteAsInt < 12) {\n return (12 - hourAsInt) + \"\";\n }\n</code></pre>\n\n<p>is making all kind of troubles. When I wrote the code, I made a theoretical assumption which doesn't stand in practical usage. What I thought was that</p>\n\n<p><img src=\"https://i.stack.imgur.com/W15M2.jpg\" alt=\"enter image description here\"></p>\n\n<p>If the hour hand travels 30° in 60 minutes, then it will travel 6° in 12 minutes. So after <code>XX:12</code> the hour hand will move. </p>\n\n<p>But in practical cases we assume that hour hand moves continuously after <code>XX:00</code>.</p>\n\n<p>Also there are corner cases for <code>12:XX</code> and <code>11:XX</code>. As <code>12 - hourAsInt - 1</code> will give <code>-ve</code> or <code>00:XX</code> value respectively.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:38:26.303",
"Id": "63383",
"Score": "0",
"body": "The *hours* hand might be moving continuously. Depends on the model of the clock ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:50:28.217",
"Id": "63386",
"Score": "0",
"body": "@retailcoder he he now I've to find Clark K.. oops, Superman to see his clock model ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T13:47:33.567",
"Id": "38068",
"ParentId": "38044",
"Score": "6"
}
},
{
"body": "<p>The challenge states that Parallel Universe Time is Normal Time, mirrored on the vertical axis of an analog clock; the examples suggest that AM/PM should be swapped. I initially found it ambiguous how noon and midnight should be treated, and assumed that 12:00 am should map to 12:00 pm and <em>vice versa</em>, consistent with @tintinmj's original code.</p>\n\n<p>However, on further thought, I believe <a href=\"/questions/38044/putparallel-universe-time-generator/38051#comment63339_38051\">@abuzittingillifirca is right</a>, that noon should map to noon and midnight should map to midnight. Consider the following diagram of the mapping. The blue lines are undisputed (for example, 1 am ⟷ 11 pm). By a continuity argument, it's more plausible that noon and midnight should be fixed points of the transformation (red lines).</p>\n\n<p><img src=\"https://i.stack.imgur.com/M09sn.png\" alt=\"Mapping of Normal Time to Parallel Universe Time\"></p>\n\n<p>Here is the revised code to implement that.</p>\n\n<pre><code>private static final Pattern TIME_FMT = Pattern.compile(\"(0?[1-9]|1[0-2]):([0-5]\\\\d)\\\\s*([ap]m)\");\nprivate static final int MINUTES_PER_DAY = 24 * 60;\n\n/**\n * Parses time as minutes since midnight.\n */\nprivate static int parse(String time) {\n Matcher m = TIME_FMT.matcher(time);\n if (!m.matches()) {\n throw new IllegalArgumentException(time);\n }\n\n int hour = Integer.parseInt(m.group(1)) % 12;\n if (\"pm\".equals(m.group(3))) hour += 12;\n int minute = Integer.parseInt(m.group(2));\n\n return 60 * hour + minute;\n}\n\n/**\n * Formats time, in minutes since midnight.\n */\nprivate static String format(int minutes) {\n String ampm = (minutes % MINUTES_PER_DAY < MINUTES_PER_DAY / 2) ? \"am\" : \"pm\";\n int hour = (minutes / 60) % 12;\n if (hour == 0) hour = 12;\n int minute = minutes % 60;\n\n return String.format(\"%02d:%02d %s\", hour, minute, ampm);\n}\n\npublic static String parallelUniverseTime(String time) {\n return format(MINUTES_PER_DAY - parse(time));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T14:03:53.840",
"Id": "63421",
"Score": "0",
"body": "Sure going to nominate this answer as `*Thousand Words*`. ^_^"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T18:04:26.767",
"Id": "63545",
"Score": "0",
"body": "You really wanted to get that \"Thousand words\" award, didn't you ;) +1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T08:13:42.533",
"Id": "38103",
"ParentId": "38044",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "38103",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T21:25:20.680",
"Id": "38044",
"Score": "10",
"Tags": [
"java",
"datetime",
"programming-challenge"
],
"Title": "PUT (Parallel Universe Time) generator"
}
|
38044
|
<p>I was inspired with this question <a href="https://stackoverflow.com/q/20597649/937125">How I can detect when other control changes it bounds?</a> and @Remy Lebeau's answer and decided to write my own control (based on ideas from <code>ExtCtrls.TLabeledEdit</code>).</p>
<p>Now I have a few concept problems: </p>
<ol>
<li><p>Should I re-use already defined <code>TLabelPosition</code> type or use my own? I was thinking that if I use <code>ExtCtrls.TLabelPosition</code> my control will be depended on <code>ExtCtrls</code> and if I use the same name in my unit, there might be a conflict when the 2 controls are used together.</p></li>
<li><p>Basically the control is always in <code>AutoSize</code> state, but I needed a so called Fixed Width/Height (I called it <code>LabelWidth</code>) so that the text could auto-wrap in that mode. not sure if the concept/naming is right. </p></li>
<li><p>I would also like to create a Left/Right anchor that always stick to a fixed parent positoin (for now its called <code>_FOriginX</code>) - not sure about naming/concept yet.</p></li>
<li><p>Todo: consider Control Align? (when it's not <code>alNone</code>) - How to sick my label in that case?</p></li>
</ol>
<p>In any way the control works really nice. It can be sticked to any <code>TControl</code>. </p>
<p>Any thoughts/ideas/improvements would be nice. Feel free to modify and share if you like it :)</p>
<hr>
<pre><code>unit StickyLabel;
{$DEFINE DEBUG}
interface
uses Messages, Windows, SysUtils, Classes, Controls, Graphics, StdCtrls;
type
TStickyLabelPosition = (slpAbove, slpBelow, slpLeft, slpRight);
TStickyLabel = class(TCustomLabel)
private
_FOriginX: Integer; // not used yet
FControl: TControl;
FControlWndProc: TWndMethod;
FLabelWidth: Integer;
FLabelHeight: Integer;
FLabelPosition: TStickyLabelPosition;
FLabelSpacing: Integer;
FSkipAdjustBounds: Boolean;
function GetAlignment: TAlignment;
function GetTop: Integer;
function GetLeft: Integer;
function GetLayout: TTextLayout;
function GetWidth: Integer;
function GetHeight: Integer;
procedure SetAlignment(const Value: TAlignment);
procedure SetHeight(Value: Integer);
procedure SetWidth(Value: Integer);
procedure SetControl(AControl: TControl);
procedure SetLabelPosition(const Value: TStickyLabelPosition);
procedure SetLabelSpacing(const Value: Integer);
procedure SetLabelWidth(const Value: Integer);
procedure SetLabelHeight(const Value: Integer);
procedure SetLayout(Value: TTextLayout);
procedure ControlWndProc(var Message: TMessage);
protected
function GetClientRect: TRect; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoPositionLabel; virtual;
{$IFDEF DEBUG}
procedure Paint; override;
{$ENDIF}
public
procedure AdjustBounds; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property LabelWidth: Integer read FLabelWidth write SetLabelWidth default 0;
property LabelHeight: Integer read FLabelHeight write SetLabelHeight default 0;
property LabelPosition: TStickyLabelPosition read FLabelPosition write SetLabelPosition default slpAbove;
property LabelSpacing: Integer read FLabelSpacing write SetLabelSpacing default 3;
property Control: TControl read FControl write SetControl;
property Alignment: TAlignment read GetAlignment write SetAlignment default taLeftJustify;
property BiDiMode;
property Caption;
property Color;
property DragCursor;
property DragKind;
property DragMode;
property Font;
property Height: Integer read GetHeight write SetHeight;
property Left: Integer read GetLeft;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowAccelChar;
property ShowHint;
property Top: Integer read GetTop;
property Transparent;
property Layout read GetLayout write SetLayout default tlCenter;
property WordWrap stored False; // todo: hide from published
property Width: Integer read GetWidth write SetWidth;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TStickyLabel]);
end;
constructor TStickyLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Layout := tlCenter;
FLabelPosition := slpAbove;
FLabelSpacing := 3;
FLabelWidth := 0;
FLabelheight := 0;
_FOriginX := -1; // todo? this would be a Left/Right anchor
end;
destructor TStickyLabel.Destroy;
begin
SetControl(nil);
inherited;
end;
procedure TStickyLabel.SetControl(AControl: TControl);
begin
if AControl = Self then Exit;
if FControl <> AControl then
begin
if FControl <> nil then
begin
FControl.WindowProc := FControlWndProc;
FControl.RemoveFreeNotification(Self);
end;
FControl := AControl;
if FControl <> nil then
begin
FControlWndProc := FControl.WindowProc;
FControl.WindowProc := ControlWndProc;
FControl.FreeNotification(Self);
end else
FControlWndProc := nil;
if FControl <> nil then
begin
Parent := FControl.Parent;
AdjustBounds;
end;
end;
end;
procedure TStickyLabel.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FControl) then
begin
FControl := nil;
FControlWndProc := nil;
//FreeAndNil(Self); // option ?
end;
end;
procedure TStickyLabel.ControlWndProc(var Message: TMessage);
begin
if Assigned(FControlWndProc) then
FControlWndProc(Message);
case Message.Msg of
CM_ENABLEDCHANGED: Enabled := FControl.Enabled;
CM_VISIBLECHANGED: Visible := FControl.Visible;
WM_WINDOWPOSCHANGED:
begin
if Parent <> FControl.Parent then
Parent := FControl.Parent;
AdjustBounds;
end;
end;
end;
procedure TStickyLabel.AdjustBounds;
begin
if FSkipAdjustBounds then Exit;
inherited AdjustBounds;
// if not (csReading in ComponentState) then // is this needed?
DoPositionLabel;
end;
function TStickyLabel.GetAlignment: TAlignment;
begin
Result := inherited Alignment;
end;
function TStickyLabel.GetLayout: TTextLayout;
begin
Result := inherited Layout;
end;
function TStickyLabel.GetClientRect: TRect;
begin
Result := Rect(0, 0, Width, Height);
end;
function TStickyLabel.GetHeight: Integer;
begin
if (FLabelHeight <> 0) then
Result := FLabelHeight else
Result := inherited Height
end;
function TStickyLabel.GetLeft: Integer;
begin
Result := inherited Left;
end;
function TStickyLabel.GetTop: Integer;
begin
Result := inherited Top;
end;
function TStickyLabel.GetWidth: Integer;
begin
if (FLabelWidth <> 0) then
Result := FLabelWidth else
Result := inherited Width
end;
procedure TStickyLabel.SetAlignment(const Value: TAlignment);
begin
if inherited Alignment <> Value then
begin
inherited Alignment := Value;
AdjustBounds;
end;
end;
procedure TStickyLabel.SetLayout(Value: TTextLayout);
begin
if inherited Layout <> Value then
begin
inherited Layout := Value;
AdjustBounds;
end;
end;
procedure TStickyLabel.SetHeight(Value: Integer);
begin
SetBounds(Left, Top, Width, Value);
end;
procedure TStickyLabel.SetWidth(Value: Integer);
begin
{
// trying to resize the TStickyLabel in design mode - does not work (move to SetBounds?)
if (csDesigning in ComponentState) and (FLabelWidth <> 0) and (FLabelWidth <> Value) then
begin
LabelWidth := Value;
Exit;
end;
}
SetBounds(Left, Top, Value, Height);
end;
procedure TStickyLabel.SetLabelWidth(const Value: Integer);
begin
if Value <> FLabelWidth then
begin
FLabelWidth := Value;
FSkipAdjustBounds := True; // prevent call to AdjustBounds twice (WordWrap calls it)
try
WordWrap := Value <> 0;
finally
FSkipAdjustBounds := False;
end;
AdjustBounds;
end;
end;
procedure TStickyLabel.SetLabelHeight(const Value: Integer);
begin
if Value <> FLabelHeight then
begin
FLabelHeight := Value;
AdjustBounds;
end;
end;
procedure TStickyLabel.SetLabelPosition(const Value: TStickyLabelPosition);
begin
if Value <> FLabelPosition then
begin
FLabelPosition := Value;
AdjustBounds;
end;
end;
procedure TStickyLabel.SetLabelSpacing(const Value: Integer);
begin
if Value <> FLabelSpacing then
begin
FLabelSpacing := Value;
AdjustBounds;
end;
end;
function AdjustedAlignment(RightToLeftAlignment: Boolean; Alignment: TAlignment): TAlignment;
begin
Result := Alignment;
if RightToLeftAlignment then
case Result of
taLeftJustify: Result := taRightJustify;
taRightJustify: Result := taLeftJustify;
end;
end;
procedure TStickyLabel.DoPositionLabel;
var
P: TPoint;
LAlignment: TAlignment;
LWidth, LHeight: Integer;
begin
if FControl = nil then Exit;
LAlignment := AdjustedAlignment(UseRightToLeftAlignment, Alignment);
LWidth := Width;
LHeight := Height;
case FLabelPosition of
slpAbove:
P.y := FControl.Top - LHeight - FLabelSpacing;
slpBelow:
P.y := FControl.Top + FControl.Height + FLabelSpacing;
slpLeft:
if UseRightToLeftAlignment {and options} then
P.x := FControl.Left + FControl.Width + FLabelSpacing
else
P.x := FControl.Left - LWidth - FLabelSpacing;
slpRight:
if UseRightToLeftAlignment {and options} then
P.x := FControl.Left - LWidth - FLabelSpacing
else
P.x := FControl.Left + FControl.Width + FLabelSpacing;
end;
case FLabelPosition of
slpAbove, slpBelow:
case LAlignment of
taLeftJustify: P.x := FControl.Left;
taRightJustify: P.x := FControl.Left + FControl.Width - LWidth;
taCenter: P.x := FControl.Left + ((FControl.Width - LWidth) div 2);
end;
slpLeft, slpRight:
case Layout of
tlTop: P.y := FControl.Top;
tlCenter: P.y := FControl.Top + ((FControl.Height - LHeight) div 2);
tlBottom: P.y := FControl.Top + FControl.Height - LHeight;
end;
end;
//if _FOriginX <> -1 then P.x := _FOriginX // ???
SetBounds(P.x, P.y, LWidth, LHeight);
end;
{$IFDEF DEBUG}
procedure TStickyLabel.Paint;
begin
inherited;
with Canvas do
begin
Pen.Style := psDot;
Pen.Color := clGray;
Brush.Style := bsClear;
Rectangle(0, 0, Width, Height);
end;
end;
{$ENDIF}
end.
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:07:41.523",
"Id": "38047",
"Score": "3",
"Tags": [
"delphi"
],
"Title": "TStickyLabel control anyone?"
}
|
38047
|
<p>I would like some help refactoring this code. This is to improve some of the nonfunctional attributes of the software to</p>
<ol>
<li>improve code readability</li>
<li>reduce complexity to improve the maintainability of the source code.</li>
</ol>
<p></p>
<pre><code>package Game;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
class GameStructure {
private String []wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday"};
private JTextField tf;
private JLabel jlLetsUsed;
static String letter;
static int []wordLength = new int[64];
public void window() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
JMenuItem menuItem = new JMenuItem("Developer", KeyEvent.VK_T);
menu.add(menuItem);
JMenuItem menuItem2 = new JMenuItem("Instructions", KeyEvent.VK_T);
menu.add(menuItem2);
JMenuItem menuItem3 = new JMenuItem("Levels", KeyEvent.VK_T);
menu.add(menuItem3);
JMenuItem menuItem4 = new JMenuItem("Restart", KeyEvent.VK_T);
menu.add(menuItem4);
JMenuItem menuItem5 = new JMenuItem("Exit", KeyEvent.VK_T);
menu.add(menuItem5);
ImageIcon ic = new ImageIcon("hangman2.png");
JFrame gameFrame = new JFrame();
JPanel bottomRight = new JPanel();
JPanel bottomLeft = new JPanel();
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JPanel imgPane = new JPanel();
JPanel panel1 = new JPanel();
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
imgPane.setLayout(new BorderLayout());
panel1.setLayout(new BorderLayout());
panel1.setOpaque(false);//!!
top.setBorder(BorderFactory.createTitledBorder(""));
bottom.setBorder(BorderFactory.createTitledBorder(""));
tf = new JTextField(1);
JLabel img = new JLabel(ic, JLabel.CENTER);
JLabel jl = new JLabel("Enter a letter", JLabel.CENTER);
jlLetsUsed = new JLabel("Letters used: ", JLabel.CENTER);
final JLabel jlLines = new JLabel("__ ", JLabel.CENTER);
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jlLetsUsed.setFont(new Font("Rockwell", Font.PLAIN, 20));
jlLines.setFont(new Font("Rockewell", Font.PLAIN, 20 ));
imgPane.add(img);//center
top.add(jl);//top center
top.add(tf);//top center
bottomLeft.add(jlLetsUsed);//bottom left position
bottomRight.add(jlLines);//bottom right position
bottom.add(bottomLeft);//bottom
bottom.add(bottomRight);//bottom
panel1.add(imgPane, BorderLayout.CENTER);//background image (center)
panel1.add(top, BorderLayout.NORTH);//text field and jlabel (top)
panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used (bottom)
gameFrame.setJMenuBar(menuBar);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(
new ImageIcon("hangmanIcon.png").getImage());
gameFrame.setResizable(false);
gameFrame.add(panel1);
gameFrame.setSize(800, 500);
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
int j = 0;
String line = "";
for(j = 0; j<64; j++) {
wordLength[j] = wordList[j].length();//gets length of words in wordList
}//end for
int f = 2;//change num to change level
int m = 0;
//creates line first then put into .setText
while(m<wordLength[f]) {
line += "__ ";
m++;
}//end for
jlLines.setText(line);
tf.addActionListener(new ActionListener() {
int wrong = 0;
@Override
public void actionPerformed(ActionEvent e) {//when enter key pressed
JTextField tf = (JTextField)e.getSource();
letter = tf.getText();
jlLetsUsed.setText(jlLetsUsed.getText() + letter + " ");//sets jlabel text to users entered letter
char[] jlabelText = jlLines.getText().toCharArray();//converts string to character array (array length is length of string)
char userEnteredChar = letter.charAt(0);
//int wrong = 0;
int level = 2;//change num to change level
if (!wordList[level].contains(letter)) {
wrong++;
if (wrong >= 6) {
System.out.println("He's dead, game over.");//prompt user
}
return;
}
int i = 0;
for(i = 0; i<wordList[level].length(); i++){
if(wordList[level].charAt(i) == userEnteredChar){
jlabelText[3 * i] = ' ';
jlabelText[3 * i + 1] = userEnteredChar;
jlLines.setText(String.valueOf(jlabelText));
}
}//end for
}//end actionPerformed method
});
}//end window method
}
public class GameMain {
public static void main(String[] args) {
GameStructure game = new GameStructure();
game.window();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some comments:</p>\n\n<ul>\n<li><p>Make sure you have a consistent indentation style. It makes it difficult to follow the code flow, if there are multiple lines with different indentation.</p></li>\n<li><p>You should separate the view and the game logic. Having both the Swing design setup and the actual game logic mixed up—in a single method—makes the code very hard to navigate. Ideally, both should be in separate classes.</p></li>\n<li><p>Consider making a subclass of <code>JFrame</code> for your game view. It will be the only thing responsible for setting up the visuals. You can pass it a <code>GameStructure</code> object (which would be only the game logic), so it can combine everything.</p></li>\n<li><p><code>for(j = 0; j<64; j++)</code> — Instead of hard-coding the length of the <code>worldList</code>, you should be able to adjust automatically if I add new words to the word list without changing anything else.</p></li>\n<li><p><code>tf.addActionListener(new ActionListener() { …</code> — Instead of having an anonymous listener, consider making an actual type to clean everything up. As you only need to have a single listener, you can also make the class you’re in implement <code>ActionListener</code>, so you can pass <code>this</code> to <code>addActionListener</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T02:10:15.643",
"Id": "63328",
"Score": "1",
"body": "Why the downvote?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:30:13.607",
"Id": "38049",
"ParentId": "38048",
"Score": "7"
}
},
{
"body": "<p>You currently <a href=\"https://stackoverflow.com/a/2125337/1937270\">aren't following Java package naming standards</a>.</p>\n\n<pre><code>package com.Game;\n</code></pre>\n\n<hr>\n\n<p>You need to keep a \"tab\" (<em>bah dum tish</em>) on your indenting. Right now it is somewhat hard to read your code because of that.</p>\n\n<hr>\n\n<p>You don't clear the text field once a letter is entered. This means the user had to clear out the field themselves and then enter a new letter. We can make the user's life a lot easier.</p>\n\n<pre><code>tf.setText(\"\");\ntf.requestFocus();\n</code></pre>\n\n<hr>\n\n<p>Every time I play, the game uses the same word that it wants me to guess. Let's add some randomness.</p>\n\n<pre><code>Random rand = new Random();\nint level = rand.nextInt(Arrays.asList(wordList).size() + 1);\n</code></pre>\n\n<hr>\n\n<p>That last point I made leads me to this point. Your code isn't very object oriented. I would recommend using an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html\" rel=\"nofollow noreferrer\">ArrayList</a> instead of a <code>String[]</code> as a start.</p>\n\n<pre><code>private ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(\"computer\", \"java\", \"activity\", \"alaska\", \"appearance\", \"article\", \"automobile\", \"basket\", \"birthday\", \"canada\", \"central\", \"character\", \"chicken\", \"chosen\", \"cutting\", \"daily\", \"darkness\", \"diagram\", \"disappear\", \"driving\", \"effort\", \"establish\", \"exact\", \"establishment\", \"fifteen\", \"football\", \"foreign\", \"frequently\", \"frighten\", \"function\", \"gradually\", \"hurried\", \"identity\", \"importance\", \"impossible\", \"invented\", \"italian\", \"journey\", \"lincoln\", \"london\", \"massage\", \"minerals\", \"outer\", \"paint\", \"particles\", \"personal\", \"physical\", \"progress\", \"quarter\", \"recognise\", \"replace\", \"rhythm\", \"situation\", \"slightly\", \"steady\", \"stepped\", \"strike\", \"successful\", \"sudden\", \"terrible\", \"traffic\", \"unusual\", \"volume\", \"yesterday\"));\n</code></pre>\n\n<p>I'll leave this up to you to include in your code.</p>\n\n<hr>\n\n<h2>Final code:</h2>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Font;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.util.Arrays;\nimport java.util.Random;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.BoxLayout;\nimport javax.swing.ImageIcon;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\nclass GameStructure\n{\n private String[] wordList = { \"computer\", \"java\", \"activity\", \"alaska\", \"appearance\", \"article\", \"automobile\", \"basket\", \"birthday\", \"canada\", \"central\", \"character\", \"chicken\", \"chosen\", \"cutting\", \"daily\", \"darkness\", \"diagram\", \"disappear\", \"driving\", \"effort\", \"establish\", \"exact\", \"establishment\", \"fifteen\", \"football\", \"foreign\", \"frequently\", \"frighten\", \"function\", \"gradually\", \"hurried\", \"identity\", \"importance\", \"impossible\", \"invented\", \"italian\", \"journey\", \"lincoln\", \"london\", \"massage\", \"minerals\", \"outer\", \"paint\", \"particles\", \"personal\", \"physical\", \"progress\", \"quarter\", \"recognise\", \"replace\", \"rhythm\", \"situation\", \"slightly\", \"steady\", \"stepped\", \"strike\", \"successful\", \"sudden\", \"terrible\", \"traffic\", \"unusual\", \"volume\", \"yesterday\" };\n private JTextField tf;\n private JLabel jlLetsUsed;\n static String letter;\n static int[] wordLength = new int[64];\n\n public void window()\n {\n JMenuBar menuBar = new JMenuBar();\n JMenu menu = new JMenu(\"File\");\n menu.setMnemonic(KeyEvent.VK_A);\n menuBar.add(menu);\n JMenuItem menuItem = new JMenuItem(\"Developer\", KeyEvent.VK_T);\n menu.add(menuItem);\n JMenuItem menuItem2 = new JMenuItem(\"Instructions\", KeyEvent.VK_T);\n menu.add(menuItem2);\n JMenuItem menuItem3 = new JMenuItem(\"Levels\", KeyEvent.VK_T);\n menu.add(menuItem3);\n JMenuItem menuItem4 = new JMenuItem(\"Restart\", KeyEvent.VK_T);\n menu.add(menuItem4);\n JMenuItem menuItem5 = new JMenuItem(\"Exit\", KeyEvent.VK_T);\n menu.add(menuItem5);\n\n ImageIcon ic = new ImageIcon(\"hangman2.png\");\n JFrame gameFrame = new JFrame();\n JPanel bottomRight = new JPanel();\n JPanel bottomLeft = new JPanel();\n JPanel top = new JPanel();\n JPanel bottom = new JPanel();\n JPanel imgPane = new JPanel();\n JPanel panel1 = new JPanel();\n bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));\n imgPane.setLayout(new BorderLayout());\n panel1.setLayout(new BorderLayout());\n panel1.setOpaque(false);// !!\n top.setBorder(BorderFactory.createTitledBorder(\"\"));\n bottom.setBorder(BorderFactory.createTitledBorder(\"\"));\n tf = new JTextField(1);\n JLabel img = new JLabel(ic, JLabel.CENTER);\n JLabel jl = new JLabel(\"Enter a letter\", JLabel.CENTER);\n jlLetsUsed = new JLabel(\"Letters used: \", JLabel.CENTER);\n final JLabel jlLines = new JLabel(\"__ \", JLabel.CENTER);\n jl.setFont(new Font(\"Rockwell\", Font.PLAIN, 20));\n tf.setFont(new Font(\"Rockwell\", Font.PLAIN, 20));\n jlLetsUsed.setFont(new Font(\"Rockwell\", Font.PLAIN, 20));\n jlLines.setFont(new Font(\"Rockewell\", Font.PLAIN, 20));\n imgPane.add(img);// center\n top.add(jl);// top center\n top.add(tf);// top center\n bottomLeft.add(jlLetsUsed);// bottom left position\n bottomRight.add(jlLines);// bottom right position\n bottom.add(bottomLeft);// bottom\n bottom.add(bottomRight);// bottom\n panel1.add(imgPane, BorderLayout.CENTER);// background image (center)\n panel1.add(top, BorderLayout.NORTH);// text field and jlabel (top)\n panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used (bottom)\n gameFrame.setJMenuBar(menuBar);\n gameFrame.setTitle(\"Hangman\");\n gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n gameFrame.setIconImage(new ImageIcon(\"hangmanIcon.png\").getImage());\n gameFrame.setResizable(false);\n gameFrame.add(panel1);\n gameFrame.setSize(800, 500);\n gameFrame.setLocationRelativeTo(null);\n gameFrame.setVisible(true);\n\n int j = 0;\n String line = \"\";\n for (j = 0; j < 64; j++)\n {\n wordLength[j] = wordList[j].length();\n }\n\n int f = 2;\n int m = 0;\n while (m < wordLength[f])\n {\n line += \"__ \";\n m++;\n }\n jlLines.setText(line);\n\n tf.addActionListener(new ActionListener()\n {\n int wrong = 0;\n\n @Override\n public void actionPerformed(ActionEvent e)\n {\n JTextField tf = (JTextField) e.getSource();\n letter = tf.getText();\n tf.setText(\"\");\n tf.requestFocus();\n jlLetsUsed.setText(jlLetsUsed.getText() + letter + \" \");\n char[] jlabelText = jlLines.getText().toCharArray();\n char userEnteredChar = letter.charAt(0);\n Random rand = new Random();\n int level = rand.nextInt(Arrays.asList(wordList).size() + 1);\n if (!wordList[level].contains(letter))\n {\n wrong++;\n if (wrong >= 6)\n {\n System.out.println(\"He's dead, game over.\");\n }\n return;\n }\n int i = 0;\n for (i = 0; i < wordList[level].length(); i++)\n {\n if (wordList[level].charAt(i) == userEnteredChar)\n {\n jlabelText[3 * i] = ' ';\n jlabelText[3 * i + 1] = userEnteredChar;\n jlLines.setText(String.valueOf(jlabelText));\n }\n }\n }\n });\n }\n}\n\npublic class Test\n{\n public static void main(String[] args)\n {\n GameStructure game = new GameStructure();\n game.window();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T01:29:06.140",
"Id": "63321",
"Score": "0",
"body": "I know I'm not supposed to say thanks in comments but thanks, you really helped me out a lot with the finishing touches of the game. If it's not too much for me to ask, can I get your email so if I have any questions I can reach you? I'm 15 and just starting off in java and I'm really looking to advance in programming. Sorry about the whole life story."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T01:51:18.570",
"Id": "63324",
"Score": "0",
"body": "Is it better to have braces on their own line?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T01:55:05.400",
"Id": "63326",
"Score": "0",
"body": "What IDE do you use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T05:20:26.013",
"Id": "63333",
"Score": "1",
"body": "IDE with auto-formatting is king. removes the need to waste time being OCD on ancillary parts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T05:14:37.757",
"Id": "70101",
"Score": "0",
"body": "Don't you mean `int level = rand.nextInt(wordList.length + 1);` ?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T00:21:49.117",
"Id": "38052",
"ParentId": "38048",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38052",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T22:18:51.853",
"Id": "38048",
"Score": "6",
"Tags": [
"java",
"optimization",
"performance",
"game",
"hangman"
],
"Title": "Hangman game code refactoring"
}
|
38048
|
<p>I'm in the process of learning python and programmed this exercise in decrypting the <a href="http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher" rel="nofollow">Vigenere square cypher</a> as practice.</p>
<p>Please comment on best practices, efficiency, or more pythonic ways to do things.</p>
<pre><code>#!/usr/bin/env python
"""Functions for encrypting and decrypting text using
the Vigenere square cipher. See:
http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
IC stands for Index of Coincidence:
http://en.wikipedia.org/wiki/Index_of_coincidence
"""
from __future__ import division
from collections import Counter
from math import fabs
from string import ascii_lowercase
from scipy.stats import pearsonr
from numpy import matrix
from os import system
#Define some constants:
LETTER_CNT = 26
ENGLISH_IC = 1.73
#Cornell English letter frequecy
#http://www.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html
ENGLISH_LETTERS = 'etaoinsrhdlucmfywgpbvkxqjz'
ENGLISH_FREQ = [0.1202, 0.0910, 0.0812, 0.0768, 0.0731, 0.0695, 0.0628,
0.0602, 0.0592, 0.0432, 0.0398, 0.0288, 0.0271, 0.0261,
0.0230, 0.0211, 0.0209, 0.0203, 0.0182, 0.0149, 0.0111,
0.0069, 0.0017, 0.0011, 0.0010, 0.0007]
ENGLISH_DICT = dict(zip(list(ENGLISH_LETTERS), ENGLISH_FREQ))
MAX_LEN = 10 #Maximum keyword length
def scrub_string(str):
"""Remove non-alphabetic characters and convert string to lower case. """
return ''.join(ch for ch in str if ch.isalpha()).lower()
def string_to_numbers(str):
"""Convert str to a list of numbers giving the position of the letter
in the alphabet (position of a = 0). str should contain only
lowercase letters.
"""
return [ord(ch) - ord('a') for ch in str]
def numbers_to_string(nums):
"""Convert a list of numbers to a string of letters
(index of a = 0); the inverse function of string_to_numbers.
"""
return ''.join(chr(n + ord('a')) for n in nums)
def shift_string_by_number(str, shift):
"""Shift the letters in str by the amount shift (either positive
or negative) modulo 26.
"""
return numbers_to_string((num + shift) % LETTER_CNT
for num in string_to_numbers(str))
def shift_string_by_letter(str, ch, direction):
"""Shift the letters in str by the value of ch, modulo 26.
Right shift if direction = 1, left shift if direction = -1.
"""
assert direction in {1, -1}
return shift_string_by_number(str, (ord(ch) - ord('a') + 1) * direction)
def chunk_string(str):
"""Add a blank between each block of five characters in str."""
return ' '.join(str[i:i+5] for i in xrange(0, len(str), 5))
def crypt(text, passphrase, which):
"""Encrypt or decrypt the text, depending on whether which = 1
or which = -1.
"""
text = scrub_string(text)
passphrase = scrub_string(passphrase)
letters = (shift_string_by_letter(ch, passphrase[i % len(passphrase)], which)
for i, ch in enumerate(text))
return ''.join(letters)
def IC(text, ncol):
"""Divide the text into ncol columns and return the average index
of coincidence across the columns.
"""
text = scrub_string(text)
A = str_to_matrix(scrub_string(text), ncol)
cum = 0
for col in A:
N = len(col)
cum += (sum(n*(n - 1) for n in Counter(col).values())
/ (N*(N - 1)/LETTER_CNT))
return cum/ncol
def keyword_length(text):
"""Determine keyword length by finding the length that makes
IC closest to the English plaintext value of 1.73.
"""
text = scrub_string(text)
a = [fabs(IC(text, ncol) - ENGLISH_IC) for ncol in xrange(1, MAX_LEN)]
return a.index(min(a)) + 1
def correlation(letter_list):
"""Return the correlation of the frequencies of the letters
in the list with the English letter frequency.
"""
counts = Counter(letter_list)
text_freq = [counts[ch]/len(letter_list) for ch in ascii_lowercase]
english_freq = [ENGLISH_DICT[ch] for ch in ascii_lowercase]
return pearsonr(text_freq, english_freq)[0]
def find_keyword_letter(letter_list):
"""Return a letter of the keyword, given every nth character
of the ciphertext, where n = keyword length.
"""
str = ''.join(letter_list)
cors = [correlation(shift_string_by_number(str, -num))
for num in xrange(1, LETTER_CNT + 1)]
return ascii_lowercase[cors.index(max(cors))]
def find_keyword(ciphertext, keyword_length):
"""Return the keyword, given its length and the ciphertext."""
A = str_to_matrix(scrub_string(ciphertext), keyword_length)
return ''.join(
[find_keyword_letter(A[j]) for j in xrange(keyword_length)])
def str_to_matrix(str, ncol):
"""Divide str into ncol lists as in the example below:
>>> str_to_matrix('abcdefghijk', 4)
[['a', 'e', 'i'], ['b', 'f', 'j'], ['c', 'g', 'k'], ['d', 'h']]
"""
A = [list(str[i:i + ncol]) for i in xrange(0, len(str), ncol)]
stub = A.pop()
B = matrix(A).T.tolist()
for i, ch in enumerate(stub):
B[i] += ch
return B
def test_functions():
"""Unit tests for functions in this module."""
assert(shift_string_by_number('unladenswallow', 15) == 'jcapstchlpaadl')
assert(shift_string_by_letter('unladenswallow', 'M', -1) == 'ngetwxglpteehp')
assert(chunk_string('terpsichorean') == 'terps ichor ean')
assert(crypt('Hello world!', "mypassword", 1) == 'udbmhplgdh')
assert(crypt('udbmhplgdh', "mypassword", -1) == 'helloworld')
assert(round(correlation('ganzunglabulich'), 6) == 0.118034)
assert(scrub_string("I'm not Doctor bloody Bernofsky!!") ==
'imnotdoctorbloodybernofsky')
assert(string_to_numbers('lemoncurry') ==
[11, 4, 12, 14, 13, 2, 20, 17, 17, 24])
assert(numbers_to_string([11, 4, 12, 14, 13, 2, 20, 17, 17, 24]) ==
'lemoncurry')
assert(round(IC('''QPWKA LVRXC QZIKG RBPFA EOMFL JMSDZ VDHXC XJYEB IMTRQ
WNMEA IZRVK CVKVL XNEIC FZPZC ZZHKM LVZVZ IZRRQ WDKEC
HOSNY XXLSP MYKVQ XJTDC IOMEE XDQVS RXLRL KZHOV''', 5)
, 2) == 1.82)
assert(keyword_length('''QPWKA LVRXC QZIKG RBPFA EOMFL JMSDZ VDHXC XJYEB
IMTRQ WNMEA IZRVK CVKVL XNEIC FZPZC ZZHKM LVZVZ IZRRQ WDKEC
HOSNY XXLSP MYKVQ XJTDC IOMEE XDQVS RXLRL KZHOV''') == 5)
assert(str_to_matrix('abcdefghijk', 4) ==
[['a', 'e', 'i'], ['b', 'f', 'j'], ['c', 'g', 'k'], ['d', 'h']])
if __name__ == '__main__':
print 'Calculating...'
with open ("plaintext.txt", "r") as infile:
plaintext = infile.read().replace('\n', ' ')
passphrase = 'Moby Dick'
ciphertext = crypt(plaintext, passphrase, 1)
kw_len = keyword_length(ciphertext)
kw = find_keyword(ciphertext, kw_len)
print 'Keyword length is {0}.'.format(kw_len)
print 'The keyword is {0}.'.format(kw)
system("""bash -c 'read -s -n 1 -p "Press any key print the decrypted text..."'""")
print crypt(ciphertext, kw, -1)
</code></pre>
|
[] |
[
{
"body": "<p>Overall this is well documented, well written code. There are a number of things I may have written differently, but they are primarily manners of personal style. But I still found some things I want to call out that might be somewhat problematic, or at least worth examining:</p>\n\n<ol>\n<li><code>scrub_string</code> might not do what you want. Notably, <code>\"\\xe9\".isalpha()</code> is <code>True</code> with my default settings, but your code probably does not handle <code>LATIN SMALL LETTER E WITH ACUTE</code>.</li>\n<li><code>shift_string_by_letter</code> seems like it might be better described as passing in the letter that <code>a</code> should become (or becomes that becomes <code>a</code>). As a related comment, make sure you are aware that <code>assert</code> lines are removed when python is run with <code>-O</code> or <code>-OO</code> so you cannot depend on them to catch run-time errors. Your use here is correct, as passing anything other than <code>1</code> or <code>-1</code> is a programming error instead of a run-time error.</li>\n<li><p><code>crypt</code> uses modulus to match what <a href=\"http://docs.python.org/2/library/itertools.html\" rel=\"nofollow\"><code>itertools</code></a> could make simpler. With <code>cycle</code> and <code>izip</code> it can become this:</p>\n\n<pre><code>letters = (shift_string_by_letter(ch, p, which)\n for ch, p in izip(text, cycle(passphrase)))\n</code></pre></li>\n<li><p><code>IC</code> doesn't appear to follow the same naming conventions as your other functions. It's short, and upper-case, possibly an abbreviation.</p></li>\n<li>In <code>__main__</code>, the use of <code>system</code> and bash is unusual. I would replace this with <code>raw_input(\"Press enter to print the decrypted text...\")</code> (or <code>input(...)</code> in python 3) to avoid the indirection that needlessly prevents this from working on systems without bash.</li>\n<li>In several places, constructs like <code>ord(ch) - ord('a')</code> or <code>chr(n + ord('a'))</code> help you convert between letters an indices. It might help either performance or readability to set up two dictionaries to do the conversion as a lookup, say <code>to_index[ch]</code> or <code>from_index[n]</code>. This would have a nice effect of catching unsupported characters more explicitly by raising a <code>KeyError</code> if one is encountered.</li>\n<li><p>As a general guideline, when you start to prioritize performance over readability, one of the lowest hanging fruits in python is function calls. While this can lead towards manually \"inlining\" other functions in order to save a few cycles, it can also lead towards other interesting approaches. For example, if the <code>text</code> for <code>crypt</code> is long enough, it's plausible that making up to 26 dictionaries mapping all 26 characters would allow for faster running code overall, despite the set-up time. The resulting code might look like this:</p>\n\n<pre><code>shift_map = { p : { ch : shift_string_by_letter(ch, p, which)\n for ch in ascii_lowercase } for p in passphrase }\nletters = (shift_map[p][ch] for ch, p in izip(text, cycle(passphrase)))\n</code></pre>\n\n<p>But that strategy would fail utterly for short lengths of <code>text</code> due to the costs of setting up the dictionary. It's also possible that all of this would be lost in the noise of using generator expressions. This pontification highlights the need to profile the scenarios for which you actually want your code to perform well, and then to be creative about how you fix them.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:48:20.730",
"Id": "63384",
"Score": "1",
"body": "This is great! I can't believe a site like this even exists, your efforts are much appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T15:39:34.210",
"Id": "38075",
"ParentId": "38055",
"Score": "3"
}
},
{
"body": "<p>You've written docstrings for all your functions, and test cases for many of them: this puts you ahead of 90% of the Python submissions here at Code Review! But there are still lots of small improvements you could make.</p>\n\n<ol>\n<li><p>Instead of:</p>\n\n<pre><code>LETTER_CNT = 26\n</code></pre>\n\n<p>I'd consider writing:</p>\n\n<pre><code>LETTERS = ascii_lowercase\nLETTER_COUNT = len(LETTERS)\n</code></pre>\n\n<p>to make it clear what is being counted. Also, there's no danger of running out of vowels, so I'd write <code>COUNT</code> out in full.</p></li>\n<li><p>By having separate tables <code>ENGLISH_LETTERS</code> and <code>ENGLISH_FREQ</code> and combining them using <code>zip</code>, you run the risk of getting these tables mismatched. It would be better to write:</p>\n\n<pre><code>ENGLISH_DICT = dict(e=0.1202, t=0.0910, a=0.0812, ...)\n</code></pre>\n\n<p>But all that you actually use this for is to build the following list in <code>correlation</code>:</p>\n\n<pre><code>english_freq = [ENGLISH_DICT[ch] for ch in ascii_lowercase]\n</code></pre>\n\n<p>So you could make this your global variable in the first place:</p>\n\n<pre><code># Frequency of letters a, b, c, ... in English.\nENGLISH_FREQ = [0.0812, 0.0149, 0.0271, ...]\n</code></pre>\n\n<p>and avoid building <code>ENGLISH_DICT</code>.</p></li>\n<li><p>This code is very nearly portable to Python 3. All that's remaining to do is to put parentheses around your print statements and change <code>xrange</code> to <code>range</code>.</p></li>\n<li><p>You name some of your parameters <code>str</code>, which is also the name of the built-in type <a href=\"http://docs.python.org/3/library/stdtypes.html#str\" rel=\"nofollow\"><code>str</code></a>. This causes your variable to shadow the built-in, which would be inconvenient if you needed the built-in (as I do below).</p></li>\n<li><p><code>shift_string_by_number</code> and <code>shift_string_by_letter</code> transform a string letter-wise. The built-in string method <a href=\"http://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"nofollow\"><code>str.translate</code></a> provides a simple and efficient way of doing this:</p>\n\n<pre><code>def shift_string_by_number(s, shift):\n shift %= LETTER_COUNT\n tr = str.maketrans(LETTERS, LETTERS[shift:] + LETTERS[:shift])\n return s.translate(tr)\n</code></pre>\n\n<p>For performance, it would make sense to pre-compute all the translation tables:</p>\n\n<pre><code>SHIFT_TABLES = [str.maketrans(LETTERS, LETTERS[shift:] + LETTERS[:shift])\n for shift in range(LETTER_COUNT)]\n\ndef shift_string_by_number(s, shift):\n return s.translate(SHIFT_TABLES[shift % LETTER_COUNT])\n</code></pre>\n\n<p>Notice that we only need 26 translation tables, even though <code>shift</code> might be negative, because the <code>%</code> operation <a href=\"http://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations\" rel=\"nofollow\">always yields a result with the same sign as its second operand</a>.</p>\n\n<p>After making this change, we no longer need <code>string_to_numbers</code> or <code>numbers_to_string</code>.</p></li>\n<li><p>The function <code>scrub_string</code> could also be rewritten to use <a href=\"http://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"nofollow\"><code>str.translate</code></a>. Here we can take advantage of the feature that \"Characters mapped to <code>None</code> are deleted\":</p>\n\n<pre><code>from collections import defaultdict\n\nSCRUB_TABLE = defaultdict(lambda:None)\nSCRUB_TABLE.update(str.maketrans(LETTERS, LETTERS))\nSCRUB_TABLE.update(str.maketrans(ascii_uppercase, LETTERS))\n\ndef scrub_string(s):\n \"\"\"Remove non-alphabetic characters and convert string to lower case. \"\"\"\n return s.translate(SCRUB_TABLE)\n</code></pre></li>\n<li><p>You could benefit from rewriting your test cases to use the features in the <a href=\"http://docs.python.org/3/library/unittest.html\" rel=\"nofollow\"><code>unittest</code></a> module. This would make it easier to run the tests (for example, by running <code>python -munittest mymodule.py</code> from the shell), but would also produce more informative results. A failed assertion just reports a bare <code>AssertionError</code>:</p>\n\n<pre><code>>>> assert(shift_string_by_number('unladenswallow', 15) == 'jcapstchlpaadm')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAssertionError\n</code></pre>\n\n<p>but if you used <code>self.assertEqual</code> in a <code>unittest.TestCase</code>, then you'd get output like this:</p>\n\n<pre><code>$ python3.3 -munittest cr38055.py\nF\n======================================================================\nFAIL: test_functions (cr38055.TestVigenere)\nUnit tests for functions in this module.\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"./cr38055.py\", line 149, in test_functions\n self.assertEqual(shift_string_by_number('unladenswallow', 15), 'jcapstchlpaadm')\nAssertionError: 'jcapstchlpaadl' != 'jcapstchlpaadm'\n- jcapstchlpaadl\n? ^\n+ jcapstchlpaadm\n? ^\n</code></pre></li>\n<li><p>In <code>test_functions</code>, you test <code>crypt</code> before you test <code>scrub_string</code>. But this means that an error in <code>scrub_string</code> will actually show up as an error in <code>crypt</code>, which will be harder for you to track down. It's best to organize your tests so that the functions are tested only after all their dependencies have been tested.</p></li>\n<li><p>The function <code>crypt</code> takes an argument <code>which</code> which needs to be −1 or +1 for encryption or decryption, but the docstring does not say which! (I think it's +1 for encryption and −1 for decryption.) Also, there's no check on the argument. It would be clearer to supply named constants:</p>\n\n<pre><code>ENCRYPTION = +1\nDECRYPTION = -1\n</code></pre>\n\n<p>and then check the argument:</p>\n\n<pre><code>assert(which in (ENCRYPTION, DECRYPTION))\n</code></pre>\n\n<p>or, better still, have two functions <code>encrypt</code> and <code>decrypt</code>.</p></li>\n<li><p>The function <code>chunk_string</code> appears not to be used.</p></li>\n<li><p>You call <code>scrub_string</code> at the start of <code>keyword_length</code>, and then that function then calls <code>IC</code> many times. Each call to <code>IC</code> therefore results in two useless calls to <code>scrub_string</code>. My suggestion would be to scrub strings just once (for example, when you read them from the source file) and not to scrub them inside worker functions like <code>keyword_length</code>, <code>IC</code>, <code>crypt</code> and so on.</p></li>\n<li><p>You use <a href=\"http://docs.python.org/3/library/math.html#math.fabs\" rel=\"nofollow\"><code>math.fabs</code></a> to compute the absolute value of a floating-point number. But in fact the built-in <a href=\"http://docs.python.org/3/library/functions.html#abs\" rel=\"nofollow\"><code>abs</code></a> would work just as well.</p></li>\n<li><p>In <code>keyword_length</code> you build a list <code>a</code> and then find the index of its minimum value:</p>\n\n<pre><code>a = [fabs(IC(text, ncol) - ENGLISH_IC) for ncol in xrange(1, MAX_LEN)]\nreturn a.index(min(a)) + 1\n</code></pre>\n\n<p>In Python it's rarely a good idea to bother with the index of an item in a sequence. Generally one should handle items directly and not via their index in a sequence.</p>\n\n<p>Note also that <code>xrange(1, MAX_LEN)</code> only goes up to <code>MAX_LEN - 1</code> which seems wrong given that you documented <code>MAX_LEN</code> as \"Maximum keyword length\".</p>\n\n<p>You could fix the off-by-one error, avoid building the list, and avoid the call to <a href=\"http://docs.python.org/3/library/stdtypes.html#str.index\" rel=\"nofollow\"><code>index</code></a>, by using the <code>key</code> argument to <a href=\"http://docs.python.org/3/library/functions.html#min\" rel=\"nofollow\"><code>min</code></a>, and writing:</p>\n\n<pre><code>def keyword_length(text):\n def key(ncol):\n return abs(IC(text, ncol) - ENGLISH_IC)\n return min(range(1, MAX_LEN + 1), key=key)\n</code></pre></li>\n<li><p>Similarly, in <code>find_keyword_letter</code>, you can use the <code>key</code> argument to <a href=\"http://docs.python.org/3/library/functions.html#max\" rel=\"nofollow\"><code>max</code></a> to avoid building a list and avoid a call to <a href=\"http://docs.python.org/3/library/stdtypes.html#str.index\" rel=\"nofollow\"><code>index</code></a>:</p>\n\n<pre><code>def find_keyword_letter(column):\n def key(letter):\n return correlation(shift_string_by_letter(column, letter, -1))\n return max(LETTERS, key=key)\n</code></pre></li>\n<li><p>In <code>IC</code>, you could avoid the call to <code>str_to_matrix</code> by using Python's string slicing: the <code>j</code>th column from <code>text</code> is <code>text[j::ncol]</code>. Also, the multiplication by <code>LETTER_CNT</code> is common to all the summands so can be postponed to the end:</p>\n\n<pre><code>def IC(text, ncol):\n total = 0\n for j in range(ncol):\n column = text[j::ncol]\n N = len(column)\n total += sum(n*(n-1) for n in Counter(column).values()) / (N*(N-1))\n return total * LETTER_COUNT / ncol\n</code></pre></li>\n<li><p>In <code>find_keyword</code> you can avoid the call to <code>str_to_matrix</code> similarly:</p>\n\n<pre><code>def find_keyword(ciphertext, ncol):\n return ''.join(find_keyword_letter(text[j::ncol]) for j in range(ncol))\n</code></pre>\n\n<p>I've called the argument <code>ncol</code> here rather than <code>keyword_length</code> for consistency with the other functions, and so as not to shadow the function of that name.</p>\n\n<p>This eliminates the need for <code>str_to_matrix</code> or <code>numpy.matrix</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T15:31:08.923",
"Id": "63698",
"Score": "0",
"body": "Many excellent comments! I actually realized last night that I should not be calling a variable str and I've also ported to python 3. Thanks for responding!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T10:51:56.967",
"Id": "38269",
"ParentId": "38055",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38075",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T01:07:49.217",
"Id": "38055",
"Score": "3",
"Tags": [
"python",
"vigenere-cipher"
],
"Title": "Vigenere square cypher decryption"
}
|
38055
|
<p>This is for an app built with Express. One of my concerns is the routes ending with <code>/</code> which I did because our previous site was an ASP app. So they named the folders that way for SEO purposes, then the page would be <code>index.aspx</code> .But in my case I just did, for example </p>
<p><code>science.jade</code> and routed it from <code>/science-bruxzir-zirconia-dental-crown/</code></p>
<p>Here is what I got for routes</p>
<p><strong>app.js</strong></p>
<pre><code>var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon(path.join(__dirname, 'public/images/template/favicon.ico')));
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', function(req, res){
res.render('home', {
title: 'Home'
});
});
app.get('/features-bruxzir-zirconia-dental-crown/', function(req, res){
res.render('features', {
title: 'BruxZir Features'
});
});
app.get('/science-bruxzir-zirconia-dental-crown/', function(req, res){
res.render('science', {
title: 'Scientific Validation'
});
});
app.get('/video-bruxzir-zirconia-dental-crown/', function(req, res){
res.render('videos', {
title: 'BruxZir Video Gallery'
});
});
app.get('/cases-bruxzir-zirconia-dental-crown/', function(req, res){
res.render('cases', {
title: 'Before & After Case Gallery'
});
});
app.get('/testimonials-bruxzir-zirconia-dental-crown/', function(req, res){
res.render('testimonials', {
title: 'Bruxzir Testimonials'
});
});
app.get('/authorized-bruxzir-labs-zirconia-dental-crown/', function(req, res){
res.render('labs', {
title: 'Authorized BruxZir Labs'
});
});
app.get('/contact-bruxzir-zirconia/', function(req, res){
res.render('contact', {
title: 'Bruxzir Contact Form'
});
});
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T06:15:32.153",
"Id": "63873",
"Score": "0",
"body": "Looks alright to me, the only thing i would suggest is to brake this file up. What exactly concerns you though?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T18:31:47.403",
"Id": "63920",
"Score": "0",
"body": "@GnrlBzik the biggest concern is that the route ending in `/` looks a bit sloppy. But our previous routing used that structure because there was a `index.aspx` inside that file. But now I am just naming that page that name. I don't know how many sites point into this, so i wanted to preserve that url so we don't lose traffic. Also the routes seem a bit verbose, I would think there is a way to make this more concise. Also wanted tips on how exactly I can break up the project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:09:46.827",
"Id": "64224",
"Score": "0",
"body": "well you already using require statements to pull ./routes and ./routes/user why not move out bottom route definitions to separate files, i would also brake set and use into separate config file that you can require, just pass app to that require statement. thats what i would do from code management stand point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:23:22.010",
"Id": "64227",
"Score": "1",
"body": "So if you want to move away from those hideous routes, why not use redirect, so that you dont lose them in any way, you could also define regex for routes for each resource to match new route and old. Its up to you, ugly urls, yes, but is that much of an issue for only about 10 urls?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:25:14.393",
"Id": "64228",
"Score": "0",
"body": "I see where you used user.list. Is this route related logic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:22:18.083",
"Id": "68110",
"Score": "0",
"body": "For all the `set`s and `use`s I would wrap them into `app.configure` like shown here http://expressjs.com/api.html#app.configure and as mentioned by @GnrlBzik, extract in multiple files."
}
] |
[
{
"body": "<p>From a once over of the code and the comments:</p>\n\n<ul>\n<li>This code is fine, especially if you have only a dozen routes, I would not advise you to build your own route building infrastructure for such a small amount of routes</li>\n<li>Dont worry about the <code>/</code></li>\n<li>Consider having your routes in separate files as per @GnrlBzik</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T16:33:21.393",
"Id": "46941",
"ParentId": "38056",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T01:57:35.147",
"Id": "38056",
"Score": "3",
"Tags": [
"javascript",
"node.js"
],
"Title": "How well or poorly structured are my routes in this NodeJS app?"
}
|
38056
|
<p>I've just completed my first JavaScript game. I strongly welcome any advice/opinions/insults on how crappy or good my game is.</p>
<p>Do you notice anything that is poorly done? </p>
<p>Is there anything that I can write better/shorter?</p>
<p>Here is a link where you can change the code/test the game/etc. <a href="http://labs.codecademy.com/Bnov#:workspace" rel="nofollow">http://labs.codecademy.com/Bnov#:workspace</a></p>
<pre><code>suits = ["spades", "diamonds", "clubs", "hearts"];
deck = [];
var h1, h2, h3, hD, nHands; //global vars
for (var x=0; x<suits.length; x++) { for (var i=2; i<10; i++) { deck.push(i + " of " + suits[x]); } }
function shuffle(deck) {
for (var i = deck.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = deck[i]; deck[i] = deck[j]; deck[j] = temp; } return deck; }
shuffle(deck);
function Hand(name, sChips, cChips) {
this.name = name;
this.sChips = sChips; // Starting Chips
this.cChips = cChips; // Current Chip count
}
function numHands() {
nHands = parseInt(prompt("How many hands do you want to play?(1,2 or 3)"), 10);
if (nHands > 0 && nHands < 4) {
x = 150000/nHands;
if (nHands > 0) { h1 = new Hand("First Hand", x, x);
if (nHands > 1) { h2 = new Hand("Second Hand", x, x);
if (nHands > 2) { h3 = new Hand("Third Hand", x, x); } }
hD = new Hand("Dealer"); } }
else { numHands(); } }
function setBetAmount(hand) {
hand.betAmount = parseInt(prompt(hand.name + ": " + "Place your bet! (bet between 0 and " + hand.cChips + ")"), 10);
if (hand.betAmount >= 0 && hand.betAmount <= hand.cChips) {
return hand.betAmount;
}
else { setBetAmount(hand); }
}
function recordBetAmount() {
if (nHands > 0) { setBetAmount(h1);
if (nHands > 1) { setBetAmount(h2);
if (nHands > 2) { setBetAmount(h3); } } } }
function dealtwo() { xy = [deck.shift(), deck.shift()]; return xy; }
function dealone() { yx = deck.shift(); return yx; }
function dealCards() {
if (nHands > 0) { h1.cards = dealtwo();
if (nHands > 1) { h2.cards = dealtwo();
if (nHands > 2) { h3.cards = dealtwo(); } }
hD.cards = dealtwo(); } }
function addValueOfCards(cards) {
var yyy = 0;
for (var x = 0; x < cards.length; x++) {
wwww = cards[x];
yyy += parseInt(wwww[0], 10);
}
return yyy;
}
function hitOrStay(cards, hand) {
var x = addValueOfCards(cards);
if (x < 17) {
var option = prompt(hand.name + ": You have " + x + ". Do you want to hit or stay?").toLowerCase();
if (option === "hit" || option === "h") {
cards.push(dealone());
hitOrStay(cards, hand);
}
else if (option === "stay" || option === "s") {
console.log(hand.name + ": " + hand.cards);
}
else {
hitOrStay(cards, hand);
}
}
else if (x === 17 || x === 18) {
console.log(hand.name + ": " + hand.cards);
}
else {
console.log(hand.name + ": " + hand.cards);
}
}
function dealerHitOrStay(cards) {
var x = addValueOfCards(cards);
if (x < 15) {
cards.push(dealone());
dealerHitOrStay(cards);
}
else if (x > 14 && x < 19) {
console.log("Dealer Hand: " + hD.cards);
}
else {
console.log("Dealer Hand: " + hD.cards);
}
}
function tableOptions() {
if (nHands > 0) {
hitOrStay(h1.cards, h1);
if (nHands > 1) {
hitOrStay(h2.cards, h2);
if (nHands > 2) {
hitOrStay(h3.cards, h3);
}
}
dealerHitOrStay(hD.cards);
}
}
function recap() {
if (nHands > 0) {
wonOrLost(h1.cards, h1);
if (nHands > 1) {
wonOrLost(h2.cards, h2);
if (nHands > 2) {
wonOrLost(h3.cards, h3);
}
}
again();
}
}
function wonOrLost(cards, hand) {
var x = addValueOfCards(cards);
var y = addValueOfCards(hD.cards);
if (x < 19 && (x > y || y > 18)) {
console.log("\n" + hand.name + ": You Won. (you had " + x + ", dealer had " + y + ")");
hand.cChips = hand.cChips + hand.betAmount;
console.log(" + " + hand.betAmount);
}
else if (x < 18 && y < 19 && y > x) {
console.log("\n" + hand.name + ": You Lost. (you had " + x + ", dealer had " + y + ")");
hand.cChips = hand.cChips - hand.betAmount;
console.log(" - " + hand.betAmount);
}
else if (x > 18) {
console.log("\n" + hand.name + ": You Lost. (you busted with " + x + ")");
hand.cChips = hand.cChips - hand.betAmount;
console.log(" - " + hand.betAmount);
}
else {
console.log("\n" + hand.name + ": You Tied. (you and dealer both had " + x + ")");
console.log(" + 0");
}
}
function again() {
if (deck.length > 10) {
xxxx = prompt("Hit Enter to play another round. Type NO, then hit enter, to stop playing.").toLowerCase();
if (xxxx === "no") {
console.log("You chose to stop. Thanks for playing!");
}
else {
console.log("____________\n");
recordBetAmount();
dealCards();
tableOptions();
recap();
}
}
else {
console.log("\nGame Over! (not enough cards to keep playing)");
console.log("_________________________________________________");
if (nHands === 1) {
x = h1.cChips; }
else if (nHands === 2) {
x = h1.cChips + h2.cChips; }
else if (nHands === 3) {
x = h1.cChips + h2.cChips + h3.cChips; }
if (x > 150000) {
x = x - 150000;
console.log("Your total score is: " + x); }
else { console.log("Your total score is: 0. (which is the worst you can do)"); }
}
}
numHands();
recordBetAmount();
dealCards();
tableOptions();
recap();
</code></pre>
|
[] |
[
{
"body": "<p>My <a href=\"https://codereview.stackexchange.com/a/37900/9357\">remarks about the Ruby version of your code</a> also apply to your JavaScript port.</p>\n\n<p>For example <code>hitOrStay()</code> should not recurse, because you're just using it as a <code>goto</code>.</p>\n\n<p>The players' hands should be stored in an array so that you don't have to write special cases for one, two, or three players.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T07:19:25.863",
"Id": "38061",
"ParentId": "38057",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T02:14:18.417",
"Id": "38057",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"game",
"playing-cards"
],
"Title": "Hot 18 game (modified Blackjack) in JavaScript"
}
|
38057
|
<p>I have built a partial human brain model and the following is an example of how I use all the classes. I was wondering if anyone could critique my implementation strategies because I feel like the following setup is very clumsy. You can view all the code at:
<a href="https://github.com/quinnliu/WalnutiQ" rel="nofollow">https://github.com/quinnliu/WalnutiQ</a> </p>
<pre><code>public class HowToUseMARK_I extends junit.framework.TestCase {
private NervousSystem nervousSystem;
private MemoryClassifier memoryClassifier_Digits;
private Gson gson;
public void setUp() throws IOException {
this.gson = new Gson();
this.nervousSystem = this.constructConnectedNervousSystem();
this.memoryClassifier_Digits = this.trainMemoryClassifierWithNervousSystem();
}
private NervousSystem constructConnectedNervousSystem() {
// construct Neocortex with just V1
Region rootRegionOfNeocortex = new Region("V1", 4, 4, 4, 50, 3);
RegionToRegionConnect neocortexConnectType = new RegionToRegionRectangleConnect();
Neocortex unconnectedNeocortex = new Neocortex(rootRegionOfNeocortex,
neocortexConnectType);
// construct LGN
Region LGNRegion = new Region("LGN", 8, 8, 1, 50, 3);
LateralGeniculateNucleus unconnectedLGN = new LateralGeniculateNucleus(
LGNRegion);
// construct Retina
VisionCell[][] visionCells = new VisionCell[65][65];
for (int x = 0; x < visionCells.length; x++) {
for (int y = 0; y < visionCells[0].length; y++) {
visionCells[x][y] = new VisionCell();
}
}
Retina unconnectedRetina = new Retina(visionCells);
// construct 1 object of NervousSystem to encapsulate all classes in
// MARK II
NervousSystem nervousSystem = new NervousSystem(unconnectedNeocortex,
unconnectedLGN, unconnectedRetina);
// connect Retina to LGN
Retina retina = nervousSystem.getPNS().getSNS().getRetina();
LateralGeniculateNucleus LGN = nervousSystem.getCNS().getBrain()
.getThalamus().getLGN();
SensorCellsToRegionConnect retinaToLGN = new SensorCellsToRegionRectangleConnect();
retinaToLGN.connect(retina.getVisionCells(), LGN.getRegion(), 0, 0);
// connect LGN to V1 Region of Neocortex
Neocortex neocortex = nervousSystem.getCNS().getBrain().getCerebrum()
.getCerebralCortex().getNeocortex();
RegionToRegionConnect LGNToV1 = new RegionToRegionRectangleConnect();
LGNToV1.connect(LGN.getRegion(), neocortex.getCurrentRegion(), 0, 0);
return nervousSystem;
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, nobody said that modelling the brain would be easy.</p>\n\n<p>However, it you find that it takes a lot of code to set up the nervous system model, it's probably a sign that your library is underdeveloped. Maybe the library should include some kind of <code>NervousSystemFactory</code> for convenience. Maybe the library should support a configuration file to describe the connections. YAML, for example, lets you <a href=\"http://www.yaml.org/spec/1.2/spec.html#id2786196\" rel=\"nofollow\">reference other nodes within a document</a>, which might be a useful feature for this application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T09:18:44.237",
"Id": "38062",
"ParentId": "38060",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>I would consider making this code:</p>\n\n<pre><code>// construct Retina\nVisionCell[][] visionCells = new VisionCell[65][65];\nfor (int x = 0; x < visionCells.length; x++) {\n for (int y = 0; y < visionCells[0].length; y++) {\n visionCells[x][y] = new VisionCell();\n }\n}\n</code></pre>\n\n<p>a factory method on <code>Retina</code> (passing in the dimensions of the cell array) as it will probably be a common thing to create.</p></li>\n<li><p>Call chains like these <code>nervousSystem.getPNS().getSNS().getRetina()</code> are a code smell. You could model your nervous system as some kind of repository where you can query the individual components like this:</p>\n\n<pre><code>nervousSystem.getRetina();\nnervousSystem.getBrain();\n</code></pre>\n\n<p>or fully generic (additional bonus points ;))</p>\n\n<pre><code>nervousSystem.get<Retina>();\nnervousSystem.get<Brain>();\n</code></pre>\n\n<p>More complex components like <code>Brain</code> can then be modeled in the same way:</p>\n\n<pre><code>nervousSystem.get<Brain>().get<Neocortex>();\n</code></pre>\n\n<p>This alleviates the caller from having to know the internal structure.</p></li>\n<li><p>I find it quite weird that your ctor for the <code>NervousSystem</code> only takes some very specific components of individual subsystems. From the looks of it the <code>NervousSystem</code> is composed out of <code>PNS</code> and <code>CNS</code> with <code>SNS</code> being part of the <code>PNS</code> and <code>Brain</code> being part of the <code>CNS</code> etc. so I'm wondering why the <code>NervousSystem</code> is not being built like that but gets some very specific subcomponents instead.</p>\n\n<p>I would have thought the setup should look something like this (I haven't checked the code on github so the class names are purely guesswork):</p>\n\n<pre><code>Neocortex neocortex = new Neocortex(...);\nCerebralCortex cerebralCortex = new CerebralCortex(neocortex, ...);\nCerebrum cerebrum = new Cerebrum(cerebralCortex, ...);\n\nLateralGeniculateNucleus lgn = new LateralGeniculateNucleus(...);\nThalamus thalamus = new Thalamus(lgn, ...);\n\nBrain brain = new Brain(cerebrum, thalamus, ...);\nCNS cns = new CNS(brain, ...);\n\nRetina retina = new Retina(...);\nSNS sns = new SNS(retina, ...);\nPNS pns = new PNS(sns, ...);\n\nNervousSystem nervousSystem = new NervousSystem(cns, pns);\n</code></pre></li>\n<li><p>For wiring individual components up you could pass a <code>WiringStrategy</code> into the <code>NervousSystem</code> which decides how things are wired up (so you can simulate broken wiring for example).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T18:05:35.620",
"Id": "63388",
"Score": "0",
"body": "Hi Chris, thank you very much. To answer your 3rd question I have only implemented very small parts of the brain and if I created the setup you suggested I would just have a lot of filler classes right now. But your suggested setup is the goal ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T07:25:52.547",
"Id": "63621",
"Score": "0",
"body": "I like your idea in #2. Can you explain how I can make the getter method fully generic? Like do I need a class that everything in a Nervous System extends?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T11:37:32.467",
"Id": "38065",
"ParentId": "38060",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38065",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T06:31:40.927",
"Id": "38060",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"unit-testing",
"junit"
],
"Title": "Review of java interface for constructing brain model"
}
|
38060
|
<p>I have solved the question, and in turn felt the need to get it reviewed. Any suggestions for clean up and optimization would help. Also please verify my complexity: \$O(V + E)\$.</p>
<p><code>GraphCycleDetection</code> should be named to <code>Graph</code>, but it was named on purpose to avoid conflict in Eclipse workspaces, so please ignore renaming it as part of feedback.</p>
<p>Thanks to <a href="http://www.keithschwarz.com/" rel="nofollow">Keith Schwarz's code</a>, which was a huge inspiration in designing my classes.</p>
<pre><code>class GraphCycleDetection<T> implements Iterable<T> {
/* A map from nodes in the graph to sets of outgoing edges. Each
* set of edges is represented by a map from edges to doubles.
*/
private final Map<T, Map<T, Double>> graph = new HashMap<T, Map<T, Double>>();
/**
* Adds a new node to the graph. If the node already exists then its a
* no-op.
*
* @param node Adds to a graph. If node is null then this is a no-op.
* @return true if node is added, false otherwise.
*/
public boolean addNode(T node) {
if (node == null) {
throw new NullPointerException("The input node cannot be null.");
}
if (graph.containsKey(node)) return false;
graph.put(node, new HashMap<T, Double>());
return true;
}
/**
* Given the source and destination node it would add an arc from source
* to destination node. If an arc already exists then the value would be
* updated the new value.
*
* @param source the source node.
* @param destination the destination node.
* @param length if length if
* @throws NullPointerException if source or destination is null.
* @throws NoSuchElementException if either source of destination does not exists.
*/
public void addEdge (T source, T destination, double length) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
/* A node would always be added so no point returning true or false */
graph.get(source).put(destination, length);
}
/**
* Removes an edge from the graph.
*
* @param source If the source node.
* @param destination If the destination node.
* @throws NullPointerException if either source or destination specified is null
* @throws NoSuchElementException if graph does not contain either source or destination
*/
public void removeEdge (T source, T destination) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
graph.get(source).remove(destination);
}
/**
* Given a node, returns the edges going outward that node,
* as an immutable map.
*
* @param node The node whose edges should be queried.
* @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null.
* @throws NoSuchElementException If node is not in graph.
*/
public Map<T, Double> edgesFrom(T node) {
if (node == null) {
throw new NullPointerException("The node should not be null.");
}
Map<T, Double> edges = graph.get(node);
if (edges == null) {
throw new NoSuchElementException("Source node does not exist.");
}
return Collections.unmodifiableMap(edges);
}
/**
* Returns the iterator that travels the nodes of a graph.
*
* @return an iterator that travels the nodes of a graph.
*/
@Override public Iterator<T> iterator() {
return graph.keySet().iterator();
}
}
/**
*
* Complexity:
* O (V + E)
* http://stackoverflow.com/questions/6850357/explanation-of-runtimes-of-bfs-and-dfs
*/
public final class DAGCycleDetection {
private DAGCycleDetection() { }
/**
* Returns true if graph contains a cycle else returns false
*
* @param graph the graph to check for cycle
* @return true if cycle exists, else false.
*/
public static <T> boolean cycle(GraphCycleDetection<T> graph) {
final Set<T> visitedNodes = new HashSet<T>();
final Set<T> completedNodes = new HashSet<T>();
for (T node : graph) {
if (dfs(graph, node, visitedNodes, completedNodes)) return true;
}
return false;
}
/**
* Returns true if graph contains a cycle else returns false
*
*
* @param graph the graph, which should be checked for cycles
* @param node the current node whose edges should be traversed.
* @param visitedNodes the nodes visited so far.
* @return true if graph contains a cycle else return false;
*/
private static <T> boolean dfs (GraphCycleDetection<T> graph,
T node,
Set<T> visitedNodes,
Set<T> completedNodes
) {
assert graph != null;
assert node != null;
assert visitedNodes != null;
if (visitedNodes.contains(node)) {
if (completedNodes.contains(node)) return false;
return true;
}
visitedNodes.add(node); // constitues O(1) for each vertex
for (Entry<T, Double> entry : graph.edgesFrom(node).entrySet()) {
if (dfs(graph, entry.getKey(), visitedNodes, completedNodes)) return true;
}
completedNodes.add(node);
return false;
}
public static void main(String[] args) {
GraphCycleDetection<Integer> gcd1 = new GraphCycleDetection<Integer>();
gcd1.addNode(1); gcd1.addNode(2); gcd1.addNode(3);
gcd1.addEdge(1, 2, 10); gcd1.addEdge(2, 3, 10); gcd1.addEdge(1, 3, 10);
System.out.println("Expected false, Actual: " + cycle(gcd1));
GraphCycleDetection<Integer> gcd2 = new GraphCycleDetection<Integer>();
gcd2.addNode(1); gcd2.addNode(2); gcd2.addNode(3);
gcd2.addEdge(1, 2, 10); gcd2.addEdge(2, 3, 10); gcd2.addEdge(3, 1, 10);
System.out.println("Expected true, Actual: " + cycle(gcd2));
GraphCycleDetection<Integer> gcd3 = new GraphCycleDetection<Integer>();
gcd3.addNode(1); gcd3.addNode(2); gcd3.addNode(3); gcd3.addNode(4); gcd3.addNode(5);
gcd3.addEdge(1, 2, 10); gcd3.addEdge(2, 3, 10); gcd3.addEdge(2, 4, 10); gcd3.addEdge(3, 4, 10); gcd3.addEdge(4, 5, 10);
System.out.println("Expected false, Actual: " + cycle(gcd3));
GraphCycleDetection<Integer> gcd4 = new GraphCycleDetection<Integer>();
gcd4.addNode(1); gcd4.addNode(2); gcd4.addNode(3); gcd4.addNode(4); gcd4.addNode(5);
gcd4.addEdge(1, 2, 10); gcd4.addEdge(2, 3, 10); gcd4.addEdge(2, 4, 10); gcd4.addEdge(3, 4, 10); gcd4.addEdge(4, 5, 10); gcd4.addEdge(5, 2, 10);
System.out.println("Expected true, Actual: " + cycle(gcd4));
// disconnected graph.
GraphCycleDetection<Integer> gcd5 = new GraphCycleDetection<Integer>();
gcd5.addNode(1); gcd5.addNode(2); gcd5.addNode(3); gcd5.addNode(10); gcd5.addNode(11);
gcd5.addEdge(1, 2, 10); gcd5.addEdge(2, 3, 10); gcd5.addEdge(3, 1, 10); gcd5.addEdge(10, 11, 10);
System.out.println("Expected true, Actual: " + cycle(gcd5));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T12:41:21.197",
"Id": "63356",
"Score": "2",
"body": "You use a *weighted* directed graph, while you only need a directed graph. Why the [Premature Generalization](http://c2.com/cgi/wiki?PrematureGeneralization)? YAGNI."
}
] |
[
{
"body": "<p>Just something minor:</p>\n\n<p>I'm not sure why you keep on insisting to name data structures after specific algorithms (you seem to do that in most of your code you post).</p>\n\n<ol>\n<li><p><code>GraphCycleDetection</code> is a graph and should therefore be named <code>Graph</code>. It can be used for many other things not just for cycle detection. </p></li>\n<li><p><code>DAGCycleDetection</code> is a bit of an oxymoron: DAG means Directed Acyclic Graph which by definition contains no cycles. The class should probably just be named <code>GraphCycleDetection</code> (which is possible if you name your data structure properly).</p></li>\n<li><p><code>cycle</code> should be named <code>hasCycle</code> - this will make it clear just by reading the method name of what the return value represents.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T18:33:19.867",
"Id": "63390",
"Score": "0",
"body": "I am fully aware of my naming being distorted. Its done because I dont want conflicts in my eclipse workspace. `GraphCycleDetection should be named to Graph, but named on purpose to avoid conflict in eclipse workspaces, please ignore renameming it as part of feedback.`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T11:56:48.157",
"Id": "38066",
"ParentId": "38063",
"Score": "3"
}
},
{
"body": "<p>You are going about this wrong.... closing the stable door after the horse has bolted.</p>\n\n<p>Your <code>addEdge()</code> method should throw an exception if adding the edge would result in an invalid DAG.</p>\n\n<p>This way you can guarantee that there are no cycles, your Graph is always valid, and you do not need to do a monolithic 'stop the world' check for every node.</p>\n\n<p>Checking for cycles <strong>before</strong> adding an edge is a whole lot easier too (although not necessarily faster) because you do not need to rely on any complicated memory structures to do it.</p>\n\n<pre><code>private boolean isReachable(T target, T from) {\n if (target.equals(from)) {\n return true;\n }\n for (T nxt : graph.get(from).keySet()) {\n if (isReachable(target, nxt)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>Then, in your <code>addEdge(...)</code> method you can simply:</p>\n\n<pre><code>if (isReachable(source, destination)) {\n throw new IllegalArgumentException(\"Cannot add this edge because it would create a cycle\");\n}\n</code></pre>\n\n<p>While this method for pre-validating the graph may, in the long run, consume (slightly) more time than a single global graph-validation, it will allow a number of other processes to make better choices and assumptions. Being able to guarantee an acyclic graph at all times is very beneficial.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T13:16:09.593",
"Id": "38067",
"ParentId": "38063",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38067",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T10:06:21.870",
"Id": "38063",
"Score": "8",
"Tags": [
"java",
"graph"
],
"Title": "Check if directed graph contains a cycle"
}
|
38063
|
<p>I have such a problem:</p>
<p>I'm parsing a lot of HTML files with Simple HTML DOM Parser, that's why I need to use three <code>foreach</code>s to parse the necessary information from it -> I am getting a lot of information and now I have three arrays which keep it. I think that it's dumb to keep the code like that and I want to keep the information in the class.</p>
<p>How can I do it in a right way? I really need your advice to have a good code in the future</p>
<p>Here is the code with three arrays:</p>
<pre><code>if(count($infos->find('.products-list-item')))
{
foreach ($infos->find('.products-list-item product-label, .products-list-item .products-list-item__brand, .products-list-item .products-list-item__type,.products-list-item .price') as $item_info)
{
$item_info_arr[] = $item_info->plaintext;
$i=0;
}
foreach ($infos->find('.products-list-item__img') as $img)
{
$src_arr[] = $img->src;
}
foreach ($infos->find('.products-list-item .products-list-item__sizes') as $sizes_info)
{
while($size = $sizes_info->children($k++))
{
$sizes_arr[] = $size->plaintext;
}
$k=0;
}
} else {echo "not found";}
</code></pre>
<p>But what can I do, then?</p>
|
[] |
[
{
"body": "<p>Please provide some more information, like the example contents of <code>$infos</code>. It is hard to find any other solution if we are not able to understand your current solution in the first place.</p>\n\n<p>However, there already are some issues with your code:</p>\n\n<ul>\n<li>avoid using variable names like <code>$i</code> and <code>$k</code>. They should be named according to their meaning (see example for <code>$k</code>)</li>\n<li><code>$i</code> seems not to be read in your code</li>\n<li><code>$k</code> and all arrays seem to be used uninitialized</li>\n</ul>\n\n<p>Your while loop seems a bit too clever to me. All you want to do is iterate $k so you should instead use a for loop:</p>\n\n<pre><code>for($childIndex = 0; $size = $sizes_info->children($childIndex); ++$childIndex)\n $sizes_arr[] = $size->plaintext;\n</code></pre>\n\n<p>The foreach loops look as if they could be better implemented by <code>array_map</code>:</p>\n\n<pre><code>$item_infos = $infos->find('.products-list-item product-label, .products-list-item .products-list-item__brand, .products-list-item .products-list-item__type,.products-list-item .price');\n$get_plaintext = function($item_info) { return $item_info->plaintext; };\n$item_info_arr = array_map($get_plaintext, $item_infos); \n</code></pre>\n\n<p>A foreach loop could be as readable however then you should at least use named variables (like <code>$item_infos</code> but with better names (I have no idea what this find returns)) to keep the head of the loop short and readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T13:01:08.063",
"Id": "38168",
"ParentId": "38064",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T11:10:42.247",
"Id": "38064",
"Score": "0",
"Tags": [
"php",
"array",
"classes"
],
"Title": "How to put a lot of information in the class?"
}
|
38064
|
<p><a href="http://projecteuler.net/problem=12" rel="nofollow">Project Euler Problem 12</a> asks (paraphrased):</p>
<blockquote>
<p>The <em>n</em><sup>th</sup> triangular number <em>T</em><sub><em>n</em></sub> = 1 + 2 + … + <em>n</em>. <em>T</em><sub>7</sub> = 28 has 6 divisors (1, 2, 4, 7, 14, 28). What is the first <em>T</em><sub><em>n</em></sub> to have over 500 divisors?</p>
</blockquote>
<p>After asking for some help on Stack Overflow, I've managed to write this code to solve it:</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <map>
//#include <algorithm>
#include <numeric>
int divisors (unsigned int num, std::map<int, int>& map)
{
int orig_num = num;
for(unsigned int i = 2; i <= num; ++i)
{
while (num % i == 0)
{
num /= i;
++map[i];
//std::cout << map[i] << "\t";
}
}
std::cout << orig_num << " = ";
for(auto& iter:map)
std::cout << iter.first << "^" << iter.second << " * ";
return 0;
}
int overall_factors(unsigned int n)
{
std::map <int, int> primefactors1, primefactors2;
int no_of_divisors = 1;
divisors(n,primefactors1);
std::cout << std::endl;
divisors(n+1,primefactors2);
std::cout << std::endl;
std::map<int, int> primefactors_triangle = std::accumulate( primefactors1.begin(), primefactors1.end(), std::map<int, int>(),
[]( std::map<int, int> &m, const std::pair<const int, int> &p )
{
return ( m[p.first] +=p.second, m );
} );
primefactors_triangle = std::accumulate( primefactors2.begin(), primefactors2.end(), primefactors_triangle,
[]( std::map<int, int> &m, const std::pair<const int, int> &p )
{
return ( m[p.first] +=p.second, m );
} );
for ( const auto &p : primefactors_triangle )
{
std::cout << "{ " << p.first << ", " << p.second << " } ";
if (p.first == 2)
no_of_divisors *= p.second;
else
no_of_divisors *= p.second+1;
}
std::cout << std::endl;
return no_of_divisors;
}
int main()
{
int i = 2;
while (overall_factors(i) < 500)
{
std::cout << overall_factors(i) << std::endl;
++i;
}
return 0;
}
</code></pre>
<p>There're some pieces left that output debugging info to see that everything is working as intended. But overall, it doesn't work as fast as I want it to - or as fast as I expect a proper solution to a Project Euler problem to work.</p>
<p>How can this code be improved? Clearly the program, as it is, now calculates <code>primefactors</code> for a given number twice. What else is wrong and could be improved? </p>
<p>UPD: After I changed the <code>while</code> loop condition, the problem was solved rather quickly. Still, I believe my code is improvable.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T17:02:10.873",
"Id": "63428",
"Score": "1",
"body": "[Optimization hints](http://stackoverflow.com/a/571526/4279) (Implementation in Python takes around 50ms)"
}
] |
[
{
"body": "<ul>\n<li><p>This:</p>\n\n<pre><code>int i = 2;\nwhile (overall_factors(i) < 500)\n{\n std::cout << overall_factors(i) << std::endl;\n ++i;\n}\n</code></pre>\n\n<p>can just be a <code>for</code>-loop:</p>\n\n<pre><code>for (int i = 2; overall_factors(i) < 500; ++i)\n{\n std::cout << overall_factors(i) << std::endl;\n}\n</code></pre>\n\n<p>I'd also recommend using a constant for <code>500</code> as it is otherwise a magic number. This will make it clear as to what this value represents.</p>\n\n<p>If the number isn't significant to the general algorithm, then a comment can be added instead.</p></li>\n<li><p>There is no need for <code>divisors</code> to just return a 0. It appears it's just modifying the map and displaying it. Also, these are two different things, and a function should just have one role. In this case, it should just modify the map. You should then have a separate <code>void</code> function for displaying the map in the desired format.</p>\n\n<p>Although passing the map by reference is okay here, passing it by value (in C++11) will also allow the compiler to decide to perform a move, if desired over a copy.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:01:17.510",
"Id": "63377",
"Score": "0",
"body": "Thanks. Could I just add a really clear comment about the intent behind `500` instead of using a constant for it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:03:30.760",
"Id": "63378",
"Score": "0",
"body": "You may, especially if the number is not that significant to the algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:05:44.547",
"Id": "63379",
"Score": "0",
"body": "originally the code had a commented link to the original project euler page about the problem (it's still in the code on my PC), therefore I expected anyone who'd read the code to read the problem statement & have a clear idea about the meaning of 500."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:09:32.033",
"Id": "63380",
"Score": "0",
"body": "I primarily meant that in general, as it's preferable to use as few magic numbers as possible. Not *every* such number needs a constant, just ones with a meaning behind them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:13:09.013",
"Id": "63381",
"Score": "0",
"body": "Got it, will try to follow yor advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T12:43:57.627",
"Id": "63493",
"Score": "0",
"body": "@Jamal: If parameter `map` in `divisors` is not needed (besides initializing `newMap`) then pass it by value and modify it instead. This avoids a copy an unused variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:21:18.570",
"Id": "63508",
"Score": "0",
"body": "@Nobody: That *may* be okay, if `map` is small and passing by value doesn't prove expensive. There's also move semantics, but I was hesitant about mentioning it since I've read that utilizing RVO is still preferred."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-18T09:07:05.373",
"Id": "95275",
"Score": "0",
"body": "@Jamal: passing `map` by value is no more expensive than making a copy in the function. Especially, it may be more efficient in C++11 since the compiler gets to decide between a copy and a move at parameter-passing time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-18T17:26:04.623",
"Id": "95427",
"Score": "0",
"body": "@LaurentLARIZZA: That is a good point. I'm not sure why I've considered this different. I'll update it."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T16:36:16.107",
"Id": "38079",
"ParentId": "38069",
"Score": "4"
}
},
{
"body": "<p>One thing you can do immediately to cut your running time by a large factor is to modify your <code>main</code> function:</p>\n\n<pre><code>int main() {\n int num_factors = 0;\n for (int i = 2; num_factors < 500; ++i) {\n num_factors = overall_factors(i);\n std::cout << num_factors << \"\\n\";\n }\n}\n</code></pre>\n\n<p>Two things:</p>\n\n<ol>\n<li>I only compute <code>overall_factors(i)</code> once instead of twice for each value of <code>i</code>.</li>\n<li>I output <code>\"\\n\"</code>, not <code>std::endl</code>, to end the line. <code>std::endl</code> not only outputs a line break, it flushes <code>std::cout</code>. Flushing output buffers is slow.</li>\n</ol>\n\n<p>Likewise, convert your <code>std::cout << std::endl</code> elsewhere into <code>std::cout << \"\\n\"</code> (or remove in-function input entirely) and you'll see a marked speed improvement. The buffer will automatically flush from time to time; if you want to see more frequent flushing, you can add this to your main loop:</p>\n\n<pre><code>if (!(i % 10)) std::cout << std::flush;\n</code></pre>\n\n<p>As to the rest of your code, it is somewhat difficult to review. Your functions and their parameters have uninformative names (e.g. <code>map</code> is not a good name for a <code>map</code> you're passing; <code>primefactorization</code> would be better in that case). Your lambdas confusingly return a statement of the form <code>return (foo(), bar());</code>; it is misleading to use the comma operator like that -- this isn't Python, your lambdas are allowed multiple statements!</p>\n\n<p>Why do you use <code>accumulate</code> at all? You can just pass the same map to both calls of <code>divisors</code> and get the same result as accumulating the two.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T23:11:05.240",
"Id": "63460",
"Score": "0",
"body": "Thanks for explaining the flushing issue. Also, I used `accumulate` to see how to - in other words, as an exercise. So I agree that there's a possibly better solution without it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T16:30:04.627",
"Id": "38121",
"ParentId": "38069",
"Score": "3"
}
},
{
"body": "<p>At a quick first-glance, one thing you can do that should cut run-time quite a bit is to change that STL map of ints to ints to an array of ints. I'm not sure how big your keys get, but even for some pretty large sizes this should be much quicker, but perhaps less elegant. In general STL maps have a reputation for being somewhat slow, so if you can eliminate your dependency on this data structure (a red-black tree) somehow, things should speed up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:49:41.400",
"Id": "38181",
"ParentId": "38069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T14:17:29.113",
"Id": "38069",
"Score": "3",
"Tags": [
"c++",
"c++11",
"project-euler",
"primes"
],
"Title": "Project Euler #12 in C++ - highly divisible triangular number"
}
|
38069
|
<p>I'm coding an algorithm to remove a parameter (let's call it <code>foo</code>) from URL strings.</p>
<p>Of course, after the <code>foo</code> parameter removal, the query string should remain valid (with a leading <code>?</code> and remaining parameters separated by <code>&</code>).</p>
<p>I'd also like to remove the leading <code>?</code> if <code>foo</code> was the only parameter.</p>
<h3>Details:</h3>
<ul>
<li>Domain and pathname should be preserved.</li>
<li>The URLs may not contain a query string. Expected output is the same as input.</li>
<li>The URLs may contain a query string which does not contain the <code>foo</code> parameter. Expected output is the same as input.</li>
<li>The URLs are already properly URL-encoded.</li>
<li>Fragments (hashes) don't necessarily need to be kept, but it would be a nice little extra.</li>
</ul>
<p>Input examples:</p>
<pre><code>http://example.com/?foo=42
http://example.com/?foo=42&bar=43
http://example.com/?bar=43&foo=42
http://example.com/?bar=43&foo=42&baz=44
http://domain.com.uk/pathname?foo=42&bar=bar%20value
http://yahoo.com/mail
http://nofoo.com/?bar=43
</code></pre>
<p>Expected output:</p>
<pre><code>http://example.com/
http://example.com/?bar=43
http://example.com/?bar=43
http://example.com/?bar=43&baz=44
http://domain.com.uk/pathname?bar=bar%20value
http://yahoo.com/mail
http://nofoo.com/?bar=43
</code></pre>
<p>My initial attempt:</p>
<pre><code>preg_replace_callback('/([?&])foo=[^&]+(&|$)/', function($matches) {
return $matches[2] ? $matches[1] : '';
}, $url);
</code></pre>
<p>The regex itself is rather simple. The callback logic is as follows: </p>
<ul>
<li>If <code>foo</code> is not the last parameter (2nd capturing group is not end of string), then the whole match is replaced by the first capturing group (<code>?</code> or <code>&</code>). This handles:
<ul>
<li><code>?foo=valuefoo&bar</code> -> <code>?bar</code></li>
<li><code>&foo=valuefoo&bar</code> -> <code>&bar</code></li>
</ul></li>
<li>If <code>foo</code> is the last parameter then the whole match is replaced by an empty string. This handles:
<ul>
<li><code>?bar=valuebar&foo=valuefoo</code> -> <code>?bar=valuebar</code></li>
<li><code>?foo=valuefoo</code> -> (empty string)</li>
</ul></li>
</ul>
<p>This logic seemed rather complicated, hence I rewrote it into a single regex:</p>
<pre><code>preg_replace('/[?&]foo=[^&]+$|([?&])foo=[^&]+&/', '$1', $url);
</code></pre>
<p>Now both logic branches are separated by the regex OR <code>|</code> and the 1st capturing group only occurs in the "foo is not the last parameter" branch.</p>
<p>I've looked at <a href="http://www.regular-expressions.info/conditional.html" rel="noreferrer">regex conditionals</a> but those would just overcomplicate an otherwise simple regex.</p>
<p>This seemed like a simple task at first glance, but now I'm wondering whether I should even use Regex for this.</p>
<p>Right now I'm thinking about <code>substr</code>'ing from the first <code>?</code>, <code>explode</code>ing the query string at <code>&</code>, <code>array_filter</code> based on the parameters names, <code>implode</code> and concatenate it to the URL again, but this looks overly verbose.</p>
<p>Is there a better approach (mainly in terms of readability and maintainability) to remove a query string parameter?</p>
<hr>
<p>New approach using native functions and borrowing some code from PHP docs' comments:</p>
<pre><code>//http://www.php.net/manual/en/function.parse-url.php#106731
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass@" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
function removeQueryParam($url, $param_to_remove) {
$parsed = parse_url($url);
if ($parsed && isset($parsed['query'])) {
$parsed['query'] = implode('&', array_filter(explode('&', $parsed['query']), function($param) use ($param_to_remove) {
return explode('=', $param)[0] !== $param_to_remove;
}));
if ($parsed['query'] === '') unset($parsed['query']);
return unparse_url($parsed);
} else {
return $url;
}
}
</code></pre>
<p>It works fine even with hashes/fragments now. Is there anything else to be improved? As far as I can see, there's no native method to parse a query string into an array, hence the <code>explode</code>, <code>array_filter</code> and <code>implode</code> method is the more maintainable I could get.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T09:59:13.527",
"Id": "63411",
"Score": "0",
"body": "dear lord, I'm sorry to say this but: Gloves... yes [gloves](http://thedailywtf.com/Articles/The_Complicator_0x27_s_Gloves.aspx) exist, that's why the market for electrically heated bike handles won't be massive"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T10:49:03.893",
"Id": "63413",
"Score": "0",
"body": "@EliasVanOotegem heh I haven't read that one before, nice one. So on-topic, I should've kept my first revision...? Mhm, guess I'm a bit of a complicator for making this question. `=]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T11:17:20.507",
"Id": "63414",
"Score": "0",
"body": "@EliasVanOotegem you can submit \"gloves\" as an answer if you'd like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T11:24:04.560",
"Id": "63415",
"Score": "0",
"body": "No, that's just a side-note. It doesn't reflect on the overall quality of the code or possible redundancies (haven't looked at the code, just glanced at it, and thought gloves). If you'd look at my previous answers here, you'd know that I'm incapable of posting short answers. I have to go through the code, or at least a sizable piece of it, line by line..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T11:28:43.917",
"Id": "63416",
"Score": "0",
"body": "@EliasVanOotegem anyway, thank you, I often over-complicate things and need someone to make me realize that."
}
] |
[
{
"body": "<p>URL's are a nightmare to process. Even though, in your case, it appears that you can use regex to isolate your specific problem, I would still recommend that you avoid regex for URL manipulation.</p>\n\n<p>PHP has native URL parsing methods (much better tested and controlled than your code), and you should use them where possible. Have a look at <a href=\"https://secure.php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\">the parse_url documentation</a>. You can use this, as well as some of the other example code on that page to parse, and rebuild the URL with the changed parameters.</p>\n\n<p>Using 'native' functions where possible is often the best solution. Even though the native function does not do the entirety of what you want done, it goes a long way to simplifying the process, and the regexes become more manageable. In this case, I think it is the right solution too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T16:17:28.283",
"Id": "63374",
"Score": "0",
"body": "I've used parse_url in the past, I just went for the quick and dirty Regex method because it seemed like a simple task but now I realize it is not that simple. Thanks for the pointers, I'll analyze this when I get home."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T15:54:37.220",
"Id": "38076",
"ParentId": "38070",
"Score": "3"
}
},
{
"body": "<p>I would also avoid using regexes or any kind of manual string parsing, you can do it all with <a href=\"http://www.php.net/manual/en/function.parse-str.php\"><code>parse_str()</code></a> and <a href=\"http://www.php.net/manual/en/function.http-build-query.php\"><code>http_build_query()</code></a>, thusly:</p>\n\n<pre><code>function removeAndReturn(&$url, $toRemove)\n{\n $parsed = [];\n parse_str(substr($url, strpos($url, '?') + 1), $parsed);\n $removed = $parsed[$toRemove];\n unset($parsed[$toRemove]);\n $url = 'http://example.com/';\n if(!empty($parsed))\n {\n $url .= '?' . http_build_query($parsed);\n }\n return $removed;\n}\n</code></pre>\n\n<p>Then with a simple script to test it:</p>\n\n<pre><code>$input = ['http://example.com/?foo=42',\n 'http://example.com/?foo=42&bar=43',\n 'http://example.com/?bar=43&foo=42',\n 'http://example.com/?bar=43&foo=42&baz=44'];\n\n$expected = ['http://example.com/',\n 'http://example.com/?bar=43',\n 'http://example.com/?bar=43',\n 'http://example.com/?bar=43&baz=44'];\n\n\n$count = count($input);\nfor($i = 0; $i < $count; $i++)\n{\n $foo = removeAndReturn($input[$i], 'foo');\n echo 'Foo: ' . $foo . '<br />' .\n 'URL: ' . $input[$i] . '<br />';\n if($input[$i] === $expected[$i])\n echo 'Match<br />';\n}\n</code></pre>\n\n<p>You get:</p>\n\n<pre><code>Foo: 42\nURL: http://example.com/\nMatch\nFoo: 42\nURL: http://example.com/?bar=43\nMatch\nFoo: 42\nURL: http://example.com/?bar=43\nMatch\nFoo: 42\nURL: http://example.com/?bar=43&baz=44\nMatch\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T10:36:42.210",
"Id": "63412",
"Score": "0",
"body": "Thanks. It'd be better to save the part prior to `?`, this way it would handle other domains and pathnames. I'd also add a check to see if the URL contains a `?` - it looks like this will fail when there's no query string. There is one more thing I didn't mention in the question, my URLs are already properly encoded so `http_build_query` would double-encode them: http://codepad.viper-7.com/3vYTm4"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T04:21:37.383",
"Id": "38097",
"ParentId": "38070",
"Score": "5"
}
},
{
"body": "<p>For this task I suggest to use as much as possible standard PHP functions, since in complex cases they've been proved to be more reliable than a simple regexp or a 'manual' explode/implode solution.\nUnfortunately, there seems not to be a standard PHP 'reverse' function for parse_url(), except for those posted by users on parse_url official PHP manual page <a href=\"http://php.net/manual/en/function.parse-url.php\" rel=\"nofollow\">http://php.net/manual/en/function.parse-url.php</a>.</p>\n\n<p>So, my solution is a blend of 3 standard PHP functions (parse_url + parse_str + http_build_query) + 1 user contributed function found on PHP manual page (unparse_url):</p>\n\n<pre><code>function removeParam($key, $sourceURL) { // Removes parameter '$key' from '$sourceURL' query string (if present)\n $url = parse_url($sourceURL);\n if (!isset($url['query'])) return $sourceURL;\n parse_str($url['query'], $query_data);\n if (!isset($query_data[$key])) return $sourceURL;\n unset($query_data[$key]);\n $url['query'] = http_build_query($query_data);\n return unparse_url($url);\n}\n\nfunction unparse_url($parsed_url) { \n $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; \n $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; \n $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; \n $user = isset($parsed_url['user']) ? $parsed_url['user'] : ''; \n $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; \n $pass = ($user || $pass) ? \"$pass@\" : ''; \n $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; \n $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; \n $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; \n return \"$scheme$user$pass$host$port$path$query$fragment\"; \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-07T16:25:59.800",
"Id": "86160",
"ParentId": "38070",
"Score": "2"
}
},
{
"body": "<p>This can easily be done with in .htaccess.</p>\n\n<p>Just add this to your .htaccess file:</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{QUERY_STRING} ^(.*)&?foo=42?(.*)$ [NC]\nRewriteRule ^/?(.*)$ /$1?%1%2 [R=301,L]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-05T07:55:42.620",
"Id": "395422",
"Score": "1",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-06T11:09:50.777",
"Id": "395535",
"Score": "0",
"body": "Please delete my contribution if you think people are better off without it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-05T00:47:28.263",
"Id": "204979",
"ParentId": "38070",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "38076",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T14:27:29.297",
"Id": "38070",
"Score": "6",
"Tags": [
"php",
"regex",
"url"
],
"Title": "Remove a parameter and its value from URL's query string"
}
|
38070
|
<p>I have an application for transferring files from clients to a server. A client opens, transfers a file to the server and closes. The server is open and may receive multiple files. Also, when transferring a file, a loader bar is created on both server (the server must have some way to display multiple loaders simultaneously) and client. Also, every file transfer is handled in a separate thread on server.
This is a structure that will be used in server function:</p>
<pre><code>struct fileWriteArgs{
int childNumber;
int sockfd;
};
</code></pre>
<p><strong>Here is the server function</strong> (the main function just parses arguments and calls this):</p>
<pre><code>int serverFileTransfer(int port, char* filename){
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd<0)
errorOpeningSocket();
struct sockaddr_in serv_addr, cli_addr;
memset((char*) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
errorOnBinding();
listen(sockfd, 5);
socklen_t cilen = sizeof(cli_addr);
pthread_t newThread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
int noOfChilds = 0;
while(1){
int newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &cilen);
noOfChilds++;
struct fileWriteArgs args;
args.sockfd = newsockfd;
args.childNumber = noOfChilds;
if(newsockfd < 0)
errorOnAccept();
pthread_create(&newThread, &attr, &fileWrite, &args);
}
pthread_attr_destroy(&attr);
return 0;
}
</code></pre>
<p>Basically, it opens a socket and creates threads for file accept (note that I am using a Linux operating system). Also, it calls some error functions that I think are pretty explicit (they just write a message and call <code>exit()</code>).</p>
<p><strong>Here are the <code>loader</code> and <code>fileWrite</code> functions:</strong></p>
<pre><code>void loader(int val, int max, int size, int row){
static int lastPrinted = 0;
int percent = (100.*val)/max;
int count = ((float)percent * size) / 100;
if(count == lastPrinted)
return;
if(row > 0){
printf("\033[s"); //save current position
printf("\033[%dB\n", row);
}
lastPrinted = count;
printf("\r[");
int i;
for(i = 0; i < count; i++)
printf("#");
for(; i < size; i++)
printf(".");
printf("] %d%%", percent);
if(row > 0)
printf("\033[u");
fflush(stdout);
}
static pthread_mutex_t STDOUT_mutex = PTHREAD_MUTEX_INITIALIZER;
void* fileWrite(void *fd){
struct fileWriteArgs *p = (struct fileWriteArgs*)fd;
int sockfd = p->sockfd;
int childNumber = p->childNumber;
char sz[32];
read(sockfd, sz, 32);
int fileSize = atoi(sz);
char fileNameSize;
int readed = read(sockfd, &fileNameSize, 1);
if(readed < 0)
errorReadingFromSocket();
else if(fileNameSize == 0)
errorBadFileName();
char filename[256];
readed = read(sockfd, filename, fileNameSize);
if(readed < 0)
errorReadingFromSocket();
FILE *f = fopen(filename, "wb");
if(f == NULL){
errorOpeningFile();
}
char buffer[BUFFER_SIZE];
int n = 0;
while(n < fileSize){
readed = read(sockfd, buffer, BUFFER_SIZE);
if(readed < 0)
errorReadingFromSocket();
write(fileno(f), buffer, readed);
n += readed;
pthread_mutex_lock(&STDOUT_mutex);
loader(n, fileSize, LOADER_LENGTH, childNumber);
pthread_mutex_unlock(&STDOUT_mutex);
}
fclose(f);
return NULL;
}
</code></pre>
<p><strong>This is the client function:</strong></p>
<pre><code>int clientFileTransfer(char *ip, int port, char* filename){
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
errorOpeningSocket();
struct hostent* server = gethostbyname(ip);
if(server == NULL)
noServerFound();
struct sockaddr_in serv_addr;
memset((char*)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
bcopy((char*) server -> h_addr, (char*) &serv_addr.sin_addr.s_addr, server -> h_length);
if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
errorConnecting();
fileRead(filename, sockfd);
return 0;
}
</code></pre>
<p><strong>And the <code>fileRead</code> function:</strong></p>
<pre><code>void fileRead(char *filename, int sockfd){
FILE *f = fopen(filename, "rb");
if(f == NULL){
errorOpeningFile();
return;
}
fseek(f, 0, SEEK_END);
int fileSize = ftell(f);
fseek(f, 0, SEEK_SET);
char size[32];
sprintf(size, "%d", fileSize);
write(sockfd, size, 32);
char *name = strrchr(filename, '/');
if(name == NULL)
name = filename;
else
name++;
char fileNameSize = strlen(name)+1;
write(sockfd, &fileNameSize, 1); //WARNING! it works only for files
//with at most 255 characters
write(sockfd, name, strlen(name)+1);
int n = 0; //total bytes read/written
char buffer[BUFFER_SIZE];
while(!feof(f)){
int read = fread(buffer, 1, BUFFER_SIZE, f);
if(read < 0)
errorReadingFromFile();
write(sockfd, buffer, read);
n+=read;
loader(n, fileSize, LOADER_LENGTH, 0);
}
fclose(f);
}
</code></pre>
<p>The <code>clientFileTransfer</code> and <code>fileRead</code> functions are used by the client in a similar manner to <code>serverFileTransfer</code> and <code>fileWrite</code>, that are used by server. </p>
<p>As the code is pretty large, I would like some parts to be reviewed especially, as I feel there is something wrong there. My primary concern is the loader function. It has a static variable that keeps the value that was written last time when the function was called (to avoid printing the same thing all over again). I do not know if this is a good thing. Also this is my first multithreaded application, so I would like some remarks about the way that multithreading is implemented here.</p>
<p>Of course, I would really appreciate if I get also a review of the other parts of this application and remarks about it (what I have done right and where something is wrong).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T19:40:29.993",
"Id": "63393",
"Score": "0",
"body": "I know that and I specified the parts that I am interested in, but I tought it will be nice if I show the whole thing, maybe I will get a superficial remark at least."
}
] |
[
{
"body": "<p>Nice code in general. Many of my comments are a bit on the\nnit-picking level, so apologies in advance.</p>\n\n<p>Your method of error handling seems to be just to exit, so the return\nvalues from various functions should probably be <code>void</code>. This method\nof error handling is certainly easy but might be considered lazy :-) I\nnotice that you don't check for EINTR in any failed socket calls -\nshould it not be handled?</p>\n\n<p>Some of the variable names are too long for my taste. <code>newsockfd</code>\nfor example in the <code>accept</code> loop could be just <code>fd</code> with no loss. \n<hr>\nIn <code>fileRead</code> and <code>fileWrite</code></p>\n\n<p>These functions seem misnamed. Clearly one does read a file and one\nwrites but I think names containing 'send' and 'receive' would be\nclearer. Having <code>clientFileTransfer</code> 'connect' to the server socket\nand then do a <code>fileRead</code> implies to me that it is receiving a file\nwhen in fact it is sending!</p>\n\n<p>Some details I noticed are that <code>fileNameSize</code> should be unsigned if\nyou want to handle names up to 255 chars long. And it would be better\nto reject files with names longer than 255 instead of just adding a\nwarning comment.</p>\n\n<pre><code>unsigned char fileNameSize = strlen(name)+1;\nwrite(sockfd, &fileNameSize, 1); //WARNING! it works only for files\n //with at most 255 characters\n\nwrite(sockfd, name, strlen(name)+1);\n</code></pre>\n\n<p>In the <code>fileRead</code> code above you could re-use <code>fileNameSize</code> in the\nlast <code>write</code> call rather than repeating the <code>strlen</code> call. And your\n<code>read</code> and <code>write</code> calls here and elsewhere should really all be\nerror-checked (some are, some are not).</p>\n\n<p>When writing the file to disk, I don't see a good reason for opening\nthe file buffered (<code>fopen</code> from stdio) but writing un-buffered\n(<code>write</code>) - I would use <code>fwrite</code>.</p>\n\n<p>A minor point is that the 32 used as the file-size buffer </p>\n\n<pre><code>char sz[32];\nread(sockfd, sz, 32);\nint fileSize = atoi(sz);\n</code></pre>\n\n<p>should really be a constant defined in a header shared between client\nand server. And I would use it just once:</p>\n\n<pre><code>char sz[SIZE_BUFFER_SIZE];\nread(sockfd, sz, sizeof sz); // use sizeof\nint fileSize = atoi(sz);\n</code></pre>\n\n<p><hr>\nIn <code>serverFileTransfer</code> the <code>filename</code> parameter is not used. I\nwould expect to see the check for the accepted socket being invalid\nimmediately after the <code>accept</code> call. Also this socket is never closed\n(not here and not in the <code>fileWrite</code> thread.</p>\n\n<p>In <code>clientFileTransfer</code> the socket is not closed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T20:54:16.233",
"Id": "63452",
"Score": "0",
"body": "You have no reason to apologize. I appreciate your answer and it is really helpful. You said that you would use SIZE_BUFFER_SIZE only once, and then use sizeof operator. Why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T22:29:56.460",
"Id": "63458",
"Score": "1",
"body": "Just that the size of `sz` is guaranteed to be given by `sizeof sz`, whereas it is not guaranteed to be `SIZE_BUFFER_SIZE` unless you really did dimension `sz` with that constant. In this case the two expressions are adjacent and it is clear, but in general they are not and it is easy for the definition and use to drift apart. BTW, `SIZE_BUFFER_SIZE` was just the first constant name that came to mind - you can probably improve it :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T14:05:59.867",
"Id": "38115",
"ParentId": "38071",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38115",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T14:55:05.137",
"Id": "38071",
"Score": "7",
"Tags": [
"c",
"multithreading",
"file",
"server"
],
"Title": "Client server application for file transfer"
}
|
38071
|
<p>I know there are countless questions on SO, and several articles on the web regarding this subject, but after looking at all the options, I was moved to write my own code to address my own requirements. However, this has raised a couple of questions for me that I would appreciate your valued input on.</p>
<p>First, the code:</p>
<pre><code><?php
// db config
$dbhost = "dbhost";
$dbuser = "dbuser";
$dbpass = "dbpass";
$dbname = "dbname";
// db connect
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// file header stuff
$output = "-- PHP MySQL Dump\n--\n";
$output .= "-- Host: $dbhost\n";
$output .= "-- Generated: " . date("r", time()) . "\n";
$output .= "-- PHP Version: " . phpversion() . "\n\n";
$output .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n\n";
$output .= "--\n-- Database: `$dbname`\n--\n";
// get all table names in db and stuff them into an array
$tables = array();
$stmt = $pdo->query("SHOW TABLES");
while($row = $stmt->fetch(PDO::FETCH_NUM)){
$tables[] = $row[0];
}
// process each table in the db
foreach($tables as $table){
$fields = "";
$sep2 = "";
$output .= "\n-- " . str_repeat("-", 60) . "\n\n";
$output .= "--\n-- Table structure for table `$table`\n--\n\n";
// get table create info
$stmt = $pdo->query("SHOW CREATE TABLE $table");
$row = $stmt->fetch(PDO::FETCH_NUM);
$output.= $row[1].";\n\n";
// get table data
$output .= "--\n-- Dumping data for table `$table`\n--\n\n";
$stmt = $pdo->query("SELECT * FROM $table");
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
// runs once per table - create the INSERT INTO clause
if($fields == ""){
$fields = "INSERT INTO `$table` (";
$sep = "";
// grab each field name
foreach($row as $col => $val){
$fields .= $sep . "`$col`";
$sep = ", ";
}
$fields .= ") VALUES";
$output .= $fields . "\n";
}
// grab table data
$sep = "";
$output .= $sep2 . "(";
foreach($row as $col => $val){
// add slashes to field content
$val = addslashes($val);
// replace stuff that needs replacing
$search = array("\'", "\n", "\r");
$replace = array("''", "\\n", "\\r");
$val = str_replace($search, $replace, $val);
$output .= $sep . "'$val'";
$sep = ", ";
}
// terminate row data
$output .= ")";
$sep2 = ",\n";
}
// terminate insert data
$output .= ";\n";
}
// output file to browser
header('Content-Description: File Transfer');
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $dbname . '.sql');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen($output));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
echo $output;
?>
</code></pre>
<p>In a nutshell, I am trying to emulate the sort of file that I would get from phpMyAdmin when using the 'Export' function. The code appears to work so far and I have used the generated file to restore a test database consisting of five tables, each of a few thousand rows.</p>
<p>My questions:</p>
<p>Is it acceptable to place numeric variables within single quotes for purposes of a db restore, or should I really be adding code to grab each field's data type and alter the structure of the resultant file accordingly?</p>
<p>This section worries me the most:</p>
<pre><code>// add slashes to field content
$val = addslashes($val);
// replace stuff that needs replacing
$search = array("\'", "\n", "\r");
$replace = array("''", "\\n", "\\r");
$val = str_replace($search, $replace, $val);
</code></pre>
<p>Although the \n and \r replacements appear to work as expected (as far as I can tell), I noticed that the phpMyAdmin export file escaped a single quote (') as (''). I'm honestly not that clued up on the syntax to know if my implementation leaves a lot to be desired. Have I missed anything?</p>
<p>Ultimately, I would prefer it if this code would work for almost all, if not 100% of cases.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:30:15.387",
"Id": "63362",
"Score": "1",
"body": "Could you possibly make use of mysqldump instead of trying to format the data yourself? You could use PHP's exec() command to capture the command's output and funnel it to the browser."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:32:23.723",
"Id": "63363",
"Score": "0",
"body": "@Lotharyx: Try as I might, I cannot get that to work on my hosting server. I suspect that functionality is disabled somehow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:33:13.273",
"Id": "63364",
"Score": "0",
"body": "phpMyAdmin is open-source. You could just observe its code to find out how it does it, since it's the behavior you want to mimic after all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:49:32.850",
"Id": "63366",
"Score": "0",
"body": "@bishop: Thanks, finally some advice I can use. Is there an easy way to migrate this question over to there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:53:20.250",
"Id": "63367",
"Score": "0",
"body": "[Yes generally](http://meta.stackexchange.com/questions/85017/moving-my-own-question-to-another-stackexchange-site), but you don't have enough rep to move to codereview. Flag it as needing moderator attention and mention you want it moved to codereview. And ping me with the new URL, so I can put my answer there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:57:03.293",
"Id": "63368",
"Score": "0",
"body": "Reinventing the wheel is indeed not rocket science."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:57:06.897",
"Id": "63369",
"Score": "0",
"body": "@bishop: Flagged for a move, thank you for your help."
}
] |
[
{
"body": "<p>The following will make use of mysql dump executable to dump the database to a file of your choice. The mysqldump command takes care of adding quotes and scaping characters. In PHP the following should work:</p>\n\n<pre><code><?php\n\necho exec('mysqldump –-user [user name] –-password=[password] [database name] > [dump file]');\n\n//or\n\necho exec('mysqldump –u[user name] –p[password] [database name] > [dump file]');\n\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-13T13:06:16.500",
"Id": "170086",
"Score": "0",
"body": "system, exec and shell_exec are often blocked by administrators of PHP hosting. With a message like \"Warning: exec() has been disabled for security reasons\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:40:53.490",
"Id": "38073",
"ParentId": "38072",
"Score": "1"
}
},
{
"body": "<p>Yes, you may put numerals in quotes/apostrophes in your queries. But I don't think replacing <code>'</code> with <code>\\'</code> and so on cuts it. Use <strike>a variant of mysqli_real_escape_string if it exists for PDO</strike> <a href=\"http://www.php.net/manual/en/pdo.quote.php\" rel=\"nofollow\">PDO::quote()</a>.</p>\n\n<p>And even then I don't think your work is quite done. Does your code address outputting triggers, functions, etc?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T16:28:37.290",
"Id": "63427",
"Score": "0",
"body": "The pointer to PDO:quote() was extremely useful indeed. You're right about my work not being done though, I've just realised what I'm getting into here - this may well end up in the started-and-never-finished directory. Thanks anyway."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:56:34.097",
"Id": "38074",
"ParentId": "38072",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38074",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T21:25:57.510",
"Id": "38072",
"Score": "2",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "Dumping a MySQL database to a file using a PHP script"
}
|
38072
|
<p>I am writing an "Enter key pressed" event-handler, so when user presses the "enter" key in the input of type text, this code is called:</p>
<pre><code> var email = "";
var subscriberInput = $("input[name='subscriber_email']")
// Subscribe RSS
subscriberInput.keyup(function(e){
if(e.which == 13){ // Enter key was pressed
email = subscriberInput.val();
$.post("/en/subscriber/add", { email: email }).done(function(data){
if(data == "success"){
subscribeBox.find('div.row').remove();
if(isEnglish){
subscribeBox.find('h5').text("You're subscribed!").addClass('green-text');
} else {
subscribeBox.find('h5').text("Sunteti abonat cu success").addClass('green-text');
}
setTimeout(function(){
subscribeBox.fadeOut('slow');
}, 5000)
} else {
alert(data);
}
});
return false;
}
});
</code></pre>
<p>How can I improve this code?</p>
|
[] |
[
{
"body": "<p>A few things to note before I explain improvements</p>\n\n<ul>\n<li><p>Never forget <code>var</code> when declaring variables. I saw this in the code.</p>\n\n<pre><code>email = subscriberInput.val();\n</code></pre>\n\n<p>Now, best case scenario is that you declared <code>email</code> somewhere in the higher scopes. However, if it wasn't then JS will declare it as a global, which may have unforseen negative effects.</p></li>\n<li><p>If you run a site that has translation capabilities, I suggest you don't hard-code messages. Use translation libraries instead. That way, you can globally change language with just a flick of a switch.</p></li>\n</ul>\n\n<p>Then here's the improved code, given what you have:</p>\n\n<pre><code>subscriberInput.keyup(function (event) {\n\n // If you intent to prevent the default action of the enter, then I\n // suggest preventDefault() instead of return false\n event.preventDefault();\n\n // I recommend the \"return if fail\" pattern rather than \"run when true\"\n // because it removes unnecessary indentation. It's a case to case basis.\n if (event.which !== 13) return;\n\n $.post(\"/en/subscriber/add\", {\n // The context of the function is the input box. We can simply use\n // the value property instead of calling out val()\n email: this.value\n }).done(function (data) {\n\n // Similar to above, use strict comparison as much as possible\n if (data === \"success\") {\n\n // Avoid repeating code by factoring out common code. In this case,\n // what set the code apart was the message.\n var message = isEnglish ? \"You're subscribed!\" : \"Sunteti abonat cu success\";\n\n subscribeBox.find('div.row')\n .remove();\n\n // jQuery actually has a delay() function which can delay animations.\n // Better than using timers manually.\n subscribeBox.find('h5')\n .addClass('green-text')\n .text(message)\n .delay(5000)\n .fadeOut('slow');\n\n } else {\n\n // Now I don't know why you are doing the alert. If you are debugging,\n // I suggest you use console.log() or a custom logging library.\n alert(data);\n }\n });\n\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T20:27:06.953",
"Id": "38087",
"ParentId": "38082",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38087",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T17:57:46.503",
"Id": "38082",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"event-handling"
],
"Title": "\"Enter key pressed\" event-handler"
}
|
38082
|
<p>Review this code for code quality.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Data URI encoder</title>
<style>
#dropbox {
padding: 18.5px 0;
max-width: 499px;
border: 2px dashed #bbb;
border-radius: 5px;
color: #bbb;
text-align: center;
}
</style>
</head>
<body>
<h1>Data URI encoder</h1>
<p>Select or drag a file to get the Data URI: <input id="fileinput" type="file"></p>
<div id="dropbox"><h3>Drop file here</h3></div>
<p id="filename"></p>
<p><textarea id="content" rows="6" cols="60" onclick="this.select()"></textarea></p>
<p id="filesize"></p>
<script>
var fileinput = document.getElementById("fileinput"),
dropbox = document.getElementById("dropbox"),
filename = document.getElementById("filename"),
content = document.getElementById("content"),
filesize = document.getElementById("filesize");
function encodeDataURI(e) {
e.stopPropagation();
e.preventDefault();
var files = e.target.files || e.dataTransfer.files,
file = files[0],
reader = new FileReader();
reader.onload = (function() {
return function(e) {
content.value = e.target.result;
filename.textContent = file.name;
filesize.innerHTML = "Data URI size: " + e.target.result.length + " bytes<br>" + "Original size: " + file.size + " bytes"
};
})();
reader.readAsDataURL(file);
}
function handleDragOver(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
}
dropbox.addEventListener("dragover", handleDragOver, false);
dropbox.addEventListener("drop", encodeDataURI, false);
fileinput.addEventListener("change", encodeDataURI, false);
</script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>There isn't much here, just a few comments though:</p>\n\n<ul>\n<li><p>Most developers I come across use <code>var</code> per variable rather than comma separated. It's down to personal preference and code habits though, so you could ignore this one.</p>\n\n<p>An advantage I see is that it makes variable declaration easier to move around without worrying about the connecting commas. </p></li>\n<li><p>I don't see the benefit of using a closure for <code>reader.onload</code>. You can simply just assign it a function.</p></li>\n<li><p>Further, you can move out the <code>reader.onload</code> handler function outside <code>encodeDataURI</code>. That way, the code won't generate that handler function for every call of <code>encodeDataURI</code>. Optimizing JS engines will do this for you though, but it's best practice if you just code it that way.</p></li>\n<li><p>Programming languages were designed for people. Name your variables verbosely. For instance, <code>e</code> into <code>event</code>. Short variables are only good in the short-term. Long-term, they aren't good for maintenance. Don't worry about file sizes, that's what minifiers are for.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T20:48:29.247",
"Id": "38088",
"ParentId": "38083",
"Score": "3"
}
},
{
"body": "<p>Your code seems pretty much picture perfect.</p>\n\n<ul>\n<li>JS beautifying does nothing, I am guessing you used it</li>\n<li>JS hint has nothing to report except a missing semicolon after <code>filesize.innerHTML = \"</code>..</li>\n<li>As for using 1 var, I think that is the right thing to do</li>\n<li>As for your closure in <code>encodeDataURI</code>, you are accessing <code>file</code>, so that is justified.</li>\n</ul>\n\n<p>I can only ask that you share this with the world through a github project or github gist.</p>\n\n<p>On a second thought; your code could use some comments, particularly as to which browsers are supported and what tricks you employ to make that work. Especially this line could use a comment as to which browser uses what:</p>\n\n<pre><code>var files = e.target.files || e.dataTransfer.files,\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T08:42:21.660",
"Id": "63409",
"Score": "0",
"body": "Thanks for your review.\nI'm a beginner at JavaScript, should I join Github right now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T20:12:18.783",
"Id": "63449",
"Score": "0",
"body": "Interesting, I think you should."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T01:16:26.533",
"Id": "38094",
"ParentId": "38083",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T18:03:26.537",
"Id": "38083",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Data URI encoder"
}
|
38083
|
<p>Here is a solution for <a href="http://projecteuler.net/problem=7">Project Euler Problem #7</a>.</p>
<blockquote>
<p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
see that the 6th prime is 13. What is the 10,001st prime number?</p>
</blockquote>
<p>I've used the pseudo code from the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation">Wikipedia page for the Sieve of Eratosthenes</a>.</p>
<blockquote>
<p><strong>Input:</strong> an integer n > 1</p>
<p>Let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true.</p>
<pre><code>for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i^2, i^2+i, i^2+2i, ..., not exceeding n :
A[j] := false
</code></pre>
</blockquote>
<p>Any suggestions would be much appreciated.</p>
<pre><code>import java.util.*;
public class FindPrimesHashMap {
public static void getPrime(int x) {
int n = (x * ((int)Math.sqrt(x) / 10)) + x;
int nSqrt = (int)Math.floor(Math.sqrt(n));
int j = 0;
int k = 0;
Map<Integer, Boolean> primeMap = new HashMap<Integer, Boolean>();
Set<Map.Entry<Integer, Boolean>> primes = primeMap.entrySet();
ArrayList<Integer> primeArray = new ArrayList<Integer>();
for (int a = 2; a < n; a++) {
primeMap.put(a, true);
}
for (int i = 2; i <= nSqrt; i++) {
if (primeMap.get(i)) {
while (true) {
j = (i * i) + (k * i);
k++;
if (j > n) {
break;
}
primeMap.put(j, false);
}
j = 0;
k = 0;
}
}
for (Map.Entry<Integer, Boolean> entry : primes) {
if (entry.getValue()) {
primeArray.add(entry.getKey());
}
}
Collections.sort(primeArray);
System.out.println(primeArray.get(x - 1));
}
</code></pre>
|
[] |
[
{
"body": "<p>Well since you didn't mention what kind of improvement you are looking for, I will share some short(LOC) and precise way to find X<sup>th</sup> prime number.</p>\n\n<pre><code>public static BigInteger getXthPrime(final int x) {\n BigInteger prime = new BigInteger(\"2\"); // first prime number\n int noOfPrimes = 1; // since we already considered a prime\n while(noOfPrimes != x) {\n prime = prime.nextProbablePrime();\n noOfPrimes++;\n }\n return prime;\n}\n</code></pre>\n\n<p><strong>NOTE</strong> : This is a <em>very slow</em> method and will take more time as <code>x</code> grow larger.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T00:08:41.483",
"Id": "63396",
"Score": "2",
"body": "That should probably be written as a for-loop."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T22:45:03.310",
"Id": "38090",
"ParentId": "38084",
"Score": "1"
}
},
{
"body": "<p>Maybe consider a simple array of <code>Boolean</code>s instead of <code>primeMap</code>, or an array of integers from indices, to get rid of that copy to another array:</p>\n\n<ol>\n<li><p>initialization</p>\n\n<pre><code>{0,0,2,3,4,5,6}\n</code></pre></li>\n<li><p>remove non-primes through <code>for</code> and <code>while</code> loop</p>\n\n<pre><code>{0,0,2,3,0,5,0}\n</code></pre></li>\n<li><p>sort</p>\n\n<pre><code>{0,0,0,0,2,3,5}\n</code></pre></li>\n<li><p>find 1<sup>st</sup> non-zero integers index for correction or for sublist</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T23:23:10.510",
"Id": "38091",
"ParentId": "38084",
"Score": "3"
}
},
{
"body": "<p>You have a proliferation of cryptically named variables, making your code hard to follow.</p>\n\n<p>Variables <code>j</code> and <code>k</code> are only ever used inside the <code>while (true)</code> loop, so they should be declared in a tighter scope. There is no need to reset <code>j</code> after the loop. Also, it would be easier to understand your code if you reset <code>k = 0</code> before the loop rather than afterwards. The <code>while (true)</code> loop could be simplified to:</p>\n\n<pre><code>for (int k = 0; ; k++) {\n int j = (i * i) + (k * i);\n if (j > n) {\n break;\n }\n primeMap.put(j, false);\n}\n</code></pre>\n\n<p>Then, why not eliminate <code>k</code> altogether?</p>\n\n<pre><code>for (int j = i * i; j <= n; j += i) {\n primeMap.put(j, false);\n}\n</code></pre>\n\n<hr>\n\n<p>I don't see why you set <code>n = x ⌈√x / 10⌉</code>. It seems that you chose it as an estimate for the upper bound of your answer, though I don't understand the justification. The answer should be somewhere around <a href=\"http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number\" rel=\"nofollow\"><em>p</em><sub><em>x</em></sub> ≈ <em>x</em> ln(<em>x</em>)</a>.</p>\n\n<p>In the end, it's not really important <em>how</em> you arrived at <code>n</code>, as long as it is large enough. An explanatory comment would have been appreciated, though.</p>\n\n<hr>\n\n<p>Using a <code>HashMap</code> to implement the Sieve of Eratosthenes is not a great idea, because:</p>\n\n<ol>\n<li>You want to iterate through the results consecutively</li>\n<li>All of the keys were initially consecutive</li>\n<li>Internally, it will be hashing each key to another number</li>\n</ol>\n\n<p>It would be a lot simpler if you simply used an array of <code>boolean</code>s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T01:37:02.067",
"Id": "63398",
"Score": "0",
"body": "Thank you very much. In regards to the calculation of \"n\" you are correct. I wanted to come up with a relationship that would always create a map large enough to find the xth prime. Also I see your point regarding my naming, will fix."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T00:57:20.373",
"Id": "38093",
"ParentId": "38084",
"Score": "6"
}
},
{
"body": "<p>// Started this review before XMas dinner. now there are many other answers. .... will post anyway....</p>\n\n<p>In some ways you follow the pseudo-code, and in others you deviate. In my opinion, you follow the worst aspects of the pseudo-code, and deviate from the best.</p>\n\n<p>Things that you copy, but I would change are:</p>\n\n<ul>\n<li>Use more meaningful variable names.... <code>A</code>, <code>i</code>, <code>j</code>, and <code>n</code> are not great names, yet you have variables <code>a</code>, <code>i</code>, <code>j</code>, <code>k</code>, and <code>x</code>. Further, your <code>a</code> and the pseudo-<code>A</code> are different things.</li>\n</ul>\n\n<p>Things you change, but I would copy:</p>\n\n<ul>\n<li>use an actual array-of-boolean for your sieve, instead of a <code>Map<Integer,Boolean></code></li>\n</ul>\n\n<p>Further, there are a number of other issues I have concerns with:</p>\n\n<ul>\n<li><p>you create <code>primes</code> as a set of the Entries in the <code>primesMap</code> immediately after creating <code>primesMap</code>:</p>\n\n<pre><code>Map<Integer, Boolean> primeMap = new HashMap<Integer, Boolean>();\nSet<Map.Entry<Integer, Boolean>> primes = primeMap.entrySet();\n</code></pre>\n\n<p>For a while this had me confused.... I am flabbergasted, actually, that this works. That the <code>primes</code> set is correctly populated after populating the backing Map. Now, don't get me wrong, this <strong>does</strong> appear to actually work, but I have <strong>never</strong> seen this done this way, and you have taught <strong>me</strong> something! I have confirmed in the JavaDoc that the <code>entrySet()</code> is 'live', and changes as you change the backing Map. Unfortunately, I cannot recommend this practice - simply due to it's unconventionality.</p></li>\n<li>The line of code <code>int n = (x * ((int)Math.sqrt(x) / 10)) + x;</code> has me confused as well. What is this formula? Why does it work? How can you be sure that the <code>x'th</code> Prime is less than this value <code>n</code>? In fact, it cannot be right, the 5th prime is 11, but, in your case, <code>n</code> would be 5. You should read up on <a href=\"http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number\" rel=\"nofollow noreferrer\">this approximation of the <em>n</em> <sup>th</sup> prime</a>.</li>\n<li>It is a <code>C</code> type construct to declare your variables at the start of a method. Don't do this. In Java you should declare your variables as close to their usage as you can. It is a 'best practice' (although <a href=\"https://stackoverflow.com/questions/1411463/in-java-should-variables-be-declared-at-the-top-of-a-function-or-as-theyre-ne\">there is some debate</a>).</li>\n<li>In your loops you do not use convenient conditional <code>whiles</code>. The <code>while (true) ... break; ....</code> is particularly concerning. You should make the conditions more explicit</li>\n</ul>\n\n<p>So, putting everything together, I would keep things as primitives. I would also make the limit of the sieve 'dynamic', and expand it as needed... perhaps 'seeding' it with some constants.</p>\n\n<h2>EDIT:</h2>\n\n<p>... after some festive cheer, I re-visited this problem, and figured I would put together a class that incrementally calculates the primes. Call it a 'project'. This is a Sieve class:</p>\n\n<pre><code>import java.util.Arrays;\n\n/**\n * This class caches prime numbers, and is able to provide you with the prime\n * numbers you want (up to close to Integer.MAX_VALUE)\n * \n * @author rolfl\n * \n */\npublic class EratosthenesSieve {\n // Since we play by inverting the logic of a boolean array,\n // I have constants that make the logic easier to see.\n private static final boolean PRIME = false;\n private static final boolean NOTPRIME = true;\n\n // Initialize to the first 5 primes.\n // Note, by seeding at least one odd prime, we never have to consider even\n // values in the sieve.\n private int[] primes = { 2, 3, 5, 7, 11 }; // seed initial primes.\n\n /**\n * Get the n<sup>th</sup> prime\n * \n * @param nth\n * The prime to get.\n * @return the n'th prime.\n */\n public int getNthPrime(final int nth) {\n if (nth < 1) {\n throw new IllegalArgumentException(\"Finding the \" + nth\n + \" prime number is not possible\");\n }\n\n while (nth >= primes.length) {\n // have not yet cached this prime.\n\n // NOTE: Integer.MAX_VALUE happens to be prime.\n // Maybe there is something we can do with that.\n\n // The estimated n'th prime: from Wikipedia:\n // http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number\n final int lastprime = primes[primes.length - 1];\n // calculate forward to 25% of where we are, or 10% + 30 more than\n // the wiki guess.\n final long longapproxsize = Math.max((long) lastprime\n + ((long) lastprime >> 2),\n 30 + (long) (nth * Math.log(nth) * 1.1));\n if (longapproxsize > Integer.MAX_VALUE) {\n throw new IllegalArgumentException(\"The \" + nth\n + \" prime number is probably too large to calculate.\");\n }\n // calculate at most 1Million primes in a loop (sieve size 1M)\n // (reduces maximum memory footprint);\n final int approxsize = Math.min((int) longapproxsize, lastprime + 1000000);\n // only need to create a sieve for what we have not yet calculated.\n // odd number after last prime.\n final int startfrom = lastprime + 2;\n\n final boolean[] sieve = new boolean[approxsize - startfrom];\n for (final int prime : primes) {\n // mark multiples of previously-calculated primes.\n if (prime == 2) {\n // can ignore 2...\n continue;\n }\n // calculating an odd-valued start position allows us to\n // optimize\n // by doing double-prime steps.\n int first = (prime - (startfrom % prime)) % prime;\n if (((first + startfrom) & 1) == 0) {\n first += prime;\n }\n for (int j = first; j < sieve.length; j += prime + prime) {\n sieve[j] = NOTPRIME;\n }\n }\n\n // OK, the sieve has been extended. But only the primes from the\n // previous round have been filtered...\n // our last prime was recorded in primes array.\n // we need to complete the prime sequence, then extract the new\n // primes.\n int pcnt = primes.length;\n int[] tmprime = Arrays.copyOf(primes, approxsize >> 1);\n int root = (int) (Math.sqrt(approxsize) + 1);\n int maxj = (int)(Math.sqrt(root) + 1);\n for (int i = 0; i < sieve.length; i += 2) {\n if (sieve[i] == PRIME) {\n // this is a newly discovered prime.\n // record it\n int prime = i + startfrom;\n tmprime[pcnt++] = prime;\n // clear any future multiples of this prime.\n // optimize by starting from square, and ignoring even\n // multiples.\n // need j > 0 to avoid overflow issues.\n if (prime > maxj) {\n continue;\n }\n for (int j = prime * prime; j > 0 && j < root; j += prime + prime) {\n if (j - startfrom < 0 || j - startfrom >= sieve.length) {\n throw new ArrayIndexOutOfBoundsException(String.format(\"Cannot access index %d in array with length %d\", j - startfrom, sieve.length));\n }\n sieve[j - startfrom] = NOTPRIME;\n }\n }\n }\n // OK, we have our new primes recorded.\n primes = Arrays.copyOf(tmprime, pcnt);\n\n }\n return primes[nth - 1];\n\n }\n\n public static void main(String[] args) {\n EratosthenesSieve sieve = new EratosthenesSieve();\n\n // From wikipedia: all primes < 1000\n int[] data = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,\n 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109,\n 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179,\n 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241,\n 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,\n 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389,\n 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461,\n 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547,\n 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617,\n 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,\n 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773,\n 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859,\n 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947,\n 953, 967, 971, 977, 983, 991, 997 };\n\n for (int i = 0; i < data.length; i++) {\n int act = sieve.getNthPrime(i + 1);\n if (act != data[i]) {\n throw new IllegalStateException(\"Could not calculate \"\n + (i + 1) + \" prime. Expect \" + data[i] + \" but got \"\n + act);\n }\n System.out.println(\"Prime \" + (i + 1) + \" is \" + act);\n }\n\n for (int i = 1000000; i > 0; i += 1000000) {\n int act = sieve.getNthPrime(i);\n System.out.println(\"Prime \" + i + \" is \" + act);\n }\n\n }\n\n}\n</code></pre>\n\n<p><strike>\nhere is some code I think better represents what should be done.... with some optimizations for Java:</p>\n\n<pre><code>public static final int findNthPrime(final int nth) {\n if (nth < 1) {\n throw new IllegalArgumentException(\"Finding the \" + nth + \" prime number is not possible\");\n }\n // we make a special case of prime number 2, so that we only need to deal with half the numbers (odd numbers only) \n if (nth == 1) {\n return 2;\n }\n\n // The estimated n'th prime: from Wikipedia:\n // http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number\n // add 25% because the approximation always under-estimates.\n final int approxsize = (int)(nth * Math.log(nth) * 1.25);\n // because boolean arrays are initialized to false, we will reverse our logic to\n // avoid re-filling the arrays, hence isnotprime instead of isprime.\n boolean[] isnotprime = new boolean[approxsize];\n int startfrom = 3;\n while (true) {\n // we may need to expand the sieve in unusual conditions.\n final int root = (int)Math.sqrt(isnotprime.length) + 1;\n for (int i = startfrom; i < root; i+=2) {\n for (int j = i * i; j < isnotprime.length; j += i) {\n isnotprime[j] = true;\n }\n }\n // even though we have only iterated to `root`, we have actually calculated all the primes to isnotprime.length.\n // let's check ahead of `root` to see if our n'th prime has been calculated.\n int tmpprimecount = 1;\n for (int i = 3; i < isnotprime.length; i+=2) {\n if (!isnotprime[i]) {\n if (++tmpprimecount == nth) {\n return i;\n }\n }\n }\n\n throw new IllegalStateException(\"The Wiki approximation is supposed to be good enough to cover this.\");\n\n // we were not able to find the nth prime in the estimated space.\n // expand the estimated space\n // tmp.length will be odd, always.\n// boolean[] tmp = Arrays.copyOf(isnotprime, 1 + isnotprime.length * 2);\n// for (int i = 3; i < root; i += 2) {\n// if (!tmp[i]) {\n// startfrom = i;\n// for (int j = isnotprime.length; j < tmp.length; j+= i) {\n// tmp[j] = true;\n// }\n// }\n// }\n// isnotprime = tmp;\n }\n</code></pre>\n\n<p></strike></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T01:52:56.393",
"Id": "63400",
"Score": "0",
"body": "This is actually my first time using a map, and also my first week of using java, hopefully this will explain some of the poorly written parts of the code! I will thoroughly read into all of your suggestions. Thank you very much for taking the time to help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T05:07:39.637",
"Id": "63405",
"Score": "0",
"body": "Updated answer to have a more comprehensive solution (make the accept-rep more worth it ...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:34:04.553",
"Id": "77280",
"Score": "0",
"body": "@rolf int first = (prime - (startfrom % prime)) % prime;\n if (((first + startfrom) & 1) == 0) {\n first += prime;\n }\n for (int j = first; j < sieve.length; j += prime + prime) {\n sieve[j] = NOTPRIME;\n } This piece of code is great but whats the official name of this theoram ? Is there some url you can paste to let me know the \"official proof\" of how it assures correctness ? I am especially confused about `int first = (prime - (startfrom % prime)) % prime` Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:34:47.883",
"Id": "77281",
"Score": "0",
"body": "@JavaDeveloper join us in the [2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor), can go through it with you there."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T01:44:22.723",
"Id": "38095",
"ParentId": "38084",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38095",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T18:46:54.100",
"Id": "38084",
"Score": "12",
"Tags": [
"java",
"project-euler",
"primes"
],
"Title": "Suggestions for improvement on Project Euler #7"
}
|
38084
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.