body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
---|---|---|---|---|
<p>What is your opinion in arguments in constructors matching members as in the following example</p>
<pre><code>public Join(final int parent, final TIntHashSet children) {
this.parent = parent;
this.children = children;
}
</code></pre>
<p>I find this annoying since I have to use <code>this.</code> and also some code review applications generate warnings.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:53:11.900",
"Id": "765",
"Score": "3",
"body": "I'm not sure if this question really fits on code review but I provided a response for it below anyway."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:20:02.620",
"Id": "768",
"Score": "1",
"body": "This is something more for Programmers.SE than for here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:21:33.073",
"Id": "860",
"Score": "2",
"body": "I feel like the question is in scope for Code Review: is using the same name for arguments and members confusing? Is it readable?"
}
] | [
{
"body": "<p>If you're worried about typing the extra characters for <code>this</code> you can consider the coding style used in C++. To avoid ambiguity between class data and parameter's passed into a method I usually use one of the following naming conventions for data members: <code>m_parent</code> and <code>m_children</code> (prefix m indicates member), <code>parent_</code> and <code>children_</code>, <code>myParent</code> and <code>myChildren</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:55:20.430",
"Id": "766",
"Score": "0",
"body": "I will consider your ideas. Since I use `this.` mainly in constructor and setters I find it inconsistent with the rest of my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:51:52.230",
"Id": "473",
"ParentId": "471",
"Score": "2"
}
},
{
"body": "<p>I've personally always found the <code>_parent</code> or Hungarian-notation letters at the beginning far uglier than just saying <code>this</code>. <code>this</code> is very straightforward, especially if somebody else is reading your code. If I inherit somebody else's code and they use _ I change it immediately.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T02:11:41.687",
"Id": "773",
"Score": "1",
"body": "I personally dislike identifiers that begin with _ as the rules in C++ for their usage are non trivial (OK its trivial if you know the rules, but most people don't). Though this question is about Java I use the same rule just to make code more consistent across languages."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T18:41:59.473",
"Id": "814",
"Score": "0",
"body": "What compiler diagnostics will be generated if the parameter is misspelled? If one calls the constructor parameter NewWhatevr then \"Whatever = NewWhatever\" will fail; if one calls it Whatevr, then \"this.Whatevr = Whatever\" will be legitimate but erroneous code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:32:14.213",
"Id": "475",
"ParentId": "471",
"Score": "12"
}
},
{
"body": "<p>If you have access to a copy of \"Clean Code\" it has a chapter called \"Meaningful Names\" that I agree with. Bottom line, your name should denote exactly what it is referring to. Creating an encoding for the name a la C++ only slows down reading and causes devs to mentally skip it anyways. Also, your ide, be it eclipse, emacs, etc. should provide highlighting that makes the difference between class variables and parameters distinct.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T02:00:51.667",
"Id": "476",
"ParentId": "471",
"Score": "4"
}
},
{
"body": "<p>Personally I use the most natural names for member variables.<br>\nThis is because these are the ones you are going to use the most often (thus I dislike the m_ prefix).</p>\n\n<p>For things that are going to happen less often (like parameters in constructors) I shorten them or add p_ depending on context and which is the most appropriate.</p>\n\n<p>I have found most Java coding standards I have encountered seem to prefer (in the constructor) the use of </p>\n\n<pre><code>this.member = member;\n</code></pre>\n\n<p>Personally I dislike this (but always stick to the coding standards) as it it feels more error prone. I like distinct names for all identifiers (overlapping names lead to easier mistakes). I also think that distinct identifiers make it easier to spot (for humans) trivial mistakes.</p>\n\n<pre><code>this.member = p_member;\n</code></pre>\n\n<p>Can't get that wrong as each identifier is unique.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T02:20:27.713",
"Id": "477",
"ParentId": "471",
"Score": "5"
}
},
{
"body": "<p>My take is that what you have should be the preferred way of doing things. First of all, the names of the input parameters are what will show up in javadocs, and therefore should not have any prefix or silly names that will make the javadocs cryptic. Second, if the input parameter names clearly define what the things are, then why name the global variables something else that will make the rest of the code less meaningful or more difficult to maintain? Third, the scope of the input parameters is so limited, that it seems to me that you would rarely find this to be error-prone, especially when simply initializing class data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T12:20:25.620",
"Id": "922",
"Score": "1",
"body": "You have a valid point with names showing in java docs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T05:20:01.963",
"Id": "543",
"ParentId": "471",
"Score": "4"
}
},
{
"body": "<p>I would start with your first instinct of giving them different names, but only if the different names make sense. No Hungarian Notation! (Learned what a mess that was recently. Why do so many style guides still recommend it?) I commonly use different names in situations like this</p>\n\n<pre><code>public Leaf(Color initialColor) {\n color = initialColor;\n}\n</code></pre>\n\n<p>If the two variables represent the same thing and have no other meaningful name, then the <code>this</code> keyword is the way to go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T12:46:23.330",
"Id": "20583",
"ParentId": "471",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "475",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:30:36.383",
"Id": "471",
"Score": "6",
"Tags": [
"java",
"constructor"
],
"Title": "Arguments in constructors matching fields"
} | 471 |
<p>I've recently been doing some mods to some old code I've been maintaining for a couple of years now. </p>
<p>As part of a wider set of scripts using YAHOO YUI 2.2 (yes, that old) for dialog-style panels, I have a function that listens to click events on 3 buttons in a given panel set:</p>
<pre><code>addFooListeners = function (panelType) {
YAHOO.util.Event.addListener("show" + panelType, "click", showFoo, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("hide" + panelType, "click", hideFoo, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("commit" + panelType, "click", commitFoo, eval(ns + ".panel_" + panelType), true);
}
</code></pre>
<p>This code is the result of a number of panels/dialogs having near identical behaviour.</p>
<p>For this round of development I've needed to add the ability to do things a little differently from time to time, so I added an object, <code>overrides</code> which allows me to point the <code>show</code>, <code>hide</code> and <code>commit</code> actions elsewhere. I came up with the following:</p>
<pre><code>addFooListeners = function (panelType, overrides) {
var handlers = {
show: ( overrides != null ? ( overrides.show != null ? overrides.show : showFoo ) : showFoo ),
hide: ( overrides != null ? ( overrides.hide != null ? overrides.hide : hideFoo ) : hideFoo ),
commit: ( overrides != null ? ( overrides.commit != null ? overrides.commit : commitFoo ) : commitFoo )
}
YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, eval(ns + ".panel_" + panelType), true);
}
</code></pre>
<p>As you can see I'm enforcing default behaviour unless an appropriate attribute in the <code>overrides</code> object is set with another function (named or anonymous).</p>
<p>Is there a cleaner / more readable way to concisely setup the <code>handlers</code> object? The nested ternary seems to my eyes to be cluttering things a bit but other approaches like <code>if ( overrides != null ) { ... }</code> seem just as messy.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T21:47:59.170",
"Id": "75726",
"Score": "1",
"body": "My personal opinion is that the `?` ternary operator is worth using only when it's not nested. In your case it just makes the code more unreadable and unmaintainable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:14:00.867",
"Id": "75727",
"Score": "0",
"body": "I like formatting nested ternary operators so they read like multiple questions: http://codereview.stackexchange.com/a/6562/8891"
}
] | [
{
"body": "<p>It looks like you can reduce that ternary a bit by using && like this:</p>\n\n<pre><code>var handlers = {\n show: ( overrides != null && overrides.show != null ? overrides.show : showFoo ),\n hide: ( overrides != null && overrides.hide != null ? overrides.hide : hideFoo ),\n commit: ( overrides != null && overrides.commit != null ? overrides.commit : commitFoo )\n}\n</code></pre>\n\n<p>I'm not too familiar with javascript but does the function parameter have to be checked against null? Like for example, can you further shorten the check by doing something like this?</p>\n\n<pre><code>show: ( overrides && overrides.show ? overrides.show : showFoo ),\nhide: ( overrides && overrides.hide ? overrides.hide : hideFoo ),\n// ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:03:44.920",
"Id": "767",
"Score": "2",
"body": "Generally speaking, I think you're right about not needing to check against null - however it can be not-null and false then it would evaluate to false (though in this case I think that'd be ok)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T01:36:48.613",
"Id": "770",
"Score": "0",
"body": "Overrides.show looks like it could be a boolean; if so, you'd need to test it against null explicitly."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T01:48:46.940",
"Id": "771",
"Score": "0",
"body": "@Fred the intention is to pass functions for show, hide and commit. If a false is passed there then showFoo() will be used. If a true is passed there then that'll be passed in place of showFoo() and cause trouble further down so I guess I need to tread carefully there. Having said that though, I'll only ever be passing a function in those parameters so I'll probably survive for now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T08:01:41.087",
"Id": "12784",
"Score": "0",
"body": "Might be worth pointing out that this use of `&&` is only valid as long as `&&` is a short-circuiting `and` operation (which is a safe assumption for C-derived languages, but not all languages)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T22:51:55.890",
"Id": "23742",
"Score": "1",
"body": "Can be even shorter: `show: overrides && overrides.show || showFoo`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:02:02.203",
"Id": "474",
"ParentId": "472",
"Score": "7"
}
},
{
"body": "<p>Let's do some fixing. First, this is how you pass optional (non-boolean) parameters in JS (the Good Way<sup>tm</sup>):</p>\n\n<pre><code>addFooListeners = function (panelType, handlers) {\n handlers = handlers || {};\n handlers.show = handlers.show || showFoo;\n handlers.hide = handlers.hide || hideFoo;\n handlers.commit = handlers.commit || commitFoo;\n</code></pre>\n\n<p>The above can be rewritten in a neater way using jQuery (not sure what the name of YUI equivalent to <code>extend</code> is):</p>\n\n<pre><code>handlers = $.extend({\n show : showFoo, \n hide : hideFoo, \n commit: commitFoo\n}, handlers || {})\n</code></pre>\n\n<p>Now, using eval for this code is criminal. Say the object <code>ns</code> refers to is <code>module</code>, then you can do this instead of <code>eval</code>:</p>\n\n<pre><code>YAHOO.util.Event.addListener(\"show\" + panelType, \"click\", handlers.show, module[\"panel_\" + panelType], true);\nYAHOO.util.Event.addListener(\"hide\" + panelType, \"click\", handlers.hide, module[\"panel_\" + panelType], true);\nYAHOO.util.Event.addListener(\"commit\" + panelType, \"click\", handlers.commit, module[\"panel_\" + panelType], true);\n</code></pre>\n\n<p>Now, as you can see, you are assigning a lot of events in a similar fashion. Did you think of defining an addPanelListener function within your function?</p>\n\n<pre><code>function addPanelListener (event, panelType, handler) {\n YAHOO.util.Event.addListener(event + panelType, \"click\", handler, module[\"panel_\" + panelType], true);\n} \n\naddPanelListener(\"show\" , panelType, handlers.show);\naddPanelListener(\"hide\" , panelType, handlers.hide);\naddPanelListener(\"commit\", panelType, handlers.commit):\n</code></pre>\n\n<p>Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T13:06:48.697",
"Id": "791",
"Score": "9",
"body": "+1 for flagging use of eval as criminal :) I find \"the Good Way\" more readable than the jQuery way."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:25:01.197",
"Id": "822",
"Score": "6",
"body": "Using `eval` in my company pretty much guarantees a 3-hour _basics of javascript_ meeting with me :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:32:02.357",
"Id": "823",
"Score": "0",
"body": "aaah good old \"the-first-one-is-free\" `eval`. Much like a drug pusher. I cringe every time I see that in my code (especially the code I post here ;-)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:34:58.157",
"Id": "825",
"Score": "0",
"body": "@glebm can you elaborate on what makes \"The Good Way\" the good way?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:36:22.243",
"Id": "826",
"Score": "2",
"body": "Of course. It is easily readable, less error-prone, and, as a bonus, it's faster. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:38:37.093",
"Id": "828",
"Score": "0",
"body": "Always welcome!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T07:58:48.267",
"Id": "482",
"ParentId": "472",
"Score": "28"
}
},
{
"body": "<p>In JavaScript, you are not required to explicitly check if a variable is null or undefined because:</p>\n\n<ol>\n<li>null or undefined return false in a boolean expression.</li>\n<li>JS expressions are evaluated from left to right. So for <code>a || b</code>, if <code>a</code> is false, then only <code>b</code> will be evaluated. But if <code>a</code> is true, <code>b</code> will not be checked. Similarly for <code>a && b</code> if <code>a</code> is false, <code>b</code> will not be evaluated.</li>\n</ol>\n\n<p>Hence, <code>if (a != null) { \"do something\" }</code> can be written as <code>if (a) { \"do something\" }</code> or simply <code>a && \"do something\"</code>.</p>\n\n<p>In the same way it can be used to set a default value when the value is set to null or undefined:</p>\n\n<pre><code>function someFunction(age){\n :\n var age= age|| 18;\n :\n}\n</code></pre>\n\n<p><code>someFunction(28)</code> results in 28 whereas <code>someFunction()</code> results in 18.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:41:32.597",
"Id": "43772",
"ParentId": "472",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "482",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-30T23:43:07.143",
"Id": "472",
"Score": "26",
"Tags": [
"javascript"
],
"Title": "Usage of the ternary \"?:\" operator with functions listening to click events"
} | 472 |
<p>There's got to be a better way than this that preserves the logic while sparing me the multitude of lines:</p>
<pre><code>sub has_path {
clearerr;
my %Graph = gref(shift);
my $A = shift;
my $B = shift;
my $C = shift;
my $D = shift;
my $E = shift;
my $F = shift;
my $G = shift;
my $H = shift;
my $I = shift;
my $J = shift;
my $K = shift;
my $L = shift;
my $M = shift;
my $N = shift;
my $O = shift;
my $P = shift;
my $Q = shift;
my $R = shift;
my $S = shift;
my $T = shift;
my $U = shift;
my $V = shift;
my $W = shift;
my $X = shift;
my $Y = shift;
my $Z = shift;
# returns VT_BOOL
my $bool = 0;
my $switcher = dectab( [ $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W, $X, $Y, $Z ] );
given ($switcher) {
when ( "--------------------------" ) {
seterr( "No path." );
} # no path
when ( "X-------------------------" ) {
seterr( "Path of one element." );
} # path of 1 element
when ( "XX------------------------" ) {
$bool = $Graph->has_path( $A, $B );
}
when ( "XXX-----------------------" ) {
$bool = $Graph->has_path( $A, $B, $C );
}
when ( "XXXX----------------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D );
}
when ( "XXXXX---------------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E );
}
when ( "XXXXXX--------------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F );
}
when ( "XXXXXXX-------------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G );
}
when ( "XXXXXXXX------------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H );
}
when ( "XXXXXXXXX-----------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I );
}
when ( "XXXXXXXXXX----------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J );
}
when ( "XXXXXXXXXXX---------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K );
}
when ( "XXXXXXXXXXXX--------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L );
}
when ( "XXXXXXXXXXXXX-------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M );
}
when ( "XXXXXXXXXXXXXX------------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N );
}
when ( "XXXXXXXXXXXXXXX-----------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O );
}
when ( "XXXXXXXXXXXXXXXX----------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P );
}
when ( "XXXXXXXXXXXXXXXXX---------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q );
}
when ( "XXXXXXXXXXXXXXXXXX--------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R );
}
when ( "XXXXXXXXXXXXXXXXXXX-------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S );
}
when ( "XXXXXXXXXXXXXXXXXXXX------" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T);
}
when ( "XXXXXXXXXXXXXXXXXXXXX-----" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U );
}
when ( "XXXXXXXXXXXXXXXXXXXXXX----" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V );
}
when ( "XXXXXXXXXXXXXXXXXXXXXXX---" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W );
}
when ( "XXXXXXXXXXXXXXXXXXXXXXXX--" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W, $X );
}
when ( "XXXXXXXXXXXXXXXXXXXXXXXXX-" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W, $X, $Y,);
}
when ( "XXXXXXXXXXXXXXXXXXXXXXXXXX" ) {
$bool = $Graph->has_path( $A, $B, $C, $D, $E, $F, $G, $H, $I, $J, $K, $L, $M, $N, $O, $P, $Q, $R, $S, $T, $U, $V, $W, $X, $Y, $Z );
}
}
return $bool;
}
</code></pre>
<p>This is the dectab (decision table) sub it refers to:</p>
<pre><code> sub dectab {
my($ref)=shift;
my ($res);
foreach my $key( @$ref){
if ( ! defined $key ) {
$res .= '-';
} else {
$res .= "X";
}
}
return $res;
}
</code></pre>
<p><code>clearerr</code>, <code>seterr</code>, and <code>gref</code>:</p>
<pre><code>sub clearerr {
$ERRORFLAGGED = 0;
$ERRORTEXT = "";
}
sub seterr {
$ERRORTEXT = shift;
$ERRORFLAGGED = 1;
}
sub gref {
my $gref = shift;
if ( defined $grefs->{$gref} ) {
return $grefs->{$gref};
} else {
return undef;
}
}
</code></pre>
<p>This is all part of a much much larger wrapping of the Graph module. It's being turned into a COM DLL using ActiveState's PerlCtrl.</p>
<p>Calling the sub would be done, in VBScript (for example), by</p>
<pre><code>set o = CreateObject("Wrapper.Graph.2")
...
if o.has_path( "tom", "dick", "harry" ) then
...
</code></pre>
<p>Graph.pm, by the way, defines <code>has_path</code> as</p>
<pre><code>has_path
$g->has_path($a, $b, $c, ..., $x, $y, $z)
Return true if the graph has all the edges $a-$b, $b-$c, ..., $x-$y, $y-$z, false otherwise.
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T06:52:11.170",
"Id": "778",
"Score": "0",
"body": "Arrays and slices, I think!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T06:53:50.763",
"Id": "779",
"Score": "0",
"body": "Can you give some sample data and a sample invocation of the function? Also, what is the `gref` function used on the first argument? It isn't in Perl 5.12.2 as a function listed at http://perldoc.perl.org/ AFAICS. Ditto the `clearerr` function (unless that's part of POSIX, or IO::Handle); what about the `seterr` function?"
}
] | [
{
"body": "<p>As I noted in a comment, I think the solution lies in using arrays and <a href=\"http://perldoc.perl.org/perldata.html#Slices\">slices</a>. Maybe like this:</p>\n\n<pre><code>sub has_path {\n clearerr;\n my %Graph = gref(shift);\n my(@States) = @_;\n my $bool = 0;\n my $switcher = dectab( [ @States ] );\n $switcher =~ m/^(X*)(?:-*)$/;\n my $number = length($1);\n if ($number == 0) {\n seterr( \"No path.\" );\n }\n else\n {\n $bool = $Graph->has_path( $States[0 .. ($length - 1)] );\n }\n\n return $bool;\n} \n\nsub dectab {\n my($ref)=shift;\n my ($res); foreach my $key( @$ref){ \n if ( ! defined $key ) { \n $res .= '-';\n } else {\n $res .= \"X\";\n }\n }\n return $res;\n}\n</code></pre>\n\n<p>The key observations are:</p>\n\n<ol>\n<li>The list of letter variables is better treated as an array - I used <code>@States</code>.</li>\n<li>The output from <code>dectab()</code> (which is unaltered) consists of some number of X's followed by some number of dashes. The regex match identifies how many X's by isolating them into a string, <code>$1</code>, and then calculating the length of the string. Note that the code does not check that the output from <code>dectab</code> matches that pattern - it probably should.</li>\n<li>The huge switch statement amounts to supplying the elements 0..(N-1) to the <code>$Graph->has_path()</code> function, so the code passes the relevant slice of <code>@States</code> to the function.</li>\n</ol>\n\n<p>There are still some bits I'm not clear about in your code. Specifically, I'm not sure about the roles (or sources) of the functions:</p>\n\n<ul>\n<li>clearerr</li>\n<li>gref</li>\n<li>seterr</li>\n</ul>\n\n<p>Because of that, I can't test my hypothesis. However, I do think that this solution scales to 200 items more easily than the original - and without needing:</p>\n\n<pre><code>use feature \"switch\";\n</code></pre>\n\n<p>With more time spent, the code could still be tidied up, I'm sure. And, since this is Perl, TMTOWTDI - there's more than one way to do it.</p>\n\n<hr>\n\n<p>Suggestion:</p>\n\n<ul>\n<li>Provide code that can be compiled and run whenever possible - you will get better code reviews that way.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T07:25:56.123",
"Id": "782",
"Score": "0",
"body": "Agreed, something compilable would be the go. In this case however, compilable means cooking up a much abbreviated PerlCtrl"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T07:36:28.153",
"Id": "783",
"Score": "0",
"body": "@boost: I think I'd want to be able to run the Pure Perl stuff before I started messing around with PerlCtrl. So, I'd make sure that I had a method of testing that would work. I don't use ActivePerl or Windows, so there's no way I can test properly. If this is the module [Graph.pm](http://search.cpan.org/perldoc?Graph) to which you refer (and it looks like it is), it is helpful to let people know. It is helpful to include the preamble to the Perl code so people can see what modules you are using. And you could surely provide some data that shows how you create the Graph?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T08:36:01.980",
"Id": "786",
"Score": "0",
"body": "Pure Perl is part of the problem. If I write the demonstration in Pure Perl, the problem evaporates because one cannot help but enter code which will evaluate correctly."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T08:41:44.983",
"Id": "787",
"Score": "0",
"body": "If I want to be able to pass up to 26 values, then I have to declare them and then figure out which ones are defined and which aren't."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T14:48:10.470",
"Id": "798",
"Score": "1",
"body": "@boost: you treat them as an array - as I did with `@State`. You know how many elements are defined from `scalar(@array)` or variations such as `$#array` (a notation I almost never use). You can, just about, make your code work with 26; you can't sanely make your code work for 260. Give or take the processing time, there's no specific size limitation on the proposed rewrite."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T07:21:20.367",
"Id": "480",
"ParentId": "478",
"Score": "10"
}
},
{
"body": "<p>Well:</p>\n\n<p>The first line can be written like this:</p>\n\n<pre><code>sub has_path\n{\n clearerr;\n my %Graph = gref(shift);\n\n my ($A, $B, $C, $D, $E, $F\n ,$G, $H, $I, $J, $K, $L\n ,$M, $N, $O, $P, $Q, $R\n ,$S, $T, $U, $V, $W, $X\n ,$Y, $Z) = @_;\n</code></pre>\n\n<p>But if all you are doing is using the parameters to call another function then just leave them in the array <code>@_</code> and pass that to the function you are calling:</p>\n\n<pre><code>sub has_path\n{\n clearerr;\n my %Graph = gref(shift);\n\n my $switcher = dectab( @_ ); # just use the input array (- graph)\n # as a parameter into dectab.\n # If you actually want to limit it then\n # splice() off then end.\n\n if ($switcher =~ /^(X+)(-*)$/) # make sure the result is XXX----\n {\n my $size = length($1); # Count the X.\n # Note this block is not entered if\n # zero X's in switcher variable\n\n # Cut the $size elements from the input array\n # and pass them as parameters to has_path()\n return $Graph->has_path(splice(@_, 0 , $size));\n }\n # If we reach here the call failed.\n # Just return the 0\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T09:54:47.560",
"Id": "483",
"ParentId": "478",
"Score": "8"
}
},
{
"body": "<p>Unless I'm misunderstanding something, your <code>has_path</code> routine and all of its supporting routines can actually be collapsed to simply this:</p>\n\n<pre><code>sub has_path {\n my $graph = $grefs->{shift};\n return\n @_ == 0? (0, \"No path.\"):\n @_ == 1? (0, \"Path of one element.\"):\n ($graph->has_path(@_), \"\");\n}\n</code></pre>\n\n<p>which is callable like this:</p>\n\n<pre><code>my ($error_flagged, $error_text) = has_path($gref, $a, $b, $c, ...);\n</code></pre>\n\n<p>There is no need to do any of that <code>dectab</code> stuff, since <code>has_path()</code> takes a variable number of arguments already, and in the order you want.</p>\n\n<p>(By the way, you wrote <code>%Graph</code> where I think you meant <code>$Graph</code>?)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-17T13:02:30.797",
"Id": "6946",
"ParentId": "478",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "480",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T04:52:54.217",
"Id": "478",
"Score": "9",
"Tags": [
"perl",
"graph"
],
"Title": "Function, taking up to 27 parameters, that checks for the existence of a path in a graph"
} | 478 |
<p>My homework question states:</p>
<blockquote>
<p>Develop a class to measure distance as feet (should be <code>int</code>), inches (should
be <code>float</code>). Include member functions to set and get attributes. Include
constructors. Develop functions to add two distances.</p>
<p>The prototype of the sum function is:</p>
<pre><code>Distance Sum(Distance d);
</code></pre>
</blockquote>
<p>Please check out my coding style and other aspects that can make this program better.</p>
<pre><code>#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inch;
public:
Distance();
Distance(int a,float b);
void setDistance();
int getFeet();
float getInch();
void distanceSum(Distance d);
};
int main()
{
Distance D1,D2;
D1.setDistance();
D2.setDistance();
D1.distanceSum(D2);
return 0;
}
/*Function Definitions*/
Distance::Distance()
{
inch=feet=0;
}
Distance::Distance(int a,float b)
{
feet=a;
inch=b;
}
void Distance::setDistance()
{
cout<<"Enter distance in feet";
cin>>feet;
cout<<endl<<"Enter inches:";
cin>>inch;
}
int Distance::getFeet()
{
return feet;
}
float Distance::getInch()
{
return inch;
}
void Distance::distanceSum(Distance d)
{
cout<<"feet="<<d.feet+feet<<endl;
cout<<"inches="<<d.inch+inch<<endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T20:28:20.247",
"Id": "3213",
"Score": "1",
"body": "Whitespace is cheap nowadays: don't be afraid to use it."
}
] | [
{
"body": "<p>When designing a class for your program, whether it's for homework or a real production application, you want to always consider how that class is going to be use and what its responsibilities should be. Each function and method should do <em>one</em> thing/task and it should be reflected by the method's name. Additionally, you want to keep to a consistent easy-to-read coding style when you actually start writing the code. With those two points in mind here's some things to consider in your code:</p>\n\n<ul>\n<li><code>Distance::distanceSum</code> is doing two tasks here.</li>\n</ul>\n\n<p>It's not only summing feet and inches but it's printing them out as well.</p>\n\n<ul>\n<li>Unnecessary type conversion. </li>\n</ul>\n\n<p>In your default Distance() ctor, there's an implicit conversion because you're assigning <code>0</code> to a float type. You should have gotten a warning from your compiler. Consider using an initializer list like so:</p>\n\n<pre><code>Distance::Distance() : feet(0), inch(0.0)\n{\n}\n</code></pre>\n\n<ul>\n<li>Code doesn't take advantage of const correctness. </li>\n</ul>\n\n<p>Which parameters aren't suppose to change? Which methods will be modifying your Distance class? For example, your <code>Distance::Distance(int a,float b)</code> isn't changing <code>a</code> or <code>b</code>. Have the compiler enforce that promise by using const:</p>\n\n<pre><code>Distance::Distance(const int a, const float b)\n</code></pre>\n\n<p>Similiarly:</p>\n\n<pre><code>void Distance::distanceSum(const Distance &d);\n</code></pre>\n\n<ul>\n<li>Inconsistent indentation and spacing.</li>\n</ul>\n\n<p>Consider indenting the methods under public: the same way you did with private:. Add spaces to your assignments to help readability. eg. <code>feet = a;</code></p>\n\n<ul>\n<li>No module separation by file.</li>\n</ul>\n\n<p>class <code>Distance</code> should probably be in a separate header/implementation file rather than putting everything in one main file.</p>\n\n<ul>\n<li>Ninja comments. </li>\n</ul>\n\n<p>Comments? What comments? Exactly. Consider adding a block comment at the top of your Distance class that explains the purpose for its existence. The block comment should answer questions like how is this class suppose to be used and what details is it abstracting away? Adding a comment to clarify how the feet and inch data members are going to be used. For example, it's not clear if your distance class is maintaining the same distance measurement but with different units or it's really meant to be used as one whole unit. eg. 6 feet 2 inches or 6 feet 72 inches?</p>\n\n<p>With the above considerations, here's one way I would refactor your code:</p>\n\n<p>In distance.h header file:</p>\n\n<pre><code>#ifndef DISTANCE_H\n#define DISTANCE_H\nclass Distance\n{\n private:\n // feet and inch is one unit. \n // invariant: inch_ < 12.\n int feet_;\n float inch_;\n public:\n Distance(const int feet = 0, const float inches = 0.0);\n void setDistance(const int feet, const float inches = 0.0);\n int getFeet() const;\n float getInch() const;\n\n // returns this instance. Permits method chaining for Distance class.\n Distance& Add(const Distance &d);\n};\n#endif\n</code></pre>\n\n<p>In distance.cpp implementation:</p>\n\n<pre><code>#include \"distance.h\"\nDistance::Distance(const int feet, const float inches) \n : feet_(feet + inches / 12), inch_(inches % 12)\n{\n}\n\nvoid Distance::setDistance(const int feet, const float inches)\n{\n feet_ = feet + inches / 12;\n inch_ = inches % 12;\n}\n\nint Distance::getFeet() const\n{\n return feet_;\n}\n\nfloat Distance::getInch() const\n{\n return inch_;\n}\n\nDistance& Distance::Add(const Distance &d)\n{\n setDistance(getFeet() + d.getFeet(), getInch() + d.getInch());\n\n return *this;\n}\n</code></pre>\n\n<p>Here are the major changes above:</p>\n\n<ul>\n<li>Distance no longer uses cin/cout for explicit IO. You can push that code into main.</li>\n<li>class definition and implementation are now in their respectively named files.</li>\n<li>Removed an extra constructor definition by taking advantage of default parameters.</li>\n<li>feet and inch data members are used together to represent the measurement in distance. inch cannot be > 12 because that would mean there's enough for a foot. We enforce this by dividing feet and inches by 12 when setting distance's data.</li>\n<li>const is used to clearly indicate what can and can't change the distance object.</li>\n<li>Changed distanceSum to Add to better reflect what it's doing. Notice that Add is implemented only through Distance's public methods -- it does not manipulate <code>feet_</code> and <code>inch_</code> directly.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T08:19:50.533",
"Id": "784",
"Score": "0",
"body": "Why an underscore in feet?(feet_)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T08:23:15.710",
"Id": "785",
"Score": "1",
"body": "@fahad that is just a coding convention I'm using, appending _ for class data members. You can certainly choose a different convention that suits you. Whatever you choose to go with just be consistent."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T09:48:32.047",
"Id": "789",
"Score": "2",
"body": "I don't think that unmodified function arguments need to be const- I would only mark the functions themselves as const."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T12:50:15.220",
"Id": "790",
"Score": "0",
"body": "Yes I had the same doubt!When passed by value,you dont need to keep it const"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T13:13:20.900",
"Id": "793",
"Score": "0",
"body": "One thing Victor T. implies but doesn't explicitly mention here is that you don't need to use indents of 8 spaces. 4 spaces is a common convention. 8 spaces is an unnecessary waste of your valuable horizontal space."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T15:21:30.630",
"Id": "802",
"Score": "0",
"body": "i'm not a C++ guy, so not certain about the 'new' syntax, but I think you should not return *this as part of the Add operation. Instead, keep this instance immutable and return a new object that contains the new state."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T20:40:19.850",
"Id": "820",
"Score": "2",
"body": "`const float inches = 0.0` should be `0.0f` else there is an implicit conversion going on to `float` from `double`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T22:23:03.450",
"Id": "829",
"Score": "0",
"body": "@john good catch hehe, I was originally thinking of making it double."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T22:48:40.150",
"Id": "830",
"Score": "0",
"body": "@bryan That's an interesting and valid point and I know some languages that take that approach. My `Distance::Add` is really a += operator in disguise and I could have overloaded that but it's clear the OP is fairly new to C++ so I didn't to avoid confusion. In C++ when you do something like `int i = 0; (i += 42)++;`, the second statement will increment `i` after adding 42. I choose this just to keep that behavior consistent with Distance."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T08:52:45.480",
"Id": "1439",
"Score": "0",
"body": "I would bet $5 the graders will be looking for `Add()` to normalize inches to be in the range [0, 12). Additional helpful methods include `float getAsFeet() const { return feet + inches / 12.0f; }` and `float getAsInches() const { return 12.0f * feet + inches; }`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T03:06:21.777",
"Id": "79513",
"Score": "0",
"body": "I'd also suggest that overflow prevention should be mandatory (e.g. if `feet` ever exceeds the range of `INT_MAX` throw an exception). Also any attempt to use negative values for feet or inches should also cause an exception (distances can't/shouldn't be negative)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-02T08:12:02.913",
"Id": "325626",
"Score": "0",
"body": "Just to add an argument why by-value function parameters generally are not set to const: It possibly and unnecessary adds constraints to an implementation. Your current implementation might not change the input parameters, but a future one will do so (for whatever reason)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T07:40:13.813",
"Id": "481",
"ParentId": "479",
"Score": "26"
}
},
{
"body": "<p>A bunch of these functions should be operators. You also seem to be confused about the purpose of addition. Also, <code>using namespace std</code> is bad. You also didn't provide any other operators- even though any class user will logically expect that if you can add a distance, you can add a distance to the current object, and that you can subtract distances too. You also didn't provide any kind of input verification or const correctness.</p>\n\n<pre><code>class Distance\n{\n int feet;\n float inch;\npublic:\n // Constructors\n Distance();\n Distance(int a, float b);\n\n // Getters\n int getFeet() const;\n float getInch() const;\n\n // Operator overloads - arithmetic\n Distance operator-(const Distance&) const;\n Distance& operator-=(const Distance&);\n Distance operator+(const Distance&) const;\n Distance& operator+=(const Distance&);\n\n // Create from console\n static Distance getDistanceFromConsole();\n};\n// Operator overloads - I/O\nstd::ostream& operator<<(std::ostream&, const Distance&);\n</code></pre>\n\n<p>And the implementations are...</p>\n\n<pre><code>Distance::Distance() : feet(0), inch(0.0f) {}\nDistance::Distance(int argfeet, float arginch) : feet(argfeet), inch(arginch) {\n // Verify that we are actually in feet and inches.\n // Not gonna write this code- dependent on the class invariants\n // which were not explicitly specified (e.g., can have negative Distance?)\n}\nint Distance::getFeet() const {\n return feet;\n}\nfloat Distance::getInch() const {\n return inch;\n}\nDistance Distance::operator-(const Distance& dist) const {\n Distance retval(*this);\n retval -= dist;\n return retval;\n}\nDistance& Distance::operator-=(const Distance& dist) {\n feet -= dist.feet;\n inches -= dist.inches;\n // Verify values- e.g. that inches is less than 12\n return *this;\n}\nDistance operator+(const Distance& dist) const {\n Distance retval(*this);\n retval += dist;\n return retval;\n}\nDistance& operator+=(const Distance& dist) {\n feet += dist.feet;\n inches += dist.inches;\n // More verification here.\n}\n\nstd::ostream& operator<<(std::ostream& output, const Distance& dist) {\n output << \"Feet: \" << dist.feet << \"\\n\";\n output << \"Inches: \" << dist.inches << std::endl; // flush when done.\n return output;\n}\n\nDistance getDistanceFromConsole() {\n int feet; float inch;\n std::cout<<\"Enter distance in feet\";\n std::cin>>feet;\n std::cout<<endl<<\"Enter inches:\";\n std::cin>>inch;\n return Distance(feet, inch);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T10:06:52.023",
"Id": "484",
"ParentId": "479",
"Score": "7"
}
},
{
"body": "<p>There's no reason to have both inches and feet since the one can be calculated from the other. Superfluous redundancy just adds complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T00:18:02.597",
"Id": "1097",
"Score": "2",
"body": "Why this is not the top comment is beyond me. Though there are lots of possible improvements like mentioned in Vicors good and elaborate answer, this hits the nail on the head. Whatever you do, fix this first (and stuff will become much simpler)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T08:56:04.697",
"Id": "1440",
"Score": "2",
"body": "Perhaps because the very first sentence of the assignment stated that the class should model feet and inches separately. I learned long ago to do what the assignment asks unless I know _for sure_ that the grader will accept optimizations."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T19:31:26.757",
"Id": "1451",
"Score": "0",
"body": "@David - the text quoted as the homework assignment doesn't say that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T21:33:51.887",
"Id": "1457",
"Score": "1",
"body": "@Crazy Eddie - The first sentence specifically states the data types of the two attributes: \"Develop a class to measure distance as feet(should be int),inch(should be float).\" The second sentence implies at least two attributes by using the plural form: \"Include member functions to set and get attributes.\" I don't know what other attributes it would be talking about."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T18:11:42.030",
"Id": "487",
"ParentId": "479",
"Score": "8"
}
},
{
"body": "<h3>C++ comments:</h3>\n\n<p>Prefer initializer lists:</p>\n\n<pre><code>Distance::Distance()\n :feet(0), inch(0)\n{\n // NOT THIS -> inch=feet=0;\n}\n</code></pre>\n\n<h3>General coding comments:</h3>\n\n<p>Don't combine functionality:<br>\nYou should define a function to add Distance objects and one to print them. (DeadMG has that covered above).</p>\n\n<pre><code>void Distance::distanceSum(Distance d)\n{\n cout<<\"feet=\"<<d.feet+feet<<endl;\n cout<<\"inches=\"<<d.inch+inch<<endl;\n}\n</code></pre>\n\n<p>Also I see you don't normalize your results. You could have 1 foot 300.05 inches. When ever the state of an object changes where one parameter flows into another you should normalize the data. Have an explicit function to do so and call it each time state changes:</p>\n\n<pre><code>private: void Normalize() { int eFeet = inches / 12; feet += eFeet; inches -= (eFeet * 12);}\n</code></pre>\n\n<h3>Implementation Comments:</h3>\n\n<p>But then again why do you store what is actually a single value in two different variables (feet and inches). Why not just store the total distance in inches (and then do conversion on the way in/out). Look at the unix time. It just counts the seconds since the epoch. All other values are calculated from this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T18:57:10.630",
"Id": "489",
"ParentId": "479",
"Score": "5"
}
},
{
"body": "<p>I also prefer to write public methods first, because when you review big classes you must scroll to see public members. </p>\n\n<p>For example:</p>\n\n<pre><code>class MyClass\n{\npublic:\n// public members\nprotected:\n// protected members\nprivate:\n// private members\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-13T10:39:47.377",
"Id": "1857",
"ParentId": "479",
"Score": "1"
}
},
{
"body": "<p>You could have written implementation of methods in the class itself where the template of methods are defined. Its generally a good practice to write all those methods in the class. In your case even if you have written the methods out side the class, C++ compiler will make then inline at the time of compilation.So it is better to write those methods as inline methods. It will make the execution bit faster and will remove the use of scope resolution operator which is seemingly difficult. Below is the example how to write..It contains just one method but you can do the same for rest of the methods. </p>\n\n<pre><code>#include <iostream>\nusing namespace std;\nclass Distance\n{\n private:\n int feet;\n float inch;\n public:\n Distance()\n {\n inch=feet=0;\n }\n Distance(int a,float b);\n void setDistance();\n int getFeet();\n float getInch();\n void distanceSum(Distance d);\n};\nint main()\n{\n Distance D1,D2;\n D1.setDistance();\n D2.setDistance();\n D1.distanceSum(D2);\n return 0;\n}\n</code></pre>\n\n<p>This is the better way. All the class methods should be defined in the class only.\nSuppose are to develop just a class in java, then you can not develope a good class by writing like this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T05:42:49.510",
"Id": "4208",
"ParentId": "479",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "481",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T06:33:47.660",
"Id": "479",
"Score": "28",
"Tags": [
"c++",
"homework"
],
"Title": "Class for measuring distance as feet and inches"
} | 479 |
<p>Okay... here's the beast:</p>
<pre><code>SELECT
SUBSTRING(DischDate, 7, 4) + SUBSTRING(DischDate, 1, 2) as YYYYMM
,Type
,SubType
,Diags
,Count(*) as Count
,SUM(Charges) as Charges
,SUM(Payments) as Payments
FROM
(
SELECT DISTINCT
ID
,Diags
FROM
(SELECT VisitID as ID
,DX01 ,DX11 ,DX21, DX31
,DX02 ,DX12 ,DX22, DX32
,DX03 ,DX13 ,DX23, DX33
,DX04 ,DX14 ,DX24, DX34
,DX05 ,DX15 ,DX25, DX35
,DX06 ,DX16 ,DX26, DX36
,DX07 ,DX17 ,DX27, DX37
,DX08 ,DX18 ,DX28, DX38
,DX09 ,DX19 ,DX29, DX39
,DX10 ,DX20 ,DX30, DX40
FROM [AGH00]...[20110128 - AGH00#TXT]) p
UNPIVOT
(Diags FOR DX IN
(DX01 ,DX11 ,DX21, DX31
,DX02 ,DX12 ,DX22, DX32
,DX03 ,DX13 ,DX23, DX33
,DX04 ,DX14 ,DX24, DX34
,DX05 ,DX15 ,DX25, DX35
,DX06 ,DX16 ,DX26, DX36
,DX07 ,DX17 ,DX27, DX37
,DX08 ,DX18 ,DX28, DX38
,DX09 ,DX19 ,DX29, DX39
,DX10 ,DX20 ,DX30, DX40)
)AS unpvt
) as DIAGS
LEFT JOIN [AGH00]...[20110128 - AGH00#TXT] as A0 on DIAGS.ID = A0.VisitID
LEFT JOIN ( SELECT VisitID, Sum(ChargsAmt) as Charges
FROM [AGH00]...[20110128 - AGH00Chg#TXT]
Group By VisitID ) as AC on A0.VisitID = AC.VisitID
LEFT JOIN ( SELECT VisitID, Sum(Pmt) as Payments
FROM [AGH00]...[20110128 - AGH00Pmt#TXT]
Group By VisitID ) as AP on A0.VisitID = AP.VisitID
Group By
SUBSTRING(DischDate, 7, 4) + SUBSTRING(DischDate, 1, 2)
,Type
,SubType
,Diags
Order By
SUBSTRING(DischDate, 7, 4) + SUBSTRING(DischDate, 1, 2)
,Type
,SubType
,Diags
</code></pre>
<p>Sample output:</p>
<blockquote>
<pre><code>YYYYMM Type SubType Diags # Charges Payments
201004 I SPEC 5185 3 224086.60 222986.60
200910 I MONT 73390 2 7573.42 6984.13
200910 O AHCW 463 4 578.00 578.00
200910 I MEDI 2766 2 67444.39 67444.39
</code></pre>
</blockquote>
<p>Notes:</p>
<ul>
<li>SQL2005 LinkedServer to a TextFile with a backing ini for field descriptions.</li>
<li><p>DischDate is "mm/dd/yyyy" text field. I want YYYYMM for grouping (as well as other fields)</p>
<ol>
<li>First "table" is a list generated via Unpivot that basically generates a list of VisitID's and unique Diags </li>
<li>Left Join main customer data by "VisitID"</li>
<li>Left Join Charges Data (Grouped to get individual charges grouped by "customer" aka VisitID) </li>
<li>Left Join Payment Data (same as last) </li>
<li>Group by/Order By/Select Date YYYYMMDD, Type, Subtype, Diags... and grouped Count/Sums </li>
</ol></li>
</ul>
<p>More information is in <a href="https://stackoverflow.com/questions/4854322/tsql-question-group-by-on-multiple-columns">this SO question</a> where someone pointed me to the unpivot option. Including a semi-confused explanation of what I want to accomplish (basically grouping information for a couple similar reports).</p>
<p>Just wondering if there is a more graceful way, and if anyone see potential errors.</p>
| [] | [
{
"body": "<p>This looks like a good use for UNPIVOT. And you can use <a href=\"http://msdn.microsoft.com/en-us/library/ms175972.aspx\" rel=\"nofollow\">common table expressions</a> to <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">avoid repeating yourself</a>. Like this:</p>\n\n<pre><code>WITH DIAGS AS\n(\n SELECT DISTINCT VisitID as ID, Diags\n FROM \n (\n SELECT *\n FROM [AGH00]...[20110128 - AGH00#TXT]\n ) p\n UNPIVOT\n (\n Diags FOR DX IN\n (\n DX01, DX11, DX21, DX31\n , DX02, DX12, DX22, DX32\n , DX03, DX13, DX23, DX33\n , DX04, DX14, DX24, DX34\n , DX05, DX15, DX25, DX35\n , DX06, DX16, DX26, DX36\n , DX07, DX17, DX27, DX37\n , DX08, DX18, DX28, DX38\n , DX09, DX19, DX29, DX39\n , DX10, DX20, DX30, DX40\n )\n ) AS unpvt\n),\nA0 AS\n(\n SELECT VisitID, DischDate, [Type], SubType\n FROM [AGH00]...[20110128 - AGH00#TXT]\n),\nAC AS\n(\n SELECT VisitID, SUM(ChargsAmt) AS Charges\n FROM [AGH00]...[20110128 - AGH00Chg#TXT]\n GROUP BY VisitID\n),\nAP AS\n(\n SELECT VisitID, SUM(Pmt) AS Payments\n FROM [AGH00]...[20110128 - AGH00Pmt#TXT]\n GROUP BY VisitID\n)\nVISITS AS\n(\n SELECT SUBSTRING(A0.DischDate, 7, 4) + SUBSTRING(A0.DischDate, 1, 2) AS YYYYMM\n , A0.[Type]\n , A0.SubType\n , DIAGS.Diags\n , AC.Charges\n , AP.Payments\n FROM DIAGS\n LEFT JOIN A0 ON DIAGS.ID = A0.VisitID\n LEFT JOIN AC ON A0.VisitID = AC.VisitID\n LEFT JOIN AP ON A0.VisitID = AP.VisitID \n)\nSELECT YYYYMM, [Type], SubType, Diags\n , COUNT(*) AS [Count]\n , SUM(Charges) AS Charges\n , SUM(Payments) AS Payments\nFROM VISITS\nGROUP BY YYYYMM, [Type], SubType, Diags\nORDER BY YYYYMM, [Type], SubType, Diags\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-26T23:37:52.180",
"Id": "1018",
"ParentId": "490",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1018",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T20:17:49.470",
"Id": "490",
"Score": "7",
"Tags": [
"sql",
"sql-server"
],
"Title": "Tame this Beast: TSQL Unpivot"
} | 490 |
<p>I have written a simple spinner wrapper, but was wondering if any of you could think of any ways to make it more robust. It only handles strings at the moment.</p>
<p><code>MySpinner</code>:</p>
<pre><code>package a.b.c;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MySpinner extends Spinner {
// constructors (each calls initialise)
public MySpinner(Context context) {
super(context);
this.initialise();
}
public MySpinner(Context context, AttributeSet attrs) {
super(context, attrs);
this.initialise();
}
public MySpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.initialise();
}
// declare object to hold data values
private ArrayAdapter<String> arrayAdapter;
// add the selected item to the end of the list
public void addItem(String item) {
this.addItem(item, true);
}
public void addItem(String item, boolean select) {
arrayAdapter.add(item);
this.setEnabled(true);
if (select) this.selectItem(item);
arrayAdapter.sort(new Comparator<String>() {
public int compare(String object1, String object2) {
return object1.compareTo(object2);
};
});
}
// remove all items from the list and disable it
public void clearItems() {
arrayAdapter.clear();
this.setEnabled(false);
}
// make the specified item selected (returns false if item not in the list)
public boolean selectItem(String item) {
boolean found = false;
for (int i = 0; i < this.getCount(); i++) {
if (arrayAdapter.getItem(i) == item) {
this.setSelection(i);
found = true;
break;
}
}
return found;
}
// return the current selected item
public String getSelected() {
if (this.getCount() > 0) {
return arrayAdapter.getItem(super.getSelectedItemPosition());
} else {
return "";
}
}
// allow the caller to use a different DropDownView, defaults to android.R.layout.simple_dropdown_item_1line
public void setDropDownViewResource(int resource) {
arrayAdapter.setDropDownViewResource(resource);
}
// internal routine to set up the array adapter, bind it to the spinner and disable it as it is empty
private void initialise() {
arrayAdapter = new ArrayAdapter<String>(super.getContext(), android.R.layout.simple_spinner_item);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
this.setAdapter(arrayAdapter);
this.setEnabled(false);
}
}
</code></pre>
<p>To use:</p>
<ol>
<li>Use <code>a.b.c.MySpinner</code> instead of <code>Spinner</code> in your XML layout file</li>
<li>Set up a variable, <code>mMySpinner = (MySpinner)findViewById(R.id.spinner);</code></li>
<li>You can then use all the functions which should be self-explanatory</li>
<li>If there are no items in the list, the spinner is disabled to prevent untoward events</li>
</ol>
<p></p>
<ul>
<li><code>mMySpinner.clearItems()</code> - to remove all the items</li>
<li><code>mMySpinner.addItem("Blue")</code> - to add Blue as an item in list (items are sorted by abc)</li>
<li><code>mMySpinner.selectItem("Red")</code> - to make the indicate item the current selection</li>
<li><code>mMySpinner.getSelected()</code> - to return the current selected item string</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T06:02:33.630",
"Id": "11475",
"Score": "0",
"body": "Why were so many common things like \"add\" and \"clear\" and \"insert\" and \"delete\" totally left out of Android Spinners, in the first place????"
}
] | [
{
"body": "<p>A few ways you could make it more robust.</p>\n\n<ol>\n<li>In <code>getSelected()</code>, why not call <code>getSelectedItem()</code> instead?</li>\n<li>You tend to use <code>super.foo()</code> instead of <code>foo()</code>; that's usually a bad idea. Just call <code>foo()</code>, unless you really want to avoid any override in your class. If you always use <code>super.foo()</code>, then if you decide you want to override <code>foo()</code>, perhaps for some debug code, you have to go change your code everywhere from <code>super.foo()</code> to just <code>foo()</code> or perhaps <code>this.foo()</code>.</li>\n<li>This code doesn't seem to enforce a consistent policy around duplicates in the spinner. If duplicates are not allowed, perhaps good to check for that at add time.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T21:49:11.817",
"Id": "529",
"ParentId": "491",
"Score": "3"
}
},
{
"body": "<p>I think it would be great to replace:</p>\n\n<pre><code>arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n</code></pre>\n\n<p>My issue was to implement two spinners with the following feature: if some string is selected in the spinner 1, it should disappear in spinner 2 and the same for the second spinner.</p>\n\n<p>So it would be very nice to have some method to \"hide\" some item. I'm just clearing the adapter and adding other items, without hidden.</p>\n\n<p>Update after half a day of workaround:</p>\n\n<p>ULTIMATE BUG:</p>\n\n<pre><code>if(arrayAdapter.getItem(i) == item)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T13:41:22.950",
"Id": "4637",
"ParentId": "491",
"Score": "5"
}
},
{
"body": "<p>This is a very nice class, and I don't wish to discredit the author (FrinkTheBrave) in any way! I do, however, want to offer a few enhancements and correct the nasty bugs that are inherent in the original.</p>\n\n<h2>The issues/enhancements addressed here:</h2>\n\n<blockquote>\n <p>o Do not insert duplicates</p>\n \n <p>o Re-do selection if new row inserted</p>\n \n <p>o getSelected will return null rather than empty string if nothing selected</p>\n \n <p>o Proper comparison of string (a.equals(b) rather than a == b)</p>\n \n <p>o Sort is now case-insensitive</p>\n \n <p>o Removed 'this.' from this.foo where unneeded (which means, everywhere).</p>\n \n <p>o Changed setDropDownViewResource as per comment by @seand</p>\n</blockquote>\n\n<p>To explain more about the re-selection: Consider the following. Spinner currently has these items (where > indicates the selected item) </p>\n\n<pre><code> Antelope\n > Cat\n Dog\n</code></pre>\n\n<p>Now, we insert Bear. Unless we re-do it, the second item will remain as 'selected.' But because we inserted Bear alphabetically, the true Selected item has moved to the third position.</p>\n\n<pre><code> Antelope\n > Bear\n Cat\n Dog\n</code></pre>\n\n<p>So, before the insertion of an non-selected String, we will save the String of the current selection (if there is one). Then, after the insertion and the sort, we will select it again.</p>\n\n<pre><code> Antelope\n Bear\n > Cat\n Dog \n</code></pre>\n\n<p>So if I may be so bold....</p>\n\n<pre><code>package c.b.a;\n\nimport java.util.Comparator;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport android.widget.ArrayAdapter;\nimport android.widget.Spinner;\n\npublic class AdvancedSpinner extends Spinner {\n\n // Thanks to CodeReview: http://codereview.stackexchange.com/questions/491/simplified-android-spinner\n // declare object to hold data values\n private ArrayAdapter<String> arrayAdapter;\n\n // constructors (each call initialize)\n public AdvancedSpinner(Context context) {\n super(context);\n initialize();\n }\n\n public AdvancedSpinner(Context context, AttributeSet attrs) {\n super(context, attrs);\n initialize();\n }\n\n public AdvancedSpinner(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n initialize();\n }\n\n // add the selected item to the end of the list\n public Boolean addItem(String item) {\n return addItem(item, true);\n }\n\n public Boolean addItem(String item, boolean select) {\n Boolean addFlag = true;\n\n for (int i = 0; i < getCount(); i++) {\n if (arrayAdapter.getItem(i).equals(item)) {\n // Don't add an item that's already in the list\n // But we do need to mark it as \"selected\" if\n // applicable.\n addFlag = false;\n if (select)\n setSelection(i);\n break;\n }\n }\n if (addFlag) {\n String saveSelected = null;\n if (! select) {\n // We need to preserve the prior selection, which may be\n // messed up by our array sort operation. So we will\n // save the selected item's value, and (after the insert)\n // we will reinstate its selection status.\n saveSelected = getSelected();\n }\n arrayAdapter.add(item);\n setEnabled(true);\n arrayAdapter.sort(new Comparator<String>() {\n public int compare(String object1, String object2) {\n return object1.compareToIgnoreCase(object2);\n };\n });\n if (select)\n selectItem(item);\n else if (saveSelected != null)\n selectItem(saveSelected);\n }\n return addFlag;\n }\n\n // remove all items from the list and disable it\n public void clearItems() {\n arrayAdapter.clear();\n setEnabled(false);\n }\n\n // make the specified item selected (returns false if item not in the list)\n public boolean selectItem(String item) {\n boolean found = false;\n for (int i = 0; i < getCount(); i++) {\n if (arrayAdapter.getItem(i).equals(item)) {\n setSelection(i);\n found = true;\n break;\n }\n }\n return found;\n }\n\n public String getSelected() {\n // return the current selected item\n // Changed (Dennis) to return null if nothing selected, rather than the\n // (misleading) empty string. Also, prior incarnation would ForceClose\n // if array was not empty but nothing was selected.\n String rtnVal = null;\n if (getCount() > 0) {\n int i = super.getSelectedItemPosition();\n if (i >= 0) // An item has been selected\n rtnVal = arrayAdapter.getItem(i);\n }\n return rtnVal;\n }\n\n // allow the caller to use a different DropDownView, defaults to android.R.layout.simple_spinner_dropdown_item\n public void setDropDownViewResource(int resource) {\n arrayAdapter.setDropDownViewResource(resource);\n }\n\n // internal routine to set up the array adapter, bind it to the spinner and disable it as it is empty\n private void initialize() {\n arrayAdapter = new ArrayAdapter<String>(super.getContext(), android.R.layout.simple_spinner_item);\n arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n setAdapter(arrayAdapter);\n setEnabled(false);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T04:09:10.653",
"Id": "25849",
"Score": "0",
"body": "Welcome to CodeReview! It would be helpful, I think, if you could summarize the issues at the top of your post, as well as having them in comments, so that they're more obvious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T08:53:01.173",
"Id": "25861",
"Score": "0",
"body": "@GlennRogers is correct, of course. I hope my edits have done an adequate job of explaining what was done, and why."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T12:16:24.403",
"Id": "26512",
"Score": "0",
"body": "@Dennis, thanks for your comments/corrections, that's why I posted it. However, I disagree mildly with preventing duplicates as that should be under the control of the calling program, and I disagree strongly with returning null if nothing selected as it makes it harder to call. How would you call getSelected if it could return a null?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T00:40:12.500",
"Id": "26649",
"Score": "0",
"body": "@FrinkTheBrave, that's why they make chocolate and vanilla. But it is a standard to return null for non-existent. How would I call it? If ((myString = getSelected()) != NULL) { // do something with myString } If that's harder to call, I apologize. But I'd be willing to bet you're going to do something like <<if (myString != \"\")>> in your code, and I see zero difference in ease or in readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-13T20:34:09.260",
"Id": "27848",
"Score": "0",
"body": "@Dennis, I was more thinking that 9 times out of 10 I'd be just assigning the spinner value to a string as data, myString = getSelected(); rather than acting on its value at the time. Also, I'm sure ((myString = getSelected()) != NULL) makes sense to all those C and Java wizards out there but it just looks complex to me. Thanks for your comments tho :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-14T10:25:05.450",
"Id": "27866",
"Score": "0",
"body": "It's all good, @FrinkTheBrave. Thanks for the original code, and the discussion. I've made my living by dealing successfully with that other 10%. And it doesn't have to be complex. You specifically asked, how would I call it. Alternative: myData = getSelected(); if myData != NULL { ... } . . . Anyway, you have yours, I have mine, and we both/each have a pretty nice spinner class."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T23:29:07.800",
"Id": "15894",
"ParentId": "491",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T20:29:24.857",
"Id": "491",
"Score": "11",
"Tags": [
"java",
"android"
],
"Title": "Simplified Android Spinner"
} | 491 |
<p>This is a simple list of items in a list, which allows the user to dynamically generate that list of events. Then a controller action does the work of serializing that into the database.</p>
<p>The issue is that there's the PHP-generated HTML segment, and there's a separate JavaScript segment to do the additions (for when someone presses the "add new page" button). This is not only duplicated; when it's done inline in the JavaScript it's extremely ugly to look at (look at the length of that line!).</p>
<p>Is there a better way of doing this?</p>
<pre><code><?php
/** @var $this Zend_View */
$this->headLink()->appendStylesheet($this->baseUrl('css/redmond/jquery-ui-1.8.5.custom.css'));
$this->headScript()->appendFile($this->baseUrl('js/jquery.js'));
$this->headScript()->appendFile($this->baseUrl('js/jquery-ui-1.8.5.custom.min.js'));
$this->headScript()->captureStart(); ?>
//<script language="text/javascript">
function CreateDateboxes(jqObject) {
jqObject.datepicker({
dateFormat: 'yy-mm-dd',
showOn: 'button',
changeYear: true,
changeMonth: true
});
}
function RemoveParent() {
$(this).parent().parent().remove();
}
function AddNewEvent() {
var today, html, temp, datestring;
today = new Date();
datestring = (today.getYear()+1900) + '-' + (today.getMonth()+1) + '-' + today.getDate();
html = '<li class="ui-content">\n <div style="float: left; width: 200px;">\n <span class="ui-icon ui-icon-trash ui-button ui-state-active" style="float: left; margin:3px;"></span>\n <input name="dates[]" class="datebox" style="width: 120px;" type="text" value="' + datestring + '" />\n </div>\n <div style="padding-left: 200px;">\n <input name="contents[]" type="text" style="width: 100%;" />\n </div>\n</li>';
$(this).after(html);
temp = $(this).next();
CreateDateboxes($('.datebox', temp));
$('.ui-icon-trash', temp).click(RemoveParent);
}
$(function() {
CreateDateboxes($('.datebox'));
$('.ui-icon-trash').click(RemoveParent);
$('.ui-icon-plus').parent().click(AddNewEvent);
});
//</script>
<?php $this->headScript()->captureEnd(); ?>
<div class="story">
<form action="<?= $this->url(array('controller' => 'admin', 'action' => 'applyEvents')) ?>" method="post">
<ul style="list-style: none; margin-bottom: 1em; padding: 0; width: 100%;">
<li class="ui-button ui-state-default" style="width: 100%; margin-bottom: 5px;"><span class="ui-icon ui-icon-plus" style="float: left;"></span>
Add a new Event</li>
<? foreach ($this->events as $event) { ?>
<li class="ui-content">
<div style="float: left; width: 200px;">
<span class="ui-icon ui-icon-trash ui-button ui-state-active" style="float: left; margin:3px;"></span>
<input name="dates[]" class="datebox" style="width: 120px;" type="text" value="<?= $event->GetDate()->format('Y-m-d') ?>" />
</div>
<div style="padding-left: 200px;">
<input name="contents[]" type="text" value="<?= $event->GetMessage() ?>" style="width: 100%;" />
</div>
</li>
<? } ?>
</ul>
<input type="submit" name="submit" value="Apply" />
<input type="submit" name="submit" value="Cancel" />
</form>
</div>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:27:17.620",
"Id": "181523",
"Score": "0",
"body": "Use something like [Mustache](http://mustache.github.com/), which is a templating framework that has renderers both on the client-side and the server side, which allows you to avoid code duplication."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T01:40:14.930",
"Id": "181524",
"Score": "0",
"body": "Templating is definitely the answer.\nAnother option is http://beebole.com/pure/ for client side templating. With templating you can write your html in one place, then add it to a variable in javascript, then append the variables html into a node applying the template. No duplicate html, no ajax."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T14:58:44.550",
"Id": "181525",
"Score": "0",
"body": "I ran into a similar problem just a week ago and I got tired of duplicating really fast, too. I just created one JavaScript function to do the printing of data to the page, and made my PHP code to print JavaScript calls to that function. The code became much cleaner that way."
}
] | [
{
"body": "<p>I'm assuming from looking the code you're using Zend Framework. I've solved similar issues in Zend and Symfony using php partials.</p>\n\n<p>You could create a partial _list_item.phtml</p>\n\n<pre><code><li class=\"ui-content\">\n <div style=\"float: left; width: 200px;\">\n <span class=\"ui-icon ui-icon-trash ui-button ui-state-active\" style=\"float: left; margin:3px;\"></span>\n <input name=\"dates[]\" class=\"datebox\" style=\"width: 120px;\" type=\"text\" value=\"<?php echo $date ?>\" />\n </div>\n <div style=\"padding-left: 200px;\">\n <input name=\"contents[]\" type=\"text\" value=\"<?php echo $message ?>\" style=\"width: 100%;\" />\n </div>\n</li>\n</code></pre>\n\n<p>Then in your view:</p>\n\n<pre><code><?php foreach ($this->events as $event): ?>\n <?php echo $this->partial('list_item.phtml', array(\n 'date' => $event->GetDate()->format('Y-m-d'),\n 'message' => $event->GetMessage(),\n )); ?>\n<?php endforeach; ?>\n</code></pre>\n\n<p>Then for your javascript:</p>\n\n<pre><code>function AddNewEvent()\n{\n var today, html, temp;\n // call str_replace because javascript doesn't like new lines in strings\n html = '<?php echo str_replace(PHP_EOL, \"\\n\", $this->partial('list_item.phtml', array(\n 'date' => $event->GetDate()->format('Y-m-d'),\n 'message' => '',\n ))); ?>';\n $(this).after(html);\n temp = $(this).next();\n CreateDateboxes($('.datebox', temp));\n $('.ui-icon-trash', temp).click(RemoveParent);\n}\n</code></pre>\n\n<p>Viola! No template duplication because the affected code is in a partial. No excess javscript templating libraries, although if this kind of thing is prevalent in your application I'd suggest some refactoring and implementing such a templating library.</p>\n\n<p>This approach will have the least impact on your work flow, little to no learning curve, and a short investment in development time for big decrease duplication (bosses love hearing that kind of thing). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T16:03:22.620",
"Id": "1316",
"Score": "1",
"body": "+1 Slick! (But if you're doing this in production you should probably use `json_encode` instead of `str_replace` :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T00:53:39.120",
"Id": "1391",
"Score": "0",
"body": "This also didn't set the date on the client as the preivous code had done. I ended up using something like this except I replaced the javascript with http://pastebin.com/MmFcrbHu"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T01:03:47.050",
"Id": "1392",
"Score": "0",
"body": "It should have print the date. The issue was a type in my partial _list_item.phtml. Just replace the `echo $message` with `echo $date`. My mistake. I've update the code above."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T01:49:03.443",
"Id": "1394",
"Score": "0",
"body": "@zxyfer: Haha -- didn't even notice that (I didn't copy/paste this exactly...)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T13:00:02.533",
"Id": "726",
"ParentId": "492",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "726",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T20:48:27.087",
"Id": "492",
"Score": "22",
"Tags": [
"php",
"javascript"
],
"Title": "Dynamically generating a list of events"
} | 492 |
<p>I've been writing a function:</p>
<pre><code>float turnToRequestedHeading(float initialHeading, float requiredHeading, float turnRate)
</code></pre>
<p>I keep thinking there must be a clever way to do it, but it escapes me.</p>
<p>All values are in Radians, Headings between -<span class="math-container">\$\pi\$</span> and +<span class="math-container">\$\pi\$</span>, and turnRate between -0.5 and +0.5.</p>
<p>If the requiredHeading is less than the turnRate away from the initialHeading then it should return requiredHeading</p>
<p>Otherwise it should return initialHeading + or - turnRate, whichever gets closer to the requiredHeading.</p>
<p>The following code is what I have so far, which I'm quite happy with, but is there anything I've missed, or is there an easier way to do this?</p>
<pre><code>// return the new heading based on the required heading and turn rate
private float turnToRequestedHeading(float initialHeading, float requiredHeading, float turnRate) {
//DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Started");
float resultantHeading;
int direction = 1; // clockwise, set anti-clockwise (-1) later if required
if ((Math.signum(initialHeading) == Math.signum(requiredHeading)) || (Math.signum(initialHeading) == 0) || (Math.signum(requiredHeading) == 0)) {
// both headings are on the same side of 0 so turn will not pass through the +/- Pi discontinuity
if (Math.max(Math.abs(requiredHeading) - Math.abs(initialHeading), Math.abs(initialHeading) - Math.abs(requiredHeading)) < turnRate) {
// angle to be updated is less than turn rate
resultantHeading= requiredHeading;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path1");
} else {
// angle to be updated is greater than turn rate
if (initialHeading < requiredHeading) {
// turn clockwise
resultantHeading = initialHeading + turnRate;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path2");
} else {
// turn anti-clockwise
resultantHeading = initialHeading - turnRate;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path3");
}
}
} else {
// headings are on different sides of 0 so turn may pass through the +/- Pi discontinuity
if (Math.abs(initialHeading) + Math.abs(requiredHeading) < turnRate) {
// angle to be updated is less than turn rate (around 0)
resultantHeading= requiredHeading;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path4");
} else if ((180 - Math.abs(initialHeading)) + (180 - Math.abs(requiredHeading)) < turnRate) {
// angle to be updated is less than turn rate (around +/- Pi)
resultantHeading= requiredHeading;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path5");
} else {
// angle to be updated is greater than turn rate so calculate direction (previously assumed to be 1)
if (initialHeading < 0) {
if (requiredHeading > PIf + initialHeading) direction = -1;
} else {
if (requiredHeading > -PIf + initialHeading) direction = -1;
}
if ((direction == 1) && (initialHeading > PIf - turnRate)) {
// angle includes the +/- Pi discontinuity, clockwise
resultantHeading = -TWO_PIf + turnRate + initialHeading;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path6 snap="+(resultantHeading > requiredHeading));
if (resultantHeading > requiredHeading) resultantHeading = requiredHeading;
} else if ((direction == -1) && (initialHeading < -PIf + turnRate)) {
// angle includes the +/- Pi discontinuity, anti-clockwise
resultantHeading = TWO_PIf - turnRate + initialHeading;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path7 snap="+(resultantHeading < requiredHeading));
if (resultantHeading < requiredHeading) resultantHeading = requiredHeading;
} else {
// angle does not includes the +/- Pi discontinuity
resultantHeading = initialHeading + direction * turnRate;
/*DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading(initialHeading="+initialHeading+", requiredHeading="+requiredHeading+", turnRate="+turnRate+"): Path8 direction="+direction);
}
}
}
// ensure -PI <= result <= PI
if (resultantHeading < -PIf) resultantHeading = resultantHeading + TWO_PIf;
if (resultantHeading >= PIf) resultantHeading = resultantHeading - TWO_PIf;
//DEBUG*/Log.d(this.getClass().getName(), "turnToRequestedHeading: Returning "+resultantHeading);
return resultantHeading;
}
</code></pre>
<p>I have written some testing code to check it out as there were quite a few different 'special cases'</p>
<pre><code>private void turnToRequestedHeadingTest(float initialHeading, float requiredHeading, float turnRate, float expectedResult) {
if (Math.round(turnToRequestedHeading(initialHeading*PIf/180, requiredHeading*PIf/180, turnRate*PIf/180)*180/PIf) != expectedResult) {
/*DEBUG*/Log.i(this.getClass().getName(), "test(initial="+initialHeading+", required="+requiredHeading+", rate="+turnRate+") Expected "+expectedResult+", Returns "+(Math.round(turnToRequestedHeading(initialHeading*PIf/180, requiredHeading*PIf/180, turnRate*PIf/180)*180/PIf)));
}
}
/*DEBUG*/Log.i(this.getClass().getName(), "turnToRequestedHeading tests:");
turnToRequestedHeadingTest( 0, 0, 0, 0);
turnToRequestedHeadingTest( 0, 0, 25, 0);
turnToRequestedHeadingTest( 10, 15, 25, 15);
turnToRequestedHeadingTest( 20, 55, 25, 45);
turnToRequestedHeadingTest( 85, 95, 25, 95);
turnToRequestedHeadingTest( 150,-170, 25, 175);
turnToRequestedHeadingTest( 170, 177, 25, 177);
turnToRequestedHeadingTest( 170,-175, 25,-175);
turnToRequestedHeadingTest( 175,-100, 25,-160);
turnToRequestedHeadingTest( 175, 0, 25, 150);
turnToRequestedHeadingTest( 180, 0, 25, 155);
turnToRequestedHeadingTest(-170,-100, 25,-145);
turnToRequestedHeadingTest(-100, -80, 25, -80);
turnToRequestedHeadingTest( -30, -15, 25, -15);
turnToRequestedHeadingTest( -30, 15, 25, -5);
turnToRequestedHeadingTest( -20, -5, 25, -5);
turnToRequestedHeadingTest( -20, 5, 25, 5);
turnToRequestedHeadingTest( -20, 15, 25, 5);
turnToRequestedHeadingTest( 10, 180, 25, 35);
turnToRequestedHeadingTest( 10,-160, 25, -15);
turnToRequestedHeadingTest( 170, 0, 25, 145);
turnToRequestedHeadingTest( 170, -15, 25,-165);
turnToRequestedHeadingTest(-170, 5, 25,-145);
turnToRequestedHeadingTest( -10, 160, 25, 15);
turnToRequestedHeadingTest( -10,-150, 25, -35);
turnToRequestedHeadingTest( 10,-170, 25, -15);
turnToRequestedHeadingTest( 0, 180, 25, 25);
turnToRequestedHeadingTest( -10, -15, 25, -15);
turnToRequestedHeadingTest( -20, -55, 25, -45);
turnToRequestedHeadingTest( -85, -95, 25, -95);
turnToRequestedHeadingTest(-150, 170, 25,-175);
turnToRequestedHeadingTest(-170,-177, 25,-177);
turnToRequestedHeadingTest(-170, 175, 25, 175);
turnToRequestedHeadingTest(-175, 100, 25, 160);
turnToRequestedHeadingTest(-175, 0, 25,-150);
turnToRequestedHeadingTest( 170, 100, 25, 145);
turnToRequestedHeadingTest( 100, 80, 25, 80);
turnToRequestedHeadingTest( 30, 15, 25, 15);
turnToRequestedHeadingTest( 30, -15, 25, 5);
turnToRequestedHeadingTest( 20, 5, 25, 5);
turnToRequestedHeadingTest( 20, -5, 25, -5);
turnToRequestedHeadingTest( 20, -15, 25, -5);
turnToRequestedHeadingTest( -10,-180, 25, -35);
turnToRequestedHeadingTest( -10, 160, 25, 15);
turnToRequestedHeadingTest(-170, 0, 25,-145);
turnToRequestedHeadingTest(-170, 15, 25, 165);
turnToRequestedHeadingTest( 170, -5, 25, 145);
turnToRequestedHeadingTest( 10,-160, 25, -15);
turnToRequestedHeadingTest( 10, 150, 25, 35);
turnToRequestedHeadingTest( -10, 170, 25, 15);
// More tests
turnToRequestedHeadingTest( 0, 15, 25, 15);
turnToRequestedHeadingTest( 0, 60, 25, 25);
turnToRequestedHeadingTest( 0, -15, 25, -15);
turnToRequestedHeadingTest( 0, -60, 25, -25);
turnToRequestedHeadingTest( 180, 165, 25, 165);
turnToRequestedHeadingTest( 180, 100, 25, 155);
turnToRequestedHeadingTest( 180,-165, 25,-165);
turnToRequestedHeadingTest( 180,-100, 25,-155);
turnToRequestedHeadingTest(-180, 165, 25, 165);
turnToRequestedHeadingTest(-180, 100, 25, 155);
turnToRequestedHeadingTest(-180,-165, 25,-165);
turnToRequestedHeadingTest(-180,-100, 25,-155);
turnToRequestedHeadingTest( 25, 0, 25, 0);
turnToRequestedHeadingTest( 25, -25, 25, 0);
turnToRequestedHeadingTest( -25, 0, 25, 0);
turnToRequestedHeadingTest( -25, 25, 25, 0);
turnToRequestedHeadingTest( 155, 180, 25, 180);
turnToRequestedHeadingTest( 155,-155, 25, 180);
turnToRequestedHeadingTest(-155, 180, 25,-180);
turnToRequestedHeadingTest(-155, 155, 25,-180);
turnToRequestedHeadingTest( 155,-180, 25,-180);
turnToRequestedHeadingTest(-155,-180, 25,-180);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:22:05.207",
"Id": "1005",
"Score": "0",
"body": "(1) You can use a code coverage tool to find out if your tests leave any branch of code untested. Then you can add more tests to cover them. This will help cover all the \"special cases\". (2) Your code contains some constants in degrees (like 360). Are you sure it is handling Radian values correctly?"
}
] | [
{
"body": "<p>Just winging it off the top of my head, pseudocode follows:\nEDIT - correcting some math\nEDIT2 - have some javascript :)</p>\n\n<pre><code>function turnToRequestedHeadingTest(initial, requested, turnRate, newAngle)\n{\n var ang1 = (Math.PI/180.0) * initial;\n var ang2 = (Math.PI/180.0) * requested;\n var na = turnToRequestedHeading(ang1,ang2,turnRate);\n na = na * (180.0/Math.PI);\n if(Math.abs(na- newAngle) > Math.epsilon)\n throw \"Failed on:\" + initial + \"-\" + requested + \" \" + na;\n}\nfunction turnToRequestedHeading(ang1,ang2,turnRate)\n{\n if(ang1 == ang2) return ang1;\n\n // pretend there's a vector v1 pointed out from \n // the origin along initialHeading of length 1\n // v1 = <cos initial, sin initial>\n var v1= [Math.cos(ang1), Math.sin(ang1)];\n\n // pretend there's a vector v2 pointed out from \n // the origin along requiredHeading of length 1\n // v2 = <cos required, sin required>\n var v2= [Math.cos(ang2), Math.sin(ang2)];\n\n // angle between v1,v2 = acos(v1 dot v2)\n var dang = Math.acos(v1[0]*v2[0], v1[1]*v2[1]);\n dang = dang > Math.PI ? Math.PI * 2 - dang : dang;\n if(dang < turnRate) return ang2;\n\n // delta angle = acos(cos initial * cos required, sin initial * sin required);\n // resulting turn = Math.Min(turnRate, delta angle) * Math.sign(delta angle);\n var deltaTurn = (Math.min(turnRate, dang) * Math.sign(ang2-ang1)) + ang1;\n\n // return initial + resulting turn; \n return deltaTurn;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:44:41.350",
"Id": "863",
"Score": "0",
"body": "Cheers for that. I'm not in a position to test Javascript, but have you tested it using my test data? As this problem is trickier than it looks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T15:33:45.580",
"Id": "1014",
"Score": "0",
"body": "Yeah, I ran your exact test cases through that first function \"turnToRequestedHeadingTest\", and nothing was thrown, so it *should* work. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:47:18.733",
"Id": "495",
"ParentId": "493",
"Score": "1"
}
},
{
"body": "<p>Just rough idea. Not tested.</p>\n\n<pre><code>// TODO: throw exception if turnRate is negative\n// TODO: throw exception if abs(turnRate) exceeds some maximum value.\nconst float FUL_CIRCLE = 360; // or (2 * Math.PI) for radian\nfloat difference = Math.IEEEremainder(requiredHeading - initialHaeding, FUL_CIRCLE);\nfloat absTurnRate = Math.abs(turnRate);\nfloat headingChange = Math.max(-absTurnRate, Math.min(+absTurnRete, difference));\nfloat resultantHeeding = Math.IEEEremainder(initialHeading + headingChange, FUL_CIRCLE);\nreturn resultantHeeding;\n</code></pre>\n\n<p>if your platform does not provide Math.IEEEremainder, use the following:</p>\n\n<pre><code>double GetRemainder(double dividend, double divisor) {\n return dividend - divisor * Math.round(dividend / divisor);\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>double GetRemainder(double dividend, double divisor) {\n return dividend - divisor * Math.floor(dividend / divisor + 0.5);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:12:14.950",
"Id": "581",
"ParentId": "493",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-01-31T20:55:47.097",
"Id": "493",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "Function to turn to requested bearing"
} | 493 |
<p>I'm looking for the most commonly used style for writing the <code>delete_item()</code> function of a singly linked list, that find a matching item and deletes it. Is what I have the 'typical' or 'normal' solution? Are there more elegant ones?</p>
<p>What seems inelegant to me about my solution below, although I don't know a better way to express it, is that the code needs to check the first record individually (i.e. a special case), then as it goes through the iteration, it's not checking <code>iter</code>, it's checking <code>iter->next</code>, ahead of the iterator's present location, because in a singly linked list you can't go backwards.</p>
<p>So, is there a cleaner way to write the <code>delete_item()</code> function?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
struct node *head;
struct node *create_item(int x);
void print_list();
void delete_item(int x);
int main(int argc, int argv) {
struct node *n;
int i;
// initialise a linked list with a few items
head = create_item(1);
n = head;
for (i = 2; i < 10; i++) {
n->next = create_item(i);
n = n->next;
}
// before
print_list();
// delete 7.
delete_item(7);
// after
print_list();
// lets delete all odd numbers for effect.
delete_item(1);
delete_item(3);
delete_item(5);
delete_item(9);
print_list();
}
struct node *create_item(int x) {
struct node *new;
new = (struct node *) malloc (sizeof(struct node));
new->x = x;
return new;
}
void print_list() {
struct node *iter;
iter = head;
while (iter != NULL) {
printf("num: %i\n", iter->x);
iter = iter->next;
}
}
//We're looking for the best way to right this.
//This is _my_ standard solution to the problem.
// (that is, to test the first element explicitly
// the use current->next != NULL to be one behind
// the search).
//I wondered what other people's is or if there
//is a convention?
void delete_item(int x) {
struct node *iter;
iter = head;
if (iter == NULL) {
printf("not found\n");
return;
}
if (iter->x == x) {
printf("found in first element: %i\n", x);
head = head->next;
return;
}
while (iter->next != NULL) {
if (iter->next->x == x) {
printf("deleting element: %i\n", x);
iter->next = iter->next->next;
return;
}
iter = iter->next;
}
printf("not found\n");
}
</code></pre>
<p>This is a complete example that can be compiled and tested. The output:</p>
<pre><code>23:28: ~$ gcc -o ll linked_list.c
23:28: ~$ ./ll
num: 1
num: 2
num: 3
num: 4
num: 5
num: 6
num: 7
num: 8
num: 9
deleting element: 7
num: 1
num: 2
num: 3
num: 4
num: 5
num: 6
num: 8
num: 9
found in first element: 1
deleting element: 3
deleting element: 5
deleting element: 9
num: 2
num: 4
num: 6
num: 8
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T23:47:22.593",
"Id": "832",
"Score": "1",
"body": "Forgetting for a moment it should invoke free() somewhere."
}
] | [
{
"body": "<p>It's been ages since I've done C++, but here are my observations:</p>\n\n<p>First off, you're using global variables, which is ill-advised. I'm not sure if C supports member functions, but if not, you should be using parameter passing, e.g. <code>delete_item(node* head, int x)</code> and so on.</p>\n\n<pre><code>if (iter == NULL) {\n printf(\"not found\\n\");\n return;\n}\n</code></pre>\n\n<p>iter is set to the head of the linked list, and if the linked list doesn't yet exist, you reply that the item is <code>\"not found\\n\"</code>. I would change this to <code>\"Linked list is empty.\\n\"</code></p>\n\n<pre><code>if (iter->x == x) {\n printf(\"found in first element: %i\\n\", x);\n return;\n}\n</code></pre>\n\n<p>This doesn't seem to work in the sense that it does not actually delete the element. If you want this item deleted -- which I'm assuming you do, given the name of the function -- then you should add this line: <code>head = head->next;</code> (You'll need to pass the head parameter \"by reference\" to make sure that this change will propagate outside the code of the <code>delete_item</code> function. Normally, if the parameter being passed wasn't a pointer, this would be done by passing the pointer. <code>head</code> is a <code>node*</code>, however, and I have forgotten how to pass a pointer by reference... I think it would either be <code>node*& head</code> or <code>node** head</code> ... sorry, but you'll have to figure that one out! :) ) Alternatively, you could have delete_item return a <code>node *</code>, and at the end of the function, you could return the first non-matching entry, and this would be called by <code>head=delete_item(head, x)</code>. It's probably slightly frowned upon to do it that way, but it would be an easy way out.</p>\n\n<p>At any rate, once you get that accomplished, it will delete the current head, and the new head will be the second element, if one exists... else it will be set to <code>NULL</code>.</p>\n\n<pre><code>while (iter->next != NULL) {\n if (iter->next->x == x) {\n printf(\"deleting element: %i\\n\", x);\n iter->next = iter->next->next;\n return;\n }\n\n iter = iter->next;\n}\n</code></pre>\n\n<p>One problem I see is that you have to decide if you want to delete duplicate entries. For example, if <code>7</code> appears twice in the linked list, do you want to delete both <code>7</code>s, or just one? If you want to delete both, you need to traverse the entire linked list by removing the <code>return</code> statements in the <code>while</code> loop and the initial check of the head node. This will create a problem as the program proceeds on to the final, \"not found\" statement, but that can be solved with an <code>if</code> statement:</p>\n\n<pre><code>if (!entryfound) printf(\"not found\\n\");\n</code></pre>\n\n<p><code>entryfound</code> would have to be declared to be <code>0</code>, and set to <code>1</code> if a match was found in the <code>while</code> loop. Alternatively, you could do <code>entryfound++</code> in the event of a match and change this last line:</p>\n\n<pre><code>if (entryfound) { printf(\"%i matches found and deleted.\\n\", entryfound); }\n else { printf(\"No matches found.\\n\"); }\n</code></pre>\n\n<p>After the changes, this is what your code should look like:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nstruct node {\n int x;\n struct node *next;\n};\n\nstruct node *create_item(int x);\nvoid print_list(node *head);\nvoid delete_item(node *&head, int x);\n\nint main(int argc, int argv) {\n struct node *head, *tail;\n\n // initialise a linked list with a few items\n head = create_item(1);\n tail = head;\n\n for (int i = 2; i < 10; i++) {\n tail->next = create_item(i);\n tail = tail->next;\n }\n\n // before\n print_list(head);\n\n // delete 7.\n delete_item(head, 7);\n\n // after\n print_list(head);\n\n // lets delete all odd numbers for effect.\n delete_item(head, 1);\n delete_item(head, 3);\n delete_item(head, 5);\n delete_item(head, 9);\n\n print_list(head);\n}\n\nstruct node *create_item(int x) {\n struct node *new;\n\n new = (struct node *) malloc (sizeof(struct node));\n new->x = x;\n return new;\n}\n\nvoid print_list(node *iter) {\n int i=0;\n\n if (iter==NULL} { printf(\"Linked list is empty.\")); }\n else {\n while (iter != NULL) {\n printf(\"Index: %i, Value=%i\\n\", i, iter->x);\n iter = iter->next;\n }\n }\n}\n\n//We're looking for the best way to right this.\n//This is _my_ standard solution to the problem.\n// (that is, to test the first element explicitly\n// the use current->next != NULL to be one behind\n// the search).\n//I wondered what other people's is or if there\n//is a convention?\n\nvoid delete_item(node *&head, int x) {\n int i=0;\n node* iter=head; // Head might have to be dereferenced here... I forget!\n\n if (iter==NULL) {\n printf(\"Linked list is empty.\\n\");\n return;\n }\n\n if (iter->x == x) {\n printf(\"Deleting Item. Index: %i, Value=%i\\n\", i, x);\n head = head->next;\n entryfound++;\n }\n\n while (iter->next != NULL) {\n i++;\n if (iter->next->x == x) {\n printf(Deleting Item. Index: %i, Value=%i\\n\", i, x);\n iter->next = iter->next->next;\n entryfound++;\n }\n\n iter = iter->next;\n }\n\n\n\n if (entryfound) { printf(\"%i matches found and deleted.\\n\", entryfound); }\n else { printf(\"No matches found.\\n\"); }\n\n}\n</code></pre>\n\n<p>As others have stated, you need to be deallocating the memory. Your program has what is known as a memory leak. The old \"deleted\" nodes are not actually deleted, they are simply removed from the chain of pointers. I'll leave it up to you to deallocate them in the event of a match.</p>\n\n<p>Again, it's been a long time since I've done C++, but that's my take. Sorry for any debugging that you might have to do in that code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T01:42:48.770",
"Id": "836",
"Score": "6",
"body": "This is C, not C++ :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T02:14:41.893",
"Id": "839",
"Score": "0",
"body": "Yep! I realize[d] that, but with that said, I don't know all of the differences between C and C++ (like I said, it's been a while... ~8 years.) The code that I posted probably won't work if you just copy & pasted it, but most of the changes should work, and anything left over should be easy to fix. The code is a big jump from where his code is now to \"where it needs to be.\" It's not perfect, but it's the best I could do. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T06:00:01.947",
"Id": "840",
"Score": "0",
"body": "The code is all C. Your text however says C++ :) If you want to test code easily there's always `codepad.org`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T00:11:00.907",
"Id": "497",
"ParentId": "496",
"Score": "4"
}
},
{
"body": "<h3>General Comments:</h3>\n<p>Why do your list handling functions not take a list as a parameter?<br />\nAs a result your application can only have one list.</p>\n<h3>Comments on Delete:</h3>\n<p>You are leaking the list item when you delete it.</p>\n<p>Since the <code>create_item()</code> is calling <code>malloc()</code> I would expect the <code>delete_item()</code> to call <code>free()</code>.</p>\n<p>I would split the <code>delete_item()</code> into two parts. The first part that deals with the head as a special case and the second part that deals with removing elements from the list (and <code>free()</code>ing them).</p>\n<pre><code>void delete_item(struct node** list, int x)\n{\n if ((list == NULL) || ((*list) == NULL))\n {\n printf("not found\\n");\n return;\n }\n \n (*list) = delete_item_from_list(*list);\n}\n\nstruct node* delete_item_from_list(struct node* head)\n{\n struct node* iter = head;\n struct node* last = NULL;\n\n while (iter != NULL)\n {\n if (iter->x == x)\n {\n break;\n }\n\n last = iter;\n iter = iter->next;\n }\n\n if (iter == NULL)\n {\n printf("not found\\n");\n }\n else if (last == NULL)\n {\n printf("found in first element: %i\\n", x);\n head = iter->next;\n }\n else\n {\n printf("deleting element: %i\\n", x);\n last->next = iter->next;\n }\n \n free(iter);\n return head;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T13:53:44.410",
"Id": "1073",
"Score": "0",
"body": "The reason I use a single global list was purely because it was a simplistic sample code block. This isn't to do with writing some generic linked list library or anything."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T00:32:57.170",
"Id": "498",
"ParentId": "496",
"Score": "5"
}
},
{
"body": "<p>Deleting an item from a singly-linked list requires finding the previous item. There are two approaches one can use to deal with this:</p>\n\n<ol>\n<li>When deleting an item, search through the list to find the previous item, then do the unlink.\n<li>Have a \"deleted\" flag for each item. When traversing the list for some other reason, check the \"deleted\" flag on each node. If a \"deleted\" node is encountered, unlink it from the previously-visited node.\n</ol>\n\n<p>Note that in a garbage-collected system, it's possible to add items to the start of the list, or perform the #2 style of deletion, in a lock-free thread-safe manner. Nodes which are deleted may get unlinked in one thread and accidentally relinked in another, but the delete flag will cause the node to be unlinked again on the next pass. In a multi-threaded system requiring explicit deallocation, such an unlink and relink sequence could be disastrous, since a node could be unlinked, deallocated, and relinked; locks would thus be necessary to avoid problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T01:40:49.503",
"Id": "834",
"Score": "0",
"body": "Not true. You have to scan the whole list in order to find the item you want to delete in any case, so there's no need to have to \"search for the item before you want to delete\" -- you just remember that as you're walking the list. And it's perfectly possible to put items at the front of the list in a non-garbage collected system."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:35:56.620",
"Id": "868",
"Score": "0",
"body": "@Billy: Searching for an item immediately prior to deletion is a reasonably common scenario, and you're correct that in that case one will have the previous-item pointer. The scenario is not universal, however. The last time I used a linked list was for an \"thread-safe lock-free arbitrary-order bag\" with O(1) insertion and removal. The creator of each node kept a link to the node itself, but would not know if a node was added immediately before its node. So in that application the only time the list had to be traversed was to enumerate it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:40:45.070",
"Id": "869",
"Score": "0",
"body": "@Billy: As for garbage collection, that's an issue if one is trying to write thread-safe lock-free code which can function correctly even if a thread is asynchronously aborted. In a non-GC lock-free system, it's almost impossible to know for certain whether anyone might hold a reference to a node, and thus whether the node can be safely deleted."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:33:38.800",
"Id": "885",
"Score": "0",
"body": "@supercat: But to remove the item from the list, you must first find the item to remove (the OP's interface specifies the value of the entry to remove, not a pointer to the node itself) which will already tell you the previous node."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:34:22.997",
"Id": "886",
"Score": "0",
"body": "As for thread-safe/lock-free, first of all that's a completely difference scenario which has nothing to do with the OP's question, second if you're using a GC in that way the code is no longer lock-free (the GC is not lock free), third it's not even possible to handle that scenario with a GC in a thread-safe/lock-free way (i.e. if an element is removed from the list while someone is enumerating it)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T05:27:34.077",
"Id": "905",
"Score": "0",
"body": "@Billy: It's clear the scenario when I was deleting something is different from the original poster's. As for thread safety in a GC system, if an element is deleted during enumeration, it will either be included in the enumeration or not; what's required is that items which are in the bag throughout enumeration be enumerated. It's generally to assume that the GC won't suffer from async abort or priority inversion than to assume that no other threads will. Anyway, I think we're drifting off-topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T12:47:16.593",
"Id": "74564",
"Score": "0",
"body": "@supercat: I'd suggest calling this \"lazy freeing\", so that people don't confuse it with generic garbage collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T23:39:40.867",
"Id": "74645",
"Score": "0",
"body": "@Brendan: Whether the node is immediately physically removed from the linked list when a \"delete\" request is issued is an implementation detail, provided that the number of nodes physically in the list can never exceed a bounded multiple of the number of nodes which are supposed to be in the list. The deletion may be \"lazy\", but in many cases the application shouldn't care, since the fact that the \"deleted\" node was still linked would not be externally visible."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T00:41:26.403",
"Id": "499",
"ParentId": "496",
"Score": "-1"
}
},
{
"body": "<p>If you don't mind recursion (although C programmers generally DO mind), then you can do:</p>\n\n<pre><code>node* delete_item(node* curr, int x) {\n node* next;\n if (curr == NULL) { // Found the tail\n printf(\"not found\\n\");\n return NULL;\n } else if (curr->x == x) { // Found one to delete\n next = curr->next;\n free(curr);\n return next;\n } else { // Just keep going\n curr->next = delete_item(curr->next, x);\n return curr;\n }\n}\n</code></pre>\n\n<p>then, in main, you should do</p>\n\n<pre><code>head = delete_item(head, 7);\n</code></pre>\n\n<p>This uses the C stack to hold the \"backwards look\" in the list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T23:34:52.573",
"Id": "1052",
"Score": "3",
"body": "As a C programmer, I love recursion as a technique (e.g. traversing trees, or printing evil numbers (http://www.bobhobbs.com/files/kr_lovecraft.html :-) )), but not when it's applied inappropriately (e.g. for something like this in the case where the lists can be large, or the machine has tiny stack)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-23T19:39:54.997",
"Id": "193223",
"Score": "0",
"body": "@MattCurtis it's not applied inappropriately. If you have a linked list so big that traversing it recursively overflows the stack, then you are having much bigger problems. This deletion is much more elegant than one where one has to keep track of the previous item explicitly and treat the head of the list specially."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-20T20:55:22.800",
"Id": "241095",
"Score": "1",
"body": "Am I missing something? How could this possibly be more efficient than simply traversing the list in a loop until you find the node just before the target? Also, this looks like it's re-writing the \"next\" pointer of every node in the list whether it needs it or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-23T21:03:21.230",
"Id": "266711",
"Score": "0",
"body": "They asked for elegant, not efficient."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T04:40:19.223",
"Id": "508",
"ParentId": "496",
"Score": "5"
}
},
{
"body": "<p>The neatest way to deal with this is to use what I was taught as the \"2 pointer trick\" (thank you Charles Lindsay all those years ago):</p>\n\n<p>Instead of holding a pointer to the record you hold a pointer to the pointer that points to it - that is you use a double indirection. This enables you to both modify the pointer to the record and to modify the record without keeping track of the previous node.</p>\n\n<p>One of the nice things about this approach is that you don't need to special case dealing with the first node.</p>\n\n<p>An untested sketch using this idea for delete_item (in C++) looks like:</p>\n\n<pre><code>void delete_item(node** head, int i) {\n for (node** current = head; *current; current = &(*current)->next) {\n if ((*current)->x == i) {\n node* next = (*current)->next;\n delete *current;\n *current = next;\n break;\n }\n }\n}\n</code></pre>\n\n<p>This loop will break after the first entry it finds, but if you remove the \"break\" then it will remove all entries that match.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T01:11:38.240",
"Id": "539",
"ParentId": "496",
"Score": "18"
}
},
{
"body": "<p>My favorite technique would look something like this (copious amounts of comments added for illustrative purposes...):</p>\n\n<pre><code>void remove_item(struct node **head, int x)\n{\n struct node *n = *head,\n *prev = NULL;\n\n /* Loop through all the nodes... */\n while (n)\n {\n /* Store the next pointer, since we might call free() on n. */\n struct node *next = n->next;\n\n /* Is this a node we're interested in? */\n if (n->x == x)\n {\n /* Free the node... */\n free(n);\n\n /* Update the link... */\n if (prev)\n {\n /* Link the previous node to the next one. */\n prev->next = next;\n }\n else\n {\n /* No previous node. Update the head of the list. */\n *head = next;\n }\n }\n else\n {\n /* We didn't free this node; track that we visited it for the next iteration. */\n prev = n;\n }\n\n n = next;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T04:34:09.920",
"Id": "2224",
"ParentId": "496",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "508",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T23:44:49.807",
"Id": "496",
"Score": "13",
"Tags": [
"c",
"linked-list"
],
"Title": "C function to find and delete a node from a singly linked list"
} | 496 |
<p>This function in my <code>Profile</code> model receive a hash from a search form and should filter the table depending on those values. I guess there is something like a pattern for such a standard behavior, right now I ended up with this (unfortunately I had to reproduce the code here, so it might not work for some reasons, but you get the idea).</p>
<p>Just a note: we're storing in the model some strings containing multiple data, each of these fields should be a one-to-many relationship (db normality violation). I give an example: <code>country_preferences</code> is a string filled up by an html <code>select :multiple => true</code>. In the string I then find values like: <code>["Australia", "China", "United Kingdom"]</code>.</p>
<pre><code> def search opts # This default doesn't work the way I would like = {:user_type => :family}
#TODO: default opts value in method sign if possible
opts[:user_type] ||= :family
# initial criteria
fields= "user_type= ?"
values= [opts[:user_type]]
# each field filters the list in one of these three ways
staight_fields = [ :country, :first_name, :last_name, :nationality ]
like_fields = [:country_preferences, :keyword, :languages ]
bool_fields = [:driver, :housework, :children ]
# cicle the options and build the query
opts.each do |k, v|
if straight_fields.include? k
fields += " AND #{k} = ?"
values += v
elsif like_fields.include? k
fields += " AND #{k} like %?%"
values += v
elsif bool_fields.include? k
fields += " AND #{k} = ?"
values += v == 'true'
else
logger.warn "opts #{k} with value #{v} ignored from search"
end
end
# execute the query and return the result
self.registered.actives.where([fields] + values)
end
</code></pre>
<p>I think I can use more <code>scope</code> but how can I combine them together? In general, how can I make this code much better?</p>
<p>The boss, when introducing the project, said one-to-many relationships for that kind of fields would be a pain in the back. What do you think about this pragmatic solution?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T18:40:24.187",
"Id": "879",
"Score": "1",
"body": "Does the code you posted in your edit actually work? It seems like you're missing `profiles =` at the beginning of every line after the first and a final `profiles` at the end of the method."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T23:21:54.470",
"Id": "1383",
"Score": "0",
"body": "Good point! - I've already corrected my code and I'm not going to refactor, but that behavior (getting rid of all the assignment) can be achieved with a **dynamic delegator** explained by Ryan Bates http://railscasts.com/episodes/212-refactoring-dynamic-delegator"
}
] | [
{
"body": "<p>Have you looked into using a pre existing gem for this? I found one called <a href=\"https://github.com/plataformatec/has_scope\" rel=\"noreferrer\">has_scope</a> that seems like it might do exactly what you're trying to refactor. You would need to add a scope for each of your filters and then add some <code>has_scope</code> calls in your controller.</p>\n\n<p>Here's a few examples. I'm not as familiar with Rails 3 scopes as I am with 2, so the code likely won't work as is.</p>\n\n<p>Model:</p>\n\n<pre><code>class Profile < ActiveRecord::Base\n scope :country, lambda {|country| where(:country => country) }\n scope :keyword, lambda {|keyword| where([\"keyword LIKE :term\", {:term => \"%#{keyword}%\"}]) }\n scope :driver, where{:driver => true)\nend\n</code></pre>\n\n<p>Controller:</p>\n\n<pre><code>class ProfileController < ApplicationController\n has_scope :country\n has_scope :keyword\n has_scope :driver, :type => :boolean\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T09:24:58.063",
"Id": "843",
"Score": "0",
"body": "this plugin looks easy tiny and tested, I would avoid to install an external plugin to substitute a single function used once, but when I have some time I'm going to dive in the code, there should be something to learn, thanks"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T09:17:55.000",
"Id": "912",
"Score": "0",
"body": "thanks a lot, that was it, but you don't need to declare scopes like country or driver, as you can see in the question edit you have by default scoped_by_driver(true) that works the same."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T13:12:12.990",
"Id": "925",
"Score": "0",
"body": "I didn't even know about the scoped_by_* methods, great tip!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T01:15:52.663",
"Id": "501",
"ParentId": "500",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "501",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T00:46:02.727",
"Id": "500",
"Score": "8",
"Tags": [
"ruby-on-rails",
"ruby"
],
"Title": "Filtering (search) a model with multiple params in hash"
} | 500 |
<p>A little background first. I've been working on a fairly large Rails application which quickly grew into a breeding ground for "smelly" code. One antipattern we were using a lot was storing objects in an STI lookup table and having lots of scattered logic based on the name of the object.</p>
<p>Here's a dumbed down example of what we had:</p>
<pre><code>class Lookup < ActiveRecord::Base
end
class AlarmStatus < Lookup
has_many :alarm_logs
end
class AlarmLog < ActiveRecord::Base
belongs_to :alarm_status
end
</code></pre>
<p>Then all over our application we would do things like:</p>
<pre><code>case @alarm_log.alarm_status.name
when "active"
# Do something
when "verified"
# Do something
when "inactive"
# Do something
end
</code></pre>
<p>This is obviously bad for a lot of reasons, but let's just say it was everywhere. After a few months of this, a consultant came along and pointed out our "code smell" and made some suggestions on how to refactor, which included a Ruby implementation of <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html" rel="nofollow noreferrer">Java's Enum class</a>. </p>
<p>We ended up using this frequently in our app, and have extracted into a ruby gem called <a href="https://github.com/beerlington/classy_enum" rel="nofollow noreferrer">classy_enum</a>. The premise of classy_enum is that you get the power of OOP mixed with the strictness of an enumerated type, which is pretty much what we were trying to mimic with our STI Lookup model.</p>
<p>Example of defining an enum:</p>
<pre><code>class Priority < ClassyEnum::Base
enum_classes :low, :medium, :high
def send_email?
false
end
end
class PriorityHigh < Priority
def send_email?
true
end
end
</code></pre>
<p>The gem's <a href="https://github.com/beerlington/classy_enum/blob/master/README.md" rel="nofollow noreferrer">README</a> has some other usage examples, including how to integrate it with a Rails project.</p>
<p>I may be asking for a lot here, but I would love some feedback from anyone willing to give it. It seems like a really cool solution to our problem and I can't imagine we're the only ones who have attempted to solve this before. Here's a list of questions that would be really useful for us:</p>
<ul>
<li>Is this a common problem?</li>
<li>Does our solution make sense? Is there a better way to do it?</li>
<li>Is the documentation clear?</li>
<li>Would you use this in your application? Why or why not?</li>
<li>How could we improve it?</li>
<li>How is the code quality?</li>
</ul>
| [] | [
{
"body": "<p>Yes, it is a common problem. </p>\n\n<p>I think this is a great way to solve this, I wish I'd done it! Back in my java days I did use the typesafe enum pattern. In ruby I tend to create method objects after the third or so repetition in cases like this, but this is a much cleaner solution and I'm going to start using it for sure.</p>\n\n<p>I found the documentation really clear. I do intend to use it in my app, because it is an excellent way to formalize what I am doing when I create method objects and suggest to others that they replace their long nested if statements with method objects.</p>\n\n<p>The only think I think of at the moment that I might want to improve on it would be to have an option to create a back reference to the owning object for cases where double dispatch will further remove conditional logic. (or like for example where I had a a set of alarms that each should ring at some percentage of the owning objects master volume)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T14:47:41.703",
"Id": "1111",
"Score": "0",
"body": "Thanks Michael, I appreciate the feedback. I'm not sure I follow your suggestion about creating a back reference. Would it be possible for you to provide an example of how you'd want to use it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T11:39:17.400",
"Id": "625",
"ParentId": "503",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T02:20:22.557",
"Id": "503",
"Score": "8",
"Tags": [
"ruby",
"ruby-on-rails",
"enum",
"lookup"
],
"Title": "RubyGem for Enums"
} | 503 |
<p>I have a class whose purpose is to display a comment. I'd like to be able to instantiate it by passing a <code>Comment</code> object if I happen to have it available, or just the values if that's what I have available at the time. Unfortunately PHP doesn't allow overloaded constructors, so here's the workaround I came up with.</p>
<pre><code>class CommentPanel extends Panel {
//Private Constructor, called only from MakeFrom methods
private function CommentPanel($text, $userName, $timestamp) {
parent::Panel(0, $top, System::Auto, System::Auto);
// Render comment
}
public static function MakeFromObject(Comment $comment) {
return new CommentPanel($comment->text, $comment->User->nickname, $comment->last_updated_ts);
}
public static function MakeFromValues($text, $userName, $timestamp) {
return new CommentPanel($text, $userName, $timestamp);
}
}
</code></pre>
<p>So here's the two methods for instantiating a <code>CommentPanel</code>:</p>
<pre><code>$cp = CommentPanel::MakeFromObject($comment);
// or...
$cp = CommentPanel::MakeFromValues($text, $user, $last_updated_ts);
// but not
$cp = new CommentPanel(); //Runtime error
</code></pre>
<p>I'm moderately satisfied, although it's not near as intuitive as an overloaded constructor. Any thoughts on improving this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T22:31:49.617",
"Id": "3537",
"Score": "0",
"body": "Partly covered by the migrated [Single array or many single argument to call a constructor with params](http://codereview.stackexchange.com/questions/2189/single-array-or-many-single-argument-to-call-a-constructor-with-params)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T22:35:35.777",
"Id": "62835",
"Score": "0",
"body": "As discussed in http://codereview.stackexchange.com/questions/2189/single-array-or-many-single-argument-to-call-a-constructor-with-params, you could use a constructor that takes an associative array."
}
] | [
{
"body": "<p>Given that php allows optional parameters and doesn't require type checking of parameters that are passed in, you can sort of \"fake\" an overloaded constructor.</p>\n\n<p>something like this:</p>\n\n<pre><code>class CommentPanel extends Panel {\n public function __construct($text_or_comment, $username=null, $timestamp=null) {\n if (is_string($text_or_comment) {\n $this->textConstructor($text_or_comment, $username, $timestamp);\n }\n else { // assume that it's a comment since it's not a string ... there are better ways to handle this though\n $this->commentConstructor($text_or_comment);\n }\n }\n\n private function textConstructor($text, username, $timestampe) { /* . . . */ }\n private function commentConstructor(Comment $comment) { /* . . . */ }\n}\n</code></pre>\n\n<p>This method will allow for a more consistent API and one that is perhaps more familiar to Java and C++ developers.</p>\n\n<p>Also, I'm not positive which version of PHP you're targeting, but I believe in the current version, uses __construct instead of the class name as the constructor. I'm not sure if this is preferred but the documentation does say that it checks for __construct first and then the class name style constructor, so I would guess that using __construct() instead of CommentPanel() would reduce runtime ever so slightly. I'm not 100% sure on that though, that's just my understanding. Please correct me if I'm wrong :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T07:55:06.763",
"Id": "841",
"Score": "5",
"body": "It is in fact preferred to use `__construct()` instead class name for constructor. The latter is deprecated, and can cause problems in name resolution when working with PHP 5.3 namespaces."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T06:24:10.867",
"Id": "509",
"ParentId": "504",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "509",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T02:57:13.353",
"Id": "504",
"Score": "7",
"Tags": [
"php",
"constructor"
],
"Title": "Workaround for overloaded constructor in PHP"
} | 504 |
<p>I intend this to be a general question on writing an effective set of test cases for a controller action.</p>
<p>I include the following ingredients:</p>
<ul>
<li><strong>Ruby on Rails</strong></li>
<li><strong>RSpec:</strong> A testing framework. I considered doing a vanilla Rails question, but I personally use RSpec, and I feel many other folks do too. The principles that come out of this discussion should be portable to other testing frameworks, though.</li>
<li><strong>Will Paginate:</strong> I include this to provide an example of code whose implementation is blackboxed to the controller. This is an extreme example of just using the model methods like <code>@programs = Program.all</code>. I chose to go this route to incorporate an additional factor for discussion, and to demonstrate that the same principles apply whether using external application code (e.g., model code) or an external plugin.</li>
</ul>
<p>There seems to be a lack, given my humble Google Fu, of style guides for RSpec testing at this level, so it is my hope that, on top of me improving my code, this can become a useful guide for my fellow travelers.</p>
<p>For example purposes, let's say I currently have in my controller the following:</p>
<pre><code>class ProgramssController < ApplicationController
def index
@programs = Program.paginate :page => params[:page], :per_page => params[:per_page] || 30
end
end
</code></pre>
<blockquote>
<p><strong>Sidebar:</strong> For those unfamiliar with <code>will_paginate</code>, it tacks onto a ActiveRecord Relation (<code>all</code>, <code>first</code>, <code>count</code>, <code>to_a</code> are other examples of such methods) and delivers a paginated result set of class <code>WillPaginate::Collection</code>, which <em>basically</em> behaves like an array with a few helpful member methods.</p>
</blockquote>
<p>What are the effective tests I should run in this situation? Using RSpec, this is what I've conceived at the moment:</p>
<pre><code>describe ProgramsController do
def mock_program(stubs={})
@mock_program ||= mock_unique_program(stubs)
end
def mock_unique_program(stubs={})
mock_model(Program).as_null_object.tap do |program|
program.stub(stubs) unless stubs.empty?
end
end
describe "GET index" do
it "assigns @programs" do
Program.stub(:paginate) { [mock_program] }
get :index
response.should be_success
assigns(:programs).should == [mock_program]
end
it "defaults to showing 30 results per page" do
Program.should_receive(:paginate).with(:page => nil, :per_page => 30) do
[mock_program]
end
get :index
response.should be_success
assigns(:programs).should == [mock_program]
end
it "passes on the page number to will_paginate" do
Program.should_receive(:paginate).with(:page => '3', :per_page => 30) do
[mock_program]
end
get :index, 'page' => '3'
response.should be_success
assigns(:programs).should == [mock_program]
end
it "passes on the per_page to will_paginate" do
Program.should_receive(:paginate).with(:page => nil, :per_page => '15') do
[mock_program]
end
get :index, 'per_page' => '15'
response.should be_success
assigns(:programs).should == [mock_program]
end
end
end
</code></pre>
<p>I wrote this with the following principles in mind:</p>
<ul>
<li><strong>Don't test non-controller code:</strong> I don't delve into the actual workings of <code>will_paginate</code> at all and abstract away from its results.</li>
<li><strong>Test all controller code:</strong> The controller does four things: assigns <code>@programs</code>, passes on the <code>page</code> parameter to the model, passes on the <code>per_page</code> parameter to the model, and defaults the <code>per_page</code> parameter to 30, and nothing else. Each of these things are tested.</li>
<li><strong>No false positives:</strong> If you take away the method body of <code>index</code>, all of the test will fail. </li>
<li><strong>Mock when possible:</strong> There are no database accesses (other ApplicationController logic notwithstanding)</li>
</ul>
<p>My concerns, and hence the reason I post it here:</p>
<ul>
<li><strong>Am I being too pedantic?</strong> I understand that TDD is rooted in rigorous testing. Indeed, if this controller acts as a part of a wider application, and say, it stopped passing on <code>page</code>, the resulting behaviour would be undesirable. Nevertheless, is it appropriate to test such elementary code with such rigor?</li>
<li><strong>Am I testing things I shouldn't be? Am I not testing things I should?</strong> It think I've done an okay job at this, if anything veering on the side of testing too much.</li>
<li><strong>Are the <code>will_paginate</code> mocks appropriate?</strong> You see, for instance, with the final three tests, I return an array containing only one program, whereas <code>will_paginate</code> is quite liable to return more. While actually delving this behaviour by adding, say 31 records, may (?) violate modular code and testing, I am a bit uneasy returning an unrealistic or restrictive mock result.</li>
<li><strong>Can the test code be simplified?</strong> This seems quite long to test one line of controller code. While I fully appreciate the awesomeness of TDD, this seems like it would bog me down. While writing these test cases were not too intensive on the brain and basically amounted to a fun vim drill, I feel that, all things considered, writing this set of tests may cost more time than it saves, even in the long run.</li>
<li><strong>Is this a good set of tests?</strong> A general question.</li>
</ul>
| [] | [
{
"body": "<p>You've coded by your principles pretty reasonably. </p>\n\n<p>My only real suggestion is to have just one assertion per test, including any <code>#should_receive</code> or <code>#should=</code> statements. The intention of most of your tests seems to be to test one single unit of functionality, so there is no need to repeat assertions, particularly when they are dependent. It will help focus more clearly on the aim of the individual tests, reducing their volume and heightening the readability. </p>\n\n<p>As far as RSpec style, there are a few idioms I have seen more commonly used:</p>\n\n<ul>\n<li>using <code>#and_return</code> in place of returning values from blocks</li>\n<li>using <code>mock_model</code> </li>\n<li>doing setup in <code>before</code> blocks</li>\n</ul>\n\n<p>Overall, I would likely have written it like this:</p>\n\n<pre><code>describe ProgramsController do\n before(:each) do\n @mock_programs = [mock_model(Program)]\n Program.stub(:paginate).and_return(@mock_programs)\n end\n\n describe \"GET index\" do\n it \"succeeds\" do\n get :index\n\n response.should be_success\n end\n\n it \"renders the index template\" do\n get :index\n\n response.should render_template(\"programs/index\")\n end\n\n it \"assigns @programs\" do\n get :index\n\n assigns(:programs).should == [mock_program]\n end\n\n it \"defaults to showing 30 results per page\" do\n Program.should_receive(:paginate).with(:page => nil, :per_page => 30).and_return(@mock_programs)\n\n get :index\n end\n\n it \"passes on the page number to will_paginate\" do\n Program.should_receive(:paginate).with(:page => '3', :per_page => 30).and_return(@mock_programs)\n\n get :index, 'page' => '3'\n end\n\n it \"passes on the per_page to will_paginate\" do\n Program.should_receive(:paginate).with(:page => nil, :per_page => '15').and_return(@mock_programs)\n\n get :index, 'per_page' => '15'\n end\n end\nend\n</code></pre>\n\n<p>I think, for the limited scope which you've provided, this is a good set of tests. You may be able to skip the test for basic success since all your other tests are dependent on a successful action. I personally can't speak too deeply about testing will_paginate, since I do much the same when testing the use of it from the controller. If it's tested well in the model that uses it, you've covered the basic behavior.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:13:26.733",
"Id": "962",
"Score": "0",
"body": "Any compelling reason why you're not checking the `assigns(:programs)` in the last three tests? I assume it's because otherwise, the call to `will_paginate` with arguments would just fail. Correct?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T21:05:44.207",
"Id": "1124",
"Score": "0",
"body": "Correct. I only stub `program#paginate` to avoid the will_paginate failure. Depending on how often I stub something, I may also move it to the `before` block of a specific context.\n\nI figure that I've already tested the `assigns` once and, without further behavior that may alter the contents of the hash, I do not need to verify it works in other examples."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T19:35:57.203",
"Id": "1326",
"Score": "0",
"body": "@PavelDruzyak above makes a good point. We've tested the interaction of the controller with the model, but not with the view layer. Whether you choose to use RSpec or Shoulda matchers (when I last checked, several weeks ago, the latest versions of each were incompatible, though that may be fixed), you ultimately should go beyond verifying the response was a success and ensure the appropriate response is returned"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T13:44:06.863",
"Id": "520",
"ParentId": "505",
"Score": "4"
}
},
{
"body": "<p>just something that i have considered how about hiding the paginate stuff behind a helper method and then stub the helper method this way you can swap out the pagination implementation with anytime you want\nand then just test the helper method is delegating the params to will_paginate</p>\n\n<pre><code>class ProgramssController < ApplicationController\n def index\n @programs = paginate_progams(params)\n end\nend\n</code></pre>\n\n<p>now you stub the paginate_programs method\nand then you can spec up the helper method paginate</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T22:18:04.843",
"Id": "682",
"ParentId": "505",
"Score": "1"
}
},
{
"body": "<p>You forgot to test what view should be rendered. If you use <a href=\"https://github.com/thoughtbot/shoulda\" rel=\"nofollow\">this</a>, your specs will be much cleaner. The last four should be standard matchers. See <a href=\"https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/assign_to_matcher.rb\" rel=\"nofollow\">this</a> as an example.</p>\n\n<pre><code>describe ProgramsController do\n let(:programs) { [mock_model(Program)] } \n\n describe \"GET index\" do\n it { should paginate(Program).with_default_per_page(30) }\n\n describe \"after pagination\" do\n before(:each) do\n Program.stub(:paginate).and_return(programs) \n get :index\n end\n\n it { should assign_to(:programs).with(programs) }\n it { should respond_with(:success) }\n it { should render_template(:index) }\n it { should_not set_the_flash } \n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T15:40:33.203",
"Id": "64712",
"Score": "0",
"body": "Some shoulda matchers have been deprecated and removed in 2.0. The removed matchers are `assign_to`, `respond_with_content_type`, `query_the_database`, `validate_format_of`, `have_sent_email`, `permit`, `delegate_method`. See http://robots.thoughtbot.com/shoulda-matchers-2-0"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-08T16:51:42.817",
"Id": "695",
"ParentId": "505",
"Score": "19"
}
},
{
"body": "<p>I'm a few years out of RoR, but worked for a company that was heavy on testing an we used RSpec.</p>\n\n<p>In a case like this we would have tested some additional points, mainly about the content of the response. A few lines like (syntax may be totally wrong, as said I'm out of this):</p>\n\n<p>test the amount of records\[email protected](30).records</p>\n\n<p>then there was a command to test if certain records are in the result\[email protected](...)\nthis requires fixtures of course.</p>\n\n<p>The idea behind this was to make sure we could replace a certain plugin against a new one and be sure it doesn't break anything or contains bugs. (For example the acts_as_taggable plugin had a bug that made it impossible to delete tags, thing was running into an infinite loop)\nAnd of course to avoid programmers to make changes while testing in the browser or similar. With will_paginate a typical bug would be to set the pagination to 10 to see several pages in the browser (because there are only 20 records in the fixtures...) and forget to set this value back to 30. And if it's not the programmer, then maybe the guy working on the HTML/CSS. We made sure every of those details were tested</p>\n\n<p>More tests would make sure that the right file would be used for rendering. \nsomething like response.should.render_template(name)</p>\n\n<p>This seems to be a lot of work. But on the positive side: When my first web site for a customer went online, after six weeks of programming and my humble 3 months of knowing about Ruby on Rails, it had no bugs at all and stood 1.000 hits/minute without a single line of code to be changed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T20:52:58.667",
"Id": "699",
"ParentId": "505",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T03:01:24.973",
"Id": "505",
"Score": "28",
"Tags": [
"ruby",
"unit-testing",
"ruby-on-rails",
"controller"
],
"Title": "Unit-testing a controller in Ruby on Rails"
} | 505 |
<p>Please review this:</p>
<pre><code>from os import path, remove
try:
video = Video.objects.get(id=original_video_id)
except ObjectDoesNotExist:
return False
convert_command = ['ffmpeg', '-i', input_file, '-acodec',
'libmp3lame', '-y', '-ac', '2', '-ar',
'44100', '-aq', '5', '-qscale', '10',
'%s.flv' % output_file]
convert_system_call = subprocess.Popen(
convert_command,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE
)
logger.debug(convert_system_call.stdout.read())
try:
f = open('%s.flv' % output_file, 'r')
filecontent = ContentFile(f.read())
video.converted_video.save('%s.flv' % output_file,
filecontent,
save=True)
f.close()
remove('%s.flv' % output_file)
video.save()
return True
except:
return False
</code></pre>
| [] | [
{
"body": "<p>Clean, easy to understand code. However:</p>\n\n<p>Never hide errors with a bare except. Change </p>\n\n<pre><code>try:\n ...\nexcept:\n return False\n</code></pre>\n\n<p>into </p>\n\n<pre><code>try:\n ...\nexcept (IOError, AnyOther, ExceptionThat, YouExpect):\n logging.exception(\"File conversion failed\")\n</code></pre>\n\n<p>Also, unless you need to support Python 2.4 or earlier, you want to use the files context manager support:</p>\n\n<pre><code>with open('%s.flv' % output_file, 'r') as f:\n filecontent = ContentFile(f.read())\n video.converted_video.save('%s.flv' % output_file, \n filecontent, \n save=True)\nremove('%s.flv' % output_file)\n</code></pre>\n\n<p>That way the file will be closed immediately after exiting the <code>with</code>-block, even if there is an error. For Python 2.5 you would have to <code>from __future__ import with_statement</code> as well.</p>\n\n<p>You might also want to look at using a temporary file from <code>tempfile</code> for the output file. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:15:26.917",
"Id": "866",
"Score": "0",
"body": "Thanks a lot for the review! I have updated the snippet to be http://pastebin.com/9fAepHaL But I am confused as to how to use tempfile. The file is already created by the \"convert_system_call\" before I use it's name in the try/catch block. Hmm,, maybe I use tempfile.NamedTemporaryFile()?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:43:30.093",
"Id": "870",
"Score": "0",
"body": "@Chantz: Yeah, exactly. If not you may end up with loads of temporary files in a current directory, where users won't find them and they ever get deleted."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:43:47.623",
"Id": "951",
"Score": "1",
"body": "Lennart following your & sepp2k's suggestion I modified my code to be like http://pastebin.com/6NpsbQhz Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T06:29:50.330",
"Id": "510",
"ParentId": "507",
"Score": "5"
}
},
{
"body": "<p>In addition to the points that Lennart made, there's just one minor thing I'd like to add:</p>\n\n<p>You repeat the expression <code>'%s.flv' % output_file</code> four times in your code. You might want to store this in a variable like <code>filename = '%s.flv' % output_file</code>. This way there's less repetition and if you ever want to change the target file format, all you'll have to change are the <code>filename</code> and <code>convert_command</code> variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T18:18:09.150",
"Id": "878",
"Score": "0",
"body": "Makes sense. Will make the change. Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:43:21.880",
"Id": "950",
"Score": "0",
"body": "sepp2k following your & Lennart's suggestion I modified my code to be like http://pastebin.com/6NpsbQhz Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:38:25.913",
"Id": "525",
"ParentId": "507",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T04:39:28.163",
"Id": "507",
"Score": "5",
"Tags": [
"python",
"converting",
"django"
],
"Title": "Converting an already-uploaded file and saving it to a model's FileField"
} | 507 |
<p>I have 2 functions used for parsing a house number and I think these can both be improved.</p>
<p>Any suggestions?</p>
<p><strong>input:</strong></p>
<blockquote>
<pre><code>45a - 47b
</code></pre>
<p>or</p>
<pre><code>45a bis 47b
</code></pre>
</blockquote>
<p><strong>output:</strong></p>
<blockquote>
<pre><code>45,a,47,b
</code></pre>
</blockquote>
<pre><code>public static string[] HausnummerAufteilen(string hausNummer)
{
string[] result = new string[4];
string[] resultVon = new string[2];
string[] resultBis = new string[2];
resultVon[0] = string.Empty;
resultVon[1] = string.Empty;
resultBis[0] = string.Empty;
resultBis[1] = string.Empty;
int pos1, pos2;
pos2 = 0;
pos1 = hausNummer.IndexOf("bis");
if (pos1 != -1)
{
pos2 = pos1 + 3;
}
else
{
pos1 = hausNummer.IndexOf("-");
if (pos1 != -1)
pos2 = pos1 + 1;
}
if (pos1 > 0)
{
resultVon = HausnummerBuchst(hausNummer.Substring(0, pos1).Trim());
resultBis = HausnummerBuchst(hausNummer.Substring(pos2, hausNummer.Length - pos2).Trim());
}
else
resultVon = HausnummerBuchst(hausNummer);
List<string> list = new List<string>();
list.AddRange(resultVon);
list.AddRange(resultBis);
result = list.ToArray();
return result;
}
public static string[] HausnummerBuchst(string hauseNummer)
{
string[] result = new string[2];
result[0] = string.Empty;
result[1] = string.Empty;
int iPos;
int testInt;
bool bFound = false;
for (iPos = 0; iPos < hauseNummer.Length; iPos++)
{
if (!int.TryParse(hauseNummer[iPos].ToString() ,out testInt))
{
bFound = true;
break;
}
}
if (bFound)
{
result[0] = hauseNummer.Substring(0, iPos).Trim();
result[1] = hauseNummer.Substring(iPos, hauseNummer.Length - iPos).Trim();
}
else
result[0] = hauseNummer;
return result;
}
</code></pre>
| [] | [
{
"body": "<p>Anytime I encounter a method that's only doing read-only parsing of strings and I see it's using <code>String.IndexOf()</code> and <em>positions</em>, it leaps out at me like a gigantic code smell.</p>\n\n<p>Sometimes upon examination it turns out to be a legitimate and wise usage. However very often the programmer is manually splitting strings and looping through parts of the string. In other words they are doing exactly what <code>String.Split()</code> and <code>foreach</code> loops would offer them, but doing it the longer and less readable way.</p>\n\n<p>This is one of those cases.</p>\n\n<p>This may be just my personal taste in code. In any case, I can show you how I would tackle this problem using <code>foreach</code> and <code>Split()</code>, which I believe would be a great improvement to your methods. Except for this difference I think we might have taken comparable approaches.</p>\n\n<h3>Variable names</h3>\n\n<p>A lot of your variables are named with very little descriptiveness. You may understand that variables are named so that someone maintaining or reading the code (like me) can understand what's going on, but you could do much better in this department.</p>\n\n<ul>\n<li><code>result</code>: You use this word many times in your variable names. The problem is this name is completely useless to me. I can see it is the result of <em>something</em> (variously a function, a loop or some other process) but beyond that you might as well just call the variable <code>foo</code> or <code>bar</code>. <code>hauseNummerVon</code> and <code>hauseNummerBin</code> are far more understandable than <code>resultVon</code> and <code>resultBin</code> - I now know exactly what it is; it's the <em>from</em> house number and the <em>to</em> house number.\n<ul>\n<li>For either <code>result[]</code> array, I am left with nothing and I would have to read all of the code before I understood what they contained. This is a little backwards - I should know what the variable contains, <em>then</em> be able to read the code - with descriptive variable names giving me a greater understanding of what's going on.</li>\n</ul></li>\n<li><code>bFound</code>: Don't shorten your variable names like this. I'm left wondering: What is a <code>b</code>? What does it mean if it's found? Maybe this would be more recognisable to a German reader, but even so, expanding <code>b</code> to a word to say exactly what's found would do wonders for readability.</li>\n<li><code>pos1</code>, <code>pos2</code>: <code>SeparatorPosition</code> and <code>SeparatorEnd</code> would have been more descriptive. Better yet these variables are entirely unnecessary if you just use <code>String.Split()</code>.</li>\n</ul>\n\n<h2>My approach</h2>\n\n<p>As I mentioned above, as oppose to editing your methods, I've written from scratch how I'd tackle this problem.</p>\n\n<h3>ParseHouseNumberRange</h3>\n\n<p>This is the entry method. You feed this method a string such as \"20a bis 21c\". It splits it up on the \"bis\" or the \"-\" (defined in the <code>separators</code> array) in order to produce smaller chunks of the original string.</p>\n\n<p>Each of these chunks is passed to then passes each of the results (in this case, \"20a \" and \" 21c\", spaces included) over to the non-public method <code>ParseHouseNumber</code> below. <code>ParseHouseNumber</code> will split these chunks up further and this method combines all the results into a single array which is returned.</p>\n\n<p>Given \"20a bis 21c\" or similar, it returns an array: <code>20, a, 21, c</code>.</p>\n\n<pre><code>public string[] ParseHouseNumberRange(string houseNumberRange)\n{\n string[] separators = new string[] {\"bis\", \"-\"};\n string[] houseNumbers = houseNumberRange.Split(separators,\n StringSplitOptions.RemoveEmptyEntries);\n\n List<string> parsedList = new List<string>();\n\n foreach (string houseNumber in houseNumbers)\n {\n parsedList.AddRange(ParseHouseNumber(houseNumber));\n }\n\n return parsedList.ToArray();\n}\n</code></pre>\n\n<h3>ParseHouseNumber</h3>\n\n<p>This method takes a segment of an address from the method above, such as \"20a \". After trimming out any spaces, it walks through the string character by character, plucking out digits and letters and sorting them into their own individual sections e.g. \"1c4ad3\" would be split into the sections <code>1, c, 4, ad, 3</code>. Any non-digit non-letter characters are ignored.</p>\n\n<p>Once all sections have been sorted out from the string provided to it, it returns those sections in the form of an array.</p>\n\n<pre><code>public string[] ParseHouseNumber(string houseNumber)\n{\n bool firstRun = true;\n bool alphabeticMode = false; // set on first run\n\n houseNumber = houseNumber.Trim();\n\n List<string> sections = new List<string>();\n string currentSection = \"\";\n\n foreach (char c in houseNumber)\n {\n bool isLetter = Char.IsLetter(c);\n bool isDigit = Char.IsDigit(c);\n\n if (!(isDigit || isLetter)) continue;\n\n // If we've switched character type, then a section's finished.\n if (firstRun)\n {\n alphabeticMode = isLetter;\n firstRun = false;\n }\n else if ((isLetter && !alphabeticMode)\n || (isDigit && alphabeticMode))\n {\n sections.Add(currentSection);\n currentSection = \"\";\n alphabeticMode = !alphabeticMode;\n }\n\n currentSection += c;\n }\n\n if (currentSection != \"\") sections.Add(currentSection);\n\n return sections.ToArray();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T09:56:09.503",
"Id": "515",
"ParentId": "513",
"Score": "22"
}
}
] | {
"AcceptedAnswerId": "515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T07:58:30.563",
"Id": "513",
"Score": "16",
"Tags": [
"c#",
"parsing"
],
"Title": "House number parsing"
} | 513 |
<pre><code><% @descriptions.each_with_index do |description, i| %>
<% description.tale2.each do |tax_ref| %>
<% if condition %>
<% if condition %>
<% if condition %>
<%= $text_first_describe%> <%= $paren_author_yr %>
<% ref_sp_uniq.each_with_index do |ref, i| %>
<% if ref == tax_ref.ref_wo_brace%>
<% execution %>
<% elsif i == (ref_sp_uniq.size - 1)%>
<%# @ref_desc = "#{@ref_desc_numb}. #{tax_ref.ref_wo_brace}" %>
<% end %>
<% end %>
<% if condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% elsif taxon_name.emend_author_year %>
<%= print %>
<% else %>
<%= print %>
<% end %>
<% end %>
<% else %>
<% if condition %>
<%= print %>
<% ref_sp_uniq.each_with_index do |ref, i| %>
<% if condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% end %>
<% end %>
<% if condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% else %>
<% execution %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T10:03:52.760",
"Id": "845",
"Score": "0",
"body": "try to edit your code with a good completion"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T10:04:34.177",
"Id": "846",
"Score": "1",
"body": "that depend your condition. Its almost impossible to help your without more information"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T10:12:52.433",
"Id": "848",
"Score": "12",
"body": "As it stands this question is _impossible_ to answer. Without knowing what conditions are being checked or what code is being executed there is literally _nothing_ we can suggest. Maybe you are repeating code, or maybe several chunks of code could just be run under a single check, but we simply do not know. We need the actual code with conditions _and_ execution before we can do anything."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T20:04:23.710",
"Id": "881",
"Score": "5",
"body": "-1: please edit your question, use code formatting (four spaces at the start of each line) and provide some context."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:59:26.863",
"Id": "1156",
"Score": "0",
"body": "This looks like code to post if you're trolling. It's practically line noise and ruby is one of the most expressive languages I know but this manages to make it look bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T06:26:04.197",
"Id": "58767",
"Score": "1",
"body": "See [Flattening arrow code](http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:58:05.367",
"Id": "108890",
"Score": "0",
"body": "Ruby has 'case when' statement that is pretty nifty and when used properly can help a lot with complicated if statements because 'case when' allows range checking which comes up a lot in conditional code."
}
] | [
{
"body": "<p>In general, you can try inverting the condition on your outermost if block, and work your way in. This will often result in less nesting, eg:</p>\n\n<pre><code>if condition1\n if condition2\n #ifblock\n else\n #elseblock2\n end\nelse\n #elseblock\nend\n</code></pre>\n\n<p>Inside a loop, as you have your code, it would become this strcture, which is less nested:</p>\n\n<pre><code>if !condition\n #elseblock\n next\nend\nif !condition2\n #elseblock2\n next\nend\n#ifblock\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:14:46.230",
"Id": "524",
"ParentId": "514",
"Score": "6"
}
},
{
"body": "<p>A thing to try: case statement</p>\n\n<pre><code>case tax_ref\nwhen a then execution1\nwhen b then execution2\nend\n</code></pre>\n\n<p><a href=\"http://www.tutorialspoint.com/ruby/ruby_if_else.htm\" rel=\"nofollow\">http://www.tutorialspoint.com/ruby/ruby_if_else.htm</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:03:05.800",
"Id": "554",
"ParentId": "514",
"Score": "1"
}
},
{
"body": "<p>Why can't you use the operators <code>||</code> and <code>&&</code> ?</p>\n\n<p>im not at all literate with the syntax but you should be able to convert:</p>\n\n<pre><code><% if condition %> \n <% if condition %>\n <% if condition %>\n <% end %>\n <% end %>\n<% end %>\n</code></pre>\n\n<p>into:</p>\n\n<pre><code><% if condition && condition && condition %>\n <% expression %>\n<% end %>\n</code></pre>\n\n<p>Looking at the docs this logical expressions are available!</p>\n\n<p>also removing the language identifiers you should be able to do:</p>\n\n<pre><code><%\n if condition && condition && condition\n expression\n end\n%>\n</code></pre>\n\n<p>When it comes down to the <code>else if</code>'s then you can increase readability by doing a switch statement:</p>\n\n<p>The main point is to remove the not so required <code><%</code> and <code>%></code> in places.</p>\n\n<p><a href=\"http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#and\" rel=\"nofollow\">http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#and</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T20:56:51.783",
"Id": "567",
"ParentId": "514",
"Score": "2"
}
},
{
"body": "<p>There are several things you should do with this template, and templates that look like this in general:</p>\n\n<ol>\n<li><p>Break some elements into partials.</p></li>\n<li><p>Push logic to the model. Instead of </p>\n\n<pre><code> <% if condition with model %>\n stuff\n <% else %>\n other stuff\n <% end %>\n</code></pre>\n\n<p>when stuff or other stuff are strings with little or no markup, do</p>\n\n<pre><code> <%= model.display_for_condition %>\n</code></pre></li>\n<li><p>Use helpers for cases like 2) where the things to be displayed have some markup:</p>\n\n<pre><code> <% condition_helper(model.condition?) %>\n</code></pre></li>\n<li><p>Use presenter objects, especially when dealing with display logic that references more than one model. </p></li>\n<li><p>Most abstractly, but most importantly for learning to write code with fewer if statements, internalize one of the key distinctions between OO style and procedural style code: with OO you ask objects to do things they know how to do. If you find yourself always asking objects for information and deciding what to do with it, you are using objects as nothing more than structs and writing procedural code. </p>\n\n<p>Or as my intern described it the other day: (this has become one of my favourite quotes about programming)</p></li>\n</ol>\n\n<blockquote>\n <p>if you're itchy it's ok to scratch your own itch, but it would be kind of weird to scratch other people's itches.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T11:14:34.537",
"Id": "622",
"ParentId": "514",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "524",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T09:36:07.163",
"Id": "514",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "How to reduce number of hierarchical 'if statements'"
} | 514 |
<p>I need a code review for <em>best practices</em> and <em>code correctness</em> of the following piece of code. <code>run</code> executes a program and validates in output. If the output is valid status can be found in <code>VALID_SOLUTIONS</code>.</p>
<pre><code>elapsed = None
tmpdir = tempfile.mkdtemp(prefix='structure-%s-' % os.path.basename(instance))
try:
for r in range(options.repeat):
run_returncode, run_status, run_elapsed = run(
r, path, program, tmpdir, options.timeout, options.satisfiable)
if run_status not in VALID_SOLUTIONS:
returncode, status, elapsed = run_returncode, run_status, None
break
if r == 0:
# Set the expected results
returncode, status = run_returncode, run_status
elapsed = [run_elapsed]
else:
if returncode != run_returncode or status != run_status:
# Results don't match
returncode, status, elapsed = None, 'inconsistent_results', None
break
else:
# Extra set
elapsed.append(run_elapsed)
except Exception as e:
# Unexpected error in script itself
print(e, file=sys.stderr)
#traceback.print_exc()
status = 'error'
except KeyboardInterrupt as e:
print('interrupted', file=sys.stderr)
returncode, status, elapsed = None, 'interrupted', None
finally:
if status in VALID_SOLUTIONS:
avg = sum(elapsed) / len(elapsed)
std = (sum((e - avg)**2 for e in elapsed) / len(elapsed)) ** 0.5
ci = 1.96 * std / (len(elapsed) ** 0.5)
print(instance, returncode, status, avg, ci)
else:
print(instance, returncode, status, None, None)
sys.stdout.flush()
exit(int(status not in ['interrupted'] + VALID_SOLUTIONS))
</code></pre>
| [] | [
{
"body": "<p>Well, firstly, don't be afraid of empty lines. This code is quite hard to read.</p>\n\n<p>Secondly, functions is good invention. ;) That code as it is now is a bare piece of code, with no indication of where most of the parameters come from, and it seems that the acceptable solutions is a global, as you have capitalized it? That doesn't make much sense to me.</p>\n\n<p>Just as you have a function called run() to run the program, it would make sense to have a function to run it multiple times, with the tests for that you have.</p>\n\n<p>I'm also not sure why you trap KeyboardInterrupt, without seeming to actually do anything with it, except setting the status, and then testing the status. You could just do exit directly from that exception handler, that would be clearer.</p>\n\n<p>Otherwise it seems fine. Feedback on correctness is impossible when your code isn't a running example. But then again, tests generally work better than code reviews there, although they are not exclusive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:04:08.687",
"Id": "856",
"Score": "0",
"body": "Thanks for the feedback. `KeboardInterrupt` because the script is run inside an infinite loop which stops when the output is invalid. Can't exit directly since exit() throws an exception (`SystemExitError` I think)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:26:01.333",
"Id": "862",
"Score": "0",
"body": "+1 for adding whitespace to enhance readability. Also moving code to separate functions would help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T13:44:42.763",
"Id": "521",
"ParentId": "519",
"Score": "12"
}
},
{
"body": "<p>Comments. Well written code tells you how a problem is being solved. Well written comments tell you <em>what</em> problem is being solved. Great comments tell you what assumptions the programmer is making about the data going in and coming out.</p>\n\n<p>In the finally clause: You have a magic constant. Best practice is that you declare constants with descriptive variables names.</p>\n\n<p>The variables 'r' and 'e': no single letter variable names please, save for those that are so basic no one will get them wrong, which is basically x,y,z and t, in the context for cartesian coordinates or parameterized plots. And 'e' was an exception a few lines ago, now it's a list element?</p>\n\n<p>Lastly, x**.5 is accurate, but sqrt(x) is more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:24:31.153",
"Id": "523",
"ParentId": "519",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "521",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T13:25:51.633",
"Id": "519",
"Score": "14",
"Tags": [
"python",
"file",
"error-handling",
"timer"
],
"Title": "Executing a program with a temporary directory and measuring the running time"
} | 519 |
<p>I'm building an ASP.NET MVC app and would like some feedback for my way to query/execute statements to the ORM.</p>
<p>I'm using Fluent NHibernate, and have mixed the UoW provided by NHibernate with a Command pattern.</p>
<p><strong>ICommand.cs</strong> (Core layer)</p>
<pre><code>using NHibernate;
namespace MyDemon.Core.Commands
{
public interface ICommand<out TResult>
{
TResult Execute(ISession session);
}
}
</code></pre>
<p><strong>ISessionExtensions.cs</strong> (Core layer)</p>
<pre><code>using NHibernate;
namespace MyDemon.Core.Commands
{
public static class ISessionExtensions
{
public static TResult Execute<TResult>(this ISession session, ICommand<TResult> unitOfWork)
{
return unitOfWork.Execute(session);
}
}
}
</code></pre>
<p><strong>GetUserById.cs</strong> (Core layer)</p>
<pre><code>using NHibernate;
namespace MyDemon.Core.Commands.User
{
using Entities;
public class GetUserById : ICommand<User>
{
public int UserId { get; set; }
public GetUserById(int userId)
{
UserId = userId;
}
#region Implementation of IUnitOfWork<out User>
public User Execute(ISession session)
{
return session.Get<User>(UserId);
}
#endregion
}
}
</code></pre>
<p><strong>AccountController.cs</strong> (Web layer)</p>
<pre><code>[AjaxOnly]
[Authorize]
public ActionResult Details(int id)
{
User userToGet = _session.Execute(new GetUserById(id));
if (userToGet == null)
{
return PartialView("Partials/UserNotFound");
}
DetailsUserViewModel userToViewModel = Mapper.Map<User, DetailsUserViewModel>(userToGet);
return PartialView("Partials/Details", userToViewModel);
}
</code></pre>
<p>What do you think? A clever design, or just another "too-much code" approach?</p>
| [] | [
{
"body": "<p>This seems to be a lot of code to say the same as this:</p>\n\n<pre><code>[AjaxOnly]\n[Authorize]\npublic ActionResult Details(int id)\n{\n User userToGet = _session.Get<User>(id);\n\n if (userToGet == null)\n {\n return PartialView(\"Partials/UserNotFound\");\n }\n\n DetailsUserViewModel userToViewModel = Mapper.Map<User, DetailsUserViewModel>(userToGet);\n\n return PartialView(\"Partials/Details\", userToViewModel);\n}\n</code></pre>\n\n<p>What problem are you trying to solve here?</p>\n\n<p>(or am I missing something?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T11:10:52.460",
"Id": "1069",
"Score": "1",
"body": "I wouldn't go as raw as having the _session in the Controller (would have a DAO or Repository layer), but definetely this is the way to go. This is the way NH is used in web apps in .NET. Unless you have a (good) reason there is no motive to come up with something so \"complicated\" (not because the inherent complexity but just because it not the standard) to deal with NH + DB."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T17:27:43.583",
"Id": "1084",
"Score": "0",
"body": "@tucaz Agree with you there. But the session was already in the controller, so I left it there rather than complicating the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-29T19:17:24.417",
"Id": "19440",
"Score": "0",
"body": "@tucaz For what reason would you have a DAO or repo layer here? Isn't NHibernate enough of a DAO in this case? (I'm new to NHibernate too so I'm curious about these things)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-30T21:13:45.613",
"Id": "19506",
"Score": "0",
"body": "@JamieDixon, it is, and I'm probably should not add another layer of indirection unless needed for some other reason, but I like to think that adding it allows me to make sure that the usage of NHibernate does not get out of hand and is spreaded where it should not be and also allows me to change strategies easily later as well encapsulating the lifecicle of the ISession."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:43:24.520",
"Id": "596",
"ParentId": "522",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T14:22:20.707",
"Id": "522",
"Score": "4",
"Tags": [
"c#",
"asp.net"
],
"Title": "NHibernate (UoW) + cCommand pattern"
} | 522 |
<p>I have a small solution to the following hypothetical problem:</p>
<blockquote>
<p>Basic sales tax is applicable at a rate of 10% on all goods, except
books, food, and medical products that are exempt. Import duty is an
additional sales tax applicable on all imported goods at a rate of 5%,
with no exemptions.</p>
<p>When I purchase items I receive a receipt which lists the name of all
the items and their price (including tax), finishing with the total
cost of the items, and the total amounts of sales taxes paid. The
rounding rules for sales tax are that for a tax rate of n%, a shelf
price of p contains (np/100 rounded up to the nearest 0.05) amount of
sales tax. Write an application that prints out the receipt details
for these shopping baskets.</p>
<p><strong>INPUT</strong>:</p>
<ul>
<li>Input 1: 1 book at 12.49 1 music CD at 14.99 1 chocolate bar at 0.85</li>
<li>Input 2: 1 imported box of chocolates at 10.00 1 imported bottle of perfume at 47.50</li>
<li>Input 3: 1 imported bottle of perfume at 27.99 1 bottle of perfume at 18.99 1 packet of headache pills at 9.75 1 box of imported
chocolates at 11.25</li>
</ul>
<p><strong>OUTPUT</strong></p>
<ul>
<li>Output 1: 1 book : 12.49 1 music CD: 16.49 1 chocolate bar: 0.85 Sales Taxes: 1.50 Total: 29.83</li>
<li>Output 2: 1 imported box of chocolates: 10.50 1 imported bottle of perfume: 54.65 Sales Taxes: 7.65 Total: 65.15</li>
<li>Output 3: 1 imported bottle of perfume: 32.19 1 bottle of perfume: 20.89 1 packet of headache pills: 9.75 1 imported box of chocolates: 11.85 Sales Taxes: 6.70 Total: 74.68</li>
</ul>
</blockquote>
<p>I'm interested in feedback on my use of design patterns, whether there are any extensibility issues, how SOLID the code is and the style/structure of the unit tests. I'd really appreciate hearing constructive criticisms.</p>
<p>Full solution is available <a href="https://github.com/manwood/SalesTax" rel="nofollow">here</a></p>
<p>This is part of the main solution:</p>
<pre><code>public class SalesItem : ISalesItem
{
private string _name;
private decimal _price;
public SalesItem(string name, decimal price)
{
#region Parameter Checking
if (String.IsNullOrWhiteSpace(name))
throw new ArgumentException("name");
if(price < 0)
throw new ArgumentException("price");
#endregion
this._name = name;
this._price = price;
}
#region ISalesItem Members
public string Name
{
get { return this._name; }
}
public decimal GetPrice()
{
return this._price;
}
public decimal GetSalesTax()
{
return 0.0M;
}
public decimal GetTotal()
{
return this.GetPrice() + this.GetSalesTax();
}
#endregion
}
public class SalesItemTaxDecorator: ISalesItem
{
protected ISalesItem _decoratedSalesItem;
protected ITax _salesTax;
public SalesItemTaxDecorator(ISalesItem salesItem, ITax salesTax)
{
this._decoratedSalesItem = salesItem;
this._salesTax = salesTax;
}
#region ISalesItem Members
public string Name
{
get { return _decoratedSalesItem.Name; }
}
public virtual decimal GetSalesTax()
{
return this._decoratedSalesItem.GetSalesTax() + _salesTax.CalculateTax(this._decoratedSalesItem.GetPrice());
}
public virtual decimal GetPrice()
{
return this._decoratedSalesItem.GetPrice();
}
public virtual decimal GetTotal()
{
return this.GetPrice() + this.GetSalesTax();
}
#endregion
}
public class Tax : ITax
{
private decimal _rate;
private IRounding _rounding;
public Tax(decimal rate, IRounding rounding)
{
this._rate = rate;
this._rounding = rounding;
}
#region ISalesTax Members
public decimal Rate
{
get { return this._rate; }
}
public IRounding Rounding
{
get { return this._rounding; }
}
public virtual decimal CalculateTax(decimal itemPrice)
{
decimal tempTax = itemPrice * this.Rate;
decimal roundedTax = Rounding.Round(tempTax);
return roundedTax;
}
#endregion
}
public static class SalesItemFactory
{
private static readonly Rounding ROUNDING = new Rounding(0.05M);
private static readonly ITax BASICTAX = new Tax(0.1M, ROUNDING);
private static readonly ITax IMPORTTAX = new Tax(0.05M, ROUNDING);
private static readonly Dictionary<ItemType, ITax> itemTaxLookup = new Dictionary<ItemType, ITax>()
{
{ ItemType.Basic, BASICTAX },
{ ItemType.Import, IMPORTTAX }
};
public static ISalesItem GetSalesItem(string name, decimal price, ItemType itemType)
{
ISalesItem item = new SalesItem(name, price);
foreach (int flag in Enum.GetValues(typeof(ItemType)))
{
if ((flag & (int)itemType) == flag)
{
item = (ISalesItem)Activator.CreateInstance(typeof(SalesItemTaxDecorator), new object[] { item, itemTaxLookup[(ItemType)flag] });
}
}
return item;
}
public static ISalesItem GetSalesItem(string name, decimal price)
{
return new SalesItem(name, price);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-13T23:49:05.500",
"Id": "228756",
"Score": "0",
"body": "This precise homework problem has been addressed before in the StackExchange universe."
}
] | [
{
"body": "<p>Wow, a lot of code to review. Unfortunately I'm too lazy to look through entire solution, let's I'll post my first 10 points. </p>\n\n<p>1) <a href=\"http://en.wikipedia.org/wiki/Overengineering\">http://en.wikipedia.org/wiki/Overengineering</a>. Looked through the solution and have found absolutely no point in having such an amount of interfaces. I would definitely get rid of ITax and IRounding because there is only one implementation for each of them and there is no point to isolate them during unit-testing because there is too small functionality to isolate. <strong>Do not make it in such a complicated way until you really need such a complicated model.</strong> You will have time to make things worse later :) </p>\n\n<p>2) I personally hate 4-line regions - they do not help at all as for me. </p>\n\n<p>3) If you have a factory for <code>salesItems</code> then why don't you want to make class <code>SalesItem</code> hidden inside <code>Factory</code> class. </p>\n\n<pre><code>public static class SalesItemFactory\n{\n class SalesItem : ISalesItem { ... }\n class SalesItemTaxDecorator : ISalesItem { ... }\n\n ...\n}\n</code></pre>\n\n<p>If you really want to unit-test them then at least make them internal and use <code>InternalsVisibleTo</code>. Or better even not to test them, test factory! </p>\n\n<p>4) <code>item = (ISalesItem)Activator.CreateInstance(typeof(SalesItemTaxDecorator), new object[] { item, itemTaxLookup[(ItemType)flag] });</code> </p>\n\n<p>Why activator at all? </p>\n\n<p><s>5) The same line as in previous point. Why do you assign this value to <code>item</code> and continue iterations? Simply return it! And in order to keep your logic you should revert collection returned by <code>Enum.GetValues</code>.</s> </p>\n\n<p>6) I would remove 'protected' and 'virtual' stuff from your decorator and replace them with 'private' and 'sealed' instead. Otherwise you're giving an ability to decorate decorator but that is strange. <strong>Too much of extensibility</strong></p>\n\n<p>7) Let's go to unit-tests :). <a href=\"https://github.com/manwood/SalesTax/tree/master/Manwood.SalesTax.Tests/Stubs\">https://github.com/manwood/SalesTax/tree/master/Manwood.SalesTax.Tests/Stubs</a>. Do not write your stubs, use for example RhinoMock instead. They make life easier due to many reasons: you do not have to write your stubs, you will not see your stubs while looking for inheritors of <code>ITax</code>, they allow you to write more precise unit-tests (your unit-tests are not that good, see next point). </p>\n\n<p>8) <a href=\"https://github.com/manwood/SalesTax/blob/master/Manwood.SalesTax.Tests/SalesItemTest.cs\">https://github.com/manwood/SalesTax/blob/master/Manwood.SalesTax.Tests/SalesItemTest.cs</a>. </p>\n\n<pre><code>[TestClass]\npublic class SalesItemTest\n{\n [TestMethod] public void SalesItemGetPriceTest() { }\n [TestMethod] public void SalesItemGetSalesTaxTest() { }\n [TestMethod] public void SalesItemGetTotalTest() { }\n}\n</code></pre>\n\n<p>Doubling your names too much in testMethods. <code>PriceTest()</code>, <code>SalesTaxTest()</code>, <code>GetTotalTest()</code> would be better names. </p>\n\n<p>9) <a href=\"https://github.com/manwood/SalesTax/blob/master/Manwood.SalesTax.Tests/SalesItemTaxDecoratorTest.cs\">https://github.com/manwood/SalesTax/blob/master/Manwood.SalesTax.Tests/SalesItemTaxDecoratorTest.cs</a> </p>\n\n<pre><code> [TestMethod]\n public void SalesItemTaxDecoratorTotalTest()\n {\n SalesItemTaxDecorator taxDecorator = new SalesItemTaxDecorator(new SalesItemStub(10M, 0M), new TaxStub(0.1M));\n decimal total = taxDecorator.GetTotal();\n Assert.AreEqual(11M, total);\n }\n</code></pre>\n\n<p>This is invalid test. What you're testing is whether it will return <code>11</code> if price is <code>10</code> and tax is <code>0.1</code>. What you should test is <strong>a)</strong> Tax was calculated for price value (it means that <code>ITax.CalculateTax</code> was invoked with parameter 10) <strong>b)</strong> result taken from tax was added to 10 and returned. RhinoMocks will help use assert <strong>a)</strong> statement and you should assert <strong>b)</strong> on your own in the same manner you do it right now. This test should not have <code>0.1</code> constants, otherwise you're testing tax class also (even though it is a stub). </p>\n\n<p>10) 10th point, I want to go sleep. </p>\n\n<p>Asking about patterns in such a simple example will never be easy, because there is no point in them in such examples and you will never need them until you will extend it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T23:30:15.890",
"Id": "892",
"Score": "0",
"body": "Hey, thanks for your thoughts. The point about over-engineering and use of patterns is clearly applicable to such a small example, but using them here was more about applying them correctly so that the example *could* be extended with minimal modification. If you wanted new tax types for example, the system would support the Open/Closed principle."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T23:33:42.860",
"Id": "894",
"Score": "0",
"body": "Point 5 - because the enum `ItemType` is comprised of flags and the item can be any number of types, so the nesting of `item` allows me to wrap the original item in 'decorators'. Point 7/9 does using RhinoMocks mean you do not need stubs at all? I take you point about `SalesItemTaxDecoratorTotalTest()` - that was one I was really uncomfortable with and can see how a mocking framework would help here. Lastly, on the subject of patterns, how would you have solved the problem of items being multiple types? (eg, Basic, Exempt, Import... SomeOtherTypeYouCreateInTheFuture etc)?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T23:36:25.680",
"Id": "896",
"Score": "0",
"body": "(Also I don't see how we can demonstrate design patterns in a brief codereview site like this without using small, hypothetical examples in which their use does constitute overengineering!)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T23:43:43.183",
"Id": "897",
"Score": "0",
"body": "@manwood, striked out point 5, didn't mention that you're wrapping item over and over. on how to review patterns' usage - I'not sure, maybe less code more class/interface definitions?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T23:47:43.537",
"Id": "898",
"Score": "0",
"body": "With rhinomock all your stubs will be dynamic - you will create them mostly in your test method. With your stubs it is not that easy to maintain them. For example if you will have your TaxStub used in several places and for each place you will have to introduce some changes in the stub (which happens more often than I would like to) then these stub changes will affect all tests which use TaxStub. Also your stubs at the moment do not allow to test whether stub was used to calculate tax for 10$ or for 100$, but you should test it too. It's pretty easy with Rhino or any other mock library."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:17:27.433",
"Id": "914",
"Score": "0",
"body": "@manwood, regarding design&patterns usage here. It of course pretty much depends on how are you going to use this `ISalesItem` instances. Your approach allows to easily calculate Tax, TotalCost, etc but I would prefer more linear structure for taxes instead of this recursive structure. Two disadvantages of your approach I see here are: **a)** It is not that convinient to debug `ISalesItem` instances, because at some point you may have to find value for price decorator decorator decorator. Linear structures are easier to observe in debug mode."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:18:22.223",
"Id": "915",
"Score": "0",
"body": "**b)** You won't be able to implement for example printing all taxes applied to a given item because taxes are completely hidden behind an abstraction wall."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T15:56:37.707",
"Id": "1079",
"Score": "1",
"body": "Just wanted to notice that I only partially agree with point 2 because the regions that are used are automatically generated by visual studio upon implementing an interface. Which is a-ok in my book."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T23:09:32.683",
"Id": "534",
"ParentId": "531",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T21:56:09.690",
"Id": "531",
"Score": "8",
"Tags": [
"c#",
"programming-challenge",
"design-patterns",
"unit-testing",
"finance"
],
"Title": "Hypothetical SalesTax challenge"
} | 531 |
<p>Is there a better (more pythonic?) way to filter a list on attributes or methods of objects than relying on lamda functions?</p>
<pre><code>contexts_to_display = ...
tasks = Task.objects.all()
tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)
tasks = filter(lambda t: not t.is_future(), tasks)
tasks = sorted(tasks, Task.compare_by_due_date)
</code></pre>
<p>Here, <code>matches_contexts</code> and <code>is_future</code> are methods of <code>Task</code>. Should I make those free-functions to be able to use <code>filter(is_future, tasks)</code>?</p>
<p>Any other comment?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:49:25.317",
"Id": "889",
"Score": "3",
"body": "I think this is too specific a question to qualify as a code review."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T16:47:05.750",
"Id": "1319",
"Score": "0",
"body": "Are you coding Django? Looks like it from the `Task.objects.all()` line."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T17:03:39.870",
"Id": "1320",
"Score": "0",
"body": "That's part of the Django app I'm writing to learn both Python and Django, yes..."
}
] | [
{
"body": "<p>I think lambdas are fine in this case. (Yeah, not much of a code review, but what can I say... You basically ask a yes/no question. Answer: \"No\". :) )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:10:29.493",
"Id": "537",
"ParentId": "533",
"Score": "2"
}
},
{
"body": "<p>The first lambda (calling <code>matches_contexts</code>) can't be avoided because it has to capture the <code>contexts_to_display</code>, but the <code>not is_future()</code> can be moved into a new <code>Task</code> method <code>can_start_now</code>: it's clearer (hiding the negative conditions), reusable, and this condition will most probably be more complicated in the future. Yes, <a href=\"http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it\" rel=\"nofollow\">YAGNI</a>, I know... ;)</p>\n\n<p>And because I did not need the sorting phase to return a copy of <code>tasks</code>, I used in-place sort. By the way, the arguments are reversed between <code>filter(f,iterable)</code> and <code>sorted(iterable,f)</code>, using one just after the other seemed akward...</p>\n\n<p>So the code is now:</p>\n\n<pre><code>class Task:\n ...\n def can_start_now(self):\n return not self.is_future()\n\n\ncontexts_to_display = ...\ntasks = Task.objects.all()\ntasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)\ntasks = filter(Task.can_start_now, tasks)\ntasks.sort(Task.compare_by_due_date)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T08:53:18.163",
"Id": "545",
"ParentId": "533",
"Score": "0"
}
},
{
"body": "<p>I would use a list comprehension:</p>\n\n<pre><code>contexts_to_display = ...\ntasks = [t for t in Task.objects.all()\n if t.matches_contexts(contexts_to_display)\n if not t.is_future()]\ntasks.sort(cmp=Task.compare_by_due_date)\n</code></pre>\n\n<p>Since you already have a list, I see no reason not to sort it directly, and that simplifies the code a bit.</p>\n\n<p>The cmp keyword parameter is more of a reminder that this is 2.x code and will need to be changed to use a key in 3.x (but you can start using a key now, too):</p>\n\n<pre><code>import operator\ntasks.sort(key=operator.attrgetter(\"due_date\"))\n# or\ntasks.sort(key=lambda t: t.due_date)\n</code></pre>\n\n<p>You can combine the comprehension and sort, but this is probably less readable:</p>\n\n<pre><code>tasks = sorted((t for t in Task.objects.all()\n if t.matches_contexts(contexts_to_display)\n if not t.is_future()),\n cmp=Task.compare_by_due_date)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:20:22.993",
"Id": "966",
"Score": "0",
"body": "Thanks for the tip about list comprehension! As `compare_by_due_date` specifically handles null values for the due date, I'm not sure I can use a key. But I'll find out!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:24:03.433",
"Id": "969",
"Score": "0",
"body": "@XavierNodet: Anything which can be compared by a cmp parameter can be converted (even if tediously) to a key by simply wrapping it. With my use of the \"due_date\" attribute, I'm making some assumptions on how compare_by_due_date works, but if you give the code for compare_by_due_date (possibly in a SO question?), I'll try my hand at writing a key replacement for it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T20:00:57.003",
"Id": "977",
"Score": "0",
"body": "Thanks! SO question is here: http://stackoverflow.com/q/4879228/4177"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T11:44:09.317",
"Id": "547",
"ParentId": "533",
"Score": "7"
}
},
{
"body": "<p>Since you are writing Django code, you don't need lambdas at all (explanation below). In other Python code, you might want to use list comprehensions, as other commenters have mentioned. <code>lambda</code>s are a powerful concept, but they are extremely crippled in Python, so you are better off with loops and comprehensions.</p>\n\n<p>Now to the Django corrections.</p>\n\n<pre><code>tasks = Task.objects.all()\n</code></pre>\n\n<p><code>tasks</code> is a <code>QuerySet</code>. <code>QuerySet</code>s are lazy-evaluated, i.e. the actual SQL to the database is deferred to the latest possible time. Since you are using lambdas, you actually force Django to do an expensive <code>SELECT * FROM ...</code> and filter everything manually and in-memory, instead of letting the database do its work.</p>\n\n<pre><code>contexts_to_display = ...\n</code></pre>\n\n<p>If those contexts are Django model instances, then you can be more efficient with the queries and fields instead of separate methods:</p>\n\n<pre><code># tasks = Task.objects.all()\n# tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks) \n# tasks = filter(lambda t: not t.is_future(), tasks)\n# tasks = sorted(tasks, Task.compare_by_due_date)\nqs = Task.objects.filter(contexts__in=contexts_to_display, date__gt=datetime.date.today()).order_by(due_date)\ntasks = list(qs)\n</code></pre>\n\n<p>The last line will cause Django to actually evaluate the <code>QuerySet</code> and thus send the SQL to the database. Therefore you might as well want to return <code>qs</code> instead of <code>tasks</code> and iterate over it in your template.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T14:25:55.053",
"Id": "1360",
"Score": "0",
"body": "`Context` is indeed a model class, but tasks may have no context, and I want to be able to retrieve the set of all tasks that 'have a given context or no context'. But `context__in=[c,None]` does not work... Maybe 'no context' should actually be an instance of Context..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T14:26:45.067",
"Id": "1361",
"Score": "0",
"body": "Similarly, the date may be null, so I can't simply filter or order on the date..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T10:40:35.640",
"Id": "743",
"ParentId": "533",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "547",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:44:01.423",
"Id": "533",
"Score": "1",
"Tags": [
"python"
],
"Title": "Is there a better way than lambda to filter on attributes/methods of objects?"
} | 533 |
<p>I'm currently working on several projects for my company to help reduce the amount of calls we have to deal with so we can focus on higher priority task, such as server resource reduction, etc.</p>
<p>The first project on my list was to reduce the number of proxy issues a user has when migrating from an internal network to an external network such as home Internet.</p>
<p>I have come up with a Windows service idea where the service would be deployed from our servers and installed via a command. Once installed and started the service would monitor the connection states of all the network interface on the computer.</p>
<p>Upon a network interface change such as:</p>
<ul>
<li>Ethernet plugged out</li>
<li>IP changes</li>
<li>Interfaces enabled / disabled</li>
<li>etc</li>
</ul>
<p>the service would attempt to ping our <code>DomainController</code>. If the ping is a success, we will then check to see if the proxy settings for the machine are set. If not, we will automatically set them and enable them. If the ping is unsuccessful, we will disable the proxy.</p>
<p>The project is not fully complete but there is still a nice bit of code there to review.</p>
<p><strong>ProxyMonitor.cs</strong></p>
<pre><code>using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Reflection;
using System.Threading;
using System.Net.NetworkInformation;
namespace Serco.Services.ProxyMonitor
{
class ProxyMonitor : ServiceBase
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
if (System.Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "/install":
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "/uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase.Run(new ProxyMonitor());
}
}
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
}
/*
* Start the main service application
*/
private ManualResetEvent MainShutdownEvent = new ManualResetEvent(false);
private Thread MainThread;
private static EventLog EventManager = new EventLog();
public static string ProxyIp;
public ProxyMonitor()
{
EventManager.Source = ServiceConfiguration.ServiceName;
}
protected override void OnStart(string[] args)
{
ProxyIp = string.Concat(args);
MainThread = new Thread(MainWorkerThread);
MainThread.Name = "MainWorkerThread";
MainThread.IsBackground = true;
MainThread.Start();
}
private void MainWorkerThread()
{
EventManager.WriteEntry("Watching for ip: " + ProxyIp);
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);
}
public static void AddressChangedCallback(object Sender,EventArgs Args)
{
//try and ping the Proxy Server
Ping Ping = new Ping();
PingReply Reply = Ping.Send("secret.domain");
if (Reply.Status == IPStatus.Success)
{
/*
* Update Proxy Settings
*/
}
}
protected override void OnStop()
{
MainShutdownEvent.Set();
if(!MainThread.Join(3000))
{
// give the thread 3 seconds to stop
MainThread.Abort();
}
}
}
}
</code></pre>
<p><strong>ManagedInstallation.cs</strong></p>
<pre><code>using System;
using System.ServiceProcess;
using System.Configuration;
using System.ComponentModel;
using System.Configuration.Install;
namespace Serco.Services.ProxyMonitor
{
[RunInstaller(true)]
public class ManagedInstallation : Installer
{
public ManagedInstallation()
{
var ProcessInstaller = new ServiceProcessInstaller();
var ServiceInstaller = new ServiceInstaller();
//set the information and privileges
ProcessInstaller.Account = ServiceConfiguration.AccountType;
ProcessInstaller.Username = null;
ProcessInstaller.Password = null;
ServiceInstaller.DisplayName = ServiceConfiguration.DisplayName;
ServiceInstaller.StartType = ServiceConfiguration.StartType;
ServiceInstaller.Description = ServiceConfiguration.Description;
ServiceInstaller.ServiceName = ServiceConfiguration.ServiceName;
Installers.Add(ProcessInstaller);
Installers.Add(ServiceInstaller);
}
private ServiceController ServiceController = new ServiceController(ServiceConfiguration.ServiceName);
protected override void OnAfterInstall(System.Collections.IDictionary savedState)
{
base.OnAfterInstall(savedState);
ServiceController.Start();
}
}
}
</code></pre>
<p><strong>ServiceConfiguration.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceProcess;
namespace Serco.Services.ProxyMonitor
{
class ServiceConfiguration
{
public static string DisplayName
{
get { return "Proxy Monitor"; }
}
public static string ServiceName
{
get { return "ProxyMonitor"; }
}
public static string Description
{
get
{
return "ProxyMonitor is a helper developed to manage the state of the proxy for the employess whilst of the internal network.";
}
}
public static ServiceStartMode StartType
{
get{return ServiceStartMode.Automatic;}
}
public static ServiceAccount AccountType
{
get{return ServiceAccount.LocalSystem;}
}
}
}
</code></pre>
<p>The <code>ServiceConfiguration</code> class may be modified to populate from a local file depending on the deployment discussion I will have with my colleges.</p>
| [] | [
{
"body": "<p>Just a few points that came to mind as I was reading your code.</p>\n\n<ul>\n<li><p>It appears to me that the main thread terminates once the <code>NetworkChange.NetworkAddressChanged</code> event is hooked, in which case the thread is redundant as the event will be raised by another thread anyway.</p></li>\n<li><p><code>MainShutdownEvent</code> is created and 'set' but I don't see anything actually using it.</p></li>\n<li><p><code>NetworkChange.NetworkAddressChanged</code> is hooked but not unhooked, it won't matter much when the appdomain is unloaded on termination but I would just feel better if it was part of the standard 'shutdown' process in <code>OnStop()</code></p></li>\n<li><p>I don't like the empty <code>UnhandledException</code> event handler, if you are going to hook it I would suggest some form of logging. At a minimum you should use log such events to the event log via the <code>EventLog</code> property on <code>ServiceBase</code>.</p></li>\n<li><p>I'm not sure which thread will be used to rais the <code>NetworkChange.NetworkAddressChanged</code>, but I wouldn't rely on it being the same one as <code>OnStop()</code> so you should probably look at some form of locking/signaling to handle any situations where <code>OnStop()</code> is called while the event handler is running. It might not cause any real issues but I personally would want to play it safe. It might be interesting to temporarily add a long sleep into the event handler just to see what happens if it's busy when told to stop.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T09:56:37.110",
"Id": "600",
"ParentId": "536",
"Score": "7"
}
},
{
"body": "<p>I would recommend to look at <em>Exception Handling</em> in your code - there is nothing except for empty CurrentDomainExceptionHandler. However it's very crucial for such services to have a clear exception hierarchy and handling policy. There should be at least 2 types: </p>\n\n<ul>\n<li><p>Non-recoverable errors - if service couldn't start because of invalid configuration etc </p></li>\n<li><p>Recoverable errors - if you couldn't pong \"secret.domain\" because it's unavailable then should you proceed? How to deal with timeout exceptions? Should there be a queue with unproceeded requests or should they immediately be discarded? Should the size of the queue be configurable if you need it? If you want your service to work in 24x7 mode then you must have answers on these and few other questions about how to deal with unexpected situations.</p></li>\n</ul>\n\n<p>Another missing point is <em>Configuration</em>. Are you goint to rewrite your code and re-install service if \"secret.domain\" changes? Or if you need to increase timeout or even change display name for service? I would recommend to have a configuration file that can be re-read on every start. It would save you a lot time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T09:49:48.377",
"Id": "619",
"ParentId": "536",
"Score": "4"
}
},
{
"body": "<p>Consider using <a href=\"http://topshelf-project.com/documentation/getting-started/\" rel=\"nofollow\">TopShelf</a> to manage the whole install/uninstall/configure service task. </p>\n\n<p>This has the wonderful feature of allowing you to debug your code from the command line instead of having to attach to a windows service.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-03T23:57:57.193",
"Id": "1148",
"ParentId": "536",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T23:26:29.873",
"Id": "536",
"Score": "10",
"Tags": [
"c#",
"proxy"
],
"Title": "Windows service for monitoring network interface changes"
} | 536 |
<p>I've written an abstract class in C# for the purpose of random number generation from an array of bytes. The .NET class <code>RNGCryptoServiceProvider</code> can be used to generate this array of random bytes, for example.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyLibrary
{
/// <summary>
/// Represents the abstract base class for a random number generator.
/// </summary>
public abstract class Rng
{
/// <summary>
/// Initializes a new instance of the <see cref="Rng"/> class.
/// </summary>
public Rng()
{
//
}
public Int16 GetInt16(Int16 min, Int16 max)
{
return (Int16)(min + (Int16)(GetDouble() * (max - min)));
}
public Int32 GetInt32(Int32 min, Int32 max)
{
return (Int32)(min + (Int32)(GetDouble() * (max - min)));
}
public Int64 GetInt64(Int64 min, Int64 max)
{
return (Int64)(min + (Int64)(GetDouble() * (max - min)));
}
public UInt16 GetUInt16(UInt16 min, UInt16 max)
{
return (UInt16)(min + (UInt16)(GetDouble() * (max - min)));
}
public UInt32 GetUInt32(UInt32 min, UInt32 max)
{
return (UInt32)(min + (UInt32)(GetDouble() * (max - min)));
}
public UInt64 GetUInt64(UInt64 min, UInt64 max)
{
return (UInt64)(min + (UInt64)(GetDouble() * (max - min)));
}
public Single GetSingle()
{
return (Single)GetUInt64() / UInt64.MaxValue;
}
public Double GetDouble()
{
return (Double)GetUInt64() / UInt64.MaxValue;
}
public Int16 GetInt16()
{
return BitConverter.ToInt16(GetBytes(2), 0);
}
public Int32 GetInt32()
{
return BitConverter.ToInt32(GetBytes(4), 0);
}
public Int64 GetInt64()
{
return BitConverter.ToInt64(GetBytes(8), 0);
}
public UInt16 GetUInt16()
{
return BitConverter.ToUInt16(GetBytes(2), 0);
}
public UInt32 GetUInt32()
{
return BitConverter.ToUInt32(GetBytes(4), 0);
}
public UInt64 GetUInt64()
{
return BitConverter.ToUInt64(GetBytes(8), 0);
}
/// <summary>
/// Generates random bytes of the specified length.
/// </summary>
/// <param name="count">The number of bytes to generate.</param>
/// <returns>The randomly generated bytes.</returns>
public abstract byte[] GetBytes(int count);
}
}
</code></pre>
<p>Any suggestions for improvements would be welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:50:00.677",
"Id": "899",
"Score": "0",
"body": "What is the purpose of the interdependent get() methods?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:59:42.587",
"Id": "900",
"Score": "0",
"body": "@Michael: The overloads with `min`/`max` params require floating-point random numbers. They in turn require integral random numbers to generate. (I see no other way, since `BitConverter.GetDouble` would skew the distribution.)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T08:03:56.680",
"Id": "908",
"Score": "0",
"body": "Are you doing this as an exercise? The built-in random number generator already has this kind of functionality. So if this is just an exercise in interface design it can be reviewed. If this is a real attempt at providing a random number interface I think you have some more explaining to do before anybody can really provide any decent feedback. Note: Random number generation done correctly is a lot harder than you would think (i.e. it is very easy to screw up and get a bad distribution)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:10:45.383",
"Id": "913",
"Score": "0",
"body": "I would add a comment to `Get...` methods regarding min/max parameters, whether these values are inclusive or exclusive. It was never obvious for me in `System.Random` class."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T12:40:27.490",
"Id": "923",
"Score": "0",
"body": "@Snowbear: Yeah, I've added comments to my local version of the code. Will update soon. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T12:42:35.287",
"Id": "924",
"Score": "1",
"body": "@Martin York: The whole point of this is to provide an abstract contract for RNGs. `System.Random` does indeed provide this sort of functionality, but it is specific to an internal PNG (that has poor entropy). The idea is that implementations can derive from this class to implement specific RNG algorithms like the CSP one (RNGCryptoServiceProvider), Mersenne Twister, etc., simply by providing a generator for random bytes. The code above says nothing as to the random bytes are generates."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:20:25.803",
"Id": "929",
"Score": "0",
"body": "@Snowbear: the terms \"minimum\" and \"maximum\" are implicitly inclusive by the definition of the words. That said, it's never bad to add documentation and, to be fair, the word \"between\" can imply inclusive or exclusive behavior which can confuse the situation. Not that everyone does so, but from the English language perspective in general min/max should only be used for inclusive behavior. The previously more common terms \"upper bound\" and \"lower bound\" are more appropriate for varying exclusivity."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:39:14.877",
"Id": "932",
"Score": "0",
"body": "@TheXenocide: Thanks for your opinion, for me also min and max should be inclusive numbers. But MS has own opinion: http://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx - that is why I've added my comment."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:40:50.787",
"Id": "933",
"Score": "1",
"body": "@TheXenocide: Also looking on this code I suppose `maximum` is exclusive here ;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:25:06.677",
"Id": "970",
"Score": "0",
"body": "Interestingly, I've come across the *Math.NET Numerics* library after having posted this question, which seems to have a pretty nice abstract implementation of an RNG class. (Though not quite as complete, it looks sufficient.) It also includes a range of probability distribution sampling methods, which is very nice."
}
] | [
{
"body": "<p>If you're planning on placing this in a reusable library you should validate inputs (min > max throws an IndexOutOfRangeException, etc.) Also, you do not need to cast to double in the GetDouble method as the division implicitly returns a double and casting the first operand of the division in GetSingle still causes the division to return a double though you may be sacrificing some precision in the randomness as a result of sacrificing 32bits before you divide. </p>\n\n<p>Otherwise the code does seems as though it would be sufficient. Depending on the scope of your solution perhaps you want to consider min/max overloads for GetSingle and GetDouble and if you're really looking to be special maybe support for System.Numerics.BigInteger and System.Decimal?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:37:46.000",
"Id": "931",
"Score": "1",
"body": "Just thought of this one, and it's no biggie really, but perhaps you want to provide a virtual void GetBytes(byte[] buffer, int offset, int length) with a default implementation. It's a very common pattern in code that uses byte arrays and implementations may leverage their underlying APIs to make this more efficient (no unnecessary allocation/GC, no need for them to copy data from one array to another, etc)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:22:59.517",
"Id": "968",
"Score": "0",
"body": "@TheXenoicde: Your points are all good ones I think. I should indeed be throwing `ArgumentExceptions`s, and that overload for `GetBytes` would probably be handy too. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:11:14.490",
"Id": "548",
"ParentId": "538",
"Score": "3"
}
},
{
"body": "<p>I think the design is pretty good. A few comments:</p>\n\n<ul>\n<li><p>I'd rename the class to something a bit more descriptive, say <code>RandomGenerator</code>. Then when you implement the class you can declare it with <code>CspGenerator: RandomGenerator</code> or <code>MersenneGenerator: RandomGenerator</code> and it's obvious what the class does.</p></li>\n<li><p>Comment the <code>get()</code> methods. IMO all public elements should be documented. Get/set could be left out, but that is a matter of preference. In particular I'd like to know what kind of range <code>min</code> anf <code>max</code> is and is used for.</p></li>\n<li><p>Is <code>getBytes()</code> needed externally? If not, I would consider making it class-level rather than public.</p></li>\n</ul>\n\n<p>The formatting is good - even in Visual Studio I've seen it get messed up as code is refactored and changed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:32:45.337",
"Id": "930",
"Score": "1",
"body": "I concur with the class rename. Comments are always good and especially in reusable libraries, though I personally tend to forget to mention them when reviewing code, lol. Generally GetBytes is publicly available on random number generators."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:49:57.367",
"Id": "952",
"Score": "0",
"body": "I think “Rng” is one of the very few cases where an abbreviation can actually be safely used (this may not be such a commending reference but the .NET framework *does* use it, after all)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:21:51.423",
"Id": "967",
"Score": "0",
"body": "Thanks for the answer. I agree with commenting the `Get` methods; in fact I did that some time after I posted this. :) You may have a point about the name, but like Konrad Rudolph I believe that RNG is a very common/understandable acronym. I wasn't sure about the modifier for `GetBytes` either, but I can foresee potential usage cases, so it doesn't hurt to expose it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:40:02.780",
"Id": "971",
"Score": "2",
"body": "I think `GetBytes` is useful as a public method, for tasks too numerous to list (e.g. generating a key of some length, fuzz testing etc.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:16:44.113",
"Id": "550",
"ParentId": "538",
"Score": "8"
}
},
{
"body": "<p>I think using <code>GetDouble</code> to generate the other random numbers can create performance problems when the user needs efficient random numbers.</p>\n\n<p>Since <code>GetBytes</code> should return a uniform distribution anyway, can’t you bypass using floating-point numbers? See e.g. Java’s <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextInt%28int%29\"><code>Random.nextInt</code> implementation</a>.</p>\n\n<p>Something else, but this may be unnecessary and YAGNI for you: have you considered decoupling the RNG from the probability density function? At the moment your RNG directly supports generating uniformly distributed numbers from within a given range – but it supports no other distributions. This could be off-loaded into a separate <code>Distribution</code> class. For reference, <a href=\"http://www.boost.org/doc/libs/1_45_0/doc/html/boost_random/reference.html#boost_random.reference.distributions\">Boost.Random</a> does just that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:19:57.507",
"Id": "965",
"Score": "0",
"body": "Ah yes, good point about the implementation for ranges. For some reason using the modulo operator did not occur to me! Regarding distributions, random numbers have to be generated according to *some* distribution to start - uniform is as good (and simpler) than any other."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:42:19.340",
"Id": "976",
"Score": "0",
"body": "@Noldorin: re distribution: of course. I was merely stating that this assumption existed anyway, so it could as well be used to generate the ranges. But in fact such a distribution shouldn’t be taken as granted. For example, LCGs exhibit different weaknesses (such as repeating lower bits, or unevenly distributed upper bits) so using either modulo or division must take that into account. The Java implementation does, but then it knows what kind of weakness the generated bytes have. [Wikipedia](http://bit.ly/59nzh) has details (“Parameters in common use” table)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T17:14:04.367",
"Id": "1019",
"Score": "0",
"body": "@Noldorin, it's not just performance: it's uniformity of distribution, which becomes a lot harder to guarantee once doubles get involved. I agree with using something à la Java's nextInt(int n). Note in particular that nextInt calculates, effectively (1<<32)%n and uses it to avoid slight bias in favour of numbers smaller than that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T00:21:19.240",
"Id": "1053",
"Score": "0",
"body": "@Peter: Well yes, indeed. Funnily, I think the above code is how `System.Random` does it (haven't checked Reflector with it though). I agree though, it's not ideal, and could potentially introduce skew."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:46:57.683",
"Id": "557",
"ParentId": "538",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "550",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:39:38.673",
"Id": "538",
"Score": "12",
"Tags": [
"c#",
"random"
],
"Title": "Random Number Generator Class"
} | 538 |
<p>I have a small 10-liner function that writes some data to a file using an <code>std::ofstream</code>. I did not explicitly call <code>.close()</code> at the end of my function, but it failed code review with the reason that it is better to explicitly call it for style and verbosity reasons. I understand there is no harm in calling <code>.close()</code> explicitly, but does calling it explicitly just before a <code>return</code> statement indicate a lack of understanding or faith in RAII?</p>
<p>The C++ standard says:</p>
<blockquote>
<p>§27.8.1.2</p>
<p><code>virtual ~ basic_filebuf ();</code></p>
<p>[3] Effects: Destroys an object of <code>class basic_filebuf<charT,traits></code>. Calls <code>close()</code>.</p>
</blockquote>
<p>Am I justified in my argument that calling <code>.close()</code> at the end of a function is redundant and/or unnecessary?</p>
<pre><code>bool SomeClass::saveData()
{
std::ofstream saveFile(m_filename);
if (!saveFile.is_open())
return false;
saveFile << m_member1 << std::endl;
saveFile << m_member2 << std::endl;
saveFile.close(); // passed review only with this line
return true;
}
</code></pre>
<p>The function is only supposed to return <code>false</code> if the file could not be opened for writing.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T11:33:17.797",
"Id": "920",
"Score": "7",
"body": "If the reviewers need reassurance that close is called automatically, then C++ is probably not the best language choice. The \"verbosity\" reason is particularly alarming."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:16:24.613",
"Id": "927",
"Score": "2",
"body": "“it failed code review with the reason that it is better to explicitly call it for … *verbosity reasons* ” – Please explain that last bit, it doesn’t make any sense."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:11:20.037",
"Id": "944",
"Score": "0",
"body": "Obviously your reviewers' style conflict with the _standard_ design of the _standard_ library."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T02:34:48.173",
"Id": "990",
"Score": "3",
"body": "@Konrad: By verbosity, I mean that we are closing the file even knowing it will be closed anyway in the destructor, because it shows that we know we are done with it. In some instances, we have files open for a long time; so we have a rule that we close every stream explicitly."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T07:16:48.790",
"Id": "999",
"Score": "0",
"body": "Was this requirement added because *the other instance* had caused a bug which wasn't caught by the code review?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:21:31.080",
"Id": "1004",
"Score": "1",
"body": "@dreamlax: but how is verbosity ever an *advantage*? I agree that *explicitness* may be, and that this sometimes entails verbosity – but this is always a trade-off between the two. I have never seen a situation where verbosity would be an advantage in itself. That’s what I meant by “it doesn’t make any sense”."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:45:14.063",
"Id": "1006",
"Score": "0",
"body": "@rwong: I would imagine so. The question is, why is the variable lingering around when the stream is no longer needed? The scope of the variable should be limited, in my opinion, to represent more-or-less the timeframe of an open file. If the stream variable is lingering, it is probably more an indication that the function is far too long."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:51:58.613",
"Id": "1007",
"Score": "0",
"body": "@Konrad: I guess in some situations it is better to \"spell things out in full\" than to use more concise versions. For example, a few lines of nicely written code is often better than a clever-yet-esoteric one-liner. The rule is not so applicable in this particular case, however, and instead I think the actual reason is for explicitness."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T12:56:40.587",
"Id": "1011",
"Score": "0",
"body": "@dreamlax: \"because it shows that we know we are done with it\" .. I think it can be a good enough reason then. It also force you to think about when you are done with it. Maybe majority of the time it is not a concern but sometimes maybe it matter. What is your industry? I agree with the commenter that said this question would be better on SO though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-22T16:40:29.420",
"Id": "364928",
"Score": "0",
"body": "I [changed the title](/q/540/revisions) so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Feel free to give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-22T16:48:15.470",
"Id": "364929",
"Score": "0",
"body": "I believe your reviewers are wrong, but not for the reason you think. If the return value is supposed to be true for success, then it should return false if *any* of the file operations fail, not just the constructor. I've answered accordingly."
}
] | [
{
"body": "<p>I'm torn on this one. You are absolutely correct. However if a coding standard requires calling close() explicitly or it's a group people's consensus of doing that, there's not much you can do. If I were you, I would just go with the flow. Arguing such things is unproductive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T07:57:25.050",
"Id": "907",
"Score": "9",
"body": "The problem with small group consensus (i.e. development teams). It can often be wrong because the group is swayed by the loudest voice. For group consensus to work the group has to be large enough so that loud individuals can be counteracted by the correct decision of a lot of people (this is why SO works (loud people may get an initial vote up but eventually the correct answer usually get the votes (eventually)))."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T00:32:11.217",
"Id": "985",
"Score": "1",
"body": "@Martin: Nice nested parenthesis."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T13:51:15.383",
"Id": "6837",
"Score": "0",
"body": "@grokus I agree with Tux-D's sentiment. But, I don't believe in design/review by committee. If someone has the power to dictate these types of standards, they need to be shown another way or proven incorrect. The strategy for this will completely depend on the individual. The only thing that is going to happen in large meetings is arguing, and eventual increase in volume unti a mediator steps in and makes the decision for you. The best response to this is to construct an app in which .close() is called and throws. Show it kills the app. Then give them a choice, handle all errors or use RAII."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T04:22:11.317",
"Id": "541",
"ParentId": "540",
"Score": "10"
}
},
{
"body": "<p>Assuming that the fstream object is local to the function, I <em>would</em> tend to argue against this. People need to become accustomed to letting RAII do its job, and closing an fstream object falls under that heading. Extra code that doesn't accomplish something useful is <em>almost</em> always a poor idea.</p>\n\n<p><strong>Edit:</strong> Lest I be misunderstood, I would argue against this, not only for this specific case, but in general. It's not merely useless, but tends to obscure what's needed, and (worst of all) is essentially impossible to enforce in any case -- people who think only in terms of the \"normal\" exit from the function really need to stop and realize that the minute they added exception handling to C++, the rules changed in a fundamental way. You <em>need</em> to think in terms of RAII (or something similar) that <em>ensures</em> cleanup on exit from scope -- and explicitly closing files, releasing memory, etc., does <em>not</em> qualify.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T05:24:11.147",
"Id": "904",
"Score": "0",
"body": "Sorry, your assumption is correct, I forgot to mention that the fstream is local to the function."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T06:41:34.280",
"Id": "906",
"Score": "0",
"body": "I feel a little bit like asking \"what's the point in having destructors if we're doing the work manually...\" but I know it won't go far. I put the explicit call in just to satisfy the code review but I felt extremely reluctant."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T08:09:29.950",
"Id": "909",
"Score": "0",
"body": "@dreamlax: Its to give you flexibility. In most cases you don't care if the close() works or not (there is nothing you can do about it (except log the information)) so the destructor works perfectly. But in the situations were you do care you have the option of calling close() manually and checking to see if the close worked (and if not sending that 2AM SMS to support telling them the file system is down and needs immediate replacement)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:54:57.773",
"Id": "917",
"Score": "0",
"body": "re. Exceptions: The next (il)logical step is to put a try/catch construct in so that the unnecessary 'close()' function still gets called if an exception is throw...."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T02:54:26.020",
"Id": "991",
"Score": "0",
"body": "One reason that the project manager gave was that under stressed conditions where file handles are scarce, we need to close files as soon as we're done with them. By creating a rule that you close every stream, regardless of how trivial the function, you force the developer to think about the lifetime of the object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T13:46:34.890",
"Id": "6835",
"Score": "0",
"body": "@dreamlax This is why development organisations should prove a legitimate need to use C++ before starting. It is not a language an average team can utilize correctly. Hopefully you were able to stick your ground and convince them that RAII is a real concept in c++, which is where I think the bad code review is stemming from."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T04:52:45.043",
"Id": "542",
"ParentId": "540",
"Score": "41"
}
},
{
"body": "<h2>I would argue the exact opposite.</h2>\n\n<p>Explicitly closing a stream is probably not what you want to do. This is because when you <code>close()</code> the stream there is the potential for exceptions to be thrown. Thus when you explicitly close a file stream it is an indication you both want to close the stream and explicitly handle any errors that can result (exceptions or bad-bits) from the closing of the stream (or potentially you are saying if this fails I want to fail fast (exception being allowed to kill the application)).</p>\n\n<p>If you don't care about the errors (ie you are not going to handle them anyway). You should just let the destructor do the closing. This is because the destructor will catch and discard any exceptions thus allowing code to flow normally. When dealing with the closing of a file this is what you normally want to do (if the closing fails does it matter?).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:40:12.933",
"Id": "916",
"Score": "2",
"body": "\"if the closing fails does it matter?\" For output streams, I think it probably does, as the output may be buffered until the call to close()."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:17:36.250",
"Id": "928",
"Score": "2",
"body": "@Roddy: but you can’t do anything to stop this from failing. It may matter to report this failure, but no other meaningful action can be taken."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:11:55.360",
"Id": "938",
"Score": "4",
"body": "@Konrad. Agree you can't stop it failing (but that's true with many exceptions). If the user selects \"Save...\" in a GUI app, and close() throws, then notifying the user and allowing him to re-try the save (maybe to a different volume) is probably very meaningful..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:16:20.333",
"Id": "940",
"Score": "0",
"body": "@Roddy: granted. But something different: does this error actually occur? I can’t remember ever seeing something like that (except when you prematurely plug off a USB drive etc. …)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:57:26.103",
"Id": "942",
"Score": "0",
"body": "@Konrad. Well, I guess hardware problems, filesystem corruptions or, network problems, for that matter are the only obvious ones it. But, isn't that also the case with writing to a fstream? I'd still *consider* what would happen with exceptions while writing, even if I decide not to catch them."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:07:18.370",
"Id": "943",
"Score": "0",
"body": "@Konrad I guess that's why they're called _exceptions_"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:11:44.390",
"Id": "945",
"Score": "0",
"body": "@kizzx: No it’s not. What has this got to do with anything?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:17:40.233",
"Id": "946",
"Score": "0",
"body": "@Konrad: I thought you were responding to \"If the user selects \"Save...\" in a GUI app, and close() throws,\" I just assumed \"throws\" means \"throws exception\", no?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:33:27.880",
"Id": "948",
"Score": "0",
"body": "@kizz: yes. So what?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:19:57.327",
"Id": "954",
"Score": "2",
"body": "@Roddy: Of course there are times when it does matter and you want ot report it (GUI applications). then you would use close() explicitly and check the error. Weather you care or not is totally situational and only the dev can decide that at the point of usage. In the above example it does not sound like any checking was done and thus they did not care."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T07:51:25.353",
"Id": "544",
"ParentId": "540",
"Score": "74"
}
},
{
"body": "<p>There is a middle ground here. The reason the reviewers want that explicit <code>close()</code> \"as a matter of style and verbosity\" is that without it they can't tell just from reading the code if you meant to do it that way, or if you completely forgot about it and just got lucky. It's also possible their egos were bruised from failing to notice or remember, at least at first, that <code>close()</code> would be called by the destructor. Adding a comment that the destructor calls <code>close()</code> isn't a bad idea. It's a little gratuitous, but if your coworkers need clarification and/or reassurance now, there's a good chance a random maintainer a few years down the road will too, especially if your team doesn't do a lot of file I/O.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:28:04.193",
"Id": "73537",
"Score": "0",
"body": "There shouldn't be any \"just got lucky\" w.r.t. resources in C++. There should be \"just works\". That's how RAII is designed, and how it works when used properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T22:30:00.287",
"Id": "79072",
"Score": "5",
"body": "I disagree. This is C++, if you need a comment reminding you that an fstream will close on its own, then you're not a C++ programmer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T11:29:32.820",
"Id": "546",
"ParentId": "540",
"Score": "19"
}
},
{
"body": "<p>I believe you are asking two questions in one. Should you use exceptions or return values? Should you use RAII or not?</p>\n\n<p><strong>If exceptions are not permitted in your company</strong>, then <code>fstream::exceptions()</code> must be set globally for your project. And you have to interrogate the error flag too.</p>\n\n<p><strong>If RAII is not permitted in your company</strong>, then do not use C++. If you use RAII, then any exception thrown in the destructor will be swallowed. This sounds terrible and it is. However I agree with others that RAII is the way to go also because any error handling here is futile and creates unreadable code. This is because \"flush\" does not do what you may think it does. It instructs the operating system to do it on your behalf. The OS will do it when it believes it is convenient. Then, when the operating flushes (which may be a minute after your function returns) similar things may happen at the hardware level. The disk may have an SSD cache which it flushes to the rotating disks later (which may happen at night when it is less busy). At last the data ends on the disk. But the story does not end here. The data may have been saved correctly but the disk gets destroyed by whichever of the many possible causes. Hence if RAII is not transactionally safe enough for you, then you need to go to a lower API level anyway and even that will not be perfect. Sorry for being a party pooper here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T15:41:04.963",
"Id": "33181",
"ParentId": "540",
"Score": "7"
}
},
{
"body": "<p>I agree with Loki's answer: the difference between calling close explicitly, and letting the destructor call close, is that the destructor will implicitly catch (i.e. conceal) any exception thrown by close.</p>\n\n<p>The destructor must do this (not propagate exceptions) because it may be called if/while there is an exception already being thrown; and throwing a 2nd exception during a 1st exception is fatal (therefore, all destructors should avoid throwing exceptions).</p>\n\n<p>Unlike Loki I would argue that you do want to call close explicitly, precisely because you do want any exception from close to be visible. For example, perhaps the data is important and you want it written to disk; perhaps the disk is full, the <code><<</code> output operator is written to in-memory cache, and no-one notices that the disk is full until close implicitly calls flush. You're not allowed to return false because false is defined as meaning that the file couldn't be opened. IMO the only sane/safe thing you can do, then, is throw an exception.</p>\n\n<p>It's up to the caller to catch any exception; having no exception thrown should be a guarantee that close was successful and the data safely written to the O/S.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:28:59.447",
"Id": "43458",
"ParentId": "540",
"Score": "11"
}
},
{
"body": "<p>You also need to check that the write operations (<code><<</code>) succeeded. So instead of checking <code>is_open()</code>, just go through the whole series of operations, and check <code>failbit</code> at the end:</p>\n\n<pre><code>bool save_data() const\n{\n std::ofstream saveFile(m_filename);\n\n saveFile << m_member1 << '\\n'\n << m_member2 << '\\n';\n\n saveFile.close(); // may set failbit\n\n return saveFile;\n}\n</code></pre>\n\n<p>Also, unless there's a pressing need to flush each line as it's written, prefer to use <code>'\\n'</code> rather than <code>std::endl</code> (as I've shown), and let <code>close()</code> write it all in one go - that can make a significant difference to the speed, particularly when there's a large number of lines to be written.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-14T10:51:37.323",
"Id": "187548",
"ParentId": "540",
"Score": "3"
}
},
{
"body": "<p>After reading through the question and the answers I came to the conclusion that this is were comments can come into play. I had recently read this Q/A <a href=\"https://codereview.stackexchange.com/questions/90111/guessing-a-number-but-comments-concerning\">Guessing a number, but comments concerning</a> and the accepted answer gave me insight to the situation here. Use comments to explain the why, let the code explain the how. I can use your function similarly for each case as an example:</p>\n\n<pre><code>bool SomeClass::saveData() {\n std::ofstream saveFile(m_filename);\n\n if (!saveFile.is_open())\n return false;\n\n saveFile << m_member1 << std::endl; // I would replace `endl` with `'\\n'`\n saveFile << m_member2 << std::endl; // for performance reasons. \n\n // I intentionally want to close the file before the closing scope to\n // free up limited resources and to log potential exceptions and errors. \n saveFile.close(); \n return true;\n} \n\nbool SomeClass::saveData() {\n std::ofstream saveFile(m_filename);\n\n if (!saveFile.is_open())\n return false;\n\n saveFile << m_member1 << std::endl; // I would replace `endl` with `'\\n'`\n saveFile << m_member2 << std::endl; // for performance reasons. \n\n // Resources and errors are not a concern: relying on RAII no need\n // to call file.close();\n return true;\n}\n</code></pre>\n\n<p>Then with the appropriate type of commenting for valid reasons might serve you well. Then at least this way; one would know that you intended to call or omit it and why! Well written code is the how and shouldn't need comments. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-22T12:06:17.277",
"Id": "190196",
"ParentId": "540",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "544",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T04:00:41.190",
"Id": "540",
"Score": "70",
"Tags": [
"c++",
"stream",
"raii"
],
"Title": "Open, write and close a file"
} | 540 |
<p>How does this class to resize an image look?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.IO;
/*
* Resizes an image
**/
public static class ImageResizer
{
// Saves the image to specific location, save location includes filename
private static void saveImageToLocation(Image theImage, string saveLocation)
{
// Strip the file from the end of the dir
string saveFolder = Path.GetDirectoryName(saveLocation);
if (!Directory.Exists(saveFolder))
{
Directory.CreateDirectory(saveFolder);
}
// Save to disk
theImage.Save(saveLocation);
}
// Resizes the image and saves it to disk. Save as property is full path including file extension
public static void resizeImageAndSave(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)
{
Image thumbnail = resizeImage(ImageToResize, newWidth, maxHeight, onlyResizeIfWider);
thumbnail.Save(thumbnailSaveAs);
}
// Overload if filepath is passed in
public static void resizeImageAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)
{
Image loadedImage = Image.FromFile(imageLocation);
Image thumbnail = resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);
saveImageToLocation(thumbnail, thumbnailSaveAs);
}
// Returns the thumbnail image when an image object is passed in
public static Image resizeImage(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
// Prevent using images internal thumbnail
ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
// Set new width if in bounds
if (onlyResizeIfWider)
{
if (ImageToResize.Width <= newWidth)
{
newWidth = ImageToResize.Width;
}
}
// Calculate new height
int newHeight = ImageToResize.Height * newWidth / ImageToResize.Width;
if (newHeight > maxHeight)
{
// Resize with height instead
newWidth = ImageToResize.Width * maxHeight / ImageToResize.Height;
newHeight = maxHeight;
}
// Create the new image
Image resizedImage = ImageToResize.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
ImageToResize.Dispose();
return resizedImage;
}
// Overload if file path is passed in instead
public static Image resizeImage(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
Image loadedImage = Image.FromFile(imageLocation);
return resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:46:29.657",
"Id": "935",
"Score": "3",
"body": "PascalCase on the methods...since you stated no matter how nitty..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:47:07.283",
"Id": "936",
"Score": "0",
"body": "Thanks, yeah I need to work on my naming convention for sure, I'm just so used to leading lower"
}
] | [
{
"body": "<p><a href=\"http://c2.com/cgi/wiki?PascalCase\">PascalCase</a> the method names and method params if you are feeling overly ambitious.</p>\n\n<pre><code> // Set new width if in bounds\n if (onlyResizeIfWider)\n {\n if (ImageToResize.Width <= newWidth)\n {\n newWidth = ImageToResize.Width;\n }\n }\n</code></pre>\n\n<p>FindBugs barks in Java for the above behavior... refactor into a single if since you are not doing anything within the first if anyways...</p>\n\n<pre><code> // Set new width if in bounds\n if (onlyResizeIfWider && ImageToResize.Width <= newWidth)\n {\n newWidth = ImageToResize.Width;\n }\n</code></pre>\n\n<p>Comments here could be a bit more descriptive; while you state what the end result is I am still lost as to why that would resolve the issue.</p>\n\n<pre><code> // Prevent using images internal thumbnail\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); \n</code></pre>\n\n<p>Maybe something similar to what is stated on <a href=\"http://smartdev.wordpress.com/2009/04/09/generate-image-thumbnails-using-aspnetc/\">this blog</a>...</p>\n\n<pre><code> // Prevent using images internal thumbnail since we scale above 200px; flipping\n // the image twice we get a new image identical to the original one but without the \n // embedded thumbnail\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:14:41.697",
"Id": "939",
"Score": "1",
"body": "I wouldn't recommend pascal casing parameters even in an ambitious scenario as I've never once seen it in any common commercial or BCL code and the purpose of class and variable/param casing being different is to identify definitions from declarations. Due to compiler optimizations and condition short-circuiting both variations of the \"if (onlyResize...\" will evaluate to the same native code so, while I hold the same opinion on combining them, there are circumstances where readability or comparison to requirements may benefit and there's no harm either way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:09:08.827",
"Id": "552",
"ParentId": "549",
"Score": "12"
}
},
{
"body": "<p>In C# it's generally common practice to use Pascal Case in method names (so SaveImageToLocation instead of saveImageToLocation) and Camel Case in parameter names (so \"public static Image ResizeImage(Image imageToResize, ...\")</p>\n\n<p>RotateFlip can be a rather expensive operation just to clear an internal thumbnail. As far as the images are concerned, do you need to support vector images or will this generally be used for Bitmap (rasterized) images (this includes compressed variations like png, jpg, gif, etc.)? If you only plan to output Bitmaps then I suggest using the <a href=\"http://msdn.microsoft.com/en-us/library/334ey5b7\" rel=\"nofollow noreferrer\">Bitmap(Image original, int width, int height)</a> constructor which will take a source image and scale it, removing the need to do costly rotations. There are a number of methods to draw scaled images, some of which are much more efficient than others and each have varying pros and cons to using them, but the biggest advantage to GetThumbnailImage is use of embedded thumbnails.</p>\n\n<p>It is generally not good practice to dispose of a parameter so it may warrant a different pattern (returning an image and letting the calling code call image.Save(filename) at its own discretion isn't that terrible), but if you intend to leave it this way you should definitely comment it. Refer to <a href=\"https://stackoverflow.com/questions/788335/why-does-image-fromfile-keep-a-file-handle-open-sometimes\">this post</a> for information about loading images without locking files. The overloads that receive a file path instead of an Image object should wrap their loaded Image files in a using block (or try/finally+dispose) like so:</p>\n\n<pre><code>public static void ResizeImageAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)\n{\n Image thumbnail = null;\n\n try\n {\n using (Image loadedImage = Image.FromFile(imageLocation)) \n {\n thumbnail = resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);\n }\n saveImageToLocation(thumbnail, thumbnailSaveAs);\n }\n finally\n {\n if (thumbnail != null) thumbnail.Dispose();\n }\n}\n</code></pre>\n\n<p>Hope this helps :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:11:32.120",
"Id": "553",
"ParentId": "549",
"Score": "5"
}
},
{
"body": "<p>If you're using C# 3.0, you can use extension methods</p>\n\n<pre><code>// declare as\npublic static Image ResizeImage(this Image source, ...\n\n// use as \nImage myThumb = myImage.Resize(...);\n</code></pre>\n\n<p>Treating width differently than height seems inconsistent. </p>\n\n<p>Never dispose passed-in arguments in a public function (<code>ImageToResize</code>). The caller almost never expects this to happen. </p>\n\n<p>Do dispose the temporary local variables (<code>loadedImage</code>). No other code can do it, and it could cause a memory leak.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:05:26.697",
"Id": "561",
"ParentId": "549",
"Score": "8"
}
},
{
"body": "<p>Some observations about the abstractions represented. </p>\n\n<p>The main abstraction that has been coded is not general image resizing but rather custom thumbnail creation. The thumbnail idea appears several times in variable names and comments, plus the code logic supports this as well. I suggest renaming classes and methods to surface this intent more clearly. Also, I suggest separating into two classes the concerns that operate on an image from those that operate on an image file. The simple \"better thumbnailer\" makes a nice extension method where it will appear (both in intellisense and logically) alongside the built-in <code>Image.GetThumbnailImage</code> method.</p>\n\n<p>I did not change any logic (except for the last method in my answer since the orig seemed broken), though I did remove a few unhelpful comments (which clutter rather than illuminate, and some are just wrong, like referring to non-existent \"save as\" property in the static class). (I find that focusing on getting the abstractions right and using descriptive class and method names makes most comments unnecessary.)</p>\n\n<p>I don't know why the build-in thumbnail-creation ability of <code>Image</code> is insufficient, so without more knowledge at the moment I named \"your\" thumbnailer extension method <code>CreateBetterThumbnail</code> to distinguish it. It is a poor name, so I would suggest something more representative of your intent like <code>CreateTinyThumbnail</code> or <code>CreateMonochromeThumbnail</code> or whatnot (where those names are just examples to illustrate a point; I know you are not trying to do either of those things).</p>\n\n<pre><code>public static class ImageExtensions\n{\n public static Image CreateBetterThumbnail(this Image ImageToThumbnail, int newWidth, int maxHeight, bool onlyResizeIfWider)\n {\n // **Should make copy of incoming image if we are going to mess with it**\n\n // Prevent using images internal thumbnail\n // **I'd like to see a comment about why this works or is important**\n ImageToThumbnail.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n ImageToThumbnail.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n\n // Set new width if in bounds\n if (onlyResizeIfWider)\n {\n if (ImageToThumbnail.Width <= newWidth)\n {\n newWidth = ImageToThumbnail.Width;\n }\n }\n\n // Calculate new height\n int newHeight = ImageToThumbnail.Height * newWidth / ImageToThumbnail.Width;\n if (newHeight > maxHeight)\n {\n // Resize with height instead\n newWidth = ImageToThumbnail.Width * maxHeight / ImageToThumbnail.Height;\n newHeight = maxHeight;\n }\n\n Image thumbnail = ImageToThumbnail.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);\n\n // Clear handle to original file so that we can overwrite it if necessary\n ImageToThumbnail.Dispose();\n\n return thumbnail;\n }\n}\n\npublic static class ThumbnailFileCreator\n{\n // Saves the image to specific location, save location includes filename\n private static void saveImageToLocation(Image theImage, string saveLocation)\n {\n // Strip the file from the end of the dir\n string saveFolder = Path.GetDirectoryName(saveLocation);\n if (!Directory.Exists(saveFolder))\n {\n Directory.CreateDirectory(saveFolder);\n }\n // Save to disk\n theImage.Save(saveLocation);\n }\n\n public static void CreateThumbnailAndSave(Image ImageToThumbnail, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)\n {\n Image thumbnail = ImageToThumbnail.CreateBetterThumbnail(newWidth, maxHeight, onlyResizeIfWider);\n thumbnail.Save(thumbnailSaveAs);\n }\n\n public static void CreateThumbnailAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)\n {\n Image loadedImage = Image.FromFile(imageLocation);\n\n CreateThumbnailAndSave(loadedImage, newWidth, maxHeight, onlyResizeIfWider, thumbnailSaveAs);\n }\n}\n</code></pre>\n\n<p>Hope this is helpful!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T03:29:17.817",
"Id": "8870",
"ParentId": "549",
"Score": "1"
}
},
{
"body": "<p>You should be using the <code>using</code> statement to dispose of types which implement <code>IDisposable</code>, such as <code>Image</code> in this case:</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.IO;\n\n/*\n * Resizes an image\n **/\npublic static class ImageResizer\n{\n // Saves the image to specific location, save location includes filename\n private static void saveImageToLocation(Image theImage, string saveLocation)\n {\n // Strip the file from the end of the dir\n string saveFolder = Path.GetDirectoryName(saveLocation);\n if (!Directory.Exists(saveFolder))\n {\n Directory.CreateDirectory(saveFolder);\n }\n // Save to disk\n theImage.Save(saveLocation);\n }\n\n // Resizes the image and saves it to disk. Save as property is full path including file extension\n public static void resizeImageAndSave(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)\n {\n using (Image thumbnail = resizeImage(ImageToResize, newWidth, maxHeight, onlyResizeIfWider))\n {\n thumbnail.Save(thumbnailSaveAs);\n }\n }\n // Overload if filepath is passed in\n public static void resizeImageAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)\n {\n using (Image loadedImage = Image.FromFile(imageLocation))\n using (Image thumbnail = resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider))\n {\n saveImageToLocation(thumbnail, thumbnailSaveAs);\n }\n }\n\n // Returns the thumbnail image when an image object is passed in\n public static Image resizeImage(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider)\n {\n // Prevent using images internal thumbnail\n ImageToResize.RotateFlip(RotateFlipType.Rotate180FlipNone);\n ImageToResize.RotateFlip(RotateFlipType.Rotate180FlipNone);\n\n // Set new width if in bounds\n if (onlyResizeIfWider)\n {\n if (ImageToResize.Width <= newWidth)\n {\n newWidth = ImageToResize.Width;\n }\n }\n\n // Calculate new height\n int newHeight = ImageToResize.Height * newWidth / ImageToResize.Width;\n if (newHeight > maxHeight)\n {\n // Resize with height instead\n newWidth = ImageToResize.Width * maxHeight / ImageToResize.Height;\n newHeight = maxHeight;\n }\n\n // Create the new image\n Image resizedImage = ImageToResize.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);\n\n // Clear handle to original file so that we can overwrite it if necessary\n // Note from Jesse C. Slicer: I wouldn't do this here - let the calling code Dispose it.\n ////ImageToResize.Dispose();\n\n\n return resizedImage;\n }\n // Overload if file path is passed in instead\n public static Image resizeImage(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider)\n {\n using (Image loadedImage = Image.FromFile(imageLocation))\n {\n return resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-17T13:55:50.153",
"Id": "14779",
"ParentId": "549",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "552",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T14:13:43.487",
"Id": "549",
"Score": "12",
"Tags": [
"c#",
"asp.net",
"image"
],
"Title": "Image resizing class"
} | 549 |
<p>Here you go:</p>
<pre><code>#define abort(msg) (fprintf(stderr, msg) && *((char*)0))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:44:24.167",
"Id": "934",
"Score": "3",
"body": "I'm pretty sure others are going to agree with me on this, but this is way way too short to be considered for a code review."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:49:45.720",
"Id": "937",
"Score": "1",
"body": "Also, interesting that you want to cause a SIGSEGV instead of a SIGABRT."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:48:17.100",
"Id": "941",
"Score": "2",
"body": "@mark: I'm not so sure, I think a meaty one liner could count as a minimum size. Of course the answers are going to be more limited, but they could cover style and efficiency."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T07:21:50.970",
"Id": "1000",
"Score": "0",
"body": "Do you intend your code to be platform-independent? The correct implementation may be platform specific. At the end of that function, it may need to raise a certain signal, or some other system call."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T17:15:45.733",
"Id": "1116",
"Score": "0",
"body": "I think accessing the null pointer results in undefined behavior. On some operating systems it might silently return some value instead of crashing."
}
] | [
{
"body": "<h3>Non-standard interface to standard function</h3>\n\n<p>The obvious criticism of that implementation is that it has a different interface from what the C standard requires:</p>\n\n<blockquote>\n <p>§7.20.4.1 The abort function</p>\n \n <p>Synopsis</p>\n\n<pre><code>#include <stdlib.h>\nvoid abort(void);\n</code></pre>\n \n <p>Description</p>\n \n <p>The <code>abort</code> function causes abnormal program termination to occur, unless the signal\n <code>SIGABRT</code> is being caught and the signal handler does not return. Whether open streams\n with unwritten buffered data are flushed, open streams are closed, or temporary files are\n removed is implementation-defined. An implementation-defined form of the status\n unsuccessful termination is returned to the host environment by means of the function\n call <code>raise(SIGABRT)</code>.</p>\n \n <p>Returns</p>\n \n <p>The abort function does not return to its caller.</p>\n</blockquote>\n\n<h3>Unreliable implementation of 'crash'</h3>\n\n<p>There were systems, notoriously the DEC VAX, where accessing the memory at address 0 did not cause problems (until the programs that were written on the VAX were ported to other platforms that did abort).</p>\n\n<p>Dereferencing a null pointer is undefined behaviour - that means anything could happen, including 'no crash'.</p>\n\n<h3>Nitpicks in implementation</h3>\n\n<p>If, for some reason, <code>fprintf()</code> returns 0, your program will not abort. For example:</p>\n\n<pre><code>abort(\"\");\n</code></pre>\n\n<p>does not abort. It is also dangerous to use the string as the format string; you should use:</p>\n\n<pre><code>#define abort(msg) (fprintf(stderr, \"%s\\n\", msg) && *((char*)0))\n</code></pre>\n\n<p>It would be better to use a comma operator in place of the <code>&&</code>:</p>\n\n<pre><code>#define abort(msg) (fprintf(stderr, \"%s\\n\", msg), raise(SIGABRT))\n</code></pre>\n\n<p>Since the standard library could have defined a macro <code>abort()</code>, you should <code>#undef</code> it before defining it yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-16T01:29:39.850",
"Id": "8125",
"Score": "0",
"body": "maybe prefer `fputs`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-16T03:34:33.470",
"Id": "8126",
"Score": "0",
"body": "One reason not to use `fputs()` is that it does not add a newline to the string (unlike `puts()` - but that writes to stdout instead of stderr), so you'd have to call it twice, once with the user string and once with the newline. It seems simpler to call `fprintf()` once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-16T03:55:58.960",
"Id": "8127",
"Score": "0",
"body": "@Johnathan: I'm pretty sure that `fputs` followed by `fputc(stderr, '\\n')` (and then flush) would be far faster than `fprintf`. When you're reporting an error, you usually want to use the most trivial functions possible (lest data corruption prevent them from running) and `fputs` and `fputc` are much much simpler than `fprintf`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:06:02.677",
"Id": "555",
"ParentId": "551",
"Score": "16"
}
},
{
"body": "<p>My criticism is you are trying to abort via a crash:</p>\n\n<pre><code>*((char*)0))\n</code></pre>\n\n<p>This invokes undefined behavior. It does not necessarily invoke a crash (or termination).</p>\n\n<p>If you want to raise the abort signal do so explicitly:</p>\n\n<pre><code>raise(SIGABRT)\n</code></pre>\n\n<p>Also you are re-defing a system method using #define (I am relatively sure this is not allowed and causes undefined behavior though I can not quote chapter and verse).</p>\n\n<pre><code>#define abort(msg) \n</code></pre>\n\n<p>Also by doing this you need to search through all the source to find any current usage of abort. As this may clash with the new usage (or will the pre-processor be intelligent about it. The fact that I ask the question should make you worry let alone the answer).</p>\n\n<p>Why not define your own function with a slightly different name (this will also allow you to call the system abort).</p>\n\n<pre><code>#define abortWithMsg(msg) do { fprintf(stderr, msg); abort(); } while (false)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:35:28.120",
"Id": "559",
"ParentId": "551",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T14:39:53.470",
"Id": "551",
"Score": "3",
"Tags": [
"c",
"error-handling"
],
"Title": "abort() implementation"
} | 551 |
<p>Please have a look at these iterators which I use for my Sudoku solver. They behave slightly different from STL iterators and don't implement all functionality that would be needed to use them in a stl context. But the basic idea behind them was to clean up the code in the Sudoku program that makes heavy use of the three access patterns (row, col, block) that I implemented.</p>
<p>The most "important" iterator is the BlockIterator, since without that iterating over all nine fields in a block looked quite ugly. Iterating rows and columns wasn't that bad, but since I started writing the stuff I decided to create a complete set.</p>
<p>Some technical details:</p>
<p>The grid class holds an (evil) array of pointers to Field objects, that's one dimensional (I could have used a two dimensional array as well, but I often do it this way and feel quite comfortable with modulo operations). Maybe I will replace this with a vector later.</p>
<p>The grid class adds a few static functions to calculate offsets in the array based on row, col or block positions.</p>
<pre><code>class Grid {
public:
Grid();
Grid(std::string s);
class Iterator {
public:
Iterator(Grid* g) : grid(g), it(0){}
Field* operator*(){return field;}
void operator++(){
++it;
if(it < 9) field = calc_field();
else field = NULL;
}
protected:
virtual Field* calc_field() = 0;
Field* field;
Grid* grid;
int it;
};
class RowIterator : public Iterator {
public:
RowIterator(Grid* g, int row) : Iterator(g){
row_offset = row * size; //Grid::block_offset(block);
field = calc_field();
}
Field* calc_field(){
int field_index = row_offset + it;
return grid->field[field_index];
}
protected:
int row_offset;
};
class ColIterator : public Iterator {
public:
ColIterator(Grid* g, int col) : Iterator(g){
col_offset = col;
field = calc_field();
}
Field* calc_field(){
int field_index = it * size + col_offset;
return grid->field[field_index];
}
protected:
int col_offset;
};
class BlockIterator : public Iterator {
public:
BlockIterator(Grid* g, int block) : Iterator(g){
block_offset = Grid::block_offset(block);
field = calc_field();
}
Field* calc_field(){
int field_index = block_offset + ((it / 3) * size) + (it % 3);
return grid->field[field_index];
}
protected:
int block_offset;
};
RowIterator& row_iter(int row){return *(new RowIterator(this, row));}
ColIterator& col_iter(int col){return *(new ColIterator(this, col));}
BlockIterator& block_iter(int block){return *(new BlockIterator(this, block));}
(...)
static int block_offset(int block){return ((block / 3) * size * 3) + ((block % 3) * 3);}
protected:
Field* field[grid_size];
</code></pre>
<p>Sample usage:</p>
<p>This function is called, when I set a value in a field. It goes through all fields, that would possibly be influenced by this field (same row, col or block)</p>
<pre><code>void Field::do_exclusions(){
// row
for(Grid::RowIterator it = grid->row_iter(row); *it; ++it)
(*it)->set_excluded(value);
// col
for(Grid::ColIterator it = grid->col_iter(col); *it; ++it)
(*it)->set_excluded(value);
// block
for(Grid::BlockIterator it = grid->block_iter(block); *it; ++it)
(*it)->set_excluded(value);
}
</code></pre>
<p>So please tell me, if something like this would be "acceptable" (not to mention "best practices"), even if it somehow takes a very free view on the iterator concept.</p>
<p>And of course every idea how this could be improved is welcome.</p>
<p>PS: I tried to add a tag "iterator" but I'm not allowed for too few reputation.</p>
| [] | [
{
"body": "<p>In my first quick scan through, here are some things I want to bring up:</p>\n\n<ul>\n<li>If you are going to overload operators, do it the way the users of the language expect, or don't do it at all. I expect <code>operator++</code> to return something, not be a <code>void</code>.</li>\n<li>Does <code>block_offset</code> really need to be public?</li>\n<li>On that same note, do your actual concrete implementations of the iterators need to be public, since you have methods to create them that are public? Would it make sense for anyone to ever want to create them a different way?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:59:18.540",
"Id": "955",
"Score": "0",
"body": "The third point is excellent. It is pretty much never necessary to explicitly create an iterator, as they are always tied to the collection being iterated over. So, the implementation should be hidden."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:59:49.730",
"Id": "956",
"Score": "0",
"body": "Thanks Mark. I changed block_offset and the classes to protected. I thought the classes would need to be public, to allow them to be used outside of the Grid class. But code still compiles. block_offset was public, because before I implemented the iterators, I used it everywhere for the purpose to \"manually\" iterate the fields."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:02:49.147",
"Id": "957",
"Score": "0",
"body": "The iterator types themselves need to be public if you want to [create variables of those types](http://codepad.org/L9zlqIpF). @Michael: The for loop code in the question needs them to be public, since it doesn't appear Field is a friend of Grid."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:04:53.153",
"Id": "958",
"Score": "0",
"body": "I took the operator from some online sample. I will have a look at Stroustrup or some other source to see how to implement them properly. I didn't think much about returning anything, since at least here I only need the incremental functionality."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:06:23.947",
"Id": "959",
"Score": "0",
"body": "@Fred: At the moment they're used only by the grid class and by the Field class (which is declared friend). I will adjust that if I need to use them elsewhere."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:08:01.353",
"Id": "960",
"Score": "2",
"body": "@Thorsten: They only need to be public if you want to explicitly reference them as a type, otherwise you can use the abstract base. With regards to operator++, here is a good resource: http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.14"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:12:02.850",
"Id": "961",
"Score": "0",
"body": "@Fred: Do they need to be public if it returned an `Iterator` rather than a `RowIterator` etc.?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:18:40.753",
"Id": "963",
"Score": "0",
"body": "@Michael: You can't return the abstract type Iterator by value. So Iterator doesn't need to be public unless you wanted a pointer or reference to it (instead of a non-pointer, non-reference variable), but for the concrete derived classes, creating variables applies (as in my previous link). I would simply make them public, as hiding them serves no purpose."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:19:18.463",
"Id": "964",
"Score": "0",
"body": "btw: Should I adjust the code in my question to the changes I made thanks to your hints? Or should I leave it as in my first edit for reference?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:46:54.173",
"Id": "560",
"ParentId": "558",
"Score": "9"
}
},
{
"body": "<p>There is a memory leak in <code>Grid::row_iter()</code>, et al. Why use <code>new</code> in this case? I'd prefer</p>\n\n<pre><code>RowIterator row_iter(int row){return RowIterator(this, row);}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-02T20:26:58.230",
"Id": "1944",
"Score": "0",
"body": "Thanks for pointing that out. I use those iterators only at a few places in the program. So I didn't notice this yet."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-02T20:16:47.237",
"Id": "1098",
"ParentId": "558",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "560",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:26:42.450",
"Id": "558",
"Score": "15",
"Tags": [
"c++",
"iterator",
"sudoku"
],
"Title": "Sudoku Grid special purpose Iterators"
} | 558 |
<p>I have a class that spawns threads to process data. I am working on instrumentation code. When the process is started, <code>time = System.currentTimeMillis();</code> When it completes, <code>time = System.currentTimeMillis() - time;</code> I have a method to retrieve this time:</p>
<pre><code>/**
* Get the time taken for process to complete
*
* @return Time this process has run if running; time it took to complete if not
*/
public long getRunTime() {
return processRunning? System.currentTimeMillis() - time : time;
}
</code></pre>
<p>Is this a clear use of the ternary operator? Is my <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html" rel="nofollow noreferrer">javadoc</a> comment clear?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T03:03:11.907",
"Id": "992",
"Score": "3",
"body": "should document your units"
}
] | [
{
"body": "<p>It appears that the method sometimes returns a timestamp (<code>time</code>) and sometimes it returns a duration (difference between timestamps) (assuming that <code>time</code> is always a timestamp - if not, then this issue simply moves to <code>time</code> having a dual definition).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:26:45.140",
"Id": "974",
"Score": "3",
"body": "What about `processRunning? System.currentTimeMillis() - startTime : completedTime - startTime;`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:30:48.960",
"Id": "975",
"Score": "1",
"body": "Works for me, as does `processRunning ? System.currentTimeMillis() - startTime : runTime;`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:23:55.380",
"Id": "563",
"ParentId": "562",
"Score": "4"
}
},
{
"body": "<p>Since the method has a return value even if the code is not finished processing the first line of your javadoc ought not read \"Get the time taken for process to complete\" but perhaps rather \"Get the current or total processing time\" or something of that nature? I also agree with Bert F's comment, but if there were clear comments explaining the behavior and you don't intend on exposing start and end times individually then there's no reason to waste an extra variable; you can either keep the code as it is and add comments or optionally get rid of the boolean \"processRunning\" and instead use your completedTime/runTime variable to establish the fact that it's still running. All minor gripes, all in all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:55:09.177",
"Id": "565",
"ParentId": "562",
"Score": "5"
}
},
{
"body": "<p>I have no problem the ternary operator.</p>\n\n<p>But it is hard to tell that the result is what the comments is saying. Without having a context on what time is (which is a bad variable name) it is hard to understand the result of the function.</p>\n\n<p>time: Bad variable name. Time of what?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T20:33:53.490",
"Id": "566",
"ParentId": "562",
"Score": "6"
}
},
{
"body": "<p>It is a matter of style and taste but I'd rather go with</p>\n\n<pre><code>public long getRunTime() {\n if(processRunning)\n return System.currentTimeMillis() - time; \n\n return time;\n}\n</code></pre>\n\n<p>I just think this reads easier, and its easier to comment this. Now set me on fire for multiple return statements :D</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T21:14:28.593",
"Id": "1649",
"Score": "0",
"body": "Actually, I don't have a problem with this style. I do have a problem with multiple exit points spread throughout the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T08:03:57.183",
"Id": "12785",
"Score": "0",
"body": "Looks a little odd without the `else`, IMHO."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T13:22:24.657",
"Id": "898",
"ParentId": "562",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "565",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-02T19:14:50.720",
"Id": "562",
"Score": "8",
"Tags": [
"java",
"multithreading",
"datetime"
],
"Title": "Spawning threads to process data"
} | 562 |
<p>I am learning clojure and decided to start out by trying to write a solution to a fairly simple algorithm, reservoir sampling. As I stated, I am learning clojure specifically and problem solving in a functional language in general. Can someone please take a look at my code and critique it on it's "clojureness". Am I using the right idiomatic conventions, is there a way that performs better (and why), formatting, anything really.</p>
<pre><code>(defn sample-seq [size data]
(loop [sample (transient (vec (take size data)))
idx size
data (drop size data)]
(if (empty? data)
(persistent! sample)
(let [rand-num (rand-int idx)
new-sample (if (< rand-num size)
(assoc! sample rand-num (first data))
sample)]
(recur new-sample (inc idx) (rest data))))))
(println (sample-seq 4 [2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0]))
</code></pre>
| [] | [
{
"body": "<p>I think your code is pretty readable and looks like idiomatic enough Clojure code¹. So from a readability standpoint your code seems fine. However performing <code>assoc</code> on a vector of length <code>n</code> takes <code>O(log n)</code> time, so your runtime will be in <code>O(n log n)</code> as opposed to <code>O(n)</code>, which an imperative implementation would be in.</p>\n\n<p>However there's not much you can do about this other than perhaps using java arrays imperatively, but that would be very unidiomatic Clojure code. And <code>O(n log n)</code> isn't that bad (definitely not as bad as the <code>O(n^2)</code> I incorrectly claimed before).</p>\n\n<p>(Note that my previous note about transients was wrong as <code>assoc!</code> on a transient vector has the same runtime complexity as on a persistent vector).</p>\n\n<hr>\n\n<p>¹ Usually you'd avoid index-based loops wherever possible, but the nature of the algorithm makes that pretty much impossible here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T10:09:25.797",
"Id": "1009",
"Score": "2",
"body": "@MGoDave: if this answer was useful, then you should probably up-vote it to thank @sepp2k..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-19T23:32:16.820",
"Id": "3936",
"Score": "2",
"body": "Note that the log factor in clojure's vectors is large: assoc is `O(log32 n)`. For any size of integer that fits in your computer, this is effectively constant."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T00:10:56.150",
"Id": "577",
"ParentId": "568",
"Score": "11"
}
},
{
"body": "<p>sepp2k's critique is incorrect - <code>assoc</code> on a vector takes <code>O(log n)</code> time not <code>O(n)</code> time because Clojure uses persistent vectors. You should avoid using <code>assoc!</code> because it is Clojure style to avoid needless destructive behavior.</p>\n\n<p>For more on persistent vectors see:\n<a href=\"http://blog.higher-order.net/2009/02/01/understanding-clojures-persistentvector-implementation/\" rel=\"nofollow\">http://blog.higher-order.net/2009/02/01/understanding-clojures-persistentvector-implementation/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T11:09:26.303",
"Id": "1581",
"Score": "1",
"body": "Damn, sorry about that. I corrected my answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T22:13:25.407",
"Id": "845",
"ParentId": "568",
"Score": "1"
}
},
{
"body": "<p>It's a bit unfortunate that the reservoir sampling algorithm is funadmentally imperative. If squeezing the last bit of performance out of it is important to you, I'd <em>try</em> using a Java Array internally. (I say try, you'd want to actually time it to see if you'd actually gained any performance.)</p>\n\n<p>The only other performance tip I'd try is to replace <code>idx size</code> with <code>idx (int size)</code> which should guarantee the type internally.</p>\n\n<p>I wouldn't worry about using transients. The Clojure source code uses them all of the time for the exact purpose you have here. Pods are likely to make the code simpler when they drop. Finally, although Kevin L is definitely correct about assoc being an O(log n) operation, I wouldn't guarantee that was also true of transient vectors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-12T18:02:06.403",
"Id": "3411",
"ParentId": "568",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "577",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T21:25:51.983",
"Id": "568",
"Score": "13",
"Tags": [
"functional-programming",
"clojure"
],
"Title": "Reservoir Sampling in Clojure"
} | 568 |
<p>I implemented a solution to <a href="https://codegolf.stackexchange.com/questions/339/binary-tree-encoding">this coding challenge</a> on the Code Golf. I have decent experience with C/C++, but it's been a while since I've used them extensively.</p>
<pre><code>#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// Prototypes
struct BTnode;
struct BTnode * bt_add_left(struct BTnode * node, int data);
struct BTnode * bt_add_right(struct BTnode * node, int data);
int bt_depth(struct BTnode * tree);
int bt_encode_preorder(int * list, struct BTnode * tree, int index);
struct BTnode * bt_node_create(int data);
int bt_node_delete(struct BTnode * node);
void bt_print_preorder(struct BTnode * tree);
int * encode(struct BTnode * tree);
struct BTnode * decode(int * list);
// Binary tree node
struct BTnode
{
int data;
struct BTnode *left, *right;
};
// Add node to this node's left
struct BTnode * bt_add_left(struct BTnode * node, int data)
{
struct BTnode * newnode = bt_node_create(data);
node->left = newnode;
return newnode;
}
// Add node to this node's right
struct BTnode * bt_add_right(struct BTnode * node, int data)
{
struct BTnode * newnode = bt_node_create(data);
node->right = newnode;
return newnode;
}
// Determine depth of the tree
int bt_depth(struct BTnode * tree)
{
int depth;
int leftdepth = 0;
int rightdepth = 0;
if( tree == NULL ) return 0;
if( tree->left != NULL )
leftdepth = bt_depth(tree->left);
if( tree->right != NULL )
rightdepth = bt_depth(tree->right);
depth = leftdepth;
if(rightdepth > leftdepth)
depth = rightdepth;
return depth + 1;
}
// Recursively add node values to integer list, using 0 as an unfolding sentinel
int bt_encode_preorder(int * list, struct BTnode * tree, int index)
{
list[ index++ ] = tree->data;
// This assumes the tree is complete (i.e., if the current node does not have
// a left child, then it does not have a right child either)
if( tree->left != NULL )
{
index = bt_encode_preorder(list, tree->left, index);
index = bt_encode_preorder(list, tree->right, index);
}
// Add sentinel
list[ index++ ] = 0;
return index;
}
// Allocate memory for a node
struct BTnode * bt_node_create(int data)
{
struct BTnode * newnode = (struct BTnode *) malloc(sizeof(struct BTnode));
newnode->left = NULL;
newnode->right = NULL;
newnode->data = data;
return newnode;
}
// Free node memory
int bt_node_delete(struct BTnode * node)
{
int data;
if(node == NULL)
return 0;
data = node->data;
if(node->left != NULL)
bt_node_delete(node->left);
if(node->right != NULL)
bt_node_delete(node->right);
free(node);
return data;
}
// Print all values from the tree in pre-order
void bt_print_preorder(struct BTnode * tree)
{
printf("%d ", tree->data);
if(tree->left != NULL)
bt_print_preorder(tree->left);
if(tree->right != NULL)
bt_print_preorder(tree->right);
}
// Decode binary tree structure from a list of integers
struct BTnode * decode(int * list)
{
struct BTnode * tree;
struct BTnode * nodestack[ list[0] ];
int i,j;
// Handle trivial case
if( list == NULL ) return NULL;
tree = bt_node_create( list[1] );
nodestack[ 1 ] = tree;
j = 1;
for(i = 2; i < list[0]; i++)
{
if( list[i] == 0 )
{
//printf("popping\n");
j--;
}
else
{
if( nodestack[j]->left == NULL )
{
//printf("Adding %d to left of %d\n", list[i], nodestack[j]->data);
nodestack[ j+1 ] = bt_add_left(nodestack[j], list[i]);
j++;
}
else
{
//printf("Adding %d to right of %d\n", list[i], nodestack[j]->data);
nodestack[ j+1 ] = bt_add_right(nodestack[j], list[i]);
j++;
}
}
}
return tree;
}
// Encode binary tree structure as a list of integers
int * encode(struct BTnode * tree)
{
int maxnodes, depth, length;
int * list;
int j;
// Handle trivial case
if(tree == NULL) return NULL;
// Calculate maximum number of nodes in the tree from the tree depth
maxnodes = 1;
depth = bt_depth(tree);
for(j = 0; j < depth; j++)
{
maxnodes += pow(2, j);
}
// Allocate memory for the list; we need two ints for each value plus the
// first value in the list to indicate length
list = (int *) malloc( ((maxnodes * 2)+1) * sizeof(int));
length = bt_encode_preorder(list, tree, 1);
list[ 0 ] = length;
return list;
}
int main()
{
struct BTnode * tree;
struct BTnode * newtree;
int * list;
int i;
/* Provided example
5
/ \
3 2
/ \
2 1
/ \
9 9
*/
tree = bt_node_create(5);
bt_add_left(tree, 3);
struct BTnode * temp = bt_add_right(tree, 2);
bt_add_right(temp, 1);
temp = bt_add_left(temp, 2);
bt_add_left(temp, 9);
bt_add_right(temp, 9);
printf("T (traversed in pre-order): ");
bt_print_preorder(tree);
printf("\n");
list = encode(tree);
printf("T (encoded as integer list): ");
for(i = 1; i < list[0]; i++)
printf("%d ", list[i]);
printf("\n");
newtree = decode(list);
printf("T' (decoded from int list): ");
bt_print_preorder(newtree);
printf("\n\n");
// Free memory
bt_node_delete(tree);
bt_node_delete(newtree);
free(list);
return 0;
}
</code></pre>
<p>How could my program be improved? I'm thinking mostly in terms of clarity/readability, maintainability, and reusability, but I also welcome any comments about my implementation of the data structures and any possible improvements in terms of performance or correctness.</p>
| [] | [
{
"body": "<p>I only have a minute before running out the door, so here's the first thing I saw:</p>\n\n<ul>\n<li>Its good practice to set your pointers to <code>NULL</code> after you free them. Just as you are testing to ensure its not set to <code>NULL</code> since you do that upon creation, you should do that when deleting.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T22:03:24.867",
"Id": "25244",
"Score": "0",
"body": "It's considered good practice *in some circles* to set pointers to `NULL` after freeing them. But in other equally valid circles, it's considered *bad* practice to assign anything to a variable which is \"dead\" at the point of the assignment. Some compilers and static analyzers will even warn about dead writes. So, various people's mileage varies on this one. Personally, I agree with Daniel's original code, and disagree with Mark. But I've worked in places that agree with Mark."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T21:33:01.317",
"Id": "571",
"ParentId": "569",
"Score": "6"
}
},
{
"body": "<h3>In int bt_depth(struct BTnode * tree)</h3>\n\n<p>Too many different checks for NULL.<br>\nYou only need to check once. The call to bt_depth() on the left and right nodes will perform there own explicit checks don't try and pre optimize.</p>\n\n<pre><code>int bt_depth(struct BTnode * tree)\n{\n if( tree == NULL ) return 0;\n int leftdepth = bt_depth(tree->left);\n int rightdepth = bt_depth(tree->right);\n\n return max(leftdepth, rightdepth) + 1;\n}\n</code></pre>\n\n<h3>In int bt_encode_preorder(int * list, struct BTnode * tree, int index)</h3>\n\n<p>You are using tree without check for NULL tree</p>\n\n<pre><code>list[ index++ ] = tree->data;\n</code></pre>\n\n<p>You are also doing a recursive call without checking.<br>\nAt some point you may end up hitting a NULL and trying to de-reference it.</p>\n\n<pre><code>if( tree->left != NULL )\n{\n index = bt_encode_preorder(list, tree->left, index);\n index = bt_encode_preorder(list, tree->right, index); // tree->right may be NULL!!!!\n}\n</code></pre>\n\n<h3>In int bt_node_delete(struct BTnode * node)</h3>\n\n<p>This is note a node delete this is a full tree delete.<br>\nIt should be named appropriately.</p>\n\n<h3>In void bt_print_preorder(struct BTnode * tree)</h3>\n\n<p>It is easier just to check if the current node is NULL.<br>\nThe always print left and right nodes.</p>\n\n<pre><code>void bt_print_preorder(struct BTnode * tree)\n{\n if (tree == NULL) return;\n\n printf(\"%d \", tree->data);\n bt_print_preorder(tree->left);\n bt_print_preorder(tree->right);\n}\n</code></pre>\n\n<h3>In encode(struct BTnode * tree)</h3>\n\n<pre><code> // Calculate maximum number of nodes in the tree from the tree depth\n maxnodes = 1;\n depth = bt_depth(tree);\n for(j = 0; j < depth; j++)\n {\n maxnodes += pow(2, j);\n }\n</code></pre>\n\n<p>This is the only use of bt_depth(). Rather than do this why not just have a function called bt_count_nodes(BTnode* tree) that actual counts the nodes (bt_depth actually traverses all the nodes anyway (why not count them instead of the depth).</p>\n\n<h3>In struct BTnode * decode(int * list)</h3>\n\n<p>I can quite work out if this is correct without running it. This is a bad sign that the code could do with simplification.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T22:06:57.390",
"Id": "25245",
"Score": "0",
"body": "Loki pointed out redundant NULL-checks in `bt_depth`; the same redundant checks also appear in `bt_node_delete`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T21:37:54.797",
"Id": "573",
"ParentId": "569",
"Score": "16"
}
},
{
"body": "<p>I recommend three improvements, one major and two minor.</p>\n\n<p>The minor one first: Don't pad out with spaces to horizontally align tokens. There's nothing wrong with doing it, it'll just end up taking time to keep everything aligned, or you'll end up not bothering (because your in a hurry perhaps) and have inconsistent alignment.</p>\n\n<p>Secondly, typedef your structure:</p>\n\n<pre><code>typedef struct BTnode_def\n{\n int data;\n struct BTnode_def *left, *right;\n} BTnode;\n</code></pre>\n\n<p>so you can just use <code>BTnode</code> instead of <code>struct BTnode</code>.</p>\n\n<p>The major one: Don't use prototypes when you can use the function/structure itself as the prototype. You can get rid of the whole prototype section in your code. You'll need to move <code>bt_node_create</code> up a bit though. This will decrease maintenance time - when you change a function's parameters / return value, you only need to do it once.</p>\n\n<p>Oh, and I've just noticed that there appears to be a few C++ features in your code, so it's not pure C code.</p>\n\n<p>UPDATE</p>\n\n<p>I've removed the prefixed underscore (I actually don't do that normally). I'm not sure about the comment mentioning the namespace thing as C doesn't have namespaces.</p>\n\n<p>As for C++ features (I'm not up to date with the C specification so some of these may be in the latest spec):</p>\n\n<ul>\n<li>Single line comments are C++</li>\n<li>Declarations at any point in the code are C++, C requires declarations to be at the start of the block, i.e. after a <code>{</code>.</li>\n</ul>\n\n<p>ANOTHER UPDATE</p>\n\n<p>This is a personal preference, but I like to put the point <code>*</code> next to the symbol without a white space:</p>\n\n<pre><code>// Instead of this\nBTNode * bt_node_create (...);\n// I like\nBTNode *bt_node_create (...);\n</code></pre>\n\n<p>which, for me, makes it quicker to differentiate between multiplication and pointer dereferences:</p>\n\n<pre><code>a * func (); // an expression: a times return value of func\na *func (); // a declaration: func returns a pointer to type a\n</code></pre>\n\n<p>I know that the context of the above would disambiguate between the two, but that requires extra parsing by my brain of the adjacent code, and the less my brain has to do the better (it is an old brain after all and not as good as the ones these young people on here have ;-) ).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T01:22:40.527",
"Id": "986",
"Score": "0",
"body": "Which features are those? I compiled with cc and gcc, and I was under the impression that those compilers didn't support any C++ features."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T01:25:13.693",
"Id": "987",
"Score": "0",
"body": "Don't put the _ before BTNode. This makes the identifier clash with the reserved identifiers. Also struct and typedef identifiers do not share the same namespace so just call it BTnode in both cases."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T01:42:19.453",
"Id": "988",
"Score": "1",
"body": "@Daniel Standage: I like the horizontal white space. I always do that I think it makes the code easier to read. Don;t be scared of lots of white space."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T19:19:59.983",
"Id": "1022",
"Score": "0",
"body": "C99 supports those new features. It also supports the `const` keyword. My understanding is that after C++ came out, some of the non-OO features were incorporated into the C standard."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T20:54:07.173",
"Id": "1026",
"Score": "0",
"body": "I find it nice when things line up horizontally, but recognize that it's seldom worth the effort because programming/editing tools have no concept of how to do such formatting. I've often wished for a program editor which would allow format-related markup in a fashion that was transparent to the compiler, but I'm unaware of any."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T00:01:48.530",
"Id": "576",
"ParentId": "569",
"Score": "4"
}
},
{
"body": "<p>A couple things in addition to the suggestions made already:</p>\n\n<ul>\n<li>As @Martin said, <code>bt_node_delete</code> deletes a branch of the tree. I think a good term for that may be \"prune\".</li>\n<li><ol>\n<li><code>list = (int *) malloc( ((maxnodes * 2)+1) * sizeof(int));</code> </li>\n<li><code>list = (int *) malloc( ((maxnodes * 2) + 1) * sizeof(int) );</code></li>\n<li><code>list = (int *) malloc(((maxnodes * 2) + 1) * sizeof(int));</code><br>\nI prefer #3, but #2 is more consistent with spacing in the style you gave.</li>\n</ol></li>\n<li>Place your pointer operators with the symbol it modifies:\n<ol>\n<li><code>struct BTnode * decode(int * list)</code></li>\n<li><code>BTnode *decode(int *list)</code></li>\n</ol></li>\n</ul>\n\n<p>Personally I don't like the convention of putting spaces inside parenthesis and square brackets ( statement ). I think it is unnecessary whitespace that is harder to maintain if you need to change the statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T00:40:40.173",
"Id": "578",
"ParentId": "569",
"Score": "2"
}
},
{
"body": "<p>Although it won't fail often, especially not in toy programs, it is still a good idea to check that <code>malloc()</code> (and <code>realloc()</code> and <code>calloc()</code> when you use them) haven't returned a null pointer. And, when you use <code>realloc()</code>, you do not assign the result to the variable passed as the first argument. That is, do <em>not</em> use:</p>\n\n<p><s></p>\n\n<pre><code>ptr = realloc(ptr, newsize);\n</code></pre>\n\n<p></s></p>\n\n<p>Use:</p>\n\n<pre><code>newptr = realloc(oldptr, newsize);\n</code></pre>\n\n<p>An alternative that is often sufficient is to use a cover function (<code>emalloc()</code> and <code>xmalloc()</code> are both used for the purpose) that guarantees not to return a null pointer.</p>\n\n<pre><code>void *emalloc(size_t nbytes)\n{\n void *ptr = malloc(nbytes);\n if (ptr == 0)\n abort();\n return(ptr);\n}\n</code></pre>\n\n<p>You can use more elegant mechanisms than <code>abort()</code> to report the error.\nUse symmetric cover functions for <code>realloc()</code>, <code>calloc()</code> and <code>free()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T05:15:51.177",
"Id": "579",
"ParentId": "569",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "573",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T21:26:15.803",
"Id": "569",
"Score": "12",
"Tags": [
"c",
"tree"
],
"Title": "Binary tree encoding"
} | 569 |
<p>I'm trying to learn a little bit about functional programming and as my tool I chose F# since I'm a .NET developer and the environment is more natural to me.</p>
<p>In one of my pet projects I'm dealing with dates, so I created a function to get the last date where a given week day occurred. For example, last Tuesday was yesterday (<code>DateTime.Now.AddDays(-1.0)</code>).</p>
<pre><code>#light
module DateTimeExtensions
open System
let rec whenWasLastBasedOnDate (weekDay:DayOfWeek, currentDate:DateTime) =
match currentDate with
| _ when currentDate.DayOfWeek = weekDay -> currentDate
| _ -> whenWasLastBasedOnDate(weekDay, currentDate.AddDays(-1.0))
let whenWasLast (weekDay:DayOfWeek) =
let currentDate = DateTime.Now
match currentDate with
| _ when currentDate.DayOfWeek = weekDay -> currentDate
| _ -> whenWasLastBasedOnDate(weekDay, currentDate.AddDays(-1.0))
let now = DateTime.Now
let lastSunday = whenWasLast DayOfWeek.Sunday
let lastMonday = whenWasLast DayOfWeek.Monday
let lastTuesday = whenWasLast DayOfWeek.Tuesday
let lastWednesday = whenWasLast DayOfWeek.Wednesday
let lastThursday = whenWasLast DayOfWeek.Thursday
let lastFriday = whenWasLast DayOfWeek.Friday
let lastSaturday = whenWasLast DayOfWeek.Saturday
</code></pre>
| [] | [
{
"body": "<p>The most obvious point to make is that <code>whenWasLast</code> repeats the entire code of <code>whenWasLastBasedOnDate</code>. You can (and should) simply write the whole method by just calling <code>whenWasLastBasedOnDate</code>:</p>\n\n<pre><code>let whenWasLast (weekDay:DayOfWeek) =\n whenWasLastBasedOnDate(weekDay, DateTime.Now)\n</code></pre>\n\n<p>Another point is that you should write <code>AddDays(-1.0)</code> as <code>AddDays -1.0</code>. In languages with ML-like syntax it is generally discouraged to add redundant parentheses around function arguments because it encourages the misconception that the parentheses are part of the method call syntax.</p>\n\n<p>On a somewhat more subjective note, I think that using <code>if</code> would read nicer than a <code>match</code> without any patterns.</p>\n\n<hr>\n\n<p>On a more general design note it is generally considered good style in functional programming to use higher order functions to express the code more abstractly. For example instead of saying \"Check if the given day was a <code>weekDay</code>. If so, return it, if not repeat with the day before\" you could say \"Look at the last seven days and return the one who is a <code>weekDay</code>\". This is not only more idiomatic functional programming, but also makes it impossible to get into infinite recursion by getting the exit condition wrong. In code it would look like this:</p>\n\n<pre><code>[-6.0..0.0] |> Seq.map currentDate.AddDays |>\n Seq.find (fun d -> d.DayOfWeek = weekDay)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T02:20:17.627",
"Id": "989",
"Score": "0",
"body": "Thank you so much! This is what I was looking for. The thought I had when created the function was exactly the same as your last one but I could not express it into code. I guess I'm too imperative yet. Refactored as you proposed. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T10:03:59.190",
"Id": "1008",
"Score": "0",
"body": "Could you please edit the first part of your answer to include the corrected code with 'just `whenWasLastBasedOnDate DateTime.Now`'? This would help people not familiar with F# to get your idea. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T22:35:29.257",
"Id": "574",
"ParentId": "572",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "574",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T21:36:26.723",
"Id": "572",
"Score": "10",
"Tags": [
".net",
"functional-programming",
"f#",
"datetime"
],
"Title": "Getting the last date where a given week day occurred"
} | 572 |
<p>My own CMS is currently using jQuery, but as one of the goals is to have the whole project to be very small, I've decided to write my own basic library. I only really need to select elements and modify them using results from my server (via Ajax).</p>
<p><strong>The JavaScript-library v0.01: (Attempt 1)</strong></p>
<pre><code>(function(){
a=this.Function;
a.prototype.extend=(function(a,b){this[a]=b;return this});
a.prototype.implement=(function(a,b){this.prototype[a]=b;return this});
$=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)})
.extend("post",(function(a,b){
c=[];
for(x in a)
c[c.length]=[x,a[x]].join("=");
d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
d.open("POST","./",true);
d.setRequestHeader("Content-type","application/x-www-form-urlencoded");
d.onreadystatechange=b;
d.send(c.join("&"));
return this;
}))
.extend("each",(function(a,b,c){
for(x in a)
if(a.hasOwnProperty(x))
b.call(c, a[x], x, a);
return this;
}));
})();
</code></pre>
<p>I know that <code>querySelectorAll</code> can't be relied on, but it is just good for the start of this.</p>
<p><strong>The JavaScript-library v0.02: (Attempt 2)</strong></p>
<p>I believe this is much improved. It has reasonable variable names, works better, and most of all is quite buggy.</p>
<pre><code>var _ = new function Sample(){}; ////////////////////////////////////////
_.temp = {}; // This Object is intended just for
_.pages = {}; // testing, I do the rest in the console
_.pid = {}; // <- Stores the current pageID
_.el = {}; // /PAGE-ID/PAGE-TITLE or #!page=PAGE-ID
_.fn = {}; ////////////////////////////////////////
_.$ = {}; // <- Lets leave JQuery alown. :)
(function(){
this.$ = function(a,b,c){
if(b&&b.isType("string")) b = $(b);
d=b?b[c|0]:document;
return document.getElementsByClassName.call(d,a);
};
var $FP = Function.prototype, $OP = Object.prototype;
$OP.isType = function (type){
return typeof this === type;
}
$OP.each = function(fun){ // `fun()` runs 3 times HOW??
if(this.isType("array")&&this.forEach) return this.forEach(a); // if this is an array and we have a browser with Array().forEach then lets use native code instead.
if(this.isType("object")||this.isType("array"))
for(var x in this)
if(this.hasOwnProperty(x))
fun.call(this[x],x,this);
return this;
};
$OP.toString = function(){
if(!this.isType("object")&&!this.isType("array")) return this;
var arr=[];
this.each(function(a){
arr[arr.length] = a+"="+this;
});
return arr.join("&");
}
$FP.multiInput = $FP.MI = function(){
var self = this;
return function(obj){
if(obj.isType("object")||obj.isType("array"))
obj.each(function(a,b){
self.call(b,a,this);
});
else
self.apply(this,arguments);
return this;
};
};
$OP.extend = function(key,val){ // I want to add all my functions dynamicly and in bulk.
(this.prototype||this)[key]=val; // Either myObject.extend("key","val") or my Object.extend({"key":"val"}) work.
return this;
}.MI(); // MI/multiInput simply allows objects to be passed instead of making it more sence to use obj.prototype.test=myvalue;
this.$.extend({
"post": function(a,b,c,d){
var e=XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
e.open("post", a, true);
e.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
e.onreadstatechange = function(){
if(xmlhttp.readyState==4) // Page has fully loaded, now did we get a status code of "200 ok" or an error? Please tell me if "304 Not modified" should be added as run `c` and not `d`
(xmlhttp.status==200?c:d).call(xmlhttp.responseText,xmlhttp);
};
e.send(b.toString());
return this;
},
"post_json": function(a,b,c){
return this.post(a,b,function(){
c.call("return "+$.Function(this)()); // This should run c with this being the object. What works better `()` or `.call()` ??
});
}
});
}).call(_); // Lets Leave JQuery alown.
_.$.prototype.each(function(){console.log(this)});
</code></pre>
| [] | [
{
"body": "<p>I would suggest writing your code with full variable names and generating your production version with a minimizer to improve readability. As it stands this is reviewable because it's small, but I have no desire to be thorough because your variables are annoying to trace. This will also make maintenance less of a hassle.</p>\n\n<p>Overall it looks to accomplish the objective. Each ajax request will require manual error checking if you plan on having any fault-tolerance. If this will be used several times you may want to refactor the error checking into the base to save overall code length later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T20:38:13.490",
"Id": "1025",
"Score": "1",
"body": "Code is full of WTF (no offensive to coder. @IvoWetzel points out some basic mistakes)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T13:36:57.910",
"Id": "1070",
"Score": "0",
"body": "+1 for making the code readable and optimizing at a later step if needed using tools."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T14:28:04.757",
"Id": "1225",
"Score": "0",
"body": "@Ivo: lol, I guess it doesn't have a +4 anymore, but I imagine it did because people agreed with my comment? Just a thought. They are valid review pointers, even if yours are more thorough..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T09:48:46.637",
"Id": "1349",
"Score": "0",
"body": "@TheXenocide The lack of `var` causing variables to be leaked into the global space (and thus defeating the use of the `(function{})()` wrapper) *is* a serious WTF - I would say that the reason why it was not immediately obvious why the code is bad is because the author minified it, making it really hard to read"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T14:29:58.400",
"Id": "1362",
"Score": "0",
"body": "@Yi I agree with everything you said and never said there wasn't WTF; my review states that I wasn't thorough specifically because of the difficult naming. I know that leaked variables are WTF, I just made no effort to track variables while scanning the code (as the review says). It's not my job to rewrite his code legibly and as all of this is explicitly stated I don't find error in my review. That said Both Ivo and Raynos felt like donating more effort and as such their reviews are better, but had they not showed up maybe he would have rewritten his code and got a better review from me."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T17:15:58.177",
"Id": "584",
"ParentId": "580",
"Score": "4"
}
},
{
"body": "<p>Rewrite it from scratch, if I were to encounter such code in any commit, I would immediately remove that code and talk with the one who committed it about JS in general...</p>\n\n<pre><code>// anonymous wrapper if fine...\n(function(){\n\n // but not using var still creates global variables\n a=this.Function; // why are you extending the builtin function constructor?\n\n // no need for extra parenthesis here\n // also, this is hardly needed.. for the code below\n a.prototype.extend= (function(a,b){this[a]=b;return this});\n\n\n // what is this being used for?\n a.prototype.implement=(function(a,b){this.prototype[a]=b;return this});\n\n\n // overrides an existing mapping of jQuery\n $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)})\n\n // hard to read\n .extend(\"post\",(function(a,b){\n\n // more leakage\n c=[];\n\n // if you don't use {} you might as well put it on the same line\n // Oh and I shouldn't forget my usual rant about the missing\n // hasOwnProperty call\n for(x in a) // leakage of x\n c[c.length]=[x,a[x]].join(\"=\"); // what about c.push() ?\n\n // leakage leakage leakage\n d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject(\"Microsoft.XMLHTTP\");\n\n d.open(\"POST\",\"./\",true);\n d.setRequestHeader(\"Content-type\",\"application/x-www-form-urlencoded\");\n d.onreadystatechange=b;\n d.send(c.join(\"&\"));\n return this;\n }))\n\n .extend(\"each\",(function(a,b,c){\n for(x in a) // leakage of x\n if(a.hasOwnProperty(x)) // why all of a sudden hasOwnProperty here?\n b.call(c, a[x], x, a);\n return this;\n }));\n})();\n</code></pre>\n\n<h3>EDIT</h3>\n\n<p>An untested cleaned up version from me.</p>\n\n<pre><code>(function() {\n function $(selector, parentSelector, index) {\n var element = parentSelector ? $(parentSelector)[index || 0] : document;\n return element.querySelectorAll(a);\n };\n\n $.extend = function(obj, props) {\n for(var i in props) {\n if (props.hasOwnProperty(i)) {\n obj[i] = props[i];\n }\n }\n return this;\n };\n\n $.extend($, {\n post: function(data, callback) {\n var params = [];\n\n for(var i in data) {\n if (data.hasOwnProperty(i)) {\n\n // might need url encoding...\n params.push([i, data[i]].join('='));\n }\n }\n\n // this might need for fallbacks, check the jQuery source for that\n var req;\n if (XMLHttpRequest) {\n req = new XMLHttpRequest();\n\n } else {\n req = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n req.open('post', '/', true);\n\n // is that really cross browser these days?\n req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n req.onreadstatechange = callback;\n req.send(params.join('&'));\n return this;\n },\n\n each: function(obj, func, that) {\n for(var i in obj) {\n if (obj.hasOwnProperty(i)) {\n func.call(that, obj[i], obj, i);\n }\n }\n return this;\n }\n });\n window.$ = $;\n})();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T20:28:40.830",
"Id": "588",
"ParentId": "580",
"Score": "13"
}
},
{
"body": "<p>This code uses some poor mistakes and has a few mistakes in it. </p>\n\n<p>See annotated code.</p>\n\n<p>Recommended reading : <a href=\"http://dailyjs.com/2010/02/25/djscript-part-1-structure/\">Let's make a framework</a> , learn from the jQuery source <a href=\"http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/\">1</a> and <a href=\"http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/\">2</a> and the jquery <a href=\"https://github.com/jquery/jquery\">source</a> (warning. Daunting!)</p>\n\n<pre><code>(function () {\n // Ok so were going to extend the global Function object?\n // Don't extend native objects it really messes with other people's code\n // If you must you can either clone them or wrap around them\n\n // Let's not forget that a is implecitly global. We do not do this.\n // If we want a global we MAKE it global. so declare it with \n // var a = ...\n // and use global.a or window.a = ... to set things in global scope\n // a doesn't even need to be global and if it's does its a horrible name.\n a = this.Function;\n // Were calling extend twice. Why don't we define $.post and $.each\n // seperately instead. This is a classic case of hardcore over-engineering\n\n // We do not extend native prototypes. This is bad, other people make \n // assumptions of what the native prototypes are like\n\n // No need to wrap functions in ( ). This is only neccesary for when you\n // want to do \n // (function() { }()) and there are no other \"symbols\" on the line.\n // We only use ( ) because function () { }() is an invalid expression \n // and throws an error without ( )\n a.prototype.extend = (function (a, b) {\n // why do we need a f.extend(\"foo\", o) \n // It's neater to just call f.foo = o\n // This function is redundant. \n this[a] = b;\n // Ok it implements chaining. It's really not worth it for chaining\n // all you can chain is f.extend. \n return this\n });\n // Dead code\n a.prototype.implement = (function (a, b) {\n // Even if its not dead again your just calling f.implement(\"foo\", o)\n // instead of f.prototype.foo = o\n // this really hurts readability and feels unneccesary.\n this.prototype[a] = b;\n return this\n });\n // Woh another implecit global this is bad. Oh and let's overwrite anyone\n // who defines $ shall we. Bye jQuery, bye prototype, bye mootools. \n // if your writing a framework then don't overwrite common names like $.\n // Dont use excuses like I will only use it. If your going to do it, \n // then do it properly.\n $ = (function (a, b, c) {\n // I might get round to \"understanding\" this block. It's messy though\n return (b ? $(b)[c ? c : 0] : document).querySelectorAll(a)\n }).extend(\"post\", (function (a, b) {\n c = [];\n for (x in a)\n c[c.length] = [x, a[x]].join(\"=\");\n d = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(\"Microsoft.XMLHTTP\");\n d.open(\"POST\", \"./\", true);\n d.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n d.onreadystatechange = b;\n d.send(c.join(\"&\"));\n return this;\n })).extend(\"each\", (function (a, b, c) {\n for (x in a)\n if (a.hasOwnProperty(x)) b.call(c, a[x], x, a);\n return this;\n }));\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T05:21:19.070",
"Id": "1131",
"Score": "0",
"body": "I removed extend and made implement extend, I thought I updated it here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T05:25:23.290",
"Id": "1132",
"Score": "0",
"body": "Humm, does $.extend extend $ or Function?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T14:18:17.393",
"Id": "1167",
"Score": "0",
"body": "@JamesM-SiteGen `$.extend(objectToExtend, ObjectToExtendWith)`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T20:48:53.930",
"Id": "589",
"ParentId": "580",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-03T07:40:05.443",
"Id": "580",
"Score": "8",
"Tags": [
"javascript",
"ajax",
"library"
],
"Title": "Basic JavaScript library"
} | 580 |
<p>This code writes to Excel using the COM interface. The general issue is that any exception handling has to handle the "Excel is busy" exception. This occurs if information is sent to Excel quicker than it can handle it - eg. latency when a workbook is loaded/created, or the user is playing with the scrollbars (there are good reasons for letting this happen).</p>
<p>This is probably the only example I know of which is simpler and cleaner in VB6 than in C#! In VB6 an ON ERROR would be used. The error handler would then create an error for most cases. But if the error code is a "busy" then it will sleep a short period of time (typically half a second) and then try again with a "RESUME". Don't get me wrong, ON ERROR is generally messier than C#'s try...catch and it is easier to produce awful code; however, this is one example where the VB6 ON ERROR works better. A long sequence of Excel calls can be trapped with one handler. The "RESUME" will then send control back to the line where the 'busy' occurred - this avoids duplicate calls or skipped calls.</p>
<p>The solution I have in C# is to create a while loop with a flag. The flag indicates a repeat of the loop is required due to a 'busy' return from Excel. See the code below.</p>
<p>Is there a simpler, more elegant way of doing this? The main problem is that this requires a method for each type of Excel call. To avoid too many duplicate Excel calls in the busy scenario, the contents of each method is atomic or close to atomic - eg. "write this formatted value"; "apply this formatting to this row". This results in lots of methods. And/or methods with lots of parameters (the example below is a short one with just one format option, but there could be more - colors, decimal points, etc).</p>
<pre><code>private void WriteDoubleValue(Excel.Worksheet sh, int x, int y, double lfval, bool bBold)
{
bool bNotSuccess = true;
while (bNotSuccess)
{
try
{
((Excel.Range)sh.Cells[y,x]).set_Value(Missing.Value, lfval);
((Excel.Range)sh.Cells[y, x]).Font.Bold = bBold;
bNotSuccess = false;
}
catch (System.Runtime.InteropServices.COMException e)
{
if ((e.ErrorCode & 0xFFFF) == 0xC472)
{ // Excel is busy
Thread.Sleep(500); // Wait, and...
bNotSuccess = true; // ...try again
}
else
{ // Re-throw!
throw e;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T16:06:25.413",
"Id": "1016",
"Score": "0",
"body": "To clarify, I'm using C# 4.0, so sepp2k's relatively advanced solution is fine. I'm a new convert from 2.0, mainly for the new multi-threading capabilities."
}
] | [
{
"body": "<p>If I understood you correctly, you have a lot of methods which are identical to the one you've shown except for the parameters they take and the contents of the <code>try</code>-block. The rest is repeated code, which is bad.</p>\n\n<p>To fix this I'd recommend to abstract the \"repeat this action as long as Excel is busy\" logic into its own method, which takes the action to be repeated as a parameter.</p>\n\n<p>On a style note, I would argue against using Hungarian Notation. It's not really commonly used in .net and basically every style guide written in this century argues against it.</p>\n\n<p>I'd also recommend making the <code>bool</code> variable positive (i.e. <code>success</code> instead of <code>notSuccess</code>). This way people don't have to perform double negation in their head when reading things like <code>notSuccess = false</code> (which would be changed to <code>success = true</code>).</p>\n\n<p>With these suggestions the code could look like this:</p>\n\n<pre><code>private void TryUntilSuccess(Action action)\n{\n bool success = false;\n while (!success)\n {\n try\n {\n action();\n success = true;\n }\n\n catch (System.Runtime.InteropServices.COMException e)\n {\n if ((e.ErrorCode & 0xFFFF) == 0xC472)\n { // Excel is busy\n Thread.Sleep(500); // Wait, and...\n success = false; // ...try again\n }\n else\n { // Re-throw!\n throw e;\n }\n }\n }\n}\n</code></pre>\n\n<p>You could then implement <code>WriteDoubleValue</code> and all the methods like it with a call to <code>TryUntilSuccess</code> like this:</p>\n\n<pre><code>TryUntilSuccess( () =>\n{\n ((Excel.Range)sh.Cells[y,x]).set_Value(Missing.Value, lfval);\n ((Excel.Range)sh.Cells[y, x]).Font.Bold = bBold;\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T15:54:24.867",
"Id": "1015",
"Score": "0",
"body": "(goes off and reads about Actions) Yes that was the type of thing I was looking for - thanks! re. Hungarian Notation: Old habits die hard! :-) re. the 'sense' of the boolean flag: Again old habits - mainly from the days when it made sense to minimize operations even in a trivial case like this. I agree that my phrasing could obfuscate slightly, and the potential performance gain is insignificant."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T18:19:31.220",
"Id": "1021",
"Score": "0",
"body": "I likes it. Lambdas are great."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T15:16:48.223",
"Id": "583",
"ParentId": "582",
"Score": "7"
}
},
{
"body": "<p>When re-throwing an exception don't specify the exception or throw a new exception with the old one as an inner exception otherwise you replace the exception stack trace with the line of the throw in the catch block which will prevent you from seeing which of the lines in the try block caused the exception. I assume you're using this in many places? I've refactored out the error check, but sepp2k's code promotes greater reusability of the pattern as a whole. Still, here's a slightly more efficient and shorter implementation of the control loop itself in case you're more comfortable with it. A hybrid of the two is probably your best bet.</p>\n\n<pre><code>private void WriteDoubleValue(Excel.Worksheet sh, int x, int y, double lfval, bool bBold)\n{\n bool retry = false;\n do\n {\n try\n {\n ((Excel.Range)sh.Cells[y,x]).set_Value(Missing.Value, lfval);\n ((Excel.Range)sh.Cells[y, x]).Font.Bold = bBold;\n retry = false;\n }\n catch (System.Runtime.InteropServices.COMException e)\n {\n if (retry = e.ShouldRetry())\n { // Excel is busy\n Thread.Sleep(500); // Wait, and...\n }\n else throw; \n //calling throw without a param *rethrows* \n //which is important to preserve the stack trace\n }\n } while (retry);\n}\n\nprivate void ShouldRetry(this COMException e) {\n return ((e.ErrorCode & 0xFFFF) == 0xC472);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T19:39:31.103",
"Id": "1023",
"Score": "0",
"body": "Thanks for the throw tip: Looks useful! Yes I think your while loop is more logical in its layout. Again, a case of adapting habits - I used to use do..while/repeat...until loops a lot but seemed to drift away from them - probably as I used more languages."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T20:22:23.283",
"Id": "1093",
"Score": "1",
"body": "The above code actually has a bug: retry should be reset either just before the try, or at the beginning of the try block. Otherwise the \"busy\" will cause an endless loop."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T14:23:06.387",
"Id": "1224",
"Score": "0",
"body": "Ahh, my apologies! Thanks for pointing it out. Such are the woes of coding in a website comment field, lol."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-03T17:41:50.593",
"Id": "585",
"ParentId": "582",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "583",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T14:32:50.913",
"Id": "582",
"Score": "6",
"Tags": [
"c#",
"exception"
],
"Title": "Handling COM exceptions / busy codes"
} | 582 |
<p>I'm writing a logger extension that allows multiple threads to log a process, and then dump that log to the main log in one atomic operation. The point of it is to make the logs easier to read when many threads are executing. Is this test valid and clear or not?</p>
<pre><code>/**
* Test that thread logs do not interlace
* @throws InterruptedException
*/
@Test
public void testDumpMultithreaded() throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
logger.bufferedMessages.get().add("t1: One");
logger.bufferedMessages.get().add("t1: Two");
logger.bufferedMessages.get().add("t1: Three");
logger.dump();
}
};
Thread t2 = new Thread() {
@Override
public void run() {
logger.bufferedMessages.get().add("t2: One");
logger.bufferedMessages.get().add("t2: Two");
logger.bufferedMessages.get().add("t2: Three");
logger.dump();
}
};
t1.start();
t2.start();
t1.join();
t2.join();
Iterator<String> i = logger.messages.iterator();
boolean t1Correct = false;
boolean t2Correct = false;
while (i.hasNext()) {
if (i.next().equals("t1: One")) {
t1Correct = true;
t2Correct &= i.next().equals("t1: Two");
t2Correct &= i.next().equals("t1: Three");
}
}
i = logger.messages.iterator();
while (i.hasNext()) {
if (i.next().equals("t2: One")) {
t2Correct = true;
t2Correct &= i.next().equals("t2: Two");
t2Correct &= i.next().equals("t2: Three");
}
}
assertEquals("Thread one's log not consecutive: ", true, t1Correct);
assertEquals("Thread two's log not consecutive: ", true, t2Correct);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T06:36:20.460",
"Id": "1061",
"Score": "2",
"body": "1. A barrier can ensure the threads execute in an interleaved fashion. 2. assertTrue instead of assertEquals(.., true, ..). 3. cut and paste error has you modifying t2Correct instead of t1Correct."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T13:44:12.780",
"Id": "1071",
"Score": "0",
"body": "How do you create a barrier? also could you post that as an answer so I can upvote it?"
}
] | [
{
"body": "<p>A barrier can ensure the threads execute in an interleaved fashion.</p>\n\n<pre><code>final CyclicBarrier rendezvous = new CyclicBarrier(2);\nfinal CyclicBarrier conclusion = new CyclicBarrier(3);\nThread a = new Thread() {\n public void run() {\n try {\n rendezvous.await();\n // do your stuff\n // do your stuff\n rendezvous.await(); // if you want to be extra sure the ops are interleaved\n // do your stuff\n } catch (...) {}\n finally { conclusion.await(); }\n }\n};\n\nThread b = new Thread() {\n public void run() {\n try {\n rendezvous.await();\n // do your other stuff\n // do your other stuff\n rendezvous.await(); // if you want to be extra sure the ops are interleaved\n // do your other stuff\n } catch (...) {}\n finally { conclusion.await(); }\n }\n};\n\na.start();\nb.start();\nconclusion.await(); \n</code></pre>\n\n<p>assertTrue instead of assertEquals(.., true, ..). </p>\n\n<p>cut and paste error has you modifying t2Correct instead of t1Correct</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T11:14:02.917",
"Id": "1163",
"Score": "0",
"body": "I've not seen the CyclicBarrier used like this; neat"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T22:34:42.630",
"Id": "614",
"ParentId": "587",
"Score": "5"
}
},
{
"body": "<p>The test in the OP and Ron's test are both valid tests, but it's important to realize that they may not fail even if there are legitimate concurrency problems.</p>\n\n<p>The test in the OP is unlikely to ever interleave the calls to add(). Even if the test ran thousands of times, t1 would usually always finish before t2 started.</p>\n\n<p>Ron's test ensures that the calls to add() do interleave by using a CyclicBarrier. However, using the CyclicBarrier ensures that the state maintained by the two threads gets flushed to main memory, potentially hiding concurrency problems in both add() <em>and</em> dump().</p>\n\n<p>Both tests are decent, and you might as well run them both. For true peace of mind though, why not post the code for the logger on this site?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T19:13:55.997",
"Id": "665",
"ParentId": "587",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "614",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-03T20:26:24.293",
"Id": "587",
"Score": "8",
"Tags": [
"java",
"unit-testing",
"multithreading"
],
"Title": "Multithreaded log test"
} | 587 |
<p>I have a block of code below. The <code>allDone()</code> method at the bottom should only be run if the <code>allCompleted == true</code>. It should run through each of the statements to test.</p>
<ul>
<li><p><code>allCompleted</code>: This starts as true so the below logic works right.</p></li>
<li><p><code>run*.Checked</code>: This is based on a check box in a form. This block should only run if this box is checked.</p></li>
<li><p><code>cmd</code>: This is a generic string variable stating whether another part of the code (not shown here) was run successfully. If it has run successfully this string will read "done".</p></li>
</ul>
<p>After those options, if all enabled (<code>run*.Checked == true</code>) methods have returned the <code>cmd*</code> string as <code>"done"</code> (everything that's checked has run successfully) then <code>allCompleted</code> should be <code>true</code> at the end so <code>allDone()</code> gets run.</p>
<p>If one single enabled method returns <code>false</code> (there was an error somewhere or otherwise it did not return <code>"done"</code>), then the <code>allDone()</code> method should not be run and the code will continue, skipping the last <code>if (allCompleted)</code> statement.</p>
<pre><code>bool allCompleted = true;
if (runPart1.Checked)
if (cmdPart1 == "done")
allCompleted = ((allCompleted)? true : false);
else
allCompleted = false;
if (runPart2.Checked)
if (cmdPart2 == "done")
allCompleted = ((allCompleted) ? true : false);
else
allCompleted = false;
if (runPart3.Checked)
if (cmdPart3 == "done")
allCompleted = ((allCompleted) ? true : false);
else
allCompleted = false;
if (runPart4.Checked)
if (cmdPart4 == "done")
allCompleted = ((allCompleted) ? true : false);
else
allCompleted = false;
if (allCompleted)
allDone();
</code></pre>
<p>So if at anytime one of the enabled parts fail the code will basically just move on.</p>
<p>As it stands this code works, I just feel like it could be written better. Is this the best way or have I got it? Something about it makes me feel awkward still. </p>
<p><strong>EDIT:</strong> Also, each time one of the parts completes, it runs this method, so it will run a few times being false in the end until the last one runs and all the others are "done" in which case it should completes and run <code>allDone()</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T06:38:06.090",
"Id": "1062",
"Score": "0",
"body": "Can you not change the 4 pairs of variables (runPartN and cmdPartN) into an array of an appropriate structure type? Then you could loop over the array."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T08:31:11.567",
"Id": "1067",
"Score": "0",
"body": "After looking at the responses, yea I realize I could do that now. But that may be a little more complicated than what I need (read my answer updated edit in my original post). But as I stated if I need a more detailed answer in the future, that is the route I may want to go."
}
] | [
{
"body": "<pre><code>allCompleted = true;\nallCompleted &= (!runPart1.Checked || cmdPart1 == \"done\"));\nallCompleted &= (!runPart2.Checked || cmdPart2 == \"done\"));\nallCompleted &= (!runPart3.Checked || cmdPart3 == \"done\"));\nallCompleted &= (!runPart4.Checked || cmdPart4 == \"done\"));\n\nif (allCompleted) {\n allDone();\n}\n</code></pre>\n\n<p>Here's a start - without more context I'm not sure what else can be done. Will edit other ideas later.</p>\n\n<p>EDIT: Possible idea for you to try:</p>\n\n<pre><code>interface RunPart {\n public boolean doAction();\n}\n</code></pre>\n\n<p>And for the action code:</p>\n\n<pre><code>ArrayList CheckActions = new ArrayList();\n\nif (RunPart1.Checked)\n CheckActions.add(new RunPart1());\n\nif (RunPart2.Checked)\n CheckActions.add(new RunPart2());\n\nif (RunPart3.Checked)\n CheckActions.add(new RunPart3());\n\nif (RunPart4.Checked)\n CheckActions.add(new RunPart4());\n\nforeach (RunPart runPart in CheckActions) {\n allCompleted &= part.doAction();\n}\n\nif (allCompleted) {\n allDone();\n}\n</code></pre>\n\n<p>All the RunParts need to implement the <code>RunPart</code> interface. This will make it a bit easier to add more actions in the future. Not sure if this is practical for you or not but here it is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:12:50.950",
"Id": "1028",
"Score": "0",
"body": "Ah, you can do \"*\"? I guess I'm showing my lack of C# foo, since I've never touched the language."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:14:31.490",
"Id": "1029",
"Score": "0",
"body": "@Mark: No, that's just a placeholder. I'll edit that. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:22:22.783",
"Id": "1032",
"Score": "0",
"body": "Wow this is clever. I do like this. But if part 3 return false and 4 is true, then in the end it will be true. It needs to be that if at any time it returns false, it stays false. So if Part 2 is false, the end result will be false even if 3 and 4 are true. if any are false then it stays false."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:24:52.747",
"Id": "1034",
"Score": "0",
"body": "It will be - `false && true == false`. So if part 3 sets `allCompleted` false, part 4 will not change that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:27:27.147",
"Id": "1035",
"Score": "0",
"body": "OOh yea thats true, good point. Thats great. I like this example. Did the other person delete his answer?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:28:39.543",
"Id": "1036",
"Score": "0",
"body": "Looks like - I can't see it either."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:29:08.067",
"Id": "1037",
"Score": "0",
"body": "Yea, that one didn't work, I just made a new one now that I understand what he's trying to do."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:35:57.480",
"Id": "1038",
"Score": "0",
"body": "@Michael: shouldn't your lines contain ` || !runPart*.Checked` ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:38:40.860",
"Id": "1040",
"Score": "0",
"body": "(!runPart*.Checked && cmdPart* == \"done\") should return false as it should only return true if it IS checked and \"done\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:46:31.927",
"Id": "1049",
"Score": "0",
"body": "@Michael: In your first code snippet, if any of the checkboxes are unchecked, then `allCompleted` will always be `false`, because `allCompleted &= false` will always set it to false."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T23:29:22.420",
"Id": "1096",
"Score": "0",
"body": "Looking at your first notion, the code after each || will only run if runPartX is checked, so there's no need to immediately repeat the test."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:10:24.117",
"Id": "592",
"ParentId": "590",
"Score": "3"
}
},
{
"body": "<p>Okay, here is how I would reduce the code duplication (if I am understanding the conditions correctly):</p>\n\n<p>Edit: <strong>Original:</strong></p>\n\n<pre><code>bool runCompleted(bool checked, string done)\n{\n if( ( checked && done == \"done\" ) || !checked )\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p><strong>New version based on Jerry's feedback:</strong></p>\n\n<pre><code>bool runCompleted(bool checked, string done)\n{\n return !checked || done == \"done\";\n}\n</code></pre>\n\n<p>Then in your code:</p>\n\n<pre><code>if( runCompleted(runPart1.Checked, cmdPart1 )\n && runCompleted(runpart2.Checked, cmdPart2 )\n && runCompleted(runpart3.Checked, cmdPart3 )\n && runCompleted(runpart4.Checked, cmdPart4 )\n )\n allDone();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:35:58.587",
"Id": "1039",
"Score": "0",
"body": "AH, this one is good too as it checks for those not run. Something that may be useful as well."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:50:44.340",
"Id": "1050",
"Score": "3",
"body": "Then refactor `runCompleted` to: `return !checked || done == \"done\";`. Anytime you have `if (x) return true else return false;`, you can factor it to `return x;` (and in this case `x` can be simplified a bit as well)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T01:33:24.453",
"Id": "1054",
"Score": "0",
"body": "@Jerry: Good point, I was throwing it together quick when I was leaving work. I'll update with a new version of runCompleted and leave the old as well."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T08:22:05.263",
"Id": "1066",
"Score": "0",
"body": "I think this is the closest to what I need to accomplish. This code also makes it rather easier to add newer parts if needed compared to the other answers. Although if I need to make it any more complex I may end up using @Michael's answer using the interface. Marking as the answer unless anyone else has any other input"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T20:35:58.713",
"Id": "1293",
"Score": "0",
"body": "The string comparison should be written `done.Equals(\"done\", StringComparison.Ordinal)`. You could choose a different `StringComparison` operator, but in general when doing a string == comparison it is better practice to call the .Equals method on the string object with a specified`StringComparison` (see [MSDN](http://msdn.microsoft.com/en-us/library/ms973919.aspx#stringsinnet20_topic6) \"Using an overload explicitly stating the StringComparison type is still recommended, even if you desire an ordinal comparison\") This is something that FxCop specifically looks for."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:28:46.867",
"Id": "593",
"ParentId": "590",
"Score": "11"
}
},
{
"body": "<p>I'm a very big noob at C# so please forgive me if this is a horrible solution, but how about using arrays?</p>\n\n<pre><code>bool allCompleted = true;\nString[] commands = { cmdPart1, cmdPart2, cmdPart3, cmdPart4 };\nCheckBox[] checkBoxes = { runPart1, runPart2, runPart3, runPart4 };\n\n// ensure commands.Length == checkBoxes.Length\nfor (int i = 0; i < checkBoxes.Length; i++)\n if (checkBoxes[i].Checked && commands[i] != \"done\")\n allCompleted = false;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:08:06.283",
"Id": "1044",
"Score": "0",
"body": "what if the last statement is like this? \n \n` for (int i = 0; i < checkBoxes.Length; i++)` \n` allCompleted &= (checkBoxes[i].Checked && commands[i] != \"done\")` \n` ` \n` if (allCompleted)` \n` allDone();` \n\nok sorry I cant seem to get code working in the comments. but the above is mixing in a little of what was done in @Michael's answer"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:12:56.387",
"Id": "1045",
"Score": "0",
"body": "@user1402: If the checkbox is not checked, then the expression will evaluate to false, and `allCompleted &= false` will set `allCompleted` to false prematurely."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:14:28.727",
"Id": "1046",
"Score": "0",
"body": "Basically, you *need* to inspect both the checkbox and the string before even considering changing the `allCompleted` variable. If the checkbox is not checked, then the second part of the `&&` expression will not be evaluated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T21:45:55.443",
"Id": "594",
"ParentId": "590",
"Score": "0"
}
},
{
"body": "<p>Others are giving you refactoring ideas, so I will just focus on one statement in your original code that is repeated 4 times. </p>\n\n<pre><code>allCompleted = ((allCompleted) ? true : false); \n</code></pre>\n\n<p>Look at this. You are inspecting <code>allCompleted</code>. If the value is true, you're setting it to true. If it is not true, you're setting it to false. You are setting it to what it already is in a sort of non-intuitive way. You could very well rewrite it as the below and have the exact same meaning.</p>\n\n<pre><code>allCompleted = allCompleted ? allCompleted : allCompleted;\n</code></pre>\n\n<p>Simplify that to </p>\n\n<pre><code>allCompleted = allCompleted;\n</code></pre>\n\n<p>And then simplify <em>that</em> to leaving it out altogether.</p>\n\n<pre><code>if(runPart1.Checked)\n if (cmdPart1 != \"done\")\n allCompleted = false;\n</code></pre>\n\n<p>Code can be complicated enough as it is. Try not to add further complexity by including code that can be non-obvious in the fact that it does nothing at all!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:28:27.990",
"Id": "1048",
"Score": "0",
"body": "Wow, how did I not see that? I think what I meant was for it to check the current value so if it was ever set to false it stayed false. I see now exactly what you mean though. Thanks for pointing it out"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T06:39:38.537",
"Id": "1063",
"Score": "0",
"body": "And the double 'if' can surely be abbreviated to `if (runPart1.Checked && cmdPart1 != \"done\")`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T08:09:06.190",
"Id": "1064",
"Score": "0",
"body": "Yea the double if I know I could have combined. I had it separated when I was still trying to work it out originally and never combined the two. Probably should have before asking this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:21:17.970",
"Id": "595",
"ParentId": "590",
"Score": "16"
}
},
{
"body": "<p>Pull that block of code out into its own method if it isn't already, and then just do:</p>\n\n<pre><code>if (runPart1.Checked && (cmdPart1 != \"done\")) return;\nif (runPart2.Checked && (cmdPart2 != \"done\")) return;\nif (runPart3.Checked && (cmdPart3 != \"done\")) return;\nif (runPart4.Checked && (cmdPart4 != \"done\")) return;\n\nallDone();\n</code></pre>\n\n<p>This isn't C. We don't have to be afraid of early returns anymore.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T05:34:33.960",
"Id": "741",
"ParentId": "590",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "593",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-03T20:59:00.940",
"Id": "590",
"Score": "11",
"Tags": [
"c#",
".net"
],
"Title": "Nested if statements with 3 different parameters"
} | 590 |
<p>I got sick of manually xrandering things on my computers (especially since I always just sequence monitors from left to right and set each at the highest resolution) so I wrote this:</p>
<pre><code>#!/usr/bin/ruby
def xrandrPairs (xList)
## Takes a split list of xrandr output and returns [[<display name>, <max-resolution>], ...]
pairs = [[matchDisplay(xList[0]), matchOption(xList[1])]]
(2..xList.length-1).to_a.each do |i| # kind of hacky, but I need to reference car and cadr here, so a call to .map won't do it
if xList[i] =~ /^\S/
pairs.push([matchDisplay(xList[i]), matchOption(xList[i+1])])
end
end
pairs
end
def matchDisplay (dispString)
## Matches a display name
dispString.match(/^([^\s]*)/)[1]
end
def matchOption (optString)
## Matches a resolution string (since they have whitespace preceding them)
optString.match(/^\s*([^\s]*)/)[1]
end
def xrandrString (xPairs)
## Takes [[<display name>, <max-resolution>] ...] and returns an xrandr command string
s = "xrandr --output #{xPairs[0][0]} --mode #{xPairs[0][1]}"
if xPairs.length >= 2
(1..xPairs.length-1).to_a.each do |i| # same as above
s += " --output #{xPairs[i][0]} --mode #{xPairs[i][1]} --right-of #{xPairs[i-1][0]}"
end
end
s
end
exec xrandrString(xrandrPairs(`xrandr`.split("\n")[1..-1]))
</code></pre>
<p>The key is that each computer I use has different displays (they're named differently and they have different maximum resolutions), so as far as I know, I have to either parse <code>xrandr</code> output or write a different script for each machine.</p>
<p>I don't care that it's inefficient (traversing the xrandr output multiple times and doing some looped string formatting) because it only runs once at startup time, and deals with a list of 30 elements at the outside. I'm using Ruby 1.8.7 straight out of the Squeeze repos for ease of installation (this is also why I wouldn't mind being shown how this works in Python/Perl; those come with the system).</p>
<p>Can I get some comments on it?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T03:46:40.970",
"Id": "1055",
"Score": "0",
"body": "Could you mention your ruby version?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T03:54:28.353",
"Id": "1056",
"Score": "0",
"body": "@sepp2k - mentioned; `1.8.7`"
}
] | [
{
"body": "<p>First of all, the convention in ruby is to use <code>snake_case</code>, not <code>camelCase</code> for variable and method names. It's generally a good idea to adhere to a language's naming conventions - if only so that the code looks consistent when you're calling standard library methods as well as your own.</p>\n\n<hr>\n\n<p>In your <code>xrandrPairs</code> method, you mention that you're using an index to iterate because you have to go through the array in pairs. You can avoid this by using <code>each_cons(2)</code> which will yield each item together with the item after it (e.g. <code>[1,2,3].each_cons(2)</code> will yield <code>1,2</code> in the first iteration and <code>2,3</code> in the second).</p>\n\n<p>However there's a better way to do this then to iterate through the lines. You can use <code>scan</code> to find all the lines that start without spaces and extract the information you want in one go:</p>\n\n<pre><code>def xrandr_pairs (xrandr_output)\n## Returns [[<display name>, <max-resolution>] ...]\n display_re = /^(\\S+)/\n option_re = /^\\s+(\\S+)/\n xrandr_output.scan(/#{display_re}.*\\n#{option_re}/)\nend\n</code></pre>\n\n<p>Since scan returns an array containing one subarray per match where each item in the subarray corresponds to one capturing group in the regex, this will produce the output you want. Note that <code>xrandr_pairs</code> now takes <code>xrandr</code>'s output as a string, not an array of lines.</p>\n\n<p>In addition to using <code>scan</code> I also changed the regexen a bit: I replaced <code>[^\\s]</code> with <code>\\S</code>, which is equivalent but shorter, and used <code>+</code> instead of <code>*</code>, so it does not match empty strings.</p>\n\n<hr>\n\n<p>The <code>xrandr_string</code> method can also be rewritten to be much nicer by using the <code>each_cons</code> method like this:</p>\n\n<pre><code>def xrandr_string (x_pairs)\n## Takes [[<display name>, <max-resolution>] ...] and returns an xrandr command string\n s = \"xrandr --output #{x_pairs[0][0]} --mode #{x_pairs[0][1]}\"\n x_pairs.each_cons(2) do |(previous_output, previous_mode), (output, mode)|\n s += \" --output #{output} --mode #{mode} --right-of #{previous_output}\"\n end\n end\n s\nend\n</code></pre>\n\n<p>You don't need to check that the size is at least 2 because <code>each_cons</code> simply doesn't do anything if the array is smaller than the given chunk-size.</p>\n\n<p>I also used the destructuring bind of block arguments to assign the elements of the subarrays to variables directly.</p>\n\n<p>Instead of building up the string imperatively you could also use <code>map</code> and <code>join</code> like this:</p>\n\n<pre><code>def xrandr_string (x_pairs)\n## Takes [[<display name>, <max-resolution>] ...] and returns an xrandr command string\n cmd = \"xrandr --output #{x_pairs[0][0]} --mode #{x_pairs[0][1]}\"\n args = x_pairs.each_cons(2).map do |(previous_output, previous_mode), (output, mode)|\n \"--output #{output} --mode #{mode} --right-of #{previous_output}\"\n end\n [cmd, *args].join(\" \")\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T04:33:03.623",
"Id": "1057",
"Score": "0",
"body": "Sweeeeet. `each_cons` does precisely what I need here (as you note, it removes the need for any imperative sequence building) and it's much more straightforward to scan for pairs with a single regex. I've noted the `snake_case` convention for the future; it wasn't an intentional infraction."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T04:34:26.523",
"Id": "1058",
"Score": "0",
"body": "Some notes though: you need `do` preceding the `|...|` sections, `option_re` should be `/^\\s+...` instead of `/^\\s*...` (this is because xrandr output starts with a non-whitespace-padded line that doesn't reference a monitor; using `*` will match that as the first monitor, returning a pair that looks something like `[\"Screen\", \"DVI-1\"]`) and you have an extra `end` in the functional version of `xrandr_string`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T04:38:03.210",
"Id": "1059",
"Score": "0",
"body": "@Inaimathi: Bah, sorry about that. I wrote the code \"blind\" without testing it and it's a bit late here. Good job reviewing my code though ;-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T04:59:42.957",
"Id": "1099",
"Score": "0",
"body": "Out of curiosity, would it be more idiomatic to make `xrandr_pairs` a method of `String` and `xrandr_string` a method of `Array` (and have them both reference `self` instead of taking an argument) so that I could call them as `x_out.xrandr_pairs.xrandr_string` instead of `xrandr_string(xrandr_pairs(x_out))`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T05:07:27.450",
"Id": "1100",
"Score": "1",
"body": "@Inaimathi: No, they're too specialized for that. For the vast majority of strings having a method `xrandr_pairs` makes no sense. What you could do is to define a class `XrandrResult` with a `pairs` method and a class `XrandrPairs` with a `command_string` method and then do something like `XrandrResult.new(`xrandr`).pairs.command_string`. However at this point that'd just be OO for OO's sake. If you ever want to add additional functionality those classes might be a useful abstraction though."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T04:15:18.193",
"Id": "598",
"ParentId": "597",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "598",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-04T03:24:48.727",
"Id": "597",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Autodetecting monitors in XFCE"
} | 597 |
<p>I'm working on a web application that I inherited from a colleague long gone. To connect to the MySQL database I use the following classes:</p>
<p><strong>statement.php</strong></p>
<pre><code><?php
//class sql
//{
class Statement
{
private $m_connection;
function __construct($connection)
{
$this->m_connection = $connection;
}
function query($query)
{
$connection = $this->m_connection;
$handle = $connection->getHandle();
$result = mysql_query($query,$handle);
if ($result === FALSE)
throw new Exception(mysql_error());
$instance = new Result($this);
$instance->setHandle($result);
return $instance;
}
}
//}
?>
</code></pre>
<p><strong>result.php</strong></p>
<pre><code><?php
//class sql
//{
class Result
{
private $m_handle;
private $m_statement;
function __construct($statement)
{
$this->m_statement = $statement;
}
function setHandle($handle)
{
$this->m_handle = $handle;
}
function fetch()
{
$handle = $this->m_handle;
$row = mysql_fetch_array($handle);
return $row;
}
}
//}
?>
</code></pre>
<p><strong>connection.php</strong></p>
<pre><code><?php
include_once("statement.php");
include_once("result.php");
//class sql
//{
class Connection
{
private $m_handle;
function __construct($server,$username,$password)
{
$handle = mysql_connect($server,$username,$password);
$this->m_handle = $handle;
}
function __destruct()
{
$handle = $this->m_handle;
@mysql_close($handle);
}
function createStatement()
{
return new Statement($this);
}
function getHandle()
{
return $this->m_handle;
}
}
//}
?>
</code></pre>
<p><strong>named.php</strong></p>
<pre><code><?php
include_once("connection.php");
function createNamedConnection($name)
{
if ($name == "dbalias1")
{
$connection = new Connection("first.host.com","user","uspw");
$statement = $connection->createStatement();
$statement->query("USE db1");
return $connection;
}
if ($name == "dbalias2")
{
$connection = new Connection("second.host.com","user2","nouse");
$statement = $connection->createStatement();
$statement->query("USE db2");
return $connection;
}
return null;
}
?>
</code></pre>
<p>To have a connection I can use the following script:</p>
<pre><code>$connection = createNamedConnection("dbalias1");
$statement = $connection->createStatement();
$query = "SELECT *
FROM tContent c
WHERE c.cID > 100";
$result = $statement->query($query);
while(($row = $result->fetch()) !== FALSE){
//do something
}
</code></pre>
<p>The problem is that those classes caused me a lot of trouble, and I'm sure there is work to be done on them. I don't know where to begin to make those classes more secure and easy to use.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T13:54:49.133",
"Id": "1074",
"Score": "4",
"body": "What kind of trouble are they causing?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T14:12:57.023",
"Id": "1075",
"Score": "0",
"body": "@Michael: Well mainly I got this kind of message: `Warning: mysql_query(): 7 is not a valid MySQL-Link resource in E:\\webroot\\dbtest\\lib\\statement.php on line 18` and it is difficult each time to find out the reason why. But it is only one example of the problem I had. To summarize debugging is quite difficult."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T14:50:55.887",
"Id": "1076",
"Score": "0",
"body": "What's the point of separating connection, statement, result?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T15:11:08.840",
"Id": "1077",
"Score": "1",
"body": "@Charlie: You tell me, I can't ask my (ex-)colleague anymore."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T15:23:09.110",
"Id": "1078",
"Score": "0",
"body": "Pdo already do it. Use it or rewrite this code by your own. Also delete those includes and use and `__autoload()` function. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T04:16:33.167",
"Id": "1129",
"Score": "0",
"body": "Colleague inheritance. interesting."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T12:44:16.400",
"Id": "1306",
"Score": "0",
"body": "How prevalently would you say the usage of these classes are with in the application? Also, what version of PHP are you using?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T14:05:16.430",
"Id": "1311",
"Score": "0",
"body": "@xzyfer: The scripts have to connect themself to the database quite often. My version of PHP is 5.2.4"
}
] | [
{
"body": "<p>Consider using mysqli instead of mysql:</p>\n\n<p><a href=\"http://www.php.net/manual/en/mysqli.connect.php\" rel=\"nofollow\">mysqli</a></p>\n\n<p>Mysqli (the \"i\" stands for \"improved\") is more OO-friendly and has better security. It also seems like the standard mysql functions are being deprecated (some of them anyway).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-30T08:43:29.270",
"Id": "7604",
"Score": "0",
"body": "I've finally taken the time to do the conversion to mysqli, and it seemed to need much more resources. Is there any performance concern about mysqli compared to mysql?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-22T21:27:20.223",
"Id": "930",
"ParentId": "601",
"Score": "4"
}
},
{
"body": "<p>I believe this code is unnecessary:</p>\n\n<pre><code>class Connection\n{\n //...\n\n function __destruct()\n {\n $handle = $this->m_handle;\n @mysql_close($handle);\n }\n //...\n}\n</code></pre>\n\n<p>As I understand it, MySQL connections should be cleaned up when your script finishes executing anyway. It looks like this is the cause of the bug, since the handle is being closed and later a query is attempted on the handle, causing the error message you're getting.</p>\n\n<p>What's not clear to me on first glance is why the <code>Connection</code> object is being destructed (and taking the MySQL database handle with it) when there's still a statement holding a reference to it. It's possible that you're cloning the connection somewhere, so that there are two connections holding the same MySQL handle. When the first one gets garbage collected the handle is closed, even though the second one is still using it. If my guess here is correct, then removing the destructor should fix the problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-19T17:05:26.760",
"Id": "2485",
"ParentId": "601",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-04T13:31:10.493",
"Id": "601",
"Score": "8",
"Tags": [
"php",
"mysql"
],
"Title": "Connecting to a database"
} | 601 |
<p><strong>The point of this question</strong></p>
<p>I'm actually using it while developing a simple application and it seems to cover all my needs. Also it uses PDO so that we don't really have to worry about SQL Injection. I know I usually code strange, but I hope you could give me suggestions and feedback in order to improve it.</p>
<p><strong>Code: Database Class</strong></p>
<pre><code>/* Operate on the database using our super-safe PDO system */
class db
{
/* PDO istance */
private $db = NULL;
/* Number of the errors occurred */
private $errorNO = 0;
/* Connect to the database, no db? no party */
public function __construct()
{
try
{
$this->db = new PDO(
'mysql:dbname='.reg::get('db-name').';host='.reg::get('db-host'), reg::get('db-username'), reg::get('db-password')
);
}
catch (Exception $e)
{
exit('App shoutdown');
}
}
/* Have you seen any errors recently? */
public function getErrors() { return ($this->errorNO > 0) ? $this->errorNO : false; }
/* Perform a full-control query */
public function smartQuery($array)
{
# Managing passed vars
$sql = $array['sql'];
$par = (isset($array['par'])) ? $array['par'] : array();
$ret = (isset($array['ret'])) ? $array['ret'] : 'res';
# Executing our query
$obj = $this->db->prepare($sql);
$result = $obj->execute($par);
# Error occurred...
if (!$result) { ++$this->errorNO; }
# What do you want me to return?
switch ($ret)
{
case 'obj':
case 'object':
return $obj;
break;
case 'ass':
case 'assoc':
case 'fetch-assoc':
return $obj->fetch(PDO::FETCH_ASSOC);
break;
case 'all':
case 'fetch-all':
return $obj->fetchAll();
break;
case 'res':
case 'result':
return $result;
break;
default:
return $result;
break;
}
}
/* Get PDO istance to use it outside this class */
public function getPdo() { return $this->db; }
/* Disconnect from the database */
public function __destruct() { $this->db = NULL; }
}
</code></pre>
<p><strong>Use</strong></p>
<pre><code>$db = new db;
$user = $db->smartQuery(array(
'sql' => "SELECT UserName FROM `post` WHERE UserUID = :uid",
'par' => array('uid' => $uid),
'ret' => 'fetch-assoc'
));
echo $user['Username'];
</code></pre>
<p><strong>What I think is wrong</strong></p>
<p>Well, I have encountered these 2 points while revisiting this code, and I'd like to get some feedback about them particularly:</p>
<ol>
<li>The error system (which, let's face it, sucks right now)</li>
<li>The first <code>try-catch</code> code, which is actually working, but I never use that so, please, look at it. </li>
</ol>
<p>Also if my application cannot connect to the database, most (if not all) features cannot be activated (such-as the PHP error log trough a database record, so that every times an error occurred, the admin is warned trough the application itself).</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T17:18:03.967",
"Id": "1083",
"Score": "1",
"body": "What is PDO? I've never heard of it before."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T18:26:15.397",
"Id": "1086",
"Score": "6",
"body": "Google it? And anyway are you kidding me?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T20:07:55.497",
"Id": "1092",
"Score": "1",
"body": "Nope. Wasn't kidding you. I have limited experience with PHP, and it's been several years since I have touched it; all pre-PHP5. You prefaced your question with \"I know I usually code strange\", so I thought it was something you made up."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T20:55:06.050",
"Id": "1095",
"Score": "1",
"body": "No, oh. Well PDO stands for PHP Data Objects (PDO) which is a db extension to interface better with a database. PDO is also safer than anything(?) because it uses Prepared Statements preventing SQL Injection that could be damage your database. For more information please visit the PHP documentation regarding it: http://www.php.net/manual/en/intro.pdo.php"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-06T08:30:57.177",
"Id": "29145",
"Score": "0",
"body": "maybe you could check out this project, quite a clear and good design: https://github.com/poplax/PHP-light-PDO-Class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-05T21:39:28.640",
"Id": "34260",
"Score": "0",
"body": "Yeah PDO was introduced as a plugin with PHP5 so that's understandable @JohnKraft."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-05T21:40:16.050",
"Id": "34261",
"Score": "0",
"body": "I must add, I was working on writing a database class myself, with the initialization in the constructor. I forgot the \"this->\" part and I think that's the solution to my problem @Jeffrey so thanks. Upvoted your question."
}
] | [
{
"body": "<h3>Why not make DB a Singleton class?</h3>\n<p>Making it Singleton will prevent multiple sign-ons. Now in your code, each time a DB object is created, you authenticate with the database server.</p>\n<p>If you make it Singleton, you just have to connect once. And whenever you need the instance, you just have to fetch it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T12:21:45.407",
"Id": "1305",
"Score": "1",
"body": "Singletons are generally considered big no no's since they're essentially global stateless objects (and we all know how evil globals are) which makes them untestable."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T15:15:40.633",
"Id": "1314",
"Score": "0",
"body": "Well, @xzyfer, I'd like to point you to http://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch - a view at the first answer will give you why Singleton can be used here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-04T15:29:13.667",
"Id": "130990",
"Score": "1",
"body": "_\"Why not make DB a Singleton class?\"_ Because the singleton pattern is an anti-pattern, makes testing a lot harder than it needs to be, it's pointless in a stateless environment (which PHP is), and it's just generally ***evil*** [there's no valid reason to use them in PHP](http://blog.gordon-oheim.biz/2011-01-17-Why-Singletons-have-no-use-in-PHP/)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T04:15:47.630",
"Id": "637",
"ParentId": "602",
"Score": "3"
}
},
{
"body": "<p>A few things. </p>\n\n<p>When you connect, don't hard code mysql, you are already fetching all the db info from a registry/config ... make the the dbtype configurable as well. That is after all, the point of PDO.</p>\n\n<p>When you catch errors in connection or when executing a query, use the <a href=\"http://www.php.net/manual/en/class.pdoexception.php\" rel=\"noreferrer\">PDOException</a> class</p>\n\n<p>use exceptions for your prepare and execute calls instead of counting the errors that happens...as that's not really useful (it will be obvious an error happened, what I care about is what that error actually is).</p>\n\n<p>personally, I would break down this class into specific methods. instead of connecting to the db in the constructor, I would have a connect() method to do this. I would also have a query, prepare, and bind method and then have interaction method: delete, update, insert and then a set of fetch methods, fetchOne, fetchAll, fetchCol, etc. </p>\n\n<p>Also the connect method would check for a set conn, and only attempt to connect if you didn't already have an existing connection. The query method would call connect(). The reason for this is that you may include your db class throughout your code, even if you dont fetch anything in particular requests...with your code if this is the case a connection will be made regardless. What you want is lazy loading...meaning a db connection will only be made if you actually attempt to use the db with a fetch/update/delete/insert/etc.</p>\n\n<p>Here is some sample pseudo code</p>\n\n<pre><code>$db = new MyPdoClass();\n$db->connect();\n$stmt = $db->query($sql, $params);\n$results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n// or call your MyPdoClass::fetchAll, which would do that so you would just call\n$results = $db->fetchAll($sql, $params);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T12:53:02.553",
"Id": "1196",
"Score": "1",
"body": "Are there samples of your class type?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T06:30:35.167",
"Id": "670",
"ParentId": "602",
"Score": "5"
}
},
{
"body": "<h3>Coupling</h3>\n\n<p>The first thing that comes to mind is the tight coupling between <code>db</code> and <code>reg</code>.</p>\n\n<p>Since <code>db</code> doesn't actually need to know anything about <code>reg</code>, and only needs a few values from it, I feel it's better practice to pass the required values in as needed:</p>\n\n<pre><code>public function __construct($host, $database, $username, $password)\n{\n ...\n}\n</code></pre>\n\n<h3>Exception handling</h3>\n\n<p>As mentioned in another answer, catch <a href=\"http://php.net/manual/en/class.pdoexception.php\" rel=\"nofollow\">PDOException</a> instead. Also, you will have a lot of frustration down the track trying to figure out what an \"App shoutdown\" error means with improved error reporting.</p>\n\n<pre><code>try\n{\n $db = new DB(...);\n}\ncatch (PDOException $e)\n{\n logError($e);\n exit('Sorry, the site is broken!');\n}\n</code></pre>\n\n<h3>Commenting</h3>\n\n<p><a href=\"http://www.phpdoc.org/\" rel=\"nofollow\">phpDoc</a> comments can prove invaluable as the size and complexity of classes grow. Even if not strictly necessary for simple projects, I've found it a useful habit to get into.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T17:06:54.357",
"Id": "1203",
"Score": "0",
"body": "#Coupling : Well, actually `reg` has now been replaced with `con` and stands for configuration, having thousands of different values. Also not setting any parameters in the construct give me the possibility to get the db class just with `$db = new db;`, and you will notice that is really fast. #Exception handling, #Commenting : Nice tips."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-08T00:24:11.720",
"Id": "2093",
"Score": "0",
"body": "@Charlie, more reason to stay away from that sort of thing. Imagine now that you had reg in 1500 files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T16:47:07.227",
"Id": "675",
"ParentId": "602",
"Score": "1"
}
},
{
"body": "<p>I'm assuming you're using PHP5, in which case do you have a <em>good</em> reason not to use existing libraries like <a href=\"http://www.doctrine-project.org/projects/dbal\" rel=\"nofollow\">Doctrine2 DBAL</a> the defacto standard for database abstraction, or <a href=\"http://pear.php.net/package/MDB2\" rel=\"nofollow\">Pear_MDB2</a>? </p>\n\n<p>In this day and age of open source libraries, rolling your own home made (and possible error prone class) to solve already <em>thoroughly</em> solved problems is doing yourself and the PHP community at large more harm than good don't you think?</p>\n\n<p>These libraries are well documented (not so much in the case of Pear_MDB2), thoroughly tested and have 1000s of hours of production use in a myriad of environments. And shoudl you find an issue or have a suggestion you'd be helping the PHP community. <strong>At the very least</strong> have a look at these fantastic projects, you might learn something and possible even answer some of your own questions should you insist on doing your own way.</p>\n\n<blockquote>\n <p>Admittedly Pear_MDB2 is a bit behind the times now, but it does a solid job</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T19:34:41.010",
"Id": "1325",
"Score": "1",
"body": "I love to create my own things. It's a way to learn by your own. I usually hate everything which is premade by someone else and I don't really think it worth something to learn an entire framework while you are developing such a simple web application as I do."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T22:57:32.077",
"Id": "1614",
"Score": "1",
"body": "Doctrine2 is potentially quite a heavyweight response that comes with the same burden when covering very wide range of use cases. There are a whole range of options available within the term DBAL"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T04:03:12.297",
"Id": "1626",
"Score": "0",
"body": "For the need described he could easily get away with just the DBAL component which is very light weight. Since Doctrine2 is set of loosely coupled components, the ORM layer wouldn't be necessary in this case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T12:32:31.043",
"Id": "725",
"ParentId": "602",
"Score": "0"
}
},
{
"body": "<p>I'd avoid Singletons - you can limit access by using a dependency injector like YADIF, which makes writing tests against components that rely on the connection easier to create (as well as testing the class itself)</p>\n\n<p>This is a tricky question - DBAL (Database Abstraction Layers) is a deceptively short acronym for a very broad (and hotly debated) topic. </p>\n\n<p>If you want to keep it light, you can write a Transaction script:</p>\n\n<p><a href=\"http://martinfowler.com/eaaCatalog/transactionScript.html\" rel=\"nofollow\">http://martinfowler.com/eaaCatalog/transactionScript.html</a></p>\n\n<p>Basically an OOP wrapper for your apps most common queries (i.e. <strong>saveCompanyEmployees</strong>, <strong>deleteEmployee</strong>, <strong>selectEmployee</strong> etc.). </p>\n\n<p>You can take this up a notch and use assemble queries programmatically, in which case your methods may become more like this:<strong>select($table,$id)</strong>, <strong>selectWhere($table,$condition)</strong> - this is more of a Data Access Object than a Transaction Script</p>\n\n<p>If you find yourself moving towards a fluent interface, or class representations of tables - then you may well want to consider an ORM of some description (it's not really worth writing your own, although it has the advantage of being more tailored to your app and possibly more lightweight, and of course you learn the hard way - which is often the best way...), although these can be a mixed blessing - and personally I think it's slightly perverse to be so averse to SQL to hide it entirely in this manner.</p>\n\n<p>I'd reserve your direct SQL execution as a \"back door\" method you can resort to when all else fails - since having to write the SQL in your application logic kinda ruins the encapsulation benefits of OOP</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T23:16:11.040",
"Id": "885",
"ParentId": "602",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "670",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-04T15:03:42.493",
"Id": "602",
"Score": "8",
"Tags": [
"php",
"mysql",
"php5",
"pdo"
],
"Title": "Database class using PDO"
} | 602 |
<p>Please take a look at my program and let me know how I can improve it.</p>
<pre><code>/*
" To Print A Line On The Display Screen"
Date:5th January 2011
Programmer:Fahad
*/
#include <iostream>
using namespace std;
class Print
{
public:
void print_();
};
int main()
{
Print Obj;
Obj.print_();
system( "pause" );
return 0;
}
void Print::print_()
{
cout << "I am in print function and the program runs fine." << endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T18:33:21.287",
"Id": "1088",
"Score": "3",
"body": "I think you misunderstood the idea of using underscore from my previous post. Usually you want to append the underscore to *private data members* of your class. As others have already pointed out, appending '_' to methods and functions is unconventional and makes it rather arkward for client code to use."
}
] | [
{
"body": "<p>Not sure what you mean by coding style. If you're talking about spacing and such, here are changes I would make. Note that these are entirely subjective and people are probably going to disagree with me.</p>\n\n<p>Don't indent the <code>public:</code> specifier in the class -- leave it flush with the curly braces that mark the class definition. The reason for this is the implicit private region in the class.</p>\n\n<p>Example code:</p>\n\n<pre><code>class Example\n{\n int a; //Shouldn't this line\n public:\n void MyFunc(); //Indent to the same place this one does?\n};\n\n\nclass Ahhhhh\n{\n int a; //Ahhh.. we match now :)\npublic:\n void MyFunc();\n};\n</code></pre>\n\n<p>For that matter this class has no private members so I would just change <code>class</code> to <code>struct</code> and remove the access specifier entirely.</p>\n\n<p>I would remove <code>using namespace std;</code> and explicitly qualify those members which are in <code>std</code>. Would really stink to get a nasty error message from the compiler because you happened to define a function called <code>copy</code> (which might conflict with <code>std::copy</code>).</p>\n\n<p><code>system(\"pause\");</code> should be <code>std::cin.get();</code></p>\n\n<p>If you're talking about \"design\", it seems overengineered to me. No reason to involve objects in a program like this at all. Just sticking the print statement in <code>main</code> would suffice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T16:35:34.053",
"Id": "1081",
"Score": "0",
"body": "I'm assuming the \"overengineering\" is because it was a homework assignment asking them to make a class and provide a method on it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T17:15:27.027",
"Id": "1082",
"Score": "2",
"body": "Personally, I prefer that `private` be explicit too. Easier on my eyes."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T18:16:13.797",
"Id": "1117",
"Score": "0",
"body": "@Mark: Probably. However I mention this because of the huge number of people who avoid free functions and think EVERYTHING_MUST_BE_AN_OBJECT which I see all the time coming from Java people. If that's required for the homework assignment then of course it's fine lol."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T16:25:46.933",
"Id": "605",
"ParentId": "604",
"Score": "9"
}
},
{
"body": "<p>In addition to what Billy said, I find <code>Obj.print_()</code> to look strange in C++ code. I would have just made the method name <code>print()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T16:32:45.367",
"Id": "606",
"ParentId": "604",
"Score": "10"
}
},
{
"body": "<p>In addition to the other comments, I would also use a different naming convention for types and objects.</p>\n\n<p>For example, this looks unconventional.</p>\n\n<pre><code>Print Obj;\nObj.print_();\n</code></pre>\n\n<p>I prefer:</p>\n\n<pre><code>Print obj;\nobj.print();\n</code></pre>\n\n<p>It's just a convention but being able to easily spot names that denote types helps if you start to use more complex expressions. For example:</p>\n\n<pre><code>Print().print();\n</code></pre>\n\n<p>Personally, I would also avoid <code>system(\"pause\")</code>. You need to <code>#include</code> either <code><stdlib.h></code> or <code><cstdlib></code> to use it. Although the system call itself is standard C++ (from the standard C library), what you pass to it is system dependent.</p>\n\n<p>In general I don't believe you should make your programs stop artificially. If they are designed to run in a terminal then the terminal user will be able to see the output even after the program exits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T23:59:47.527",
"Id": "1260",
"Score": "2",
"body": "And if they are designed to run in a terminal, you should run them from a terminal or from a wrapper script which itself holds the terminal open after your program exits."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T16:36:23.403",
"Id": "607",
"ParentId": "604",
"Score": "18"
}
},
{
"body": "<p>I prefer seeing class names that are nouns and method names that are verbs. <code>Print</code> might read better as <code>Printer</code>, <code>ObjectPrinter</code> or <code>WhateverPrinter</code>.</p>\n\n<p>I've seen the _ suffix (or a m_ prefix) to denote members quite a bit but I've never found it useful to attach this sort of decoration to a name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T18:17:10.150",
"Id": "608",
"ParentId": "604",
"Score": "5"
}
},
{
"body": "<p>Under the circumstances, a <code>using</code> directive seems highly suspect. While there are times/places that it's useful, this doesn't seem (to me) to be one of them.</p>\n\n<p>The name of a typical class should also be a noun, not a verb. A verb signals that what you have is a single action, which is not a good candidate for a normal class. If it's going to be a class at all, it should probably be a functor. I'd also add a parameter (with a default value) so it would be easy to use a stream other than <code>std::cout</code> when/if necessary:</p>\n\n<pre><code>struct Print { \n std::ostream &operator()(std::ostream &os = std::cout) { \n return os << \"whatever\\n\";\n }\n};\n</code></pre>\n\n<p>Using <code>system(\"pause\");</code> is also quite non-portable. If you want to wait for the user to press a key before ending the program, it's generally better to build that into your own code:</p>\n\n<pre><code>void pause() { \n std::cout << \"Press \\\"enter\\\" when ready.\\n\";\n getchar();\n}\n\nint main() { \n Print()();\n pause();\n return 0;\n}\n</code></pre>\n\n<p>Frankly, even using the functor strikes me as silly in this case though -- you're taking something simple (print out a string) and making it much more complex without getting anything in return. Given how little the program does, the <code>Print</code> class accomplishes nothing useful or positive at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T18:27:52.493",
"Id": "610",
"ParentId": "604",
"Score": "6"
}
},
{
"body": "<p>The one thing that is not C++ like for me is this:</p>\n\n<pre><code>Obj.print_();\n</code></pre>\n\n<p>This tightly couples the print method to a particular output method.<br>\nIt would be better to allow the user of your object to define what the output method is:</p>\n\n<pre><code>std::cout << Obj << \"\\n\";\n</code></pre>\n\n<p>Which means you need to define an output operator for you object:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& str, Print const& data)\n{\n // STUFF\n return str;\n}\n</code></pre>\n\n<p>Though not technically wrong. I am not a fan of underscore at the ends of identifiers:</p>\n\n<pre><code>print_()\n</code></pre>\n\n<p>Looks wierd to me. But this is a style thing. See you local coding conventions for rules. If you had put it on the front I would have been a lot more complainey about it.</p>\n\n<p>System is hard to use cross platform. Especially when you do system(\"pause\").</p>\n\n<pre><code>system( \"pause\" );\n</code></pre>\n\n<p>I prefer the platform neutral:</p>\n\n<pre><code>std::cout << \"Hit Enter to continue\\n\";\nstd::cin.clear();\nchar plop;\nstd::cin >> plop; // cin is buffered. So nothing is sent until you hit enter.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T21:52:02.957",
"Id": "613",
"ParentId": "604",
"Score": "7"
}
},
{
"body": "<p>I'm really not a fan of putting the <code>main()</code> function in the middle. I prefer it to be the first thing in the file, or the last thing in the file. I would personally have defined your <code>Print</code> class in a header file, put the actual code for it a separate source file, and then put your main function in the main source file... This would make your <code>Print</code> class a lot easier to reuse in another application or turn into a library.</p>\n\n<p>For example</p>\n\n<p><strong>Print.h</strong></p>\n\n<pre><code>#ifndef __PRINT_H__\n#define __PRINT_H__\n\nclass Print\n{\n public:\n void print_();\n};\n\n#endif //__PRINT_H__\n</code></pre>\n\n<p><strong>Print.cpp</strong></p>\n\n<pre><code>#include <iostream>\n#include \"Print.h\"\n\nvoid Print::print_()\n{\n std::cout << \"I am in print function and the program runs fine.\" << std::endl;\n}\n</code></pre>\n\n<p><strong>main.cpp</strong></p>\n\n<pre><code>/*\n\" To Print A Line On The Display Screen\"\n Date:5th January 2011\n Programmer:Fahad\n*/\n#include <stdlib.h>\n#include \"Print.h\"\n\nint main()\n{\n Print Obj;\n Obj.print_();\n system( \"pause\" );\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T22:55:06.530",
"Id": "61535",
"Score": "0",
"body": "Definitely prefer to place your classes in separate source files. It will allow you to reuse code in other projects. It will also help you to think about separating concerns, and can reduce dependencies when you start making large numbers of classes. If everything is in the same file, everything must be recompiled when that one file changes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-09T00:09:44.883",
"Id": "10714",
"ParentId": "604",
"Score": "5"
}
},
{
"body": "<p>The concept of printing is better defined as a method of an object, for instance of the <code>World</code> class. For example, we can define the following:</p>\n\n<pre><code>#include <iostream>\nint main(int argc, char* argv[]){\n class World{\n public:\n World(void){\n std::cout << \"Hello \" << __FUNCTION__ << \"\\n\";\n }\n } Hello;\n}\n</code></pre>\n\n<p>The constructor will print the message as soon as the <code>World</code> object is instantiated as Hello. It is more common to define the class outside of the main, but not forbidden...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-29T00:45:18.773",
"Id": "261851",
"Score": "1",
"body": "If you're going to make a broad statement like `The concept of printing is better defined as a method of an object`, please explain why it is better. Is it more efficient? Does it better meet some Software Design Principal? Your answer is a little lacking and needs to be improved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-29T01:14:03.937",
"Id": "261853",
"Score": "0",
"body": "Thank you for giving me the opportunity to refine my reply. My answer is concise because I prefer to stay to the point and avoid distractions, but in this case, we are dealing with a methodology, Object Oriented Programming, that aims at creating a model and defining how it works. To remain within the spirit of the methodology, we gain in clarity by representing verbs, like \"print\", as being what the object does, and using nouns to describe behavior. This is why I named the class of the object \"World\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-29T00:33:24.773",
"Id": "139893",
"ParentId": "604",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "607",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-04T16:19:12.370",
"Id": "604",
"Score": "13",
"Tags": [
"c++",
"beginner",
"console"
],
"Title": "\"Hello, world!\" program using a class for printing"
} | 604 |
<p>The function below is called to determine if a given file is the archive of another file. I'm also looking for a way to supports wildcards. For example if the original log file is serverw3c.log and we type serverw3c*.log, it returns true for the following:</p>
<ul>
<li>serverw3c.log.2011-02-04</li>
<li>serverw3c.log</li>
<li>serverw3c.log.20110204_120132</li>
<li>serverw3c_20110204.log</li>
</ul>
<p>The code:</p>
<pre><code>/// <summary>
/// Check if a given file is an archive of an original file.
/// The check is performed on the names of the files only.
/// </summary>
/// <param name="originalFile">The original file.</param>
/// <param name="archivedFile">The file which is supposed to be an archive of the original one.</param>
/// <returns>True if the file is an archive, False otherwise.</returns>
public bool IsArchive(string originalFile, string archivedFile)
{
// We assume that an archived file has the name of the original
// concatenated with a timestamp '.YYYYMMDD_HHMMSS'
Regex exp = new Regex(string.Concat(originalFile, ".", "[0-9][0-9][0-9][0-9][0-1][0-9][0-9][0-9]_[0-2][0-9][0-5][0-9][0-5][0-9]"));
if (exp.IsMatch(archivedFile))
return true;
exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile), "_", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]", Path.GetExtension(".log")));
if (exp.IsMatch(archivedFile))
return true;
exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile), "_", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]", "_", "[0-9][0-9][0-9]", Path.GetExtension(".log")));
if (exp.IsMatch(archivedFile))
return true;
exp = new Regex(string.Concat(originalFile, ".", "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]"));
if (exp.IsMatch(archivedFile))
return true;
return false;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T19:04:32.723",
"Id": "1090",
"Score": "0",
"body": "I'm sorry, I can't make the code formatting to work properly."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T19:57:01.513",
"Id": "1091",
"Score": "1",
"body": "Do you need those wildcards to be those date formats, or could they be anything, e.g. `serverw3BACKUP.log`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T20:29:42.847",
"Id": "1094",
"Score": "0",
"body": "Anything, this could replace the function"
}
] | [
{
"body": "<p>Your regex can be shortened using <code>{x}</code>, which repeat a pattern <code>x</code> times. So your third regex would become:</p>\n\n<pre><code>exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile),\n \"_[0-9]{8}_[0-9]{3}\",\n Path.GetExtension(\".log\")));\n</code></pre>\n\n<p>As far as wildcards, if you use <code>*</code> it will be entered into the regex. It looks from <a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.aspx\" rel=\"nofollow\">MSDN</a> that it won't be removed from the file name when you call <code>GetFileNameWithoutExtension()</code>. However, I was unable to test this as I don't have Visual Studio on my computer. It worked as a wildcard on my regex tests.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T19:52:33.120",
"Id": "612",
"ParentId": "611",
"Score": "4"
}
},
{
"body": "<p>Here is the wildcard alternative</p>\n\n<pre><code>public bool IsArchive(string filePattern, string archivedFile)\n{\n return new Regex(filePattern.Replace(\"*\", \"[^ ]*\")).IsMatch(archivedFile);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T10:03:21.743",
"Id": "620",
"ParentId": "611",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "612",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T19:02:43.127",
"Id": "611",
"Score": "6",
"Tags": [
"c#",
"regex"
],
"Title": "How to reduce this archive detection function and make it supports wildcards"
} | 611 |
<p>After asking <a href="https://stackoverflow.com/questions/4868049/how-to-efficiently-wrap-the-index-of-a-fixed-size-circular-buffer">this question</a>, I decided to write a test and determine the fastest way to wrap an index (where my <code>maxSize</code> is always a power of 2).</p>
<p>There are 3 functions that I'm comparing:</p>
<pre><code>// plain wrap
public static int WrapIndex(int index, int endIndex, int maxSize)
{
return (endIndex + index) > maxSize ? (endIndex + index) - maxSize : endIndex + index;
}
// wrap using mod
public static int WrapIndexMod(int index, int endIndex, int maxSize)
{
return (endIndex + index) % maxSize;
}
// wrap my masking out the top bits
public static int WrapIndexMask(int index, int endIndex, int maxSize)
{
return (endIndex + index) & (maxSize - 1);
}
</code></pre>
<p>Here is my test:</p>
<pre><code>public static void WrapTest(int numRuns = 10000)
{
int index = 256;
int endIndex = 0;
int maxSize = 4096;
long wrapPlain = 0;
long wrapMod = 0;
long wrapMask = 0;
Stopwatch sw = new Stopwatch();
for (int i = 0; i < numRuns; i++)
{
// plain
sw.Start();
for (int j = 0; j < numRuns; j++)
{
WrapIndex(index, endIndex, maxSize);
}
sw.Stop();
wrapPlain += sw.ElapsedTicks;
sw.Reset();
// mod
sw.Start();
for (int j = 0; j < numRuns; j++)
{
WrapIndexMod(index, endIndex, maxSize);
}
sw.Stop();
wrapMod += sw.ElapsedTicks;
sw.Reset();
// mask
sw.Start();
for (int j = 0; j < numRuns; j++)
{
WrapIndexMask(index, endIndex, maxSize);
}
sw.Stop();
wrapMask += sw.ElapsedTicks;
sw.Reset();
// change indexes
endIndex++;
endIndex = endIndex % maxSize;
index++;
index = index % maxSize;
}
Console.WriteLine(String.Format("Plain: {0} Mod: {1} Mask: {2}", wrapPlain / numRuns, wrapMod / numRuns, wrapMask / numRuns));
}
</code></pre>
<p>I ran the test and I'm consistently getting the following results (in ticks):</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Plain: 25 Mod: 16 Mask: 16 (maxSize = 512)
Plain: 25 Mod: 17 Mask: 17 (maxSize = 1024)
Plain: 25 Mod: 17 Mask: 17 (maxSize = 4096)
</code></pre>
</blockquote>
<p>I was expecting that the mask will be faster than all of them, but it seems to be as fast as using the modulo operator. I've also tried increasing the <code>numRuns</code>, but the results are consistent. </p>
<p>Is my test valid? Is there a better way to test the performance?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T08:17:44.393",
"Id": "40986",
"Score": "0",
"body": "I think this link may be useful for future visitors: [Benchmarking small code samples in C#](http://stackoverflow.com/questions/1047218/benchmarking-small-code-samples-in-c-can-this-implementation-be-improved)"
}
] | [
{
"body": "<p>Your results do seem odd, so I tried to rewrite your test and see if I can get different results. I suspected that you might be starting and stopping the stopwatch too frequently, which can skew your results due to the loss of precision every time you start and stop. In my code, I only start and stop the stopwatch once per type of calculation.</p>\n\n<p>Using the code below, I get results more in line with what you would expect, namely that masking is the fastest, followed by plain subtraction, followed by modulo division.</p>\n\n<p>Here is a typical output from one of my test runs:</p>\n\n<pre><code>Plain: 59.7033\nMod: 64.6872\nMask: 58.1923\n</code></pre>\n\n<p>In various runs, Plain and Mask tend to vary with respect to each other, and sometimes show very similar numbers. Mod always tends to be slower.</p>\n\n<p>And here is the code:</p>\n\n<pre><code>static void Main(string[] args)\n{\n TestPerf(WrapIndex, \"Plain\");\n TestPerf(WrapIndexMod, \"Mod\");\n TestPerf(WrapIndexMask, \"Mask\");\n}\n\npublic static void TestPerf(Func<int, int, int, int> getIndex, string label, int numRuns = 10000)\n{\n int maxSize = 4096;\n\n Stopwatch sw = new Stopwatch();\n sw.Start();\n\n for (int i = 0; i < numRuns; i++)\n {\n for (int index = 0; index < maxSize; index++)\n {\n getIndex(index, 1234, maxSize);\n }\n }\n\n sw.Stop();\n Console.WriteLine(string.Format(\"{0}: {1}\", label, ((double)sw.ElapsedTicks) / numRuns));\n}\n</code></pre>\n\n<p>EDIT: Also notice that I cast ElapsedTicks to double before dividing to avoid rounding. You should be careful to avoid rounding in your calculations because that just adds noise to your final result.</p>\n\n<p>EDIT 2:\n<br>\nI played around with the code snippet in your pastie link and I was originally getting the same results as you, but I think I've finally gotten to the bottom of it.</p>\n\n<p>What's happening is that without that Func wrapper, the jitter is able to do some serious optimizing. I know it's the jitter and not the C# compiler, because all of the code is intact in the ildasm output. In fact, for 2 out of your 3 methods (mod and mask), it's able to deduce that the methods aren't accomplishing anything at all (because they're doing a simple calculation, and the return value is just discarded), so it doesn't even bother calling them.</p>\n\n<p>To validate that statement, simply comment out the line in WrapIndex() and return a plain 0, which is sure to get optimized out. Run your program again and you'll see that all three methods now report the same times. There's no way that doing a mod or a mask has the same cost as returning a constant 0, so that tells you that the code just isn't being executed.</p>\n\n<p>This is another issue you have to be aware of when doing perf tests. If your test is too simple, the optimizer will just discard all of your code.</p>\n\n<p>In my test, the Func wrapper was preventing the jitter from optimizing as much, because it doesn't know which code is going to be executed, so it can't inline and then discard the code, which is why you get more reasonable numbers.</p>\n\n<p>So I think the results from my code, using the Func delegate, give a more accurate reflection of the relative costs of your three index methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T08:11:49.477",
"Id": "1102",
"Score": "0",
"body": "Are you running it in release mode? I'm seeing almost no difference even if I only reset the stopwatch once and I cast the elapsed ticks to doubles: `Plain: 0.011272 Mod: 0.001699 Mask: 0.001698`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T08:29:40.337",
"Id": "1104",
"Score": "0",
"body": "Note that the version you've suggested also captures the incrementation of the indexes (which should always be the same, but it may have some impact). The above results were with a version nearly identical to yours although I avoid the use of the `Func` delegate, here is a pastie for it: http://www.pastie.org/1530568"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T08:33:09.860",
"Id": "1105",
"Score": "0",
"body": "Any time you're doing perf tests, you have to build it in release mode, and then run it outside of Visual Studio. Even in release mode, VS does extra things to aid in debugging. Try running from the command line and see what happens."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T08:35:00.110",
"Id": "1106",
"Score": "0",
"body": "@Saeed, I was running it in release mode through the exe this whole time... in command prompt I get similar results: `Plain: 0.0114577 Mod: 0.0017611 Mask: 0.001707`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T08:43:47.887",
"Id": "1107",
"Score": "0",
"body": "@Lirik, I updated my answer. Updating the index in the loop shouldn't matter since we're doing it the same for all operation types, but it does add a lot of noise to do two % operations in a perf test that's testing the effects of %. I updated the test to just do a simple iteration over start indices, and always use a fixed end index. This still gives the same kind of results, though plain and mask tend to be closer to each other now, while mod is relatively more expensive."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T11:55:40.640",
"Id": "1109",
"Score": "0",
"body": "@Lirik, see EDIT 2 in my answer. I think I have a good explanation for why your code gives different results than mine."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T07:38:34.980",
"Id": "616",
"ParentId": "615",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "616",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-05T01:28:10.697",
"Id": "615",
"Score": "6",
"Tags": [
"c#",
"performance",
"unit-testing"
],
"Title": "Performance testing functions for wrapping an index"
} | 615 |
<p>I have a piece code similar to below:</p>
<p>But I keep having this nagging feeling that there has to be an easier way!
Any ideas?</p>
<pre><code>var synch = false
var indexArray = new Array();
var rowCount = theTable.find('tr').length;
$(".views").each(function(index) {
indexArray.push( $(this).val()); // Not the real code but something to this effect
if (rowCount <= (index+1)) synch = true;
});
while (!synch);
DO something with indexArray.....
</code></pre>
| [] | [
{
"body": "<p>There is absolutely no need for the <code>synch</code> part - <a href=\"https://stackoverflow.com/questions/2035645/when-is-javascript-synchronous\">JavaScript <em>is</em> synchronous</a>, and you should not get into a situation where the processing of that function (the one you're showing) will not be completed before the next line runs. </p>\n\n<p>(By the way, that function you have there can be rewritten for greater efficiency) </p>\n\n<pre><code>var indexArray = $('.views').map(function(){\n return this.value;\n}).get();\n</code></pre>\n\n<hr>\n\n<p>Let's assume that you <em>are</em> doing something async in that each loop, for instance, ajax calls. Your best bet is to keep a count of how many of the calls are completed in the callback function, then execute the rest of your code when the last callback function is called: </p>\n\n<pre><code>var views = $('.views'), \n completed = 0,\n total = views.length;\n\nviews.each(function(){\n someAsyncFunction (function(){\n // Process data\n if(++completed === total) {\n // We're done! Let's move on..\n }\n });\n});\n</code></pre>\n\n<p>This can be abstracted away into another function, though doing that is left as an exercise for the reader. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T09:43:35.843",
"Id": "1108",
"Score": "0",
"body": "Thanks for that response, I am definitely doing an async call. I just thought that there may be an more elegant solution."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T13:14:32.127",
"Id": "1110",
"Score": "0",
"body": "@Sydwell If you're talking about ajax specifically, you can look at the [`ajaxStop`](http://api.jquery.com/ajaxStop/) function"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T09:14:08.890",
"Id": "618",
"ParentId": "617",
"Score": "3"
}
},
{
"body": "<p>The answer that I was looking for, was very straight forward.</p>\n\n<p>All was required was to put JQuery in synchronis mode by placing using</p>\n\n<pre><code>$.ajaxSetup({async:false});\n</code></pre>\n\n<p>and then doing the ajax calls using $.post(\"...</p>\n\n<p>then just turning it on again</p>\n\n<pre><code>$.ajaxSetup({async:true});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T14:13:55.237",
"Id": "1443",
"Score": "2",
"body": "You uh... do understand what synchronous mode does, right? There is a reason why ajax is asynchronous, a very good one. If you choose to use this, the browser will lock up waiting for the ajax to complete. Seriously, don't disable async unless you can live with that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T11:42:11.893",
"Id": "789",
"ParentId": "617",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "618",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-05T07:57:03.443",
"Id": "617",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"synchronization"
],
"Title": "Making sure all elements are processed in a JQuery call"
} | 617 |
<p>I have written another program in C++. Excluding the point that the class definition should be in a separate header file, is there anything that needs to be improved?</p>
<pre><code>/*
Date:5th January 2011
Programmer:Fahad
*/
#include <iostream>
#include <string>
using namespace std;
class Persons //A class that will store the name,addresses and id numbers of the users
{
private:
string name_;
string address_;
int id_number_;
public:
static int count; //This is the count of the objects created
Persons();
void getData(int n);
void displayData(int n);
~Persons();
};
int Persons count;//initializing the static member
int main()
{
cout << "Enter Number Of Persons:";
int n; //This is the number of objects that the user wants to make.
cin >> n;
Persons *ptr; //A pointer that will be used for the dynamic memory allocation.
/*Exception Handling*/
////////////////////////////////////////////////////////////////////
try
{
//ptr=new [sizeof(Persons) * n];
ptr=new Persons[n];
}
catch(bad_alloc xa)
{
cout<<"Sorry,Program Can Not Continue";
cin.get();
exit(1);
}
/////////////////////////////////////////////////////////////////////
for(int i = 0; i< n; i++)
{
ptr[i].getData(n);
}
for(int j = 0; j< n; j++)
{
ptr[j].displayData( n );
}
cin.get();
delete[] ptr;
return 0;
}
/*Function Definitions*/
Persons::Persons()
{
name_="";
address_="";
id_number_=0;
count++;
}
void Persons::getData(int n)
{
cout<<"Enter Name (Press '$' To Exit):";
getline(cin,name_,'$');
cout<<endl<<"Enter Address (Press '$' To Exit):";
getline(cin,address_,'$');
cout<<endl<<"Enter Identitiy Card Number:";
cin>>id_number_;
}
void Persons::displayData(int n)
{
cout<<"Name:"<<name_;
cout<<endl<<"Address:"<<address_;
cout<<endl<<"Identitiy Card Number:"<<id_number_;
}
</code></pre>
| [] | [
{
"body": "<p>I <a href=\"https://stackoverflow.com/questions/1265039/using-std-namespace/1265092#1265092\">avoid</a> <code>using namespace std;</code>.</p>\n\n<hr>\n\n<pre><code>cout << \"Enter Number Of Persons:\";\nint n; //This is the number of objects that the user wants to make.\ncin >> n;\n</code></pre>\n\n<p>Personally, I always use <code>getline</code> to capture a line at a time when using <code>std::cin</code> for interactive input. The fact that <code>>></code> stops at whitespace means that it is very easy for the user to enter two fields in a single line and then the second field gets used at a subsequent point in the program without the user being able to respond to a later prompt.</p>\n\n<p>Also you should always check whether the input operation succeeded.</p>\n\n<pre><code>std::string inputline;\nif( std::getline( cin, inputline ) )\n{\n std::istringstream iss( inputline );\n if( iss >> n )\n {\n // success\n }\n else\n {\n } // fail\n}\nelse\n{\n // fail\n}\n</code></pre>\n\n<hr>\n\n<pre><code>catch(bad_alloc xa)\n{\n cout<<\"Sorry,Program Can Not Continue\";\n cin.get();\n exit(1);\n}\n</code></pre>\n\n<p>For all that you actually do in the exception handler, you may as well let the expection propogate. The runtime might actually give a more meaningful error message for <code>bad_alloc</code>. Also, unless you have a good reason, always catch exception by <code>const</code> reference. e.g. <code>catch( const std::bad_alloc& ba )</code>.</p>\n\n<hr>\n\n<p>Looking at your definition of <code>Persons</code>, I think that <code>Person</code> is a better name for the class. I see one name and one address member, if the class represented multiple people (e.g. a household) you would need at least multiple names, I would have thought.</p>\n\n<p>Always try and avoid needing to use <code>delete[]</code> explicitly. Here a vector would be much simpler and safer.</p>\n\n<pre><code>std::vector<Person> persons(n);\n</code></pre>\n\n<hr>\n\n<pre><code>int Persons count;//initializing the static member\n</code></pre>\n\n<p>Class <code>static</code> variables are normally not advisable. This isn't valid, it should be:</p>\n\n<pre><code>int Persons::count;\n</code></pre>\n\n<p>In this program it isn't giving you anything that <code>n</code> isn't so I would just remove it.</p>\n\n<hr>\n\n<pre><code>Persons::Persons()\n{\n name_=\"\";\n address_=\"\";\n id_number_=0;\n count++;\n}\n</code></pre>\n\n<p>Always prefer to initialize member variables. Assigning <code>\"\"</code> to a newly constructed <code>std::string</code> is redundant so you could do either.</p>\n\n<pre><code>Persons::Persons()\n : name_()\n , address_()\n , id_number(0)\n{\n count++;\n}\n</code></pre>\n\n<p>or even this (although some people prefer an explicit initializer for all members and bases).</p>\n\n<pre><code>Persons::Persons()\n : id_number(0)\n{\n count++;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>for(int i = 0; i< n; i++)\n{\n ptr[i].getData(n);\n}\nfor(int j = 0; j< n; j++)\n{\n ptr[j].displayData( n );\n}\n</code></pre>\n\n<p>Why do <code>getData</code> and <code>displayData</code> take an <code>int</code>? They don't use the parameter, and I don't understand why you are passing <code>n</code>.</p>\n\n<hr>\n\n<pre><code>cin.get();\n</code></pre>\n\n<p>This seems redundant.</p>\n\n<hr>\n\n<pre><code>void Persons::getData(int n)\n{\n\n cout<<\"Enter Name (Press '$' To Exit):\";\n getline(cin,name_,'$');\n cout<<endl<<\"Enter Address (Press '$' To Exit):\";\n getline(cin,address_,'$');\n cout<<endl<<\"Enter Identitiy Card Number:\";\n cin>>id_number_;\n\n}\n</code></pre>\n\n<p>Again, my comments about the unused parameter, always using <code>getline</code> and always checking the success of input operations all apply.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T16:58:00.397",
"Id": "1114",
"Score": "0",
"body": "The class does represent multiple people.If you have a closer look to the new function used.I take in the number of people the user wants to enter.Thanks a lot for the descriptive answer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T17:01:38.630",
"Id": "1115",
"Score": "0",
"body": "@fahad: Does it? When you ask how many \"Persons\" you then create that number of `Persons` objects. Doesn't that mean you have one `Persons` per \"Person\" (if that makes sense) ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T20:06:22.977",
"Id": "1119",
"Score": "0",
"body": "Oh sorry!I agree,even if the object is one or hundred,each and everyone of them will be modeling individual person."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T20:08:10.867",
"Id": "1120",
"Score": "0",
"body": "Can you please tell me why should I avoid using namespace std?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T20:13:49.843",
"Id": "1123",
"Score": "0",
"body": "@fahad: To some extent it's a matter of style, but the link I provided contains my justification. http://stackoverflow.com/questions/1265039/using-std-namespace/1265092#1265092"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T23:00:39.940",
"Id": "1126",
"Score": "0",
"body": "@Charles:Do you think that I should have a destructor to delete the memory allocated ?Or its ok to do it in main?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T23:22:48.687",
"Id": "1127",
"Score": "0",
"body": "@fahad: A destructor for what? `Persons` doesn't allocate any memory. If you use the recommendation of using a `vector` instead of `new[]` you should be able to avoid doing having to do any deallocation manually."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T11:16:42.823",
"Id": "623",
"ParentId": "621",
"Score": "16"
}
},
{
"body": "<p>First the errors: the static member attribute has to be initialized as:</p>\n\n<pre><code>int Persons::count = 0;\n</code></pre>\n\n<p>Then in general: you should use <code>std::vector</code> to avoid having to manually manage resources. While they are correctly managed in this small code sample, if you start building bigger projects you will most probably make a mistake some day (all of us do it). Program defensively to avoid errors: use existing libraries.</p>\n\n<p>The <code>getData()</code> and <code>displayDAta()</code> member functions do not need the argument, nor they use it. Remove it from the interface.</p>\n\n<p>You are not handling errors in the <code>getData()</code> member function nor in main. You should check the state of the <code>istream</code> after each operation.</p>\n\n<p>I tend to avoid <code>using namespace</code> directives, but this is a matter of taste.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T16:51:08.863",
"Id": "1113",
"Score": "1",
"body": "I guess the static member initializes itself to 0"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T11:23:27.157",
"Id": "624",
"ParentId": "621",
"Score": "3"
}
},
{
"body": "<p>if you need to comment about the use of a variable like:</p>\n\n<pre><code>static int count; //This is the count of the objects created\n</code></pre>\n\n<p>you should use self descriptive names like <code>object_count</code> instead.</p>\n\n<p>same goes for</p>\n\n<pre><code>int n; //This is the number of objects that the user wants to make.\n</code></pre>\n\n<p>which could e <code>amount_of_objects</code> ore something like that</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T12:34:35.897",
"Id": "626",
"ParentId": "621",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p><em>Persons</em> name is quite confusing to represent a single person</p></li>\n<li><p>It looks like the main idea is to serialize/deserialize instance of <em>Person</em> (correct me if I'm wrong here). The more natural is to override <em>operator >></em> and <em>operator <<</em> - it would allow you to specify every stream you want as data source/destination not only standart out/in.</p>\n\n<pre><code>istream& operator>> (istream& in, Person& p) \n{ \n in >> p.Name \n in >> p.Address; \n return in;\n} \n\nostream& operator<< (ostream& out, const Person& p) \n{ \n out << p.Name << 't'; \n out << p.Address << endl; \n return out; \n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T12:36:28.413",
"Id": "627",
"ParentId": "621",
"Score": "3"
}
},
{
"body": "<p>This probably isn't going to be the case, but is this class ever going to be used in a multithreaded application? If so, you should be locking around the incrementing of <code>count</code> since multiple threads could be allocating an object of that type at the same time. In general, be careful when doing that sort of thing though and ask yourself if your class really cares how many times its been constructed, or if you should be keeping track outside of the class itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T14:46:00.840",
"Id": "628",
"ParentId": "621",
"Score": "2"
}
},
{
"body": "<p>When you are including a static count, include a copy constructor which also increments the static variable. If you had used vector instead of array, your count variable will not give the correct count. Also make sure you decrement in destructor. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-07T09:27:04.313",
"Id": "1711",
"ParentId": "621",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-05T10:55:43.063",
"Id": "621",
"Score": "12",
"Tags": [
"c++",
"classes"
],
"Title": "Class for holding person's information"
} | 621 |
<p>I've got a Clojure function here that's meant to parse a string of form:</p>
<blockquote>
<p>"DDXXXYYY"</p>
</blockquote>
<p>where DD is meant to be discarded, and XXX and YYY are string representations of integers.</p>
<pre><code>(defn split-id [tileid]
(map #(Integer/parseInt %)
(map (partial apply str)
(partition 3 (drop 2 tileid)))))
</code></pre>
<p>Or, written with the threading macro:</p>
<pre><code>(defn split-id [tileid]
(map #(Integer/parseInt %)
(map (partial apply str)
(->> tileid (drop 2) (partition 3)))))
</code></pre>
<p>Does anyone have any recommendations for a simple way to do this? It feels like <code>clojure.contrib.string</code> should have a partition function that takes a string and an integer.</p>
<p>I think I've come up with a fairly good block of code for the above function, which I had to extend a bit. I'd love comments and suggestions on the final block.</p>
<pre><code>(defn parse-ints
"Converts all strings in the supplied collection to their integer
representation."
[coll]
(map #(Integer/parseInt %) coll))
(def res-map
^{:doc "Map between the second digit in a MODIS TileID
metadata value and the corresponding resolution."}
{:1 "1000"
:2 "500"
:4 "250"})
(defn tileid->res
"Returns a string representation of the resolution referenced by the
supplied MODIS TileID."
[tileid]
(res-map (keyword (subs tileid 1 2))))
(defn tileid->xy
"Extracts integer representations of the MODIS X and Y coordinates
referenced by the supplied MODIS TileID."
[tileid]
(parse-ints
(map (partial apply str)
(partition 3 (subs tileid 2)))))
(defn split-id
"Returns a sequence containing the resolution, X and Y
coordinates (on the MODIS grid) referenced by the supplied MODIS
TileID."
[tileid]
(flatten
((juxt tileid->res
tileid->xy) tileid)))
</code></pre>
| [] | [
{
"body": "<p>You could try the following, using the Java substring method and a vector of offsets:</p>\n\n<pre><code>(defn split-id [tileid]\n (map \n #(Integer. (.substring tileid % (+ % 3)) ) \n [2 5]))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T00:50:07.453",
"Id": "635",
"ParentId": "631",
"Score": "2"
}
},
{
"body": "<p>Alternative solution is to keep it really simple:</p>\n\n<pre><code>(defn extract-int [s start end]\n (Integer/parseInt (subs s start end)))\n\n(defn split-id [s]\n (list\n (extract-int s 2 5)\n (extract-int s 5 8)))\n</code></pre>\n\n<p>I believe that hardcoding two calls to extract-int is a simpler and more elegant way to meet the requirement than a solution which involves a map. Sure it's nice to use abstraction with higher-order functions, but YAGNI principle applies.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-19T16:11:13.053",
"Id": "2483",
"ParentId": "631",
"Score": "6"
}
},
{
"body": "<p>Just a though, perhaps you're looking at this the wrong way. This is a parsing question, and simple parses are often best executed through regular expressions. Clojure has reader macros and special functions to work with Java regexes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-03T15:55:46.583",
"Id": "3847",
"ParentId": "631",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "2483",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-05T20:46:52.977",
"Id": "631",
"Score": "7",
"Tags": [
"strings",
"clojure"
],
"Title": "Partitioning strings into substrings of fixed length"
} | 631 |
<p>This is what I've done so far:</p>
<pre><code>$block-height: 180px;
@mixin block {
float: left;
margin-bottom: 20px !important;
margin-right: 20px !important;
overflow: hidden;
}
#content h2 {
height: 30px;
}
#top-bar {
overflow: hidden;
}
.block-1 {
@include block;
width: 340px;
height: 390px;
h2 {
color: #555;
font-size: 28px;
font-weight: 400;
line-height: 120%;
}
}
.block-2 {
@include block;
width: 340px;
height: $block-height;
}
.block-3 {
@include block;
width: 160px;
height: $block-height;
}
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><div id="content">
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&locations=Front Page&page_sections=Profile');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-1">
<?php the_post_thumbnail('large'); ?>
</div>
<?php endwhile; ?>
<?php // Start the main loop
if ( have_posts() ) while ( have_posts() ) : the_post();
?>
<div class="block-2 padding-top">
<?php the_content(); ?>
</div><!-- .entry-content -->
<?php endwhile; // end of the loop. ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&locations=Front Page&page_sections=Themep');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-2 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&locations=Front Page&page_sections=ThemeCL');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="float-left">
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&locations=Front Page&page_sections=Theme Child Right');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="float-right">
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&locations=Front Page&page_sections=FromBlog');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-3 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
<p><?php echo get_post_meta($post->ID, "Other_Work", true); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&locations=Front Page&page_sections=Featured');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-2 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail('large'); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Last');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-3 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
<p><?php the_meta(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Lastest');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-7 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
</div><!-- #content -->
</code></pre>
<p>Do you have any other tips for good practice?</p>
| [] | [
{
"body": "<p>It looks a bit like block-1's height is calculated from @block-height, in which case I would do that calculation rather than putting in a literal value. This way if you change @block-height, block-1 will adjust with it.</p>\n\n<p>Beyond Sass and efficiency, I would also advise you to think again about the class names block-1, block-2 and block-3. If there will only be one of each of these on a page then use IDs rather than classes and name them after the content (eg. site-nav-block or article-block). If there will be more than one then give it a class name and name it after the content type (eg. nav-item or article-summary).</p>\n\n<p>This will be much less confusing for a third party like myself to read, and indeed for you as your page gets bigger and requires more styling.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T20:30:28.363",
"Id": "666",
"ParentId": "634",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T00:09:11.227",
"Id": "634",
"Score": "5",
"Tags": [
"php",
"css",
"sass"
],
"Title": "Adding flair to PHP page with Sassy (SCSS)"
} | 634 |
<p>I haven't had anyone help me out with code review, etc, so I thought I'd post a Python class I put together for interfacing with Telnet to get information from a memcached server.</p>
<pre><code>import re, telnetlib
class MemcachedStats:
_client = None
def __init__(self, host='localhost', port='11211'):
self._host = host
self._port = port
@property
def client(self):
if self._client is None:
self._client = telnetlib.Telnet(self._host, self._port)
return self._client
def key_details(self, sort=True):
' Return a list of tuples containing keys and details '
keys = []
slab_ids = self.slab_ids()
for id in slab_ids:
self.client.write("stats cachedump %s 100\n" % id)
response = self.client.read_until('END')
keys.extend(re.findall('ITEM (.*) \[(.*); (.*)\]', response))
if sort:
return sorted(keys)
return keys
def keys(self, sort=True):
' Return a list of keys in use '
return [key[0] for key in self.key_details(sort=sort)]
def slab_ids(self):
' Return a list of slab ids in use '
self.client.write("stats items\n")
response = self.client.read_until('END')
return re.findall('STAT items:(.*):number', response)
def stats(self):
' Return a dict containing memcached stats '
self.client.write("stats\n")
response = self.client.read_until('END')
return dict(re.findall("STAT (.*) (.*)\r", response))
</code></pre>
<p>This is also up on <a href="https://github.com/dlrust/python-memcached-stats/blob/master/src/memcached_stats.py" rel="nofollow">GitHub</a>. </p>
<p>I would love some feedback on:</p>
<ul>
<li>Organization</li>
<li>Better ways of accomplishing the same result</li>
</ul>
| [] | [
{
"body": "<p>The pattern</p>\n\n<pre><code>self.client.write(\"some command\\n\")\nresponse = self.client.read_until('END')\n</code></pre>\n\n<p>appears three times in your code. I think this is often enough to warrant refactoring it into its own method like this:</p>\n\n<pre><code>def command(self, cmd):\n self.client.write(\"%s\\n\" % cmd)\n return self.client.read_until('END')\n</code></pre>\n\n<hr>\n\n<p>In <code>key_details</code> you're using <code>extend</code> to build up a list. However it's more pythonic to use list comprehensions than building up a list imperatively. Thus I'd recommend using the following list comprehension:</p>\n\n<pre><code>regex = 'ITEM (.*) \\[(.*); (.*)\\]'\ncmd = \"stats cachedump %s 100\"\nkeys = [key for id in slab_ids for key in re.findall(regex, command(cmd % id))]\n</code></pre>\n\n<hr>\n\n<p>Afterwards you do this:</p>\n\n<pre><code>if sort:\n return sorted(keys)\nreturn keys\n</code></pre>\n\n<p>Now this might be a matter of opinion, but I'd rather write this using an <code>else</code>:</p>\n\n<pre><code>if sort:\n return sorted(keys)\nelse:\n return keys\n</code></pre>\n\n<p>I think this is optically more pleasing as both <code>return</code>s are indented at the same level. It also makes it immediately obviously that the second <code>return</code> is what happens if the <code>if</code> condition is false.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T05:24:21.443",
"Id": "1189",
"Score": "0",
"body": "thanks! I've incorporated some of these into the code on github. I also added precompiled versions of the regex into the class"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T05:26:09.680",
"Id": "1190",
"Score": "0",
"body": "Also, as far as the list comprehension goes. Since `re.findall(regex, command(cmd % id))` can return multiple items, I am using extend. Is there a way to build a list that extends itself vs item by item building?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T05:31:04.700",
"Id": "1191",
"Score": "0",
"body": "@dlrust: Yes, of course, you need to add another `for` in the list comprehension to get a flat list. I actually meant to do that, but forgot somehow."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T19:39:37.137",
"Id": "1207",
"Score": "0",
"body": "Thanks. Not sure if this is the best way to do this, but it works `keys = [j for i in [self._key_regex.findall(self.command(cmd % id)) for id in self.slab_ids()] for j in i]`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T19:43:32.983",
"Id": "1208",
"Score": "0",
"body": "@lrust: By using an inner list like that, you need one more `for` than you would otherwise. Does `[key for id in slab_ids for key in self._key_regex.findall(self.command(cmd % id))]` not work for you?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T05:08:06.750",
"Id": "638",
"ParentId": "636",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "638",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T01:42:42.690",
"Id": "636",
"Score": "10",
"Tags": [
"python",
"networking"
],
"Title": "Python class w/ Telnet interface to memcached"
} | 636 |
<p>I basically have an AJAX-fetched skin (html/css) that's loaded into a dummy element (id=SkinContainer) when the page is loaded, and then the content of one of its divs (contentdiv) is fetched with another AJAXHTTPRequest.</p>
<p>At any rate, when the page is loaded, the user can click a button to swap the theme/skin. Below is the (working) code for my theme swap, but I'm wondering whether or not it's the best way to do this:</p>
<pre><code>function themeSwap() {
var oldTheme = themeSelect;
themeSelect++;
if (themeSelect>2 || themeSelect<1) {themeSelect=1;}
$('html').addClass('js');
var tempContentDiv = document.getElementById("contentdiv");
var tempContent = tempContentDiv.innerHTML;
ReplaceJSCSSFile("css/skin" + oldTheme + ".css", "css/skin" + themeSelect + ".css", "css");
AJAX_LoadResponseIntoElement("skinContainer", "skin" + themeSelect + ".txt", function() {themeSwapCallback(tempContent)} );
}
function themeSwapCallback (tempContent) {
initPage();
document.getElementById("contentdiv").innerHTML = tempContent;
setCookie("themeSelection",themeSelect,365);
}
</code></pre>
<p>What this basically does is stores the innerHTML of contentdiv into the "tempContent" variable, loads the new skin into skinContainer with an AJAX fetch, and then restores the original content by setting contentdiv's innerHTML to "tempContent."</p>
<p>The reason why it has to use an AJAX fetch on top of the CSS swap is because the structure of the elements changes. </p>
<p>Have I finally have this done correctly? or is this still not perfect? :(</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T06:30:32.000",
"Id": "1145",
"Score": "2",
"body": "Have you looked at http://www.alistapart.com/articles/bodyswitchers/?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T06:54:22.597",
"Id": "1146",
"Score": "0",
"body": "I did read it, but I don't understand it and don't understand what advantages it offers. Unfortunately, I only have about 3 months experience with web development."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T10:43:14.600",
"Id": "58771",
"Score": "2",
"body": "Also look at http://www.csszengarden.com/ which should help you understand that you only ever need to change CSS to make a theme swap."
}
] | [
{
"body": "<p>My 2 cents:</p>\n\n<ul>\n<li><p>The code is not bad, I really only have minor nitpickings</p></li>\n<li><p>Your theme selection code use a trinary:</p></li>\n</ul>\n\n<blockquote>\n<pre><code>var oldTheme = themeSelect;\nvar themeSelect = themeSelect==1?2:1;\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Since you only use tempContentDiv once, you might as well do</li>\n</ul>\n\n<blockquote>\n <p><code>var tempContent = document.getElementById(\"contentdiv\").innerHTML;</code></p>\n</blockquote>\n\n<ul>\n<li>Alternatively, you could store the reference to <code>contentdiv</code> somewhere else, so that you do not have to repeat the <code>document.getElementById</code> call</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T13:52:09.827",
"Id": "36958",
"ParentId": "639",
"Score": "2"
}
},
{
"body": "<p>Without having any other information available as to the restrictions of the project, I have to say that I do not like this implementation whatsoever.</p>\n\n<p>The smartest way to go about swapping css \"themes\" is by ONLY changing class definitions. There are several ways to do this, but in the case of a \"themed\" application the most practical approach would be having seperate .css files for each theme. </p>\n\n<p>So for example, given the following HTML:</p>\n\n<pre><code><div class=\"header\">\n <div id=\"logo\"></div>\n</div>\n</code></pre>\n\n<p>...and theme-default.css:</p>\n\n<pre><code>.header { background-color: black; height: 200px; width: 100%; }\n.logo { background-image: url('/images/logo.jpg'); height: 200px; width: 200px; }\n</code></pre>\n\n<p>...and theme-red.css:</p>\n\n<pre><code>.header { background-color: red; height: 200px; width: 100%; }\n.logo { background-image: url('/images/logo-red.jpg'); height: 200px; width: 200px; }\n</code></pre>\n\n<p>You would only need to swap out the css URL that is being called, something like this:</p>\n\n<pre><code>$(function(){\n $(\"#btnChange\").click(function() {\n $('link[href=\"theme-default.css\"]').attr('href','theme-red.css');\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T14:36:08.607",
"Id": "36962",
"ParentId": "639",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T05:23:13.670",
"Id": "639",
"Score": "8",
"Tags": [
"javascript",
"html",
"css",
"ajax"
],
"Title": "Theme/skin swap... version 2! (CSS-driven)"
} | 639 |
<p>Instead of writing four almost identical <code>setOnClickListener</code> method calls, I opted to iterate over an array, but I'm wondering if this was the best way to do it. Do you have any suggestions for improving it?</p>
<pre><code>/* Set up the radio button click listeners so two categories are not selected
at the same time. When one of them is clicked it clears the others.
*/
final RadioButton[] buttons = {radio_books,radio_games,radio_dvds,radio_electronics};
for (int i = 0; i < 4; i++) {
final int k = i;
buttons[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int j = 0; j < 4; j++) {
if (buttons[j] != buttons[k]) {
buttons[j].setChecked(false);
}
}
}
});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T18:24:55.580",
"Id": "6789",
"Score": "0",
"body": "One thing I'd recommend is to use lowerCamelCase for variable names. That's the variable naming convention for Java"
}
] | [
{
"body": "<p>It's typical callback method, you just <strong>defined</strong> <code>setOnClickListener</code> once. Calling 4 times is not bad <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smell</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T03:18:24.573",
"Id": "642",
"ParentId": "640",
"Score": "2"
}
},
{
"body": "<p>What GUI framework is this? Is the <code>View v</code> being passed to the <code>OnClick</code> method actually the clicked <code>RadioButton</code>? If so, here are some changes to consider</p>\n\n<pre><code>final RadioButton[] buttons = {radio_books,radio_games,radio_dvds,radio_electronics};\n\nfinal OnClickListener onClickHandler =\n new OnClickListener() {\n @Override\n public void onClick(final View v) {\n final RadioButton checkedButton = (RadioButton) v;\n for (final RadioButton button : buttons) {\n if (button != checkedButton) {\n button.setChecked(false);\n }\n }\n }\n };\n\nfor (final RadioButton button : buttons) {\n button.setOnClickListener(onClickHandler);\n}\n</code></pre>\n\n<p>If <code>View v</code> != the checked radio button, then:</p>\n\n<pre><code>final RadioButton[] buttons = {radio_books,radio_games,radio_dvds,radio_electronics};\nfor (final RadioButton thisButton: buttons) {\n thisButton.setOnClickListener(\n new OnClickListener() {\n @Override\n public void onClick(final View v) {\n for (final RadioButton button : buttons) {\n if (button != thisButton) {\n button.setChecked(false);\n }\n }\n }\n }\n );\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T06:17:05.733",
"Id": "1141",
"Score": "0",
"body": "Why are you still looping over the button array in the listener in your first solution?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T06:20:33.707",
"Id": "1142",
"Score": "0",
"body": "@Paul - Because he's trying to uncheck the buttons that were not the clicked one, so it loops to get to all the buttons and uses the if to exclude the one that was clicked. Or am I misunderstanding your question?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T06:26:02.843",
"Id": "1144",
"Score": "0",
"body": "@Paul - lol - its 1:24am here - I risking misread the code myself, so I understand the feeling. Actually, thanks for reminding me of the time :-) need sleep ..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T07:09:02.917",
"Id": "1147",
"Score": "1",
"body": "It's the android GUI framework. The RadioGroup that handles the boilerplate of making sure only one radio button is active at a time failed on me because I need a layout that was a bit more complicated."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T07:12:22.087",
"Id": "1148",
"Score": "0",
"body": "Also, I like your take on using the View passed into the onClick method and I'll see if I can get away with not having `final int k = i`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T07:20:35.440",
"Id": "1149",
"Score": "1",
"body": "Ok, thanks for the feedback. I think with the improved 'for' loops and using the View argument of onClick to perform the exclusion it can't be improved further."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T06:12:52.973",
"Id": "643",
"ParentId": "640",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "643",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-06T03:08:27.397",
"Id": "640",
"Score": "13",
"Tags": [
"java",
"event-handling",
"gui"
],
"Title": "Setting up radio button click ActionListeners"
} | 640 |
<p>I wrote the following Ruby script several years ago and have been using it often ever since.</p>
<p>It opens a text editor with the list of files in current directory. You can then edit the file names as text. Once you save and exit the files are renamed.</p>
<p>The <code>renamer</code> allowed me to maintain spreadsheet-like file names thanks to the powerful column editing capabilities of vi (emacs also has those).</p>
<p>Here is how one such directory looks:</p>
<p><img src="https://i.stack.imgur.com/gvomL.png" alt="enter image description here"></p>
<p>I would like to use it as an example for a Ruby workshop. Could you please suggest best-practice and design pattern improvements?</p>
<pre><code>#!/usr/bin/ruby
RM = '/bin/rm'
MV = '/bin/mv'
from = Dir.entries('.').sort; from.delete('.'); from.delete('..')
from.sort!
from.delete_if {|i| i =~ /^\./} # Hidden files
tmp = "/tmp/renamer.#{Time.now.to_i}.#{(rand * 1000).to_i}"
File.open(tmp, 'w') do |f|
from.each {|i| f.puts i}
end
ENV['EDITOR'] = 'vi' if ENV['EDITOR'].nil?
system("#{ENV['EDITOR']} #{tmp}")
to = File.open(tmp) {|f| f.readlines.collect{|l| l.chomp}}
`#{RM} #{tmp}`
if to.size != from.size
STDERR.puts "renamer: ERROR: number of lines changed"
exit(1)
end
from.each_with_index do |f, i|
puts `#{MV} -v --interactive "#{f}" "#{to[i]}"` unless f == to[i]
end
</code></pre>
| [] | [
{
"body": "<p>Just a couple of things:</p>\n\n<pre><code>#!/usr/bin/ruby\n</code></pre>\n\n<p>It's possible that on some systems this isn't where ruby lives, it's better to do:</p>\n\n<pre><code>#!/usr/bin/env ruby\n</code></pre>\n\n<hr>\n\n<pre><code>from = Dir.entries('.').sort; from.delete('.'); from.delete('..')\n</code></pre>\n\n<p>Can be written as</p>\n\n<pre><code>from = Dir.entries('.').sort - ['.', '..']\n</code></pre>\n\n<p>Which is more succinct and eliminates having three statements on one line (which you shouldn't do).</p>\n\n<p>Or you could eliminate hidden files and . / .. in one go with:</p>\n\n<pre><code>from = Dir.entries(.).select do |filename|\n filename[0].chr != '.'\nend\n</code></pre>\n\n<p><em>Edit:</em></p>\n\n<pre><code>from = Dir.glob(\"*\").sort\n</code></pre>\n\n<p>Is definitely the best solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T07:53:38.223",
"Id": "1150",
"Score": "0",
"body": "Using the `/usr/bin/env` trick is especially important for people who've compiled Ruby themselves or (like me, and a lot of the Ruby world) are using RVM."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:06:11.630",
"Id": "1153",
"Score": "3",
"body": "I just replaced the whole thing with `from = Dir.glob(\"*\").sort`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T07:37:31.497",
"Id": "647",
"ParentId": "645",
"Score": "5"
}
},
{
"body": "<pre><code>RM = '/bin/rm'\nMV = '/bin/mv'\n</code></pre>\n\n<p>In general it's preferable to use the <a href=\"http://ruby-doc.org/stdlib/libdoc/fileutils/rdoc/index.html\"><code>FileUtils</code> class</a> rather than relying on shell utilities. Though in this particular case, you might want to stick at least with <code>mv</code> since the <code>FileUtils.mv</code> method does not have an <code>:interactive</code> option.</p>\n\n<hr>\n\n<pre><code>tmp = \"/tmp/renamer.#{Time.now.to_i}.#{(rand * 1000).to_i}\"\n</code></pre>\n\n<p>Ruby has a <a href=\"http://ruby-doc.org/stdlib/libdoc/tempfile/rdoc/index.html\"><code>Tempfile</code> class</a> which can generate a unique temporary file more reliably than this. You should use it.</p>\n\n<hr>\n\n<pre><code>from.each {|i| f.puts i}\n</code></pre>\n\n<p>Calling <code>puts</code> on an array will <code>puts</code> each line individually, so the above can just be shortened to <code>f.puts from</code>.</p>\n\n<hr>\n\n<pre><code>ENV['EDITOR'] = 'vi' if ENV['EDITOR'].nil?\n</code></pre>\n\n<p>Can be shortened to <code>ENV['EDITOR'] ||= 'vi'</code>. Though what you have isn't particularly verbose either, so it doesn't really matter much which one you choose.</p>\n\n<hr>\n\n<pre><code>system(\"#{ENV['EDITOR']} #{tmp}\")\n</code></pre>\n\n<p>Use <code>system(ENV[EDITOR], tmp)</code> instead. This way you get rid of the string interpolation and the code still works if either <code>ENV['EDITOR']</code> or <code>tmp</code> should contain a space or other shell meta-character (not that they're particularly likely to, but it's a good idea to use the multiple-argument-form of <code>system</code> where ever possible).</p>\n\n<hr>\n\n<pre><code>to = File.open(tmp) {|f| f.readlines.collect{|l| l.chomp}}\n</code></pre>\n\n<p>Usually this could be replaced with <code>to = File.readlines(tmp).collect {|l| l.chomp}</code>. However if you follow my suggestion of using <code>Tempfile</code>, that won't be an option any more.</p>\n\n<hr>\n\n<pre><code>`#{RM} #{tmp}`\n</code></pre>\n\n<p>If you use fileutils, this will just be <code>FileUtils.rm(tmp)</code> (or <code>rm(tmp)</code> if you include <code>FileUtils</code>). If you don't want to use <code>FileUtils</code>, you should at least use <code>system(RM, tmp)</code> for the same reasons as above.</p>\n\n<p>However if you use <code>Tempfile</code>, which you should, this becomes redundant anyway.</p>\n\n<hr>\n\n<pre><code>from.each_with_index do |f, i|\n puts `#{MV} -v --interactive \"#{f}\" \"#{to[i]}\"` unless f == to[i]\nend\n</code></pre>\n\n<p>To iterate over two arrays in parallel, use <code>zip</code>:</p>\n\n<pre><code>from.zip(to) do |f, t|\n system(MV, \"-v\", \"--interactive\", f, t) unless f == t\nend\n</code></pre>\n\n<p>Note that here using <code>system</code> instead of backticks is especially important since one of the files in <code>from</code> or <code>to</code> containing spaces is actually somewhat likely.</p>\n\n<hr>\n\n<p>So with all my suggestions, your code should now look like this:</p>\n\n<pre><code>#!/usr/bin/env ruby\nrequire 'tempfile'\n\nMV = '/bin/mv'\n\nfrom = Dir.glob('*').sort\n\nENV['EDITOR'] ||= 'vi'\n\nto = nil\nTempfile.open(\"renamer\") do |f|\n f.puts from\n f.close\n system(ENV['EDITOR'], f.path)\n f.open\n to = f.readlines.collect {|l| l.chomp}\nend\n\nif to.size != from.size\n STDERR.puts \"renamer: ERROR: number of lines changed\"\n exit(1)\nend\n\nfrom.zip(to) do |f, t|\n system(MV, \"-v\", \"--interactive\", f, t) unless f == t\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T21:33:07.620",
"Id": "1185",
"Score": "0",
"body": "Surprisingly, `to = Tempfile.open(...){...; \"result\"}` does not work. `to` gets nil. Ruby 1.8.7"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T21:39:35.563",
"Id": "1186",
"Score": "0",
"body": "@Aleksandr: Bah, stupid of me to forget to replace the `tmp`. That `open` does not return the block's result surprises me too (I had not tested it previously). Anyway I've fixed it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T01:32:14.303",
"Id": "1266",
"Score": "0",
"body": "A very good review of the code and a good look at \"idiomatic\" Ruby. Well done"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T16:40:31.397",
"Id": "660",
"ParentId": "645",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "660",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T06:51:17.670",
"Id": "645",
"Score": "10",
"Tags": [
"ruby",
"file-system"
],
"Title": "A text editor driven file renamer in Ruby"
} | 645 |
<p>I just want to make sure there aren't any deadlocks or inconsistencies (the code is also available on <a href="https://github.com/ripper234/Basic/blob/master/java/src/main/java/org/basic/concurrent/SynchedQueue.java" rel="nofollow noreferrer">GitHub</a>). </p>
<p><strong>Disclaimer</strong> - In real life, I would not implement a queue myself, but use an existing implementation. This is just preparations for job interviews.</p>
<pre><code>package org.basic.concurrent;
import java.util.ArrayList;
import java.util.List;
public class SynchedQueue<T> {
private final Object lock = new Object();
private final Object full = new Object();
private final Object free = new Object();
private final List<T> buffer;
private int head;
private int tail;
private int size;
private final int capacity;
public SynchedQueue(int capacity) {
// http://stackoverflow.com/questions/4912088/how-to-create-a-fixed-size-generic-buffer-in-java
buffer = new ArrayList<T>(capacity);
for (int i = 0; i < capacity; ++i)
buffer.add(null);
this.capacity = capacity;
}
public void enqueue(T x) {
if (x == null)
throw new RuntimeException("Doesn't allow storing nulls");
synchronized (lock) {
while (!tryEnqueue(x)) {
try {
free.wait();
} catch (InterruptedException ignored) {
}
}
full.notify();
}
}
public T dequeue() {
synchronized (lock) {
while (true) {
T item = tryDequeue();
if (item != null)
{
free.notify();
return item;
}
try {
full.wait();
}
catch (InterruptedException ignored) {}
}
}
}
private boolean tryEnqueue(T x) {
assert size <= capacity;
if (size >= capacity) {
return false;
}
buffer.set(tail, x);
tail = (tail + 1) % capacity;
++size;
return true;
}
private T tryDequeue() {
assert size >= 0;
if (size == 0)
return null;
T item = buffer.get(head);
head = (head + 1) % capacity;
--size;
return item;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T06:29:09.063",
"Id": "1194",
"Score": "0",
"body": "(1) if you are prepping for interviews, consider what tests you could write for this. (2) call trimToSize() on your buffer after you're done adding to it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T06:38:17.793",
"Id": "1195",
"Score": "2",
"body": "I don't think your notify and wait calls will work because you haven't synchronized on the free and full objects before calling those methods."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T16:30:48.863",
"Id": "1201",
"Score": "0",
"body": "@Ron, thanks for the second comment, it's invaluable."
}
] | [
{
"body": "<p>I have not coded in Java for a few years so it might be good to get another opinion, though some points did stand out while reading your code.</p>\n\n<ul>\n<li><p>It seems odd to me that you would use an <code>ArrayList</code> with a fixed size, personally I would just use an array for the buffer.</p></li>\n<li><p>when you dequeue, you do not overwrite the value until you enqueue over the top of it. This might not seem like an issue (and if you only queue primative types like <code>int</code>, its not) but if you use reference types and the queue cycles slowly then it means you hold a reference to the object for longer than needed and it cannot be collected.</p></li>\n<li><p>I'm a bit worried about catching the <code>InterruptedException</code> inside a while(true) loops without breaking out of the loop. The most common reason I have seen for one thread to interrupt another is when the interrupting thread wants to give the interrupted thread the opportunity to terminate gratefully, but this will prevent that option. I thought about what can be returned in such a case and eventually decided it might be best to let this exception flow through and be handled by the caller.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T11:08:28.897",
"Id": "1162",
"Score": "0",
"body": "+1 for the memory leak. Regarding your first point, see http://stackoverflow.com/questions/4912088/how-to-create-a-fixed-size-generic-buffer-in-java. Regarding your third point - you have to do it like this in order to handle spurious wakups. If you want to be able to break from the wait, you have to add another state variable and check that. http://stackoverflow.com/questions/1050592/do-spurious-wakeups-actually-happen"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:17:44.713",
"Id": "649",
"ParentId": "646",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>It looks like a BlockingQueue not just SynchQueue</p></li>\n<li><p><em>throw new RuntimeException(\"Doesn't allow storing nulls\");</em> - there is <em>IllegalArgumnetException</em> for this.</p></li>\n<li><p>It would better to add <em>throws InterruptedException</em> to method declaration rather than swallowing it.</p></li>\n<li><p>You are going to add/remove from the tail/head of the internal buffer - LinkedList looks like better options for internal storage. You don't need tons of Array.Copy in this case. It would also remove those <em>tryDequeue()</em> and <em>tryEnqueue()</em> and greatly simplify the code. </p></li>\n<li><p>This code doesn't work in a single thread scenario. Consider the situation when I call <em>enqueue()</em> for the first time on queue then <em>full.notify()</em> will fail immediately.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T11:05:58.293",
"Id": "1161",
"Score": "0",
"body": "Regarding 2 - no it is not. http://stackoverflow.com/questions/442564/avoid-synchronizedthis-in-java. Regarding 6 - why do you think full.notify() will fail?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T11:24:18.650",
"Id": "1164",
"Score": "0",
"body": "Regarding 2 - thanks for link. Regarding 6 - we are using notify/wait pattern on object that is different from one that is's used in synchronized block. Therefore, we should either use synchronized on method level and use queue's notify/wait or synchronize on the same object."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T14:06:39.273",
"Id": "1199",
"Score": "0",
"body": "ArgumentNullException is for C# I think."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T15:19:40.580",
"Id": "1200",
"Score": "0",
"body": "Thanks for check for ArgumentNullException - fixed. As for call to notify() - even if I run a new Object().notify() as a only line in a main() routine?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T17:14:30.030",
"Id": "1204",
"Score": "0",
"body": "I see what you mean, I think you're right."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T17:23:38.367",
"Id": "1205",
"Score": "0",
"body": "I tried to explain the problem with notify() with a little more detail in my answer now."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T17:25:07.540",
"Id": "1206",
"Score": "0",
"body": "I agree with @ripper234 that it's better to not mark methods as synchronized."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:27:55.167",
"Id": "650",
"ParentId": "646",
"Score": "1"
}
},
{
"body": "<p>Have you tried running this implementation? It fails immediately with a <code>java.lang.IllegalMonitorStateException</code> which according to the Javadoc is:</p>\n\n<blockquote>\n <p>Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.</p>\n</blockquote>\n\n<p>The problem is that the implementation synchronizes on the field <code>lock</code> but calls <code>notify()</code> and <code>wait()</code> on <code>full</code> and <code>free</code> without holding their locks. When you fix this, it's important to keep in mind that calling wait() automatically releases the lock of the object you are waiting on, but does not release locks on other objects. If you don't take that into account, it's quite easy to create deadlocks.</p>\n\n<p>For readability, I'd recommend using <a href=\"http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html\" rel=\"nofollow\">java.util.concurrent.locks.Condition</a> instead of <code>wait()</code> and <code>notify()</code> which are fairly low level and difficult to reason about. In fact, the example usages in the Javadoc for Condition come from the implementation of a bounded buffer.</p>\n\n<p>I also have to echo Brian's concern: it's important that you don't silently swallow <code>InterruptedException</code>. You have two choices on how to handle interruption. If you want to handle the exception yourself, then JCIP says you need to set the interrupted status back.</p>\n\n<pre><code>catch (InterruptedException e)\n{\n Thread.interrupt();\n // Handle the interruption\n}\n</code></pre>\n\n<p>The other choice, which is better in my opinion, is to just propagate the exception. Java's built in libraries use this strategy, for an example see <a href=\"http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#take%28%29\" rel=\"nofollow\">BlockingQueue.take()</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T18:34:31.430",
"Id": "663",
"ParentId": "646",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-06T07:12:24.630",
"Id": "646",
"Score": "8",
"Tags": [
"java",
"multithreading"
],
"Title": "Java synchronous queue implementation"
} | 646 |
<p>I wanted a class which executes any number of tasks but only a certain amount at the same time (e.g. to download various internet content and keep the overall download speed at a good level). The class I wrote seems to work but there are probably things that can be improved.</p>
<ol>
<li>Do these locks make sense? Should there be other locks as well?</li>
<li>I have a method and an event that is only relevant if a specific constructor is used. Is there a way to improve that?</li>
<li>The class I use for tasks is <code>ThreadStart</code>. Is that a good idea?</li>
<li>There might be better method names/class names.</li>
<li>Are there any general errors (e.g. that more Threads than the max-count will be executed)?</li>
</ol>
<p>There are probably more points that could be improved. Also, if anyone knows a good open source library (or native .NET class even) which does just what my class is supposed to do, I would be interested in that too.</p>
<pre><code>public class ThreadQueue
{
private readonly HashSet<ThreadStart> WorkingThreads = new HashSet<ThreadStart>();
private readonly Queue<ThreadStart> Queue = new Queue<ThreadStart>();
private bool RaiseCompleteEventIfQueueEmpty = false;
private int ThreadsMaxCount;
public ThreadQueue(int threadsMaxCount)
{
ThreadsMaxCount = threadsMaxCount;
}
/// <summary>
/// Creates a new thread queue with a maximum number of threads and the tasks that should be executed.
/// </summary>
/// <param name="threadsMaxCount">The maximum number of currently active threads.</param>
/// <param name="tasks">The tasks that should be executed by the queue.</param>
public ThreadQueue(int threadsMaxCount, ThreadStart[] tasks) : this(threadsMaxCount)
{
RaiseCompleteEventIfQueueEmpty = true;
foreach (ThreadStart task in tasks)
{
Queue.Enqueue(task);
}
}
/// <summary>
/// Starts to execute tasks. Used in conjunction with the constructor in which all tasks are provided.
/// </summary>
public void Start()
{
CheckQueue();
}
private readonly object addlock = new object();
/// <summary>
/// Adds a task and runs it if a execution slot is free. Otherwise it will be enqueued.
/// </summary>
/// <param name="task">The task that should be executed.</param>
public void AddTask(ThreadStart task)
{
lock (addlock)
{
if (WorkingThreads.Count == ThreadsMaxCount)
{
Queue.Enqueue(task);
}
else
{
StartThread(task);
}
}
}
/// <summary>
/// Starts the execution of a task.
/// </summary>
/// <param name="task">The task that should be executed.</param>
private void StartThread(ThreadStart task)
{
WorkingThreads.Add(task);
BackgroundWorker thread = new BackgroundWorker();
thread.DoWork += delegate { task.Invoke(); };
thread.RunWorkerCompleted += delegate { ThreadCompleted(task); };
thread.RunWorkerAsync();
}
private void ThreadCompleted(ThreadStart start)
{
WorkingThreads.Remove(start);
CheckQueue();
if (Queue.Count == 0 && WorkingThreads.Count == 0 && RaiseCompleteEventIfQueueEmpty) OnCompleted();
}
private readonly object checklock = new object();
/// <summary>
/// Checks if the queue contains tasks and runs as many as there are free execution slots.
/// </summary>
private void CheckQueue()
{
lock (checklock)
{
while (Queue.Count > 0 && WorkingThreads.Count < ThreadsMaxCount)
{
StartThread(Queue.Dequeue());
}
if (Queue.Count == 0 && WorkingThreads.Count == 0 && RaiseCompleteEventIfQueueEmpty) OnCompleted();
}
}
/// <summary>
/// Raised when all tasks have been completed. Will only be used if the ThreadQueue has been initialized with all the tasks it should execute.
/// </summary>
public event EventHandler Completed;
/// <summary>
/// Raises the Completed event.
/// </summary>
protected void OnCompleted()
{
if (Completed != null)
{
Completed(this, null);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T22:12:55.893",
"Id": "1294",
"Score": "0",
"body": "I added an answer with a good, imho, open source library."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T14:58:57.620",
"Id": "58725",
"Score": "0",
"body": "Well there is a .Net built-in class System.Threading.ThreadPool which is probably worth looking at.... http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T15:10:25.917",
"Id": "58726",
"Score": "2",
"body": "I am aware of that class and i looked at it a few times but i don't quite get how to use it, also it is static which is problematic if you need multiple pools/queues."
}
] | [
{
"body": "<p>In <code>ThreadCompleted</code> looks like you're raising <code>OnCompleted</code> twice - once in this method itself and another one in <code>CheckQueue</code> method</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T14:00:59.153",
"Id": "1165",
"Score": "0",
"body": "You are right! I added that to have the event being raised if there are no tasks at all. I should move that from `CheckQueue` to the constructor i think."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T14:54:10.870",
"Id": "1168",
"Score": "0",
"body": "No wait, that's a bad idea, of course the event needs to be attached first, `Start` would be a better destination."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T12:30:29.560",
"Id": "655",
"ParentId": "654",
"Score": "2"
}
},
{
"body": "<p>There is a lot that needs to be taken into consideration when implementing a threaded work queue and I wouldn't recommend doing it manually unless you've got a really good reason because existing solutions are tested and reliable and without very specific design needs and some hardcore coding to go with it you'll likely wind up with something less efficient/powerful than the existing options. That said, as an exercise this can be a very educational challenge and I'll try to review it as such; production relevant notes are below.</p>\n\n<p>Technically it's just a matter of preference, but generally speaking, private member variables don't have capitalized first letters to help differentiate between public members and internal implementation details (typical .NET style is CamelCase for public members and pascalCase for fields/variables/parameters). </p>\n\n<p>It seems you are using the <code>Complete</code> event for two different meanings; you should make this two separate events. I wouldn't bother with <code>RaiseCompleteEventIfQueueEmpty</code>, instead just have an <code>ItemComplete</code> event and a <code>QueueComplete</code> event or something like that and always raise the events; if the caller doesn't care about one or the other (or either) they simply don't attach handlers to them.</p>\n\n<p>There are synchronization issues due to your locking strategy. Because your <code>AddTask</code> and <code>CheckQueue</code> methods use different lock objects it's possible to be adding to and accessing the queue at the same time. Because <a href=\"http://msdn.microsoft.com/en-us/library/7977ey2c.aspx\" rel=\"nofollow noreferrer\"><code>Queue</code></a> is not inherently thread-safe this could cause issues. You're better off using a single lock between the two. If you're on framework 4.0 you may want to consider using <a href=\"http://msdn.microsoft.com/en-us/library/dd267265.aspx\" rel=\"nofollow noreferrer\"><code>ConcurrentQueue</code></a> instead.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\"><code>BackgroundWorker</code></a> contains provisions intended to make it easy to setup simple background tasks separate from a UI thread. <code>BackgroundWorker</code> is also a Component, which technically means you should Dispose of it when you're done (not from its own thread) although I don't think its implementation depends on it currently, that could change and you want to follow proper practices regarding <code>IDisposable</code>. It doesn't look like you need much of the convenience it offers and are mainly using it for the completion event, which you could implement yourself pretty easily. You would have more control and less overhead using <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx\" rel=\"nofollow noreferrer\">Thread</a> which should also keep you conscious of everything that's happening in something this low level. <a href=\"https://stackoverflow.com/questions/1506838/backgroundworker-vs-background-thread\">Here's a brief discussion on Stack Overflow</a>. Also worth noting: <code>BackgroundWorker</code> uses <code>BeginInvoke</code> internally which executes the work on a <code>ThreadPool</code> thread.</p>\n\n<p>In regard to using <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.threadstart.aspx\" rel=\"nofollow noreferrer\"><code>ThreadStart</code></a>, it's just a delegate like any other, but if you are wanting to parallelize work, it's likely that you will want to provide a context or workload to each thread. It's possible to work around this a few ways, including using closures when defining the delegate but that's messy and not suitable for all situations. The Thread class, which uses <code>ThreadStart</code>, also supports <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx\" rel=\"nofollow noreferrer\"><code>ParameterizedThreadStart</code></a>. Since you're using Invoke you can probably accept any delegate and any number of parameters, perhaps like so:</p>\n\n<pre><code>private readonly Queue<KeyValuePair<Delegate, object[]>> Queue = new Queue<KeyValuePair<Delegate, object[]>>();\nprivate readonly object queueSync = new object();\n\npublic void AddTask<F>(F task, params object[] parameters) where F : Delegate\n{\n lock (queueSync)\n {\n if (WorkingThreads.Count == ThreadsMaxCount)\n {\n Queue.Enqueue(new KeyValuePair<Delegate, object[]>(task, parameters));\n }\n else\n {\n StartThread(task, parameters);\n }\n }\n}\n\nprivate void StartThread(Delegate task, object[] parameters)\n{\n WorkingThreads.Add(task);\n BackgroundWorker thread = new BackgroundWorker();\n thread.DoWork += delegate { task.Invoke(parameters); };\n thread.RunWorkerCompleted += delegate { ThreadCompleted(task); };\n thread.RunWorkerAsync();\n}\n</code></pre>\n\n<p>Warnings: this code doesn't take into account my other suggestions and was written ad-hoc in the text editor here so it has not been compiled or tested; the idea is all I'm trying to demonstrate. There are several better ways to make use of generics or the delegate choice in general and you would probably also want to provide the context data in your completion event.</p>\n\n<p>You should probably provide a little more information in your completion event so that the attached code can see <em>what</em> completed (consider one event handler can be used for many threads and even many pools). Use an object that inherits from EventArgs to contain your task (and the parameters if you take that bit of advice).</p>\n\n<hr>\n\n<p>In regard to Darragh's answer and your comments there: if you would like to leverage the <code>ThreadPool</code> but need to know when work is complete you can use Task Parallel Library which now ships with 4.0 to use Task objects which by default are scheduled using the <code>ThreadPool</code>. Alternatively, if your tasks will be very long running and you still want to run on your own threads or specify your own concurrency regulations you can <a href=\"http://msdn.microsoft.com/en-us/library/ee789351.aspx\" rel=\"nofollow noreferrer\">implement</a> a <a href=\"http://msdn.microsoft.com/en-us/library/dd997402.aspx\" rel=\"nofollow noreferrer\">Task Scheduler</a> and continue to leverage the existing patterns/classes. This will promote usability and maintenance and if at some point you wanted to use a different scheduling mechanism it would require minimal change. It should be noted (as can be see in the documentation above) that there is already support for long running tasks not using the <code>ThreadPool</code> even in the default scheduler.</p>\n\n<p>The following free \"books\" have a lot of good information, both on the new parallelism extensions to the framework (TPL, PLINQ, Parallel.For, etc.) as well as information on synchronization primitives and the raw patterns used to manage multi-threaded workloads:</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/en/details.aspx?FamilyID=86b3d32b-ad26-4bb8-a3ae-c1637026c3ee&displaylang=en\" rel=\"nofollow noreferrer\">Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ff963553.aspx\" rel=\"nofollow noreferrer\">Parallel Programming with Microsoft .NET</a></p>\n\n<p><a href=\"http://www.albahari.com/threading/\" rel=\"nofollow noreferrer\">Threading in C#</a></p>\n\n<p>Most of these contain very similar information, but each has their own style as well as different juicy nuggets of wisdom.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T18:07:36.240",
"Id": "1291",
"Score": "0",
"body": "Oh wow, what a response, thank you very much for all the effort! Shows me once again that i have *a lot* left to learn, and all the links you provided will certainly help and keep me busy for a while. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T21:55:35.090",
"Id": "1328",
"Score": "0",
"body": "Not a problem and remember: we all always have a lot left to learn. Forgetting that is the first step to getting old! ;P"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-09T17:37:16.390",
"Id": "711",
"ParentId": "654",
"Score": "20"
}
},
{
"body": "<p>We use <a href=\"http://smartthreadpool.codeplex.com/\" rel=\"nofollow\">Smart Thread Pool</a>. It is simple and tested. You should be able to implement your requirements with less effort and more confidence by building on it rather than implementing your own.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T22:39:27.017",
"Id": "1295",
"Score": "2",
"body": "Thank you for the link, i wrote my own class for two reasons, the first is that I only needed it for a small throw-away console application and the second is that i thought it'd be some interesting practice to try my hands at writing my own thread-pool."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T19:56:25.417",
"Id": "712",
"ParentId": "654",
"Score": "3"
}
},
{
"body": "<p>I know you have already marked one of the answers as the answer, and rightly so, it is very complete and helpful. I am adding this answer as well as no one mentioned this and it is part of your first question: 1. Do those locks make sense? Should there be other locks as well?</p>\n\n<p>In regards to the second half of that, Should there be other locks as well. Yes. You are using a <code>HashSet</code> to keep track of working threads. You are adding to, removing from, and getting the count of this set without any locking. That is a disaster waiting to happen. You need to mutex around your reads and writes to the <code>HashSet</code>. As has already been mentioned, if you can use .Net 4.0 then there is a <a href=\"http://msdn.microsoft.com/en-us/library/dd381779.aspx\" rel=\"nofollow\">ConcurrentBag</a> collection that you can use. Otherwise you need to add another lock object and lock around access to your <code>HashSet</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T22:40:58.217",
"Id": "1296",
"Score": "0",
"body": "Thank you for your input as well, i am quite a novice when it comes to threading (and many other things too sadly) so i appreciate any feedback which may help me improve :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T22:45:18.993",
"Id": "1297",
"Score": "2",
"body": "Also about the marked answer, i do mot think answers like TheXenocide's are all too commonplace so for a site like this were the goal is not to solve a specific problem it sure would be nice if one could accept all the answers that bring the pieces together..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T13:57:01.883",
"Id": "1310",
"Score": "0",
"body": "@H.B. Glad to be of help. The only reason I caught the lack of mutex was I was looking for it. I look for it because I made a subtle error like that in production code that made it into customer hands and caused our software (which is supposed to run in a server room 24/7 unattended) to randomly dead lock. Turns out we had a collection that almost all access to it was read access and I had believed was only written to in a static initializer, well I missed a code path that caused it to be written to at a later time. When two threads collided one reading, one writing the whole thing deadlocked."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T20:20:20.553",
"Id": "713",
"ParentId": "654",
"Score": "4"
}
},
{
"body": "<p>I noticed that <code>ThreadStart</code> is not such a good delegate even if you just want to pass a simple method, in that case the <code>Action</code> delegate is to be preferred because the framework can implicitly convert <a href=\"http://msdn.microsoft.com/en-us/library/bb397687.aspx\" rel=\"nofollow\">lambda expressions</a> to it, which makes it more convenient to create a simple task. So one task constructor/add-task-method which takes an action as parameter would always be good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-10T00:27:35.093",
"Id": "5937",
"ParentId": "654",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "711",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T12:04:29.877",
"Id": "654",
"Score": "19",
"Tags": [
"c#",
"multithreading",
"queue",
"locking"
],
"Title": "A custom thread-pool/queue class"
} | 654 |
<p>I have inherited this snippet of jQuery JavaScript and am currently brushing up on my jQuery. NetBeans IDE complains that <code>Anonymous function does not always return a value</code>. So there is not always an explicit exit point.</p>
<p>I am aware that the <code>$()</code> shortcut is not being used. This is because it is running within a WordPress environment and needs to be in no-conflict mode.</p>
<pre><code>function init() {
jQuery("#post").submit(function(_e) {
// Make sure question is supplied
var contents;
if(window.tinyMCE && document.getElementById("content").style.display=="none") { // If visual mode is activated.
contents = tinyMCE.get("content").getContent();
} else {
contents = document.getElementById("content").value;
}
if(!contents) {
alert(msg_enter_question);
_e.preventDefault();
_e.stopPropagation();
return true;
}
// We must have atleast 2 answers.
var answer_count = 0
jQuery(".answer").each(function() {
if(this.value) answer_count++;
});
//if(answer_count < 2) {
// alert("<?php //_e("Please enter atleast two answers"); ?>");
// _e.preventDefault();
// _e.stopPropagation();
// return true;
//}
//A correct answer must be selected.
var correct_answer_selected = false;
jQuery(".correct_answer").each( function(_e) {
if(this.checked) {
correct_answer_selected = true;
return true;
}
});
if(!correct_answer_selected) {
alert(msg_correct_answer);
_e.preventDefault();
_e.stopPropagation();
}
});
}
jQuery(document).ready(init);
</code></pre>
<p>My question is - do I always have to return something in an anonymous function? I.e. is NetBeans right to complain? </p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T16:22:39.350",
"Id": "1171",
"Score": "0",
"body": "it depends, does the function call require the function to return a value. such as: `value = (function(){return 1})(document)`;"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T06:26:32.967",
"Id": "1193",
"Score": "0",
"body": "No, it doesn't require an actual value to be returned. It just checks if a form field is populated or whether at least one of several checkboxes is checked."
}
] | [
{
"body": "<p>Netbeans is right to complain about this (there are <a href=\"http://wiki.netbeans.org/JavaScript_anonnoreturnvalue\" rel=\"nofollow\">some details</a> on the website about it but they are a bit sparse). Also this isn't Netbeans specific, for example Firefox with <a href=\"http://kb.mozillazine.org/Javascript.options.strict\" rel=\"nofollow\">strict-mode enabled</a> will warn about this also.</p>\n\n<p>So in:</p>\n\n<pre><code>jQuery(\".correct_answer\").each( function(_e) {\n if(this.checked) {\n correct_answer_selected = true;\n return true;\n }\n});\n</code></pre>\n\n<p>In the event that <code>this.checked</code> is false, your function returns <code>undefined</code> so it is much better to explicitly handle that event.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T18:37:40.097",
"Id": "664",
"ParentId": "656",
"Score": "2"
}
},
{
"body": "<p>While I understand how it may seem a pointless little nitpick for such simple code to have to have a <code>return something</code> from all code paths if it has one from any, pretty much every thing that a reviewer could say something about can be seen the same way. Individually the rules like the one Netbeans wants to enforce here don't do much, but when all followed together they make for much more maintainable code (especially after letting it sit there until you have forgotten about it for 16 months).</p>\n\n<h2>Further recommendations</h2>\n\n<ol>\n<li><p>Wrap the code in an IIFE (and add <code>'use strict';</code>)</p>\n\n<p>On top of other things this allows you to use a <code>$</code> for <code>jQuery</code> here and not worry about messing with any conflict issues.</p></li>\n<li><p>There is no reason to name the init function that you are just passing to <code>$.ready</code>; inline it.</p></li>\n<li><p>Cache the jQuery elements.</p></li>\n<li><p>Pass in global variables used to the IIFE (<code>window</code>, <code>alert</code>, <code>msg_enter_question</code>, <code>msg_correct_answer</code>).</p></li>\n<li><p><code>document.getElementById(\"content\").style.display</code> has too many <code>.</code> I'd rewrite it as <code>$content.css('display')</code> after caching the element. Better still:</p>\n\n<pre><code>!$content.is(':visible')\n</code></pre></li>\n<li><p><code>_e</code> is an awful variable name; that underscore adds nothing to it but makes it more annoying to type. Rename to <code>e</code>.</p></li>\n<li><p>This:</p>\n\n<pre><code>var answer_count = 0\n$(\".answer\").each(function() {\n if(this.value) answer_count++;\n});\n</code></pre>\n\n<p>is better written as:</p>\n\n<pre><code>var answer_count = $answers.filter(function () { return this.value !== ''; }).length;\n</code></pre>\n\n<p>But it is even better to be commented out or otherwise removed since you aren't using it anywhere.</p></li>\n<li><p>Similarly:</p>\n\n<pre><code>var correct_answer_selected = false;\n$(\".correct_answer\").each( function(_e) {\n if(this.checked) {\n correct_answer_selected = true;\n return true;\n } \n});\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>var correct_answer_selected = $correctAnswers.is(':checked');\n</code></pre></li>\n<li><p>Move variables to the top of their respective functions (personal preference in agreement with <a href=\"http://www.jslint.com/\">JSLint</a>).</p></li>\n<li><p>Returning <code>false</code> from a handler is equivalent to calling both <code>.preventDefault()</code> and <code>.stopPropagation()</code> on the event object. Thus:</p>\n\n<pre><code>if(!contents) {\n alert(msg_enter_question);\n e.preventDefault();\n e.stopPropagation();\n return true;\n}\n</code></pre>\n\n<p>may as well be:</p>\n\n<pre><code>if(!contents) {\n alert(msg_enter_question);\n return false;\n}\n</code></pre>\n\n<p>Most obvious there is that the <code>return true</code> statement is exactly <strong>not</strong> what is actually happening and thus is wrong. Since I would prefer to be explicit I would probably do this:</p>\n\n<pre><code>if(!contents) {\n alert(msg_enter_question);\n e.preventDefault();\n e.stopPropagation();\n return false;\n}\n</code></pre>\n\n<p>As this same if statement is used twice (with different values) I would prefer to pull it out into a function:</p>\n\n<pre><code>function check(item, e, msg) {\n if (!item) {\n alert(msg);\n e.preventDefault();\n e.stopPropagation();\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>This leaves:</p>\n\n<pre><code> //...\n if(!check(contents, e, msg_enter_question)) {\n return false;\n }\n correct_answer_selected = $correctAnswers.is(':checked');\n check(correct_answer_selected, e, msg_correct_answer);\n}\n</code></pre></li>\n<li><p>The problem of not all paths returning something is still here, so change the last line to <code>return check...</code>.</p></li>\n<li><p>If you inline <code>correct_answer_selected</code> then the pattern <code>if (!x) { return false; } return y;</code> logic can be replaced with <code>return x && y</code>:</p>\n\n<pre><code>return check(contents, e, msg_enter_question) &&\n check($correctAnswers.is(':checked'), e, msg_correct_answer);\n</code></pre></li>\n</ol>\n\n<p>The Full Monty then becomes (after some very minor spacing changes to pass jslint):</p>\n\n<pre><code>(function ($, window, alert, msg_enter_question, msg_correct_answer) {\n 'use strict';\n\n $(function () {\n var $correctAnswers = $(\".correct_answer\"),\n $content = $('#content');\n\n function check(item, e, msg) {\n if (!item) {\n alert(msg);\n e.preventDefault();\n e.stopPropagation();\n return false;\n }\n return true;\n }\n $(\"#post\").submit(function (e) {\n // Make sure question is supplied\n var contents;\n if (window.tinyMCE && !$content.is(':visible')) { // If visual mode is activated.\n contents = window.tinyMCE.get(\"content\").getContent();\n } else {\n contents = $content.val();\n }\n\n return check(contents, e, msg_enter_question) &&\n check($correctAnswers.is(':checked'), e, msg_correct_answer); //A correct answer must be selected.\n });\n });\n}(jQuery, window, alert, msg_enter_question, msg_correct_answer));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T22:25:56.323",
"Id": "75509",
"Score": "1",
"body": "Upvote 'cause it's a fantastic answer though I disagree with #7 'cause your suggestion is a bit harder to read."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-15T22:18:03.840",
"Id": "12628",
"ParentId": "656",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T12:32:10.430",
"Id": "656",
"Score": "5",
"Tags": [
"javascript",
"jquery"
],
"Title": "Do I always have to return something in an anonymous function?"
} | 656 |
<p>The following code retrieve custom post types with their custom taxonomy.</p>
<p>I'm just a beginner in PHP and I would like to know tips in order to improve readability and perhaps efficiency.</p>
<p><strong>home.php:</strong></p>
<pre><code><?php
/**
* Template Name: Home
* @package WordPress
* @subpackage Prominent
* @since Prominent 1.0
*/
get_header(); ?>
<div id="sidebar">
<?php get_sidebar(); ?>
</div><!-- #sidebar -->
<div id="content">
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Profile');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-1">
<?php the_post_thumbnail('large'); ?>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Tagline');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-2 padding-top">
<h2><?php the_title(); ?></h2>
<p><?php the_content(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Themep');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-2 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=ThemeCL');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?> <div class="float-left">
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Theme Child Right');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?> <div class="float-right">
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=FromBlog');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?> <div class="block-3 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Featured');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-2 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail('large'); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Last');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-3 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
<p><?php the_meta(); ?></p>
</div>
<?php endwhile; ?>
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=page_content&page_sections=Lastest');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<div class="block-7 border-top">
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail(); ?></a>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile; ?>
</div><!-- #content -->
<?php get_footer(); ?>
</code></pre>
| [] | [
{
"body": "<p>Some general tips</p>\n\n<ol>\n<li>Mind your nesting. Indent at new block-level tags always, and at line-level when it aids legibility</li>\n<li>Wrap where it makes sense: between arguments, at attributes, etc</li>\n<li>Be consistent!</li>\n</ol>\n\n<p>For example, this chunk</p>\n\n<pre><code> <?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=ThemeCL');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n ?> <div class=\"float-left\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>\" rel=\"bookmark\"><?php the_post_thumbnail(); ?></a>\n <p><?php the_excerpt(); ?></p>\n </div>\n <?php endwhile; ?>\n</code></pre>\n\n<p>I would rewrite like so</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=ThemeCL');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n <div class=\"float-left\">\n <a href=\"<?php the_permalink(); ?>\"\n title=\"<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>\"\n rel=\"bookmark\"><?php the_post_thumbnail(); ?></a>\n <p>\n <?php the_excerpt(); ?>\n </p>\n </div>\n<?php endwhile; ?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T22:49:37.517",
"Id": "752",
"ParentId": "657",
"Score": "2"
}
},
{
"body": "<p>DRY is a term coined by developers who believe that repetetive code is bad. I'm one of them :)</p>\n\n<p>First the code goes like this:</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=Profile');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n[..snip html (and some php)...]\n<?php endwhile; ?>\n</code></pre>\n\n<p>Then</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=Tagline');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n[..snip html (and some php)...]\n<?php endwhile; ?>\n</code></pre>\n\n<p>Then</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=Themep');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n[..snip html (and some php)...]\n<?php endwhile; ?>\n</code></pre>\n\n<p>Then</p>\n\n<pre><code> <?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=ThemeCL');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n ?>\n [..snip html (and some php)...]\n <?php endwhile; ?>\n</code></pre>\n\n<p>And again...</p>\n\n<pre><code> <?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=Theme Child Right');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n ?>\n [..snip html (and some php)...]\n <?php endwhile; ?>\n</code></pre>\n\n<p>And yet again...</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=FromBlog');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n[..snip html (and some php)...]\n<?php endwhile; ?>\n</code></pre>\n\n<p>One more time...</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=Featured');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n[..snip html (and some php)...]\n<?php endwhile; ?>\n</code></pre>\n\n<p>They just keep coming...</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=Last');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n[..snip html (and some php)...]\n<?php endwhile; ?>\n</code></pre>\n\n<p>Finally, the last one...</p>\n\n<pre><code><?php // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query('post_type=page_content&page_sections=Lastest');\n while ($custom_posts->have_posts()) : $custom_posts->the_post();\n?>\n[..snip html (and some php)...]\n<?php endwhile; ?>\n</code></pre>\n\n<p>I suppose it is clear now that the code is very repetitive. If you aren't convinced that this pattern is bad, consider reading up on <a href=\"http://sourcemaking.com/antipatterns/cut-and-paste-programming\" rel=\"nofollow\">cut'n'paste programming</a>.</p>\n\n<p><em>If</em> you are using PHP 5.3 or greater (which is most likely today), you can rewrite this stuff using anonymous functions as callbacks:</p>\n\n<pre><code>function print_posts($query, $content_cb) {\n // Create and run custom loop\n $custom_posts = new WP_Query();\n $custom_posts->query($query);\n while ($custom_posts->have_posts()) {\n $custom_posts->the_post();\n $content_cb();\n }\n}\n</code></pre>\n\n<p>...and then just use the function:</p>\n\n<pre><code>print_posts(\n 'post_type=page_content&page_sections=Profile',\n function() {\n echo '<div class=\"block-1\">';\n echo the_post_thumbnail('large');\n echo '</div>'\n }\n);\n</code></pre>\n\n<p>...and so on.</p>\n\n<p>This will eliminate a lot of boilerplate code that is just getting in the way and make the whole thing somewhat shorter, which by itself is something to be desired, since the number of bugs is proportional to the number of lines (or statements, at least).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-20T23:19:48.203",
"Id": "28761",
"ParentId": "657",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-06T14:17:58.370",
"Id": "657",
"Score": "6",
"Tags": [
"php",
"wordpress"
],
"Title": "modify custom loops to improve readability and efficiency for Wordpress?"
} | 657 |
<p><strong>Question + Desired Outcome</strong></p>
<p>The code below works currently, however I'm not convinced the utilisation of an <code>Array</code> to iterate through numerous non-existent form fields is anywhere near efficient enough for my liking. Can this process be improved to effectively eliminate the first step in the Suggested Solution?</p>
<p>Desired Outcome: When a response is submitted on FormB, validate data on FormA to ensure entries have been at least some input on each field.</p>
<p><strong>Background</strong></p>
<p>We're using a support ticketing system within our organisation which thus far is working pretty well. One minor niggle however is that the 'View Ticket' page separates "Important Ticket Variables" (assigned technician, ticket category etc.) - from the "Reply to Ticket" form. Two forms, one page. Validation for both forms happens post-submit on the next page, again each is separate from the other.</p>
<p>In theory, that method makes sense. However, as they are two separate forms, what this often means is that people are able to bypass often-critical data from the "important ticket variables", and just add a reply. An element of human-training exists here but as ever, a programmatic change will satisfy the need for consistency.</p>
<p>Save for rewriting the whole process to resolve this issue, I've looked at putting in a fairly simple JS "overlay" on the view ticket page, so that when they submit a "Reply to ticket" - it does a quick verification to make sure all the 'Important Ticket Variables' have some form of entry. It's a quick fix but comes with some (for me) interesting challenges.</p>
<p><strong>Languages</strong></p>
<p>The main application is written in PHP, using MySQL, complemented with jQuery v1.3.2.</p>
<p><strong>Constant</strong></p>
<p>"Important ticket variables" always have a name= of <code>ticket_fields[customXX]</code>, where XX is basically the id in the database, which at present means we're at an upper limit of around 60 at the moment, obviously this may increase in time as more ticket_fields are created!</p>
<p>Not all <code>ticket_fields</code> are used on every ticket, some tickets use 5-10 fields, others use none.</p>
<p><strong>Example FormA data (formatting stripped out)</strong></p>
<pre><code><input type="radio" name="ticket_fields[custom5][selection]" id="custom50" value="3" />&nbsp;<label for="custom50">No</label>&nbsp;
<input type="radio" name="ticket_fields[custom5][selection]" id="custom51" value="4" />&nbsp;<label for="custom51">Yes</label>&nbsp;
<input type="checkbox" name="ticket_fields[custom6][selections][]" id="custom60" value="1" />&nbsp;<label for="custom60">A</label>
<input type="checkbox" name="ticket_fields[custom6][selections][]" id="custom64" value="5" />&nbsp;<label for="custom64">B</label>&nbsp;
<select name="ticket_fields[custom27][parent]" id="ticket_fields_custom27_parent" >
<option value="0">Please Select</option>
<option value="129562786078">Sample Option - Add new option, then delete this</option>
<option value="129562792948">Top level</option>
</select>
</code></pre>
<p><strong>Suggested Solution</strong></p>
<p>This JS executes <code>onSubmit</code> of FormB:</p>
<pre><code> // ####################################################################
// The following bits validate the 'Additional Ticket Fields' on submit
// ####################################################################
// Need an array of numbers for some horrible hacking. Used to iterate through the dynamically generated "ticket_fields" 100 should be safe, famous last words.
var numArray = new Array();
var b;
for (b = 0; b < 100; b++) { numArray[b] = b; }
// Text boxes
// Radio Buttons
// iterates through existing ticket_fields and finds existing radio buttons, then validates on that radio button
$.each(numArray, function(i, v) {
var radbut = $('input:radio[name^="ticket_fields[custom' + v + ']"]');
// If found a checkbox, validate it
if (radbut.length > 0) {
var radbut2 = $('input:radio[name^="ticket_fields[custom' + v + ']"]:checked');
console.log(radbut2.length);
if (radbut2.length > 0) { } else { validationFail = true; }
} else {
// do nowt
}
});
// Check boxes
// iterates through existing ticket_fields and finds existing checkboxes, then validates on that checkbox
$.each(numArray, function(i, v) {
var chkbox = $('input:checkbox[name^="ticket_fields[custom' + v + ']"]');
// If found a checkbox, validate it
if (chkbox.length > 0) {
var chkbox2 = $('input:checkbox[name^="ticket_fields[custom' + v + ']"]:checked');
if (chkbox2.length > 0) { } else { validationFail = true; }
} else {
// do nowt
}
});
// Select boxes ... includes multi-levels
// Checks each select box in turn, fails if value set to 0. Does nothing if no selectors exist.
$('select[name^="ticket_fields"] option:selected').each(function(){
if (this.length) {
} else {
if(this.value == 0) {
validationFail = true;
}
}
});
if (validationFail) {
alert('Please ensure all Additional Ticket Fields are completed. \n REMEMBER: Click Update when done.');
return false;
}
</code></pre>
| [] | [
{
"body": "<p>I managed to get around a generic array by pulling out the numbers from the name= attribute on each form field with the following:</p>\n\n<pre><code>// Pulls numbers from submitted \"ticket_fields\" which are stored in the name= attribute.\n// Used to iterate through the dynamically generated \"ticket_fields\"\nvar numArray = new Array();\n$(':input[name^=\"ticket_fields\"]').each(function(){\n fieldId = $(this).attr('name').replace(/\\D/g, \"\");\n if ($.inArray(fieldId,numArray) > -1) { } else { numArray.push(fieldId); } \n});\n</code></pre>\n\n<p>This makes it much friendlier, so rather than numArray having a ridiculous level of integers to iterate through, it gets exactly the right values from the form fields themselves every time. Also allows it to scale infinitely.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:53:28.233",
"Id": "697",
"ParentId": "673",
"Score": "3"
}
},
{
"body": "<p>You could do a simple <a href=\"http://api.jquery.com/map/\" rel=\"nofollow\"><code>map</code></a>, instead of the code you have there in your self-answer: </p>\n\n<pre><code>var numArray = $(':input[name^=\"ticket_fields\"]').map(function(){\n fieldId = this.name.replace(/\\D/g, \"\");\n if ($.inArray(fieldId,numArray) === -1) return fieldId;\n}).get();\n</code></pre>\n\n<p>Also using <code>this.name</code> instead of <code>$(this).attr('name')</code>, which is <a href=\"http://whattheheadsaid.com/2010/10/utilizing-the-awesome-power-of-jquery-to-access-properties-of-an-element\" rel=\"nofollow\">massively inefficient</a>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T09:34:02.090",
"Id": "742",
"ParentId": "673",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "697",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-07T11:12:54.570",
"Id": "673",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"validation",
"form"
],
"Title": "Basic form validation"
} | 673 |
<p>Is there a better way to accomplish the following?</p>
<pre><code>/**
* Performs an access check given a user.
*
* @param Cas_Acl_Sid $user The user or SID being checked.
* @param Cas_Acl_Privilege $privilege The privilege to check.
* @return int|null 1 if user access allowed, 2 if group access allowed, false if access is denied, null if access cannot be determined.
*/
public function accessCheck(Cas_Acl_Sid $user, Cas_Acl_Privilege $privilege)
{
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$usersQuery = $db->select()->from('AccessControlEntries', array('Allowed', new Zend_Db_Expr('1 AS Type')))
->where('Acl = ?', $this->_id)
->where('Sid = ?', $user->GetGuid())
->where('Privilege = ?', $privilege->GetId());
$groupsQuery = $db->select()->from('AccessControlEntries', array('Allowed', new Zend_Db_Expr('2 AS Type')))
->join('GroupMembers', $db->quoteIdentifier(array('GroupMembers', 'Group')) . ' = ' .
$db->quoteIdentifier(array('AccessControlEntries', 'Sid')), array())
->where('Acl = ?', $this->_id)
->where($db->quoteIdentifier(array('GroupMembers', 'User')) . ' = ?', $user->GetGuid())
->where('Privilege = ?', $privilege->GetId());
$query = $db->select()
->union(array($usersQuery, $groupsQuery), Zend_Db_Select::SQL_UNION_ALL)
->order('Type')
->order('Allowed')
->limit(1);
$dbResult = $db->fetchAll($query);
if (!count($dbResult))
{
return null;
}
else {
if ($dbResult[0]['Allowed'])
{
return (int)$dbResult[0]['Type'];
}
else
{
return false;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T06:43:54.113",
"Id": "1346",
"Score": "3",
"body": "could you supply a basic schema of the tables involved?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-15T23:34:13.100",
"Id": "18898",
"Score": "1",
"body": "Any reason your method starts with an uppercase letter? This is against Zend coding standards. I always follow the convention of the framework I'm using, even if I don't like it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-16T17:25:13.333",
"Id": "18938",
"Score": "0",
"body": "@Cobby: I was not aware there was a convention on this. (Doesn't matter much now, as I've thrown Zend by the wayside a long time ago now, thank <insert deity>)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-17T02:11:11.380",
"Id": "18980",
"Score": "0",
"body": "I'm a big fan of Zend Framework, but Zend_Db wasn't a very good library. That being said, it was still a good move changing from Zend Framework; given that PHP v5.3+ frameworks are wayy better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-17T02:12:55.513",
"Id": "18982",
"Score": "0",
"body": "@Cobby: Well, really, what I did was dump PHP itself :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-17T02:16:28.470",
"Id": "18983",
"Score": "0",
"body": "@BillyONeal Yea, probably a good move too. PHP is really starting to show it's age in between all the new features."
}
] | [
{
"body": "<h2>Stored procedure</h2>\n\n<p>The query above is enough big to move it from the application layer to the database in the form of a stored procedure. It will be clearer and faster, the only disadvantage is that an SP has a hard dependency on the database type (MySQL, MSSQL, other).</p>\n\n<h2>Return value(s)</h2>\n\n<p>You are returning 3 types in your method: null, integer and boolean.\nKeep your logic clean, and return always one type if you can (yes, PHP has it's type juggling \"issue\" but still, clean code talks).</p>\n\n<pre><code>public function accessCheck(Cas_Acl_Sid $user, Cas_Acl_Privilege $privilege)\n{\n //execute the query in a stored procedure\n\n $dbResult = // stored procedure result\n\n if (empty($dbResult) || !$dbResult[0]['Allowed'])\n {\n return 0;\n }\n\n return (int)$dbResult[0]['Type'];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T23:42:14.570",
"Id": "34578",
"Score": "0",
"body": "If you can accept a hard dependency on a single database type, there's little reason to use Zend_Db at all. As for faster, there is little evidence of that. As for returning different types; the value `0` is a valid primary key value, so your \"return 0\" example above is not correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T07:04:01.493",
"Id": "34588",
"Score": "0",
"body": "In most cases the primary key seed is 1 so 0 is invalid. Second if you are dealing with an ACL problem, then the valid values should be the nth power of second: 1, 2, 4, 8 and so on plus the 0. Why? You can apply a logical and to get who can read or write something ( if ($result & WRITE) { /* can write */ } ). If the result is 0 then the if statement will be false."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T07:53:32.467",
"Id": "34590",
"Score": "0",
"body": "Only if you can represent all your permissions in a bit field."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T21:21:26.523",
"Id": "21522",
"ParentId": "676",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-07T17:46:50.907",
"Id": "676",
"Score": "8",
"Tags": [
"php",
"zend-framework"
],
"Title": "Large Zend_Db query"
} | 676 |
<p>I started to write a code with top-down tests.
My first version, grow to something like this:</p>
<pre><code>public class Worker
{
public void Execute(Foo foo)
{
//Do X on Foo
//Do Y on Foo
//Do Z on Foo
//Get Bar from Foo
//Do A on Bar
//Do B on Bar
//Do C on Bar
}
}
</code></pre>
<p>then this started to grow more. So, I've to add more actions like X,Y,Z</p>
<p>I refactorized the code in something like:</p>
<pre><code>public interface IFooVisitor
{
void Visit(Foo foo);
}
public interface IBarVisitor
{
void Visit(Bar bar);
}
public class Worker
{
public Worker(
IEnumerable<IFooVisitor> fooVisitors,
IEnumerable<IBarVisitor> barVisitors)
{ ... }
public void Execute(Foo foo)
{
foreach(var fooVisitor in fooVisitors) { fooVisitor.Visit(foo); }
var bar = getbarfromfoo(foo);
foreach(var barVisitor in barVisitors) { barVisitor.Visit(bar); }
}
}
</code></pre>
<p>The code is much more cleaner, but the problem is that i need some specific order in the execution of visitors. So, one alternative is to add a property to each visitor like:</p>
<pre><code>public int Priority {get { return 1; } }
</code></pre>
<p>The project is opensource and the full code is <a href="http://code.google.com/p/heredar/source/browse/" rel="nofollow">here</a>:</p>
<ul>
<li>IAbcVisitor is ICloneVisitor</li>
<li>IXyzVisitor is IPostWeaveAction</li>
</ul>
| [] | [
{
"body": "<p>Have you considered using the Chain of Command instead of the visitor?</p>\n\n<pre><code>public interface IFooChainLink\n{\n void Execute(Foo foo);\n}\n\npublic interface IBarChainLink\n{\n void Execute(Bar bar);\n}\n\npublic class Worker\n{\n public Worker(IFooChainLink fooChain, IBarChainLink barChain)\n { ... }\n\n public void Execute(Foo foo)\n {\n fooChain.Execute(foo);\n var bar = getbarfromfoo(foo);\n barChain.Execute(bar);\n }\n}\n</code></pre>\n\n<p>Your chain links would look like this</p>\n\n<pre><code>public DoXToFoo : IFooChainLink\n{\n private static IFooChainLink NextInChain = new DoYToFoo();\n\n public void Execute(Foo foo)\n {\n // DO STUFF HERE\n NextInChain.Execute(foo);\n }\n}\n</code></pre>\n\n<p>You will also need an EndOfFooChain</p>\n\n<pre><code>public EndOfFooChain : IFooChainLink\n{\n public void Execute(Foo foo)\n {\n // DO NOTHING HERE\n }\n}\n</code></pre>\n\n<p>And you might want a start point that makes more sense in your calling code, such as</p>\n\n<pre><code>public FooChainActivator : IFooChainLink\n{\n private static IFooChainLink NextInChain = new DoXToFoo();\n\n public void Execute(Foo foo)\n {\n // DO NOTHING\n NextInChain.Execute(foo);\n }\n}\n</code></pre>\n\n<p>With this, you can have your chain well sequenced and easily insert links into the chain, even the beginning and end without ever changing the calling code.</p>\n\n<p>If you would rather have your chain sequence declared in one place, you can pass NextInChain as a constructor parameter to each layer of the chain, so that your calling code becomes</p>\n\n<pre><code>var worker = new Worker(\n new DoXToFoo(\n new DoYToFoo(\n new DoZToFoo(\n new EndOfFooChain()))),\n new DoAToBar(\n new DoBToBar(\n new DoCToBar(\n new EndOfBarChain())))\n );\n</code></pre>\n\n<p>This has an added advantage that you can send arguments to the links in the chain, but I feel it's a little messier than defining the NextLinkInChain within the links themselves.</p>\n\n<p>I guess that's a matter of personal preference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T09:29:20.940",
"Id": "1212",
"Score": "0",
"body": "I like the second pattern better. The first pattern is more fragile (imagine inserting a new link badly, and the chain missing out important steps) and can't be manipulated at run time."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T09:29:41.253",
"Id": "1213",
"Score": "0",
"body": "Maybe a third option would be a factory that produced the chain for you to insert into the worker. That way you can still hard-code stuff but can also chop and change at run time."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T12:43:17.453",
"Id": "1221",
"Score": "0",
"body": "Thank you for your answer, still not convinced: 1-I don't like the fist aproach because it requires to hard code the next visitor inside the class and the instantiaton. 2-the second aproach seems better but i feel it is not dependency injection friendly, every visitor has his own set of dependencies injected by an DI container (well.... it is MEF)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:23:08.627",
"Id": "1227",
"Score": "0",
"body": "@Jose - It doesn't really need to be DI container friendly. You can test your Worker class by passing it a mock IFooChainLink and IBarChainLink and each of your chain links independantly using a similar approach (with just one mock). That's the beauty of it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T19:34:30.590",
"Id": "679",
"ParentId": "677",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "679",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T18:29:30.293",
"Id": "677",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"object-oriented"
],
"Title": "Sorting Visitors"
} | 677 |
<p>This seems a bit wrong because there's a lot of business logic going on inside the bootstrapper. Is there a better way to accomplish what's going on here?</p>
<pre><code><?php
/**
* Zend_Application Bootstrapper
*
* @copyright 2011 Case Western Reserve University, College of Arts and Sciences
* @author Billy O'Neal III ([email protected])
*/
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function __construct($application)
{
parent::__construct($application);
Cas_Ldap::SetGlobalOptions($this->getOption('ldapserver'), $this->getOption('ldapsearchbase'));
}
protected function _initLayout()
{
$layout = Zend_Layout::startMvc();
$layout->setLayoutPath(APPLICATION_PATH . '/layouts/scripts');
$layout->setLayout('layout');
return $layout;
}
protected function _initView()
{
$this->bootstrap('db');
$view = new Zend_View();
//Set the version string with subversion revision if found.
$version = '0.1';
$svnPath = APPLICATION_PATH . '/../.svnrev';
if (file_exists($svnPath))
{
$hFile = fopen($svnPath, 'r');
$version .= '.' . fgets($hFile);
fclose($hFile);
$lastModTime = filemtime($svnPath);
$dateTime = new DateTime('@' . $lastModTime, new DateTimeZone('America/New_York'));
$version .= ' ' . $dateTime->format('o-n-j G:i') . 'Z';
}
$view->version = $version;
// Setup Navigation
$nav = array();
$nav[] = array(
'label' => 'Welcome',
'controller' => 'index',
'action' => 'index',
'order' => -1
);
$loggedIn = Cas_Users_User::LoggedIn();
$logxLink = array('controller' => 'User', 'order' => 1000);
$logxLink['label'] = $loggedIn ? 'Logout' : 'Login';
$logxLink['action'] = strtolower($logxLink['label']);
$logxLink['pages'] = array(array(
'controller' => 'User',
'action' => 'AccessDenied',
'visible' => false,
'label' => 'Access Denied'
));
$nav[] = $logxLink;
$adminPermission = Cas_Acl_Privilege::CreateExisting('refreshAdmin');
unset($hasAdmin);
$hasAdmin = (bool)Cas_Users_User::CurrentPrivilegeCheck($adminPermission);
$nav[] = array(
'controller' => 'admin',
'action' => 'index',
'order' => 2,
'label' => 'Administration',
'visible' => $hasAdmin,
'pages' => array(array(
'controller' => 'admin',
'action' => 'useradmin',
'label' => 'User Administration',
'order' => 1
),array(
'controller' => 'admin',
'action' => 'globalpermissions',
'label' => 'System Permissions',
'order' => 2
),array(
'controller' => 'admin',
'action' => 'editevents',
'label' => 'Edit Events List',
'order' => 3
),array(
'controller' => 'template',
'action' => 'index',
'label' => 'Edit Templates',
'order' => 4
), array(
'controller' => 'admin',
'action' => 'notauthorized',
'label' => 'Access Denied',
'visible' => false
), array(
'controller' => 'admin',
'action' => 'usermembership',
'label' => 'User Membership Edit',
'visible' => false
))
);
$nav[] = array(
'controller' => 'faq',
'action' => 'index',
'order' => 3,
'label' => 'Frequently Asked Questions'
);
if ($loggedIn)
{
$nav[] = array(
'order' => 4,
'label' => 'My Refresh',
'uri' => '#',
'pages' => array(
array(
'label' => 'Accelerate My Refresh',
'order' => 1,
'controller' => 'accelerate',
'action' => 'index'
)
)
);
$standardSystems = array();
$standardSystems[] = array(
'label' => 'About Standard Computers'
);
$standardSystems[] = array(
'label' => 'Dell Optiplex 980 MT',
'make' => 'Dell',
'model' => 'Optiplex980MT'
);
$standardSystems[] = array(
'label' => 'Dell Latitude E4310',
'make' => 'Dell',
'model' => 'LatitudeE4310'
);
$standardSystems[] = array(
'label' => 'Dell Latitude E6410',
'make' => 'Dell',
'model' => 'LatitudeE6410'
);
$standardSystems[] = array(
'label' => 'Dell Latitude E6510',
'make' => 'Dell',
'model' => 'LatitudeE6510'
);
$standardSystems[] = array(
'label' => 'Apple iMac 21.5&quot;',
'make' => 'Apple',
'model' => 'iMac'
);
$standardSystems[] = array(
'label' => 'Apple MacBook Pro 13&quot;',
'make' => 'Apple',
'model' => 'MacBookPro'
);
$standardSystems[] = array(
'label' => 'Apple MacBook Air 11&quot;',
'make' => 'Apple',
'model' => 'MacBookAir'
);
foreach ($standardSystems as $key => &$value)
{
$value['controller'] = 'StandardSystem';
$value['action'] = 'index';
$value['order'] = $key;
if (!isset($value['make']))
continue;
$value['params'] = array('make' => $value['make'], 'model' => $value['model']);
unset($value['make']);
unset($value['model']);
}
$nav[] = array(
'controller' => 'StandardSystem',
'action' => 'index',
'label' => 'Standard Computers',
'order' => 5,
'pages' => $standardSystems
);
$nav[] = array(
'uri' => 'mailto:[email protected]',
'label' => 'Send Feedback',
'order' => 6
);
}
$nav = new Zend_Navigation(new Zend_Config($nav));
$view->navigation($nav);
//Done setting up navigation.
//Register the view, and return it.
$viewRenderer =
Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($view);
$view->setHelperPath(APPLICATION_PATH . '/views/helpers', 'Cas_View_Helper');
return $view;
}
protected function _initFrontController()
{
$fc = Zend_Controller_Front::getInstance();
$fc->setControllerDirectory(APPLICATION_PATH . '/controllers');
$fc->registerPlugin(new Cas_Controller_DefaultViews());
Zend_Controller_Action_HelperBroker::addPrefix('Cas_Controller_Helper');
return $fc;
}
}
</code></pre>
| [] | [
{
"body": "<p>You're right, there's a lot of work going on here.</p>\n\n<p>You probably need to be a bit more granular in your use of _init methods. You have navigation, ACL, view configuration and plugin registration all wrapped up in the _initView method. Try breaking these up into their own _init methods. Try to limit each _init method to a single purpose. </p>\n\n<p>Personally, I prefer to limit the Bootstrap to a \"spark plug\" rolle , and move this kind of logic into Resource Plugins:</p>\n\n<p><a href=\"http://framework.zend.com/manual/en/zend.application.theory-of-operation.html#zend.application.theory-of-operation.resources\" rel=\"nofollow\">http://framework.zend.com/manual/en/zend.application.theory-of-operation.html#zend.application.theory-of-operation.resources</a></p>\n\n<p>I divide those plugins into components that I'm likely to reuse on other projects, and components that are specific to the project under development. I store these in separate \"namespaced\" folders in the application library. </p>\n\n<p>Externalise parameters (like $standardSystems ) into ini|php|xml files where possible - this will help you swap parameters based on application environment where required (i.e. database connectors).</p>\n\n<p>If I have a lot of sequential logic in a class, I tend to use one function for traffic control duties - but keep the details in separate methods. Currently, I feel that there are too many points of potential failure in the _initView method which will make debugging tricky.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T22:41:29.777",
"Id": "882",
"ParentId": "678",
"Score": "1"
}
},
{
"body": "<p>Resource plugins allow one to encapsulate a plugin class to perform one purpose & can be unit tested. Otherwise the bootstrap becomes a GOD class. Plugins have hooks too. </p>\n\n<p>Worst case at least split up your '_initView' method as it is massive.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T19:54:25.190",
"Id": "26122",
"ParentId": "678",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "882",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-07T18:47:18.450",
"Id": "678",
"Score": "3",
"Tags": [
"php",
"zend-framework"
],
"Title": "Zend_Application bootstrapper"
} | 678 |
<p>I am trying to write a LISP interpreter in C#, so I started with a tokenizer. I haven't finished it yet (have to handle floating point numbers & symbols), but I already rewrote it two times because I can't wasn't satisfied with design. </p>
<pre><code> public class TokenizerException : System.ApplicationException
{
public TokenizerException() {}
public TokenizerException(string message) {}
public TokenizerException(string message, System.Exception inner) {}
// Constructor needed for serialization
// when exception propagates from a remoting server to the client.
protected TokenizerException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) {}
}
public abstract class Token
{
public string val;
public Token(string val)
{
if(val != null) this.val = val;
else this.val = "";
}
}
class OpenParenToken: Token
{
public OpenParenToken(string value) : base(value) {}
}
class CloseParenToken: Token
{
public CloseParenToken(string value) : base(value) {}
}
class NumberToken: Token
{
public NumberToken(string value) : base(value) {}
}
class StringToken: Token
{
public StringToken(string value) : base(value) {}
}
class IdToken: Token
{
public IdToken(string value) : base(value) {}
}
class SymbolToken: Token
{
public SymbolToken(string value) : base(value) {}
}
public class Tokenizer
{
private const string parens = "([])";
private string code;
private char ch;
private object token;
private List<Token> tokens;
private int p = 0;
public Tokenizer(string code)
{
this.code = code;
tokens = new List<Token>();
}
private char getCh()
{
ch = code[p];
return ch;
}
public void DumpTokens()
{
foreach(object t in tokens)
{
Console.Write("<"+t.GetType()+", "+(t as Token).val+"> ");
}
Console.WriteLine();
}
private char NextCh()
{
if(p >= code.Length) throw new TokenizerException("End of input reached, cant get more chars");
ch = getCh();
if(char.IsWhiteSpace(ch)) { p++; return NextCh(); }
else return ch;
}
private Token NextParenToken(char ch)
{
Token t;
if(parens.IndexOf(ch) <= parens.Length/2)
{
t = new OpenParenToken(ch.ToString());
}
else t = new CloseParenToken(ch.ToString());
tokens.Add(t);
return t;
}
private Token NextNumberToken()
{
int startPos = p;
while(p < code.Length)
{
char c = getCh();
if(!char.IsDigit(c)) break;
p++;
}
p--;
NumberToken n = new NumberToken(code.Substring(startPos, p - startPos + 1));
tokens.Add(n);
return n;
}
private Token NextStringToken()
{
if(p + 1 > code.Length) throw new TokenizerException("Unmatched \" at the end of the code");
int startPos = ++p;
while(p < code.Length)
{
char c = getCh();
if(c == '\"') break;
p++;
}
StringToken t = new StringToken(code.Substring(startPos, p - startPos + 1));
tokens.Add(t);
return t;
}
private Token NextIDToken()
{
int startPos = p;
while(p < code.Length)
{
getCh();
if(parens.IndexOf(ch) > parens.Length/2 || char.IsWhiteSpace(ch)) break;
if(parens.IndexOf(ch) >= 0 && parens.IndexOf(ch) <= parens.Length/2) throw new TokenizerException("Bad identifier at " + p);
p++;
}
p--;
string id = code.Substring(startPos, p - startPos + 1);
IdToken t = new IdToken(id);
tokens.Add(t);
IdTable.insert(id, t);
return t;
}
public Token NextToken()
{
char ch = NextCh();
if(parens.Contains(ch))
{
return NextParenToken(ch);
}
if(char.IsDigit(ch))
{
return NextNumberToken();
}
if(ch == '\"')
{
return NextStringToken();
}
// identifiers
return NextIDToken();
}
public void Lex()
{
tokens.Clear();
for(p=0; p < code.Length; p++)
{
NextToken();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T23:45:22.237",
"Id": "1211",
"Score": "1",
"body": "Are you sure you want to write a tokenizer in C#? Why not go with a language that is specifically designed to tokenize a stream. Such as LEX."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T12:26:23.193",
"Id": "1219",
"Score": "0",
"body": "Yeah. I choose it as my C# course assignment. Of course, the best language to write LISP intepreter is Lisp itself ;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T14:16:22.557",
"Id": "1223",
"Score": "1",
"body": "You can still use C# and make use of lexer/parser generators (unless the assignment explicitly forbids it of course). Tools like LEX+YACC or ANTLR use domain specific languages in which you only specify the lexing logic and then compile them into code in your main language for you. So all you have to write yourself is the logic for actually running the lisp code after it has been lexed and parsed."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T05:37:26.993",
"Id": "1342",
"Score": "0",
"body": "Honestly, using lex is overkill for something as simple as Lisp's tokens."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-12T18:11:35.310",
"Id": "6064",
"Score": "0",
"body": "@munificent: Totally disagree. Using any other language (apart from regular expressions) would be overkill. LEX (or another appropriate parser generator language) is so simple to both read and write."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-13T01:33:48.060",
"Id": "6082",
"Score": "1",
"body": "Sure, but there's also the overhead of requiring the people working with your code to now know two languages, the effort to integrate it into your build process, inability to step through it in your debugger... And you've saved, what, a hundred lines of code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-20T17:48:34.020",
"Id": "19135",
"Score": "0",
"body": "@munificent I like your opinion to external tools, especially \"when do I need them?\". Another argument against LEX: You may want to *learn* how to do lexical analysis / parsing in your main programming language. ;)"
}
] | [
{
"body": "<p>1) I would remove <code>string val</code> from your base <code>Token</code> class, it smells like stringly typed code. Your inheritors may have more specific information, for example number token may provide a double instead of string<br>\n2) <code>public string val;</code> - Pascal case for public properties is a rule for .Net<br>\n3) <code>if(val != null) this.val = val; else this.val = \"\";</code> is a long form for:<br>\n<code>this.val = val ?? \"\";</code><br>\n4) <code>private char NextCh()</code> recursion makes no sense here, regular loop is more than enough.<br>\n5) haven't found any sense having this field: <code>private char ch;</code>, you have it as local variable everywhere. This field should be removed.<br>\n6) <code>code</code> field can be made readonly<br>\n7) <code>getCh()</code> one-line method should be removed<br>\n8) 'token' field should be removed since it doesn't seem to be used and doesn't make any sense in 'Tokenizer' context<br>\n9) Is <code>IdTable</code> a singleton? Singletons are evil.<br>\n10) String.IndexOf(c) does the same as this</p>\n\n<pre><code> while(p < code.Length)\n {\n char c = getCh();\n if(c == '\\\"') break;\n p++;\n }`\n</code></pre>\n\n<p>11) Your tricks with parentheses and <code>indexOf <= Length/2</code> do not improve readability at all<br>\n12) IMO your class is too stateful, while parsing tokens in each method you have to keep in mind all those fields you have in your class. I would recommend remove ALL fields and use method parameters instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T00:11:25.903",
"Id": "684",
"ParentId": "680",
"Score": "5"
}
},
{
"body": "<p>In adition to Snowbear's points:</p>\n\n<p>1) I don't use an inheritance hierarchy for the token, instead I find it more convenient to use an enum property on the token to identify the type.</p>\n\n<p>2) You might want to think about \"reading\" the whitespace as a token that simply isn't returned (this is an extension of Snowbear's point about not using recursion to read the next char).</p>\n\n<p>3) LL(1) is a term that refers to parsers, not scanners (tokenisers).</p>\n\n<p>4) I also like implement my scanners as an IEnumerator that takes the string to be scanned in the constructor ... but that's just a matter of personal taste. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:45:38.747",
"Id": "2604",
"Score": "0",
"body": "\"parser not scanners\". Right. Altought its possible to make tools to mix scanning & parsing, its complicated, and sort of \"bad practice\" or \"antipattern\". Specially for someone new to compiler design stuff"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T01:58:36.777",
"Id": "686",
"ParentId": "680",
"Score": "8"
}
},
{
"body": "<p>The main comment I have is that I think that C# is the <strong>wrong</strong> language to pick for tokenizing a language. Its perfectly good for the main bulk of the lisp interpretor but one of the major skills of software engineer is picking the correct language for the job. Not just of ease of writing but ease of maintainability and future work.</p>\n\n<p>Now I personally like LEX but there are other lexical generators out there. But I just want to show you how simple the LEX file is. Even if you don't know the exact syntax of LEX it is simple enough that most people will immediately be able to read (assuming a CS background) and even the most complex modification can be done within an hour given an appropriate book.</p>\n\n<p>OK I am not 100% sure of the exact rules for tokenizing Lisp. </p>\n\n<pre><code>DIGIT [0-9]\nNUMBER [+-]?{DIGIT}+\nEXP [EeDd]{NUMBER}\nIDTOKEN [^)(; \\t\\v\\r]\nIDENTIFIER {IDTOKEN}+\nSPACE [ \\t\\v\\r]\n\n%x STRING COMMENT\n%%\n\n; { BEGIN(COMMENT); }\n<COMMENT>[^\\n]+ { /* IGNORE */ }\n<COMMENT>\\n { BEGIN(INITIAL); }\n\n{NUMBER} { return CONSTANT_NUMBER_INT; }\n\n{NUMBER}{EXP} { return CONSTANT_NUMBER_FLOAT; }\n{NUMBER}?\".\"{DIGIT}+{EXP}? { return CONSTANT_NUMBER_FLOAT; }\n{NUMBER}\".\"{DIGIT}*{EXP}? { return CONSTANT_NUMBER_FLOAT; }\n\n{NUMBER}\\/{NUMBER} { return CONSTANT_NUMBER_RATIO; }\n\n\\\" { BEGIN(STRING); yymore(); }\n<STRING>[^\\\"\\\\\\n]+ { yymore(); }\n<STRING>\\\\. { yymore(); }\n<STRING>\\\" { BEGIN(INITIAL); return CONSTANT_STRING; }\n<STRING>\\n { error(\"NewLine inside string\");}\n\n{IDENTIFIER} { return NAME; }\n\n\\( { return '('; }\n\\) { return ')'; }\n\n\\n { lineCount++; }\n{SPACE}+ { /* Ignore Space */ }\n\n%%\n/* Add this rule if there are things that can't match\n * But Lisp seems to be very flexible on Identifier\n * names so it seems like it is not required.\n . { error(\"Unknown character\"); }\n */\n</code></pre>\n\n<p>50 lines is a lot easier to read than 200.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T16:22:48.350",
"Id": "694",
"ParentId": "680",
"Score": "3"
}
},
{
"body": "<p>Suggestion, many tools like your code have a \"next\" operation. It will be a good idea to separate that functions, into a \"read\" and a \"move\".</p>\n\n<p>The first function will read the next token, but allow to stay in the same pointer, and the second function will confirm that the token has been accepted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:50:41.503",
"Id": "1506",
"ParentId": "680",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-07T19:37:41.053",
"Id": "680",
"Score": "12",
"Tags": [
"c#",
"parsing"
],
"Title": "LL(1) tokenizer for LISP"
} | 680 |
<p>I wrote this <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">sieve of Eratosthenes</a> with MPI, but I'm not sure if it's good enough. Should I use <code>MPI_Scatter</code> and <code>MPI_Gather</code> instead of collecting arrays of separate processes in the root process?</p>
<p>Also, I'm not sure if I call </p>
<pre><code>printArray(myArray, (N/size)-1);
</code></pre>
<p>right, where <code>myArray</code> is an array of pointers. GCC gives a warning at this point. </p>
<pre><code>#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 60
int main(int argc, char *argv[])
{
long timeCPU;
int rank, size, k, i, v, n, scatterSize;
int **tmpArray, *myArray, firstElement, lastElement;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if(N%size != 0)
{
MPI_Finalize();
printf("ERROR!");
exit(0);
}
firstElement = (rank*N)/size;
lastElement = floor(((rank+1)*N)/size);
myArray = (int*) (malloc(((N/size)-1)*sizeof(int)));
for(i=0, v=firstElement+2; i<=(N/size)-1; i++, v++)
{
myArray[i] = v;
}
printArray(myArray, (N/size)-1);
/* All processes have to execute above code first */
MPI_Barrier(MPI_COMM_WORLD);
k = 2;
do
{
markMultiples(k, myArray, lastElement-firstElement);
k = nextNumber(k, myArray, lastElement-firstElement);
MPI_Bcast(&k, 1, MPI_INT, 0, MPI_COMM_WORLD);
}
while(k*k <=N);
MPI_Send(myArray, (N/size)-1, MPI_INT, 0, 50, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0)
{
// Initialize 2D array
tmpArray = (int**) (malloc(size*sizeof(int)));
for(i=0;i<size;i++)
{
tmpArray[i] = (int*) (malloc(((N/size)-1)*sizeof(int)));
}
// Gather from every process his own array
for (i=0; i<size;i++)
{
MPI_Recv(tmpArray[i], (N/size)-1, MPI_INT, i, 50, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
printArray(tmpArray[i], (N/size)-1);
printf("-----------------------------------------\n");
}
// Build 1d array with primes - TODO
}
//printArray(array, lastElement-firstElement);
free(myArray);
MPI_Finalize();
return 0;
}
int nextNumber(int k, int *array, int n)
{
int i;
for(i=0; i<=n; i++)
{
if(array[i] > k)
return array[i];
}
return -1;
}
void markMultiples(int k, int *array, int n)
{
int i;
for (i=0; i<=n; i++)
{
if(array[i] % k == 0 && array[i] != k)
{
array[i] = -1;
}
}
}
void printArray(int *array, int n)
{
int i;
for(i=0; i<=n; i++)
{
printf("array[%d] = %d\n", i, array[i]);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T01:19:18.410",
"Id": "113429",
"Score": "2",
"body": "My advice: split up that main function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-14T07:59:23.263",
"Id": "121287",
"Score": "0",
"body": "It definitely is a good idea to use the collectives offered by MPI instead of re-implementing them yourself."
}
] | [
{
"body": "<p>Since you tagged this question <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a> I assume you would like a C++ approach also.</p>\n\n<p>I would suggest using <code>std::vector<int></code> rather than an <code>int*</code> and <code>malloc</code>. Using the vector will give you a number of useful advantages over a normal pointer, for example, memory management is greatly simplified, and there is no need to worry about how big an <code>int</code> is. With <code>vector</code>, the order of all elements is guaranteed to be contiguous.</p>\n\n<pre><code>#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <vector>\n\nint nextNumber(int k, const std::vector<int> &array, int n)\n{\n std::vector<int>::iterator i = std::find_if(array.begin(), array.begin() + n, std::bind2nd(std::greater<int>(), k));\n\n return (i == array.end() ? -1 : *i);\n}\n\nbool isMultiple(int a, int b)\n{\n return (a % k == 0) && (a != k);\n}\n\nvoid markMultiples(int k, std::vector<int> &array, int n)\n{\n std::replace_if(array.begin(), array.begin() + n, std::bind2nd(std::ptr_fun(isMultiple), k), -1);\n}\n\n\nvoid printArray(const std::vector<int> &array)\n{\n for(int i = 0; i < array.size(); i++)\n std::cout << \"array[\" << i << \"] = \" << array[i] << std::endl;\n}\n</code></pre>\n\n<h3>Disclaimer:</h3>\n\n<p>I am not very good at C++, so you may want to take this advice with a teaspoon of salt.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-10T12:24:46.187",
"Id": "1235",
"ParentId": "683",
"Score": "11"
}
},
{
"body": "<ul>\n<li><p>This error message reveals nothing about the actual error:</p>\n\n<blockquote>\n<pre><code>if(N%size != 0)\n{\n MPI_Finalize();\n printf(\"ERROR!\");\n exit(0);\n}\n</code></pre>\n</blockquote>\n\n<p>Just displaying \"ERROR!\" won't tell the user <em>what</em> this exact error is and/or <em>why</em> it has happened. Yes, it's certainly important to make sure the input size and number of processes are divisible in MPI to maintain load balance, but the user <em>must</em> still know about this so that either input can be adjusted accordingly.</p>\n\n<p>It may also help others (and yourself) to display the computed portion size, whether or not this error has occurred. If you get an unreasonable value (usually if the portion size cannot fit inside an <code>int</code> (overflow), which is a commonly used size type by the MPI functions), then the user will know about this and will attempt to fix it for next time.</p>\n\n<p>This error, and any others, should be printed to <code>stderr</code> via <code>fprintf()</code> instead.</p>\n\n<p>As this is <em>not</em> a successful exit, you should use a different exit/return value other than <code>0</code>. This may ideally depend on the language you'll be using (this uses C and C++), but it may be good to use <code>1</code> (or <code>EXIT_FAILURE</code>) for this.</p>\n\n<p>Finally, you can just have process 0 display the error so that it's displayed only once (any normal output should just be printed by this process). Of course, all of the processes should still call <code>MPI_Finalize()</code> and <code>exit()</code>/<code>return()</code>.</p></li>\n<li><p>Regarding memory allocation:</p>\n\n<p>You allocate memory for <code>tmpArray</code>, but never deallocate it. Since it's only allocated by process 0, just have that process handle the deallocation, so that it's done only once (very important).</p>\n\n<pre><code>if (rank == 0) free(tmpArray);\n</code></pre>\n\n<p>You may also consider terminating the program if <em>any</em> allocation has failed:</p>\n\n<pre><code>if (myArray == NULL) // nullptr if using C++11\n{\n fprintf(stderr, \"could not allocate array\\n\");\n MPI_Finalize();\n return EXIT_FAILURE; // or use any suitable non-zero error value\n}\n</code></pre></li>\n<li><p>Regarding cleanliness:</p>\n\n<p>Indentation is inconsistent in some places. Also, you don't indent entire function bodies, which could greatly hurt readability if one cannot tell where some code belongs.</p>\n\n<p>Some lines, such as this one:</p>\n\n<blockquote>\n<pre><code>for(i=0, v=firstElement+2; i<=(N/size)-1; i++, v++)\n</code></pre>\n</blockquote>\n\n<p>could use a little more whitespace between some operators:</p>\n\n<pre><code>for (i = 0, v = firstElement+2; i <= (N/size)-1; i++, v++)\n</code></pre>\n\n<p>It's mostly up to you, but it may be clearer to at least have the equality and assignment operators separated to help identify the operands.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-28T21:59:43.340",
"Id": "64113",
"ParentId": "683",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-07T22:21:35.953",
"Id": "683",
"Score": "16",
"Tags": [
"c++",
"c",
"primes",
"sieve-of-eratosthenes",
"mpi"
],
"Title": "Eratosthenes sieve and MPI"
} | 683 |
<p>Here is the pertinent code:</p>
<p>index.html</p>
<pre><code><!-- DOM INITIALIZATION -->
<script type="text/javascript">
$().ready(function() {
getThemeInfo();
if (themeSelect==2) {
ReplaceJSCSSFile("css/skin1.css", "css/skin2.css", "css"); // overwrite CSS
}
AJAX_LoadResponseIntoElement("skinContainer", "skin" + themeSelect + ".txt", function() {
AJAX_LoadResponseIntoElement("contentdiv", "index.txt", initPage);
});
});
</script>
</code></pre>
<p>funcs.js</p>
<pre><code>function initPage()
{
setContentDimensions();
replaceCSSMenu();
showContainer();
setContentPositions();
}
function setContentPositions()
{
var contentTop = findTop(document.getElementById('NavMenu')) + 4;
var contentLeft = findLeft(document.getElementById('kwick1')) + 226;
document.getElementById('contentdiv').style.top = (contentTop)+ "px";
}
</code></pre>
<p>Quick recap: It fetches the theme selection, and if it's not the default (1), then it changes the CSS file to skin2.css. Then, it fetches the page with AJAX and initializes it, and part of initialization is setting the div dimensions and positions.</p>
<p>Although the theme swap works perfectly through the button (code not shown here,) it does not work in Opera if the theme setting, stored in cookies, is a non-default theme, causing the CSS to be swapped during the loading of the page (i.e. this code here.) For whatever reason, the .top and .left of my "contentdiv," which is set in ContentPositions() function, is wrong.</p>
<p>I'd assumed this was happening because the CSS styles were not loaded prior to the JavaScript attempting to set contentdiv's position. To test this theory, I put an alert() in setContentPositions() to test that contentTop & contentTop were indeed wrong (they were,) and then another alert() after the DOM init line that changes the CSS file. With the addition of the alert() after the CSS change within DOM init, it loads perfectly.</p>
<p>Why is the CSS file not processed by the time it does two AJAX fetches? Is a callback function the proper way to fix this?</p>
<p>Edit...</p>
<p>The code for some of the functions used in the above code was requested. Here it is:</p>
<pre><code>function ReplaceJSCSSFile(oldfilename, newfilename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none";
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none";
var allElements=document.getElementsByTagName(targetelement);
for (var i=allElements.length; i>=0; i--){
if (allElements[i] && allElements[i].getAttribute(targetattr)!=null && allElements[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
var newelement=CreateJSCSSFile(newfilename, filetype);
allElements[i].parentNode.replaceChild(newelement, allElements[i]);
}
}
}
function CreateJSCSSFile(filename, filetype){
if (filetype=="js"){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}
else if (filetype=="css"){
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
return fileref;
}
function AJAX_LoadResponseIntoElement (elementId, fetchFileName, cfunc) {
var XMLHRObj;
if (window.XMLHttpRequest) { XMLHRObj=new XMLHttpRequest(); }
else { XMLHRObj=new ActiveXObject("Microsoft.XMLHTTP"); }
XMLHRObj.onreadystatechange=function()
{
if (XMLHRObj.readyState==4 && XMLHRObj.status==200)
{
document.getElementById(elementId).innerHTML=XMLHRObj.responseText;
cfunc();
}
}
XMLHRObj.open("GET",fetchFileName,true);
XMLHRObj.send();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T13:00:16.900",
"Id": "1403",
"Score": "0",
"body": "We are missing relevant details: please include the code of the functions used to fetch CSS from server. I noticed that script.readyState was not reliable in some versions of Opera: http://stackoverflow.com/questions/1929742/can-script-readystate-be-trusted-to-detect-the-end-of-dynamic-script-loading. There might be something similar for CSS."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T13:39:33.797",
"Id": "1404",
"Score": "0",
"body": "The CSS swap code has been added, along with the AJAX code."
}
] | [
{
"body": "<p>I would suggest to take a different approach. It is complicated to get a callback for the complete loading of a CSS stylesheet loaded dynamically: see this Stack Overflow question for reference:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3078584/link-element-onload\">Is there anyway to listen to the onload event for a element?</a></p>\n\n<p>Do not use JavaScript to set the content position: it is part of styling and should be done in CSS instead. Isn't the role of your CSS skins to modify the appearance of the page?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T13:17:00.813",
"Id": "1420",
"Score": "0",
"body": "Hmmm... I suppose, in this case, it isn't needed since the position will be static. Good call."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T13:03:40.437",
"Id": "771",
"ParentId": "687",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "771",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T09:24:24.270",
"Id": "687",
"Score": "2",
"Tags": [
"javascript",
"css"
],
"Title": "Do I need to use a callback function here, or is there another way?"
} | 687 |
<p>This sample code works fine, but it looks awful. How would you improve this?</p>
<pre><code>data.Add(((Adress)(((OwnerIDList)owner.Adresses.Value)[0].Adress.Value)).FirstName.Value.ToString());
data.Add(((Adress)(((OwnerIDList)owner.Adresses.Value)[0].Adress.Value)).LastName.Value.ToString());
</code></pre>
<p>Why do we use <code>.Value</code> in <code>FirstName.Value.ToString()</code>?</p>
<p><code>FirstName</code> is a <code>DTString</code> object (implements a basic interface for all data types to be stored in data base).</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T11:46:22.027",
"Id": "1217",
"Score": "0",
"body": "What are the types of Addresses and Address? Can you change them, perhaps using generics, to avoid having to cast altogether?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T18:32:02.560",
"Id": "1230",
"Score": "0",
"body": "I see in the code sample you are using the index of 0, but I was wondering if this is actually being done in a loop. If so, I would also suggest that extract a variable for the `OwnerIDList` outside of the loop."
}
] | [
{
"body": "<p>at least I would extract a variable: </p>\n\n<pre><code>var address = (Adress)((OwnerIDList)owner.Adresses.Value)[0].Adress.Value;\ndata.Add(address.FirstName.Value.ToString());\ndata.Add(address.LastName.Value.ToString());\n</code></pre>\n\n<p>All these cast operations make me believe that your code is not that strongly typed. If it so then there is not that much you can do with readability in this code.</p>\n\n<p>P.S.: <code>Address</code> in English has two <code>d</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T11:55:43.460",
"Id": "1218",
"Score": "0",
"body": "I am using .net 2.0 so instead var we need to use Adress. Thanks"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T13:04:20.860",
"Id": "1222",
"Score": "1",
"body": "@thedev, as far as I'm aware you can use `var` even for .Net 2.0 if you're using VS 2008"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T21:55:51.053",
"Id": "1255",
"Score": "1",
"body": "@Snowbear, but why would you want to in this situation? Using Adress is strictly better if you ask me. var saves you a few keystrokes while writing the code, but Adress gives you additional information about the type of the variable every time you read it. IMO, var should be used for its intended purpose only - to declare a variable that will hold an anonymous type."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T23:46:59.473",
"Id": "1258",
"Score": "1",
"body": "@Saeed, I do not agree. I believe you should have your variables named in that way so you will not need ANY additional information. `Address address = ...` is redundant."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T23:50:19.360",
"Id": "1259",
"Score": "0",
"body": "@Saeed: And I will add that with the cast to Adress on the right of the assignment, the type is already very visible in the statement. Using `var` here would be DRY."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T00:00:36.950",
"Id": "1261",
"Score": "0",
"body": "`Address address = AddresResolver.DefaultAddressResolver.ResolveAddress()` =)))"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T10:54:42.647",
"Id": "689",
"ParentId": "688",
"Score": "8"
}
},
{
"body": "<p>What's with all the .Value is it because the variables are defined as Nullable< T > variables?</p>\n\n<p>In that case, you can substitute </p>\n\n<pre><code>FirstName.Value.ToString()\n</code></pre>\n\n<p>With</p>\n\n<pre><code>FirstName.ToString()\n</code></pre>\n\n<p>Besides that, the place where I would clean up would be the actual objects that you are querying for data. You have a lot of casts, and a lot of .Value lookups to get to the real data. </p>\n\n<p>This results in the code that uses those classes reflects the design choices made when implementing those classes, And that is the real reason why your code looks awful. </p>\n\n<p>I would change those types, so you would be able to write:</p>\n\n<pre><code>data.Add(owner.Adresses[0].Adress.FirstName);\n</code></pre>\n\n<p>Also it seems illogical that an object that you retrieve from an Addresses collection should have a property called Address? Maybe that should have a better name.</p>\n\n<p>And as already mentioned, there are two d's in address.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T15:06:52.597",
"Id": "1226",
"Score": "0",
"body": "FirstName.ToString() ... done"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T12:29:42.623",
"Id": "691",
"ParentId": "688",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "689",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-08T10:42:26.507",
"Id": "688",
"Score": "4",
"Tags": [
"c#",
"casting"
],
"Title": "Multiple explicit cast operations"
} | 688 |
<pre><code>public boolean connectedOnGameServer = false;
public final Object conGameServerMonitor = new Object();
public void connectedToGameServer() {
synchronized (conGameServerMonitor) {
if (connectedOnGameServer != false)
throw new RuntimeException("Player connected twice");
connectedOnGameServer = true;
conGameServerMonitor.notifyAll();
}
}
public void waitForGameServerConnection() {
synchronized (conGameServerMonitor) {
try {
long startTime = System.currentTimeMillis();
long waited = 0;
while (!connectedOnGameServer && waited < GAMESERVER_CONNECT_TIMEOUT) {
conGameServerMonitor.wait(GAMESERVER_CONNECT_TIMEOUT - waited);
waited = System.currentTimeMillis() - startTime;
}
if (waited > GAMESERVER_CONNECT_TIMEOUT && connectedOnGameServer) {
throw new RuntimeException("Client didn't connect to game server in time (" + GAMESERVER_CONNECT_TIMEOUT + " ms)");
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for client to connect to game server", e);
}
}
}
</code></pre>
<p>What I need is:</p>
<ul>
<li>Thread A calls <code>waitForGameServerConnection</code></li>
<li>Thread B calls <code>connectedToGameServer</code></li>
<li>Thread A continues</li>
</ul>
| [] | [
{
"body": "<p>My code examples are excerpts. Don't copy/paste them, they are suggestions you can incorporate into your code. </p>\n\n<pre><code>if (waited > GAMESERVER_CONNECT_TIMEOUT && connectedOnGameServer)\n{\n throw new RuntimeException(\"Client didn't connect to game server in time (\" + GAMESERVER_CONNECT_TIMEOUT + \" ms)\");\n} \n</code></pre>\n\n<p>can be reduced to:</p>\n\n<pre><code>if (!connectedOnServer) {\n throw new RuntimeException(\"Client didn't connect to game server in time (\" + GAMESERVER_CONNECT_TIMEOUT + \" ms)\");\n}\n</code></pre>\n\n<p>Now, you can handle this without an exception. Connections fail quite regularly, and it's easy to handle that.</p>\n\n<pre><code>public boolean waitForConnection() {\n synchronized (conGameServerMonitor) {\n // loop, guard\n return connectedOnGameServer? true : false;\n }\n}\n</code></pre>\n\n<p>With this you can ask the player if he wants to try again, or wait a bit and try again, etc without having to catch an exception.\nBut what if B calls <code>connectedToGameServer()</code> <em>after</em> the wait completes?</p>\n\n<pre><code>boolean connectionInProgress;\n\npublic void connectedToGame() {\n synchronized (conGameServerMonitor) {\n if (connectionInProgress) {\n connectedOnGameServer = true;\n conGameServerMonitor.notifyAll(); \n }\n }\n}\n\npublic boolean waitForConnection() {\n synchronized (conGameServerMonitor) {\n connectionInProgress = true;\n // wait\n connectionInProgress = false;\n return connectedOnGameServer? true : false;\n }\n}\n</code></pre>\n\n<p>You handle the wakeups and interuptions correctly. Kudos for the <code>waited</code> part - I thought \"Useless!\" for a second, but I forgot that a thread could wake anytime, and it's the thread's responsibility to be sure that it's conditions are fulfilled.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T15:12:08.887",
"Id": "693",
"ParentId": "690",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "693",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-08T11:57:36.830",
"Id": "690",
"Score": "7",
"Tags": [
"java",
"synchronization",
"timeout",
"locking"
],
"Title": "Waiting for game server connection"
} | 690 |
<p>I'm writing a quiz application in PHP and am querying the DB for questions and their associated answers. I then wrangle the result set into a usable array for my front end. However, it always seems like a wrestling match and I'm wondering if I could have got to my desired array structure more efficiently.</p>
<p>What I wanted was an associative array / dictionary which was structured so that the questions were at the top level with their associated answers underneath. I also wanted a numeric index above the question level so that I can later use that to match my <code>current_step</code> session variable for stepping through the form.</p>
<pre><code>function get_question_data( $quiz_id)
{
global $wpdb;
if ( !isset($quiz_id)) {
return FALSE;
}
$sql = $wpdb->prepare("SELECT q.ID AS 'question_id', question, explanation, q.sort_order, qa.ID AS 'answer_id', qa.answer, qa.correct, qa.hint
FROM {$wpdb->prefix}my_quiz_questions q
LEFT JOIN wp_nmsi_quiz_answers AS qa ON q.ID = qa.question_id
WHERE quiz_id=%d ORDER BY q.ID", $quiz_id);
$quiz_data = $wpdb->get_results($sql, ARRAY_A);
fb($quiz_data,'DATABASE RESULTS');
//build into a user-friendly array which we can use to manage quiz steps and questions later.
$question_array = array();
foreach ($quiz_data as $key=>$value) {
foreach ($value as $k => $v) {
if ($k == 'question' ) {
if (!array_key_exists('question_'.$value['question_id'], $question_array)) {
$question_array['question_'.$value['question_id']]['question_text'] = $v;
$question_array['question_'.$value['question_id']]['question_id'] = $value['question_id'];
}
}
if ($k == 'answer'){
$question_array['question_'.$value['question_id']]['answers'][$value['answer_id']]['text'] = $v;
}
if ($k == 'hint') {
$question_array['question_'.$value['question_id']]['answers'][$value['answer_id']]['hint'] = $v;
}
if ($k == 'correct') {
$question_array['question_'.$value['question_id']]['answers'][$value['answer_id']]['correct'] = $v;
}
if ($k == 'explanation' ) {
$question_array['question_'.$value['question_id']]['explanation'] = $v;
}
}
}
//echo $wpdb->last_query;
return array_values($question_array);
}
</code></pre>
<p>I ended up with <a href="http://cl.ly/2F313J2j0K0t0i2O2g3V" rel="nofollow">this solution</a>.</p>
<p><strong>Update: Query Results</strong></p>
<pre><code>array(6) {
[0]=>
array(8) {
["question_id"]=>
string(1) "1"
["question"]=>
string(34) "Question 1. What is the question ?"
["explanation"]=>
string(38) "This is the explanation for question 1"
["sort_order"]=>
string(1) "0"
["answer_id"]=>
string(2) "20"
["answer"]=>
string(16) "this is answer 4"
["correct"]=>
string(1) "0"
["hint"]=>
string(29) "this is the hint for answer 4"
}
[1]=>
array(8) {
["question_id"]=>
string(1) "1"
["question"]=>
string(34) "Question 1. What is the question ?"
["explanation"]=>
string(38) "This is the explanation for question 1"
["sort_order"]=>
string(1) "0"
["answer_id"]=>
string(2) "19"
["answer"]=>
string(16) "this is answer 3"
["correct"]=>
string(1) "0"
["hint"]=>
string(29) "this is the hint for answer 3"
}
[2]=>
array(8) {
["question_id"]=>
string(1) "1"
["question"]=>
string(34) "Question 1. What is the question ?"
["explanation"]=>
string(38) "This is the explanation for question 1"
["sort_order"]=>
string(1) "0"
["answer_id"]=>
string(2) "18"
["answer"]=>
string(16) "this is answer 2"
["correct"]=>
string(1) "0"
["hint"]=>
string(29) "this is the hint for answer 2"
}
[3]=>
array(8) {
["question_id"]=>
string(1) "1"
["question"]=>
string(34) "Question 1. What is the question ?"
["explanation"]=>
string(38) "This is the explanation for question 1"
["sort_order"]=>
string(1) "0"
["answer_id"]=>
string(2) "17"
["answer"]=>
string(16) "this is answer 1"
["correct"]=>
string(1) "1"
["hint"]=>
string(29) "this is the hint for answer 1"
}
[4]=>
array(8) {
["question_id"]=>
string(1) "2"
["question"]=>
string(10) "Question 2"
["explanation"]=>
string(26) "Explanation for question 2"
["sort_order"]=>
string(1) "0"
["answer_id"]=>
string(2) "24"
["answer"]=>
string(28) "test answer 2 for question 2"
["correct"]=>
string(1) "0"
["hint"]=>
string(13) "answer 2 hint"
}
[5]=>
array(8) {
["question_id"]=>
string(1) "2"
["question"]=>
string(10) "Question 2"
["explanation"]=>
string(26) "Explanation for question 2"
["sort_order"]=>
string(1) "0"
["answer_id"]=>
string(2) "23"
["answer"]=>
string(28) "test answer 1 for question 2"
["correct"]=>
string(1) "1"
["hint"]=>
string(13) "answer 1 hint"
}
}
</code></pre>
| [] | [
{
"body": "<p>From the structure of the sql query, it looks like your output is going to have duplicate rows, due to the fact that a single question can have multiple answers. This means you're going to have to do some screwy stuff, like what you did with the nested <code>foreach</code> loops. I would recommend splitting this into two separate queries, one to get the questions and one to get the answers, and then just assigning the responses straight into the array without all the <code>if(key==whatever) { // assign something }</code> magic.</p>\n\n<p>As for the array itself, it looks quite good. Some pretty minor points:</p>\n\n<ol>\n<li><p><code>question_array</code> doesn't really need to have a string-based key (e.g., <code>$question_array['question_1']</code>); it may be easier to work with if you just use numbers (e.g., <code>$question_array[1]</code>).</p></li>\n<li><p>You don't have a field for how many points each question is worth.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T07:06:42.763",
"Id": "1271",
"Score": "1",
"body": "Thanks for the reply:) It does have some duplication of data but not duplicate rows. My motivation for doing it in one query was to try and minimise the number of hits on the DB. I realise that for a simple quiz this probably isn't an issue but like to try and employ 'best practice' to improve my programming. Thanks for your additional pointers re the array."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:36:33.513",
"Id": "696",
"ParentId": "692",
"Score": "1"
}
},
{
"body": "<p><strong>First Cut:</strong> Since every row contains the same set of fields, you can clean up the code considerably by skipping the inner loop.</p>\n\n<pre><code>$question_array = array();\nforeach ($quiz_data as $row) {\n $qId = $row['question_id'];\n $aId = $row['answer_id'];\n $answer = array(\n 'id' => $aId,\n 'text' => $row['answer'],\n 'hint' => $row['hint'],\n 'correct' => $row['correct'],\n );\n if (!array_key_exists($qId, $question_array)) {\n $question_array[$qId] = array(\n 'id' => $qId,\n 'text' => $row['question'],\n 'explanation' = $row['explanation'],\n 'sort' = $row['sort_order'],\n );\n }\n $question_array[$qId]['answers'][$aId] = $answer;\n}\n</code></pre>\n\n<p><strong>Second Cut:</strong> Use objects instead of arrays. While it may seem to have little payoff at first, as you start performing more complex operations on questions and answers you'll gain much from the encapsulation.</p>\n\n<pre><code>$question_array = array();\nforeach ($quiz_data as $row) {\n $qId = $row['question_id'];\n $answer = new Answer($row['answer_id'], $row['answer'], $row['hint'], $row['correct']);\n if (!array_key_exists($qId, $question_array)) {\n $question_array[$qId] = $question \n = new Question($qId, $row['question'], $row['explanation'], $row['sort_order']);\n }\n else {\n $question = $question_array[$qId];\n }\n $question->addAnswers($answer);\n}\n</code></pre>\n\n<p>Here are the most basic definitions for the Question and Answer classes to get you started.</p>\n\n<pre><code>class Question {\n private $id;\n private $text;\n private $explanation;\n private $sortOrder;\n private $answers = array();\n public function __construct($id, $text, $explanation, $sortOrder) {\n $this->id = $id;\n $this->text = $text;\n $this->explanation = $explanation;\n $this->sortOrder = $sortOrder;\n }\n public addAnswer(Answer $answer) {\n $this->answers[$answer->getId()] = $answer;\n }\n ... property accessors and other methods ...\n}\n\nclass Answer {\n private $id;\n private $text;\n private $hint;\n private $correct;\n public function __construct($id, $text, $hint, $correct) {\n $this->id = $id;\n $this->text = $text;\n $this->hint = $hint;\n $this->correct = $correct;\n }\n ... property accessors and other methods ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T06:17:39.740",
"Id": "1343",
"Score": "0",
"body": "Wow, thanks David. That is definitely more succinct and presumably more performant without the extra loop. I plan to release the quiz code as a plugin at some point. I will definitely consider encapsulating the answers and questions in objects during refactoring."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T06:31:46.373",
"Id": "1345",
"Score": "0",
"body": "Would this be a candidate for dependency injection do you think? A quiz would contain several question objects which in turn would contain several answer objects"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T07:14:14.193",
"Id": "1347",
"Score": "0",
"body": "@codecowboy - DI is more geared toward configuring system services such as a Data Access Object with a DB connection or an API Service with a REST Connection Manager which probably doesn't mean much to you now. It's a tougher sell (for me) in PHP since the PHP processes are short lived. In a Java web application you can build all of the necessary services and reuse them. With PHP you must build them for every request so you want to build only what you'll use. I haven't investigated DI libraries for PHP yet, however."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T18:28:47.033",
"Id": "1371",
"Score": "0",
"body": "Thanks again. You could take a look at http://components.symfony-project.org/dependency-injection/"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T03:20:44.103",
"Id": "739",
"ParentId": "692",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "739",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-08T12:57:24.190",
"Id": "692",
"Score": "6",
"Tags": [
"php",
"sql",
"array"
],
"Title": "Extract a joined result set into a parent-child hierarchy"
} | 692 |
<p>I recently had a discussion in the forum of an API, because they changed an exception from checked to unchecked. I believed it needs to be checked, because it is recoverable. The arguments of "the other side" were verbosity and tediousness of try/catch or throws.</p>
<p>If it were purely theoretical question, I'd be right, but I agree that in practice it is sometimes tedious to write all these try/catches just for the sake of rethrowing unchecked exceptions, or logging.</p>
<p>So, an idea came to my mind, and I wonder whether it's viable. I'll illustrate with simple code:</p>
<pre><code>public interface Foo {
String foo() throws Exception;
}
public interface EasyFoo extends Foo {
String foo();
}
</code></pre>
<p>These are two interfaces that define the same method (and this is enforced by inheritance), but the "easy" version does not define throwing checked exceptions. Then come 2 default implementations:</p>
<pre><code>public class FooImpl implements Foo {
@Override
public String foo() throws Exception {
return "foo";
}
}
public class EasyFooImpl implements EasyFoo {
Foo foo;
public EasyFooImpl(Foo foo) {
this.foo = foo;
}
@Override
public String foo() {
try {
return foo.foo();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
</code></pre>
<p>The latter delegates to the former, wrapping all exceptions in runtime exceptions.</p>
<p>And finally a factory:</p>
<pre><code>public class FooFactory {
public static Foo createFoo() {
return new FooImpl();
}
public static EasyFoo createEasyFoo() {
return new EasyFooImpl(new FooImpl());
}
}
</code></pre>
<p>The benefits:</p>
<ul>
<li>the user of the API can choose how he likes to use the implementation. If he doesn't intend to do anything with the checked exceptions, he can use the "easy" version</li>
<li>you support only one interface. The 2nd is the same, and you'll just have to add the methods that you have in the main one.</li>
<li><p>the user can use the <code>EasyFoo</code> in places where <code>Foo</code> is required:</p>
<pre><code>EasyFoo foo = FooFactory.createEasyFoo();
helper.doSomething(foo); // which is public void doSomething(Foo foo);
</code></pre></li>
</ul>
<p>Enough foos - the question is, is this a viable solution that can reduce verbosity while retaining the good sides of checked exceptions?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:43:36.367",
"Id": "1231",
"Score": "1",
"body": "if you really want to recover from an unchecked exception, you can still explicitly catch it right?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:45:03.853",
"Id": "1232",
"Score": "1",
"body": "@hvgotcodes you can, but the API becomes less evident. And by default users will start coding without even knowing exceptions can arise there. They'll be lucky if the exception happens soon, but it might happen in production. And as I noted - unchecked exceptions are not meant to be recovered from."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:46:23.277",
"Id": "1233",
"Score": "0",
"body": "@bozho, right -- Im just trying to decide if its worth the work to stand up 2 implementations for the same functionality. If you were to do it, your approach seems reasonable..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:47:28.847",
"Id": "1234",
"Score": "0",
"body": "incidentally, is this hibernate?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:48:54.133",
"Id": "1235",
"Score": "0",
"body": "@hvgotcodes the point is that they are actually one interface, and this is enforced by inheritance. There is no possibility for a mismatch between the two interfaces. Yes, it would require writing the wrapper implementation, but it might be the lesser evil."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:49:09.373",
"Id": "1236",
"Score": "0",
"body": "@hvgotcodes no, it's restfb :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:51:06.583",
"Id": "1237",
"Score": "2",
"body": "just because the exception can be recovered from, will most people want to recover? You Pattern actually looks pretty good -- you could do some config magic so the developer could basically say 'easy' or 'full' so that way they don't need to do anything to go one way or the other..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:52:48.733",
"Id": "1238",
"Score": "0",
"body": "@hvgotcodes well, they'd have to choose an interface at least, so just config won't do, alas."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:53:36.120",
"Id": "1239",
"Score": "0",
"body": "This may be a silly question, but are you even allowed to override a method throwing a checked exception with one that doesn't?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:54:03.460",
"Id": "1240",
"Score": "0",
"body": "+1 for the sentence \"just because the exception can be recovered from, will most people want to recover\". I guess this summarizes the problem, and why there is no easy choice between checked and unchecked."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:54:34.893",
"Id": "1241",
"Score": "0",
"body": "@Daniel Bingham The above code compiles perfectly fine (in eclipse at least), and behaves as desired."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:55:16.990",
"Id": "1242",
"Score": "0",
"body": "ah right...sorry my head is not on straight -- is this the type of the exception that most people would want to recover from? I ask because Im wondering if the implemented it according to the rule, not the exception -- you're wanting to recover being the exception"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:56:05.057",
"Id": "1243",
"Score": "0",
"body": "@Bozho Feels wrong. Feels like something that shouldn't be allowed. Kind of like decreasing access. Inheritance is meant to take you from less functionality to more, not the reverse direction."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:57:55.860",
"Id": "1244",
"Score": "0",
"body": "@hvgotcodes the concrete exception can occur if the network is down, or if facebook fails to respond. In my case alone I have two ways of recovering - retrying, and returning an empty result to the caller, which is a valid behaviour in my case."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T18:04:09.623",
"Id": "1245",
"Score": "0",
"body": "@bozho, yeah this seems like it should just be a checked exception then. hmm...."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T18:05:57.760",
"Id": "1246",
"Score": "0",
"body": "@hvgotcodes well, after the change I retained my catches, but catching runtime exceptions feels odd."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T19:06:41.383",
"Id": "1247",
"Score": "0",
"body": "@bozho, what change? After your change? The quickest way to resolve this would be to catch the unchecked exception, put a comment in 'gee this should be a checked exception to start', and move on. For solving the general problem, either 1 submit a bug saying that the exception should be checked, because it makes sense the majority of users would want to handle the exception to return an appropriate response, or 2 do what you did and code around it. Seems like a heavy hammer to drop though, doing a significant amount of design for the issue"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T19:22:22.903",
"Id": "1248",
"Score": "0",
"body": "@hvgotcodes the change from checked to unchecked. I'm not going to add an interface in my code, I was posing a theoretical question for API design :) as for my code - I'll just retain the catch-es."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T19:31:11.677",
"Id": "1249",
"Score": "0",
"body": "@bozho, I think your design is good. I can't think of anything simpler...the one thing that bugs me is if you wanted to switch, you would have to change the interface -- when the point of interfaces is you just have the (transparently) change the implementation. But I dont think thats possible in java, in this scenario..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T19:55:12.443",
"Id": "1250",
"Score": "0",
"body": "Ignoring the checked vs. unchecked debate (I personally prefer unchecked after working with both for a decade and reading the arguments), the above has a major drawback: you can no longer use a simple `catch` block with a named exception. You must catch every `RuntimeException` and check the type of the wrapped exception. That's a huge PITA."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T19:57:09.827",
"Id": "1251",
"Score": "0",
"body": "If you want to _catch_, then use the checked version."
}
] | [
{
"body": "<p>Ok, I'm going to assume that this is a honest-to-goodness exceptional case, that is extremely unlikely to happen. It isn't like java.sql, that throws an exception when opening a connection fails, which can happen very easily and should be handled by returning <code>null</code>.</p>\n\n<p>If there are people who want this exception unchecked, they should write their own wrapper for it, IMO. If you did want it in the library, though, I'd do it exactly as you did for interfaces. The unchecked version doesn't depend on the checked vesion's implementation, so you only ever need one wrapper <code>EasyFooImpl</code>.</p>\n\n<p>I would wonder about the design of the library if I ever saw that. Checked or unchecked, it's best to avoid throwing exceptions altogether. There are only two valid reasons I see as being \"exception-worthy\":</p>\n\n<ul>\n<li>Where an unknown operation leaves the code in a unknown/invalid state. This should unrecoverable by the code that throws the exception.</li>\n<li>Where it is impossible to return an invalid state, such as <code>null</code> or <code>0</code>. An example that comes to mind is <code>Integer.parse()</code>. You can't return <code>null</code>; it requires <code>int</code>. And you can't return <code>0</code> or <code>NAN</code> because that is in the valid return set of the method. An exception the cleanest, most readable way you can signal that the string is unparsable to an integer.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T21:37:56.680",
"Id": "1254",
"Score": "1",
"body": "well, in this case the failure can be due to network problem. So I can retry, or decide return empty result, or to propagate above"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T00:47:25.350",
"Id": "1263",
"Score": "1",
"body": "The fact that you do not like exceptions, does not make them worthless. Exceptions are useful, especially unchecked ones."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T13:39:47.593",
"Id": "1279",
"Score": "0",
"body": "It's not that I don't like exceptions; I think that they are very useful. They are just overused in many cases. However, checked exceptions force the exceptional case to be handled close to the point it was thrown. In most cases, that code has the best context to handle the problem, and it can swallow it if the problem is not a show-stopper."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T13:45:21.787",
"Id": "1280",
"Score": "0",
"body": "I feel that in a framework/library, all exceptions should be checked. If the *framework* can't handle the problem, then it's probably important. The calling code should not be able to ignore the problem without acknowledging that it exists. To me, making the exception unchecked is tantamount to saying that it doesn't matter."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T15:11:09.110",
"Id": "1285",
"Score": "1",
"body": "Usually, the calling code does not care which exception has occured, as it cannot handle it anyway. Just let it bubble up to the main loop, which can show a dialog to the user, generate an error htlm page, or log it to a log file, depending on the type of application. The direct caller does not know the type of application, so cannot select the correct action."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T21:22:37.817",
"Id": "700",
"ParentId": "698",
"Score": "1"
}
},
{
"body": "<p>Just accept the fact that the exception is unchecked and move on.</p>\n\n<p>The industry is moving away from checked exceptions: C++ never had them, C# decided not to follow Java in this place, and the latest frameworks for Java are using unchecked exceptions.</p>\n\n<p>Face it, checked exceptions are a nice idea that doesn't work in practice.</p>\n\n<p>As a result, the thing you try in your code, will never pass any code review I'll be part of.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T07:29:52.563",
"Id": "1274",
"Score": "2",
"body": "luckily, I'm not doing the above, I'm just having an idea. ;) as of why checked exceptions don't work in practice - because they were misused too much. They have to exist, but need to be used rarely."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T15:06:55.110",
"Id": "1284",
"Score": "0",
"body": "@Bozho Checked exceptions do not work because they do not scale to RL sized projects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T20:58:44.017",
"Id": "61827",
"Score": "0",
"body": "Can you stop the industry coercing the [super first statement in constructor](http://stackoverflow.com/questions/1168345) in the same way?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T00:55:02.890",
"Id": "701",
"ParentId": "698",
"Score": "4"
}
},
{
"body": "<p>Just to add in conversation:</p>\n\n<p>IMHO Checked Exception are included for a reason. A method with a reasonable chance of failure should throw a checked Exception. e.g. IO classes rely on IO Devices which might not available at the time and thus throw a checked exception, IOException. The benefit of declaring IOException as checked is that Java enforces providing error handling or alternative solution. This is not enforced in the case of exceptions derived from RuntimeException. IMHO this enforcement encourages coders to write robust code which is better then not having an extra throws clause.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T01:35:11.417",
"Id": "1393",
"Score": "0",
"body": "The trouble with checked exceptions is that the language/framework is trying to guess whether or not you should handle an exception. But the guesses aren't perfect and in some cases it will make me catch the exception when I can't do anything about it, and it won't make me catch the exception when I should. Furthermore, my experience suggests that instead of writing robust code, java coders too often catch and throw away the exceptions."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T23:40:01.240",
"Id": "1413",
"Score": "2",
"body": "If Java would only force me to handle a checked exception, I would be happy. I would a catch-all try-catch in the main loop, and report an error in an appropiate way. However, Java does not allow me to do that. In fact, Java forces me to handle a checked exception in the **direct** calling code. The trouble is the **direct** in that statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:26:01.473",
"Id": "65988",
"Score": "0",
"body": "@Sjoerd: If a method throws a checked exception in a situation where the direct calling code doesn't expect it, even code further up the call stack is expecting that particular exception might be thrown, it's probably not expecting the situation that actually exists; code expecting the checked exception probably shouldn't receive one."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T16:35:00.790",
"Id": "756",
"ParentId": "698",
"Score": "1"
}
},
{
"body": "<p>If I had to do anything like that I'd just use <code>java.lang.reflect.Proxy</code> and generate the wrappers on the fly. You an check if the methods of Foo and EasyFoo are matching properly and disallow the EasyFoo impl (both interfaces should have the same method signatures but EasyFoo, no declared exceptions). In the end you have a reusable library to do dirty stuff. The invocation through the proxy will be slower but who cares.</p>\n\n<p>So basically you need one class the generates proxies and one designated exception for the wrapping. You should wrap exceptions that are declared only.</p>\n\n<p>Overall the code is synthetic sugar to me, though. You can always live w/ throws declaration instead. Even possible, I guess altering the compiler is not very feasible but the runtime verifier doesn't care of the exception declarations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-04T10:47:32.863",
"Id": "1154",
"ParentId": "698",
"Score": "0"
}
},
{
"body": "<p>Best practice in exception-handling is to <strong>\"throw early, catch late\"</strong>. </p>\n\n<p>Exceptions should mostly be handled at the business/ or request level -- it makes absolute sense to reconnect to an external system/ or resend a failed request. It generally <strong>does not</strong> make sense to retry a single byte, or a single SQL query.</p>\n\n<p>Given that, the concept of <strong>checked exceptions</strong> -- forcing you to \"handle immediately\" or declare -- is of limited use. </p>\n\n<p>Originally they were intended for <em>contingencies</em>, as opposed to <em>failures</em>. For example, an InsufficientFundsException when making a payment. Their spread to instead be used for all kinds of unrecoverable low-level systemic failures was largely a mistake.</p>\n\n<p>You should design API insteads to use runtime exceptions, and (if you need to catch) should rethrow checked as runtime exceptions. In my projects, I declare AppSqlException, AppInternalException, AppConfigException etc which work very well.</p>\n\n<p>See: </p>\n\n<ul>\n<li><a href=\"http://literatejava.com/uncategorized/checked-exceptions-javas-biggest-mistake/\" rel=\"nofollow\">http://literatejava.com/uncategorized/checked-exceptions-javas-biggest-mistake/</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-31T03:49:11.380",
"Id": "52142",
"ParentId": "698",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "21",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T17:37:42.390",
"Id": "698",
"Score": "9",
"Tags": [
"java",
"api",
"exception",
"exception-handling"
],
"Title": "Providing unchecked exception \"wrapper\" interfaces for an API with checked exceptions"
} | 698 |
<p>I have a rectangle with size <code>w</code> and height <code>h</code>. Now I want to split this rectangle into <code>n</code> new rectangles that are as similar as possible to a square. Afterwards I'd like to calculated the center of each square.</p>
<pre><code>public static List<Point> getCenters(int number, double width, double height)
{
List<Point> points = new List<Point>();
int originalNumberOfSquares = number;
int numberOfSquares = number;
if (numberOfSquares % 2 == 1)
{
numberOfSquares++;
}
int rectangleWidth = Convert.ToInt32(width);
int rectangleHeight = Convert.ToInt32(height);
double minDistance = Double.MaxValue;
int nSquaresInRow = -1;
int nSquaresInColumn = -1;
for (int i = 0; i <= numberOfSquares; i++)
{
for (int j = 0; j <= numberOfSquares; j++)
{
if (i * j == numberOfSquares)
{
if (Math.Abs(i - j) < minDistance)
{
minDistance = Math.Abs(i - j);
nSquaresInRow = i;
nSquaresInColumn = j;
}
}
}
}
int squareWidth = rectangleWidth / nSquaresInColumn;
int squareHeight = rectangleHeight / nSquaresInRow;
for (int r = 0; r < originalNumberOfSquares; r++)
{
int xSquareCenter = (((r + 1) * 2) - 1) * (squareWidth / 2);
while (xSquareCenter > rectangleWidth)
{
xSquareCenter = xSquareCenter - rectangleWidth;
}
int row = (r / nSquaresInColumn) + 1;
int ySquareCenter = ((2 * row) - 1) * (squareHeight / 2);
points.Add(new Point(Convert.ToDouble(xSquareCenter), Convert.ToDouble(ySquareCenter)));
}
return points;
}
</code></pre>
<p>Now the code works, but I think it's a little bit ugly. Any hints on how I can improve it?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T02:53:11.713",
"Id": "1270",
"Score": "0",
"body": "Are you sure your code does what you say it does? The best way to place 4 rectangles in a 2x8 rectangle would be if each one was 2x2 and thus square. However your algorithm would prefer 1x4 rectangles, since it looks for the size where the number of rectangles in a row and in a column are most similar, not where they are most square."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T09:34:36.417",
"Id": "1275",
"Score": "0",
"body": "@sepp2k: I'm not really sure what you're referring to. But for example if I call the method with (4, 20, 80), I get as results (20/5)\n(60/5)\n(20/15)\n(60/15). So I think the ordering is 2x2?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T14:50:42.947",
"Id": "1283",
"Score": "0",
"body": "@Rofcloptr: The ordering is 2x2, but the size of each of the rectangles is 40x10. But according to your description, you want the rectangles to be as close to a square as possible, so the ordering should be 4x1, which would make the size of each rectangle 20x20. So either your problem description or your code is wrong."
}
] | [
{
"body": "<p>Your first step should be to use meaningful variable names, even for your looping variables. I've never looked at this code before. I have no idea what it's doing. When other members of your team (if you have one) look at this code, they'll have no idea what's happening. If you come back to this code in a few days, weeks, months, etc., you will be in the same boat as the rest of us. Once you've given variables good names, it will be easier to reason about the code for both yourself and anyone else who comes after you. In turn, it will be easier to give additional refactoring advice, if appropriate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T02:11:04.963",
"Id": "703",
"ParentId": "702",
"Score": "3"
}
},
{
"body": "<p>A couple of notes:</p>\n\n<ul>\n<li>The width, height and number of sub-rectangles should be parameters, not local variables. If you should, for example, want to print out the centres for differing values of <code>w</code>, <code>h</code> and <code>n</code>, calling the method in a loop with different arguments is more convenient than changing the code and rerunning it multiple times.</li>\n<li>Determining the size of the sub-rectangles and collecting their centres could be done in two separate methods because a) they can easily be separated as they're not intertwined b) it makes it immediately obvious which part is done by which code and c) they might be useful on their own.</li>\n<li>Rather than outputting the centres, you should return them in an array or list. This way you can also easily use the method in a context where you don't want to print the centres or want to do something to them before printing. Also it's generally a good practice to separate IO code from logic code.</li>\n<li>Since both <code>i</code> and <code>j</code> are ints and thus <code>minDistance</code> will only ever hold integer values, it should have type <code>int</code>, not <code>double</code>. Otherwise it leaves the impression that it could possibly have a non-integer value.</li>\n<li>On a similar note you should probably make the type of <code>width</code> and <code>height</code> <code>int</code> as well since the first thing you do is to truncate them to <code>int</code>s. Having their type be <code>double</code> might make the user of your method think the results will be more accurate than they really are.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T02:33:00.470",
"Id": "1269",
"Score": "0",
"body": "+1 Thanks. I refactored the code according to your suggestions and updated it in the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T02:25:07.823",
"Id": "704",
"ParentId": "702",
"Score": "5"
}
},
{
"body": "<p>1) Your code doesn't handle <code>number=0</code> properly anyway (it will throw on <code>int squareWidth = rectangleWidth / nSquaresInColumn;</code>) so I would start your first loops (<code>i</code>,<code>j</code> iterators) from 1 since 0 rows/columns won't fit anyway. </p>\n\n<p>2) You do not actually need <code>j</code> loop. Instead of: </p>\n\n<pre><code> for (int i = 0; i <= numberOfSquares; i++)\n {\n for (int j = 0; j <= numberOfSquares; j++)\n {\n if (i * j == numberOfSquares) { ... }\n }\n } \n</code></pre>\n\n<p>It can simplified to (and taking into account my #1): </p>\n\n<pre><code> for (int i = 1; i <= numberOfSquares; i++)\n {\n int j = numberOfSquares / i;\n if (i * j == numberOfSquares) { ... }\n }\n</code></pre>\n\n<p>3) You don't need to iterate up to <code>numberOfSquares</code> here: <code>for (int i = 1; i <= numberOfSquares; i++)</code>. Since <code>i=2,j=6</code> is the same as <code>i=6,j=2</code> and you're looking only for first one you can iterate up to root square of <code>numberOfSquares</code>: </p>\n\n<pre><code>int maxI = (int)Math.Sqrt(numberOfSquares);\nfor (int i = 1; i <= maxI; i++)\n</code></pre>\n\n<p>4) Since you're looking for minimal <code>i-j</code> difference you should start iterating from closest one and stop iterating as soon as you will find matching pair. Original: </p>\n\n<pre><code> int maxI = (int)Math.Sqrt(numberOfSquares);\n for (int i = 1; i <= maxI; i++)\n {\n int j = numberOfSquares / i;\n if (i * j == numberOfSquares)\n {\n if (Math.Abs(i - j) < minDistance)\n {\n minDistance = Math.Abs(i - j);\n nSquaresInRow = i;\n nSquaresInColumn = j;\n }\n }\n }\n</code></pre>\n\n<p>Modified: </p>\n\n<pre><code> int maxI = (int)Math.Sqrt(numberOfSquares);\n for (int i = maxI; i >= 1; i--) // looping in reverse order\n {\n int j = numberOfSquares / i;\n if (i * j == numberOfSquares)\n {\n // if (Math.Abs(i - j) < minDistance) we do not need this check anymore\n {\n minDistance = Math.Abs(i - j);\n nSquaresInRow = i;\n nSquaresInColumn = j;\n break;\n }\n }\n }\n</code></pre>\n\n<p>5) With my #3 change you do not need <code>Math.Abs</code> anymore since <code>i</code> is always less or equal than <code>j</code>: </p>\n\n<pre><code>minDistance = j - i;\n</code></pre>\n\n<p>Now let's go to second loop: </p>\n\n<p>6) <code>int xSquareCenter = (((r + 1) * 2) - 1) * (squareWidth / 2);</code> here <strong>double</strong> maths should be used otherwise you're loosing precision here. </p>\n\n<p>7) Also this line is a little bit difficult to understand. I would introduce <code>row</code> and <code>column</code> variables to make it more clear: </p>\n\n<pre><code>int column = r % nSquaresInRow;\ndouble xSquareCenter = (column + 0.5) * squareWidth;\nint row = r / nSquaresInRow;\ndouble ySquareCenter = (row + 0.5) * squareHeight;\n</code></pre>\n\n<p>8) Last thing, I would replace both loops with Linq. Final result: </p>\n\n<pre><code>public static List<Point> getCenters(int number, double width, double height)\n{\n List<Point> points = new List<Point>();\n int originalNumberOfSquares = number;\n int numberOfSquares = number;\n if (numberOfSquares % 2 == 1)\n {\n numberOfSquares++;\n }\n int rectangleWidth = Convert.ToInt32(width);\n int rectangleHeight = Convert.ToInt32(height);\n\n int nSquaresInRow = -1;\n int nSquaresInColumn = -1;\n\n int maxI = (int)Math.Sqrt(numberOfSquares);\n int nSquaresInRow\n = Enumerable.Range(1, maxI)\n .Reverse()\n .First(i => numberOfSquares % i == 0);\n int nSquaresInColumn = numberOfSquares / nSquaresInRow;\n\n int squareWidth = rectangleWidth / nSquaresInColumn;\n int squareHeight = rectangleHeight / nSquaresInRow;\n\n return Enumerable.Range(0, originalNumberOfSquares)\n .Select(r => new { Column = r % nSquaresInRow, Row = r / nSquaresInRow})\n .Select(p => new { \n xSquareCenter = (p.Column + 0.5) * squareWidth,\n ySquareCenter = (p.Row + 0.5) * squareHeight})\n .Select(p => new Point(p.xSquareCenter, p.ySquareCenter))\n .ToList();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-06T11:55:35.760",
"Id": "1175",
"ParentId": "702",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "704",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-09T01:09:51.197",
"Id": "702",
"Score": "5",
"Tags": [
"c#",
"algorithm",
"computational-geometry"
],
"Title": "Find the center of n squares which together build a rectangle"
} | 702 |
<p>Here's a function that interpolates between a given value and a value fetched out of a legacy serialization buffer:</p>
<pre><code>template<typename T>
T interpolate(Buffer& buffer, const T currentValue, const float prop)
{
T bufferValue;
buffer.readT(&buferValue);
return currentValue + (bufferValue-currentValue)*prop;
}
</code></pre>
<p>This works great for <code>interpolate<float></code> and <code>interpolate<int></code> and so on. However if I want to pass a more complex structure such as a vector, I'd rather the currentValue parameter was passed by reference instead of by value. I can use overloading to handle that situation:</p>
<pre><code>// in addition to original function
Vector interpolate(Buffer& buffer, const Vector& currentValue, float prop)
{
Vector bufferValue;
buffer.readT(bufferValue);
return currentValue + (bufferValue-currentValue)*prop;
}
</code></pre>
<p>Even if you rip out the lerp into a helper function, it still isn't ideal to repeat the function like this when the only difference from the original is the & parameter, especially if there's more than one type I'd like to pass by reference.</p>
<p>I can use traits to auto-detect when to use a reference:</p>
<pre><code>// to replace original function
template<typename T>
struct RefTrait { typedef const T Ref; }
template<>
struct RefTrait<Vector> { typedef const Vector& Ref; }
template<typename T>
T interpolate(Buffer& buffer, typename RefTrait<T>::Ref currentValue, const float prop)
{
T bufferValue;
buffer.readT(&buferValue);
return currentValue + (bufferValue-currentValue)*prop;
}
</code></pre>
<p>However now the compiler can't induce the type of T by default, and the calling code has to explicitly state type:</p>
<pre><code>floatVal = interpolate<float>(buffer, floatVal, 0.5f);
vectorVal = interpolate<Vector>(buffer, vectorVal, 0.5f);
</code></pre>
<p>Is there anyway to have compact calling code as well as a single defined function?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T16:10:10.930",
"Id": "1286",
"Score": "2",
"body": "Is there a particular reason you don't want to pass ints, floats, etc. by reference?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T16:20:08.267",
"Id": "1287",
"Score": "0",
"body": "This is from a realtime app, and if this function is called a lot of times a frame then the extra dereferencing would be undesirable."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T18:20:17.260",
"Id": "1292",
"Score": "3",
"body": "@tenpn: If the function is inlined, then there will be no extra dereferencing to worry about. If it isn't, then that's what you need to fix; the cost of the function call will be much higher than the cost of the dereference."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T08:09:40.243",
"Id": "1301",
"Score": "0",
"body": "But you can't guarentee inlining, it's up to the compiler even if you use the keyword. But anyway I'm interested in the academic point - can I get rid of the reference without impacting client code?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T15:28:33.027",
"Id": "1363",
"Score": "0",
"body": "Is there any reason you can't just make a second template like \"interpolateByRef\" for the ones you want to use references on? Seems a mite bit easier than having to explicitly define separate traits per type."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T15:37:07.753",
"Id": "1364",
"Score": "0",
"body": "@TheXenocide not sure I follow you. Do you mean the calling code becomes `interpolate<byref>(buffer, myVec, 0.5f)`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T15:57:30.933",
"Id": "1366",
"Score": "0",
"body": "@tenpn no, I mean a separate template all together, like interpolateByRef<Vector> and interpolate<int> though it has been a long time since I've been deep in C++ so it's just as much a question as it is a suggestion."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T16:09:26.983",
"Id": "1367",
"Score": "0",
"body": "well if I want two very similar functions then I can use overloading like i did in the OP."
}
] | [
{
"body": "<p>If I understand your question correctly, using the <code>RefTrait</code> policy in your second solution is acceptable but you want to avoid specifying template parameters from the client code that's using it.</p>\n\n<p>If so then perhaps one possible idea is to create an inline wrapper function around your <code>interpolate</code> for marshaling the call so type deduction happens automatically:</p>\n\n<pre><code>template <>\nstruct RefTrait<Vector> { typedef const Vector &Ref; };\n\ntemplate <typename T>\nT interpolateImp(Buffer& buffer, typename RefTrait<T>::Ref currentValue, const float prop)\n{\n T bufferValue;\n buffer.readT(&bufferValue);\n return currentValue + (bufferValue-currentValue)*prop;\n}\n\ntemplate <typename T>\ninline T interpolate(Buffer& buffer, T &currentValue, const float prop)\n{\n return interpolateImp<T>(buffer, currentValue, prop);\n}\n</code></pre>\n\n<p>It doesn't avoid the overloading but it'll at least help with the automatic type-deduction when you try to use it:</p>\n\n<pre><code>floatVal = interpolate(buffer, floatVal, 0.5f);\nvectorVal = interpolate(buffer, vectorVal, 0.5f);\n</code></pre>\n\n<p>And the <code>interpolate</code> wrapper should get optimized away into just a <code>interpolateImp</code> call when the compiler inlines it.</p>\n\n<p>But I would recommend taking a look at what Mike said first and find out really how much of a performance impact this is. If afterwards you still decide to pursue this route there are two things to keep in mind.</p>\n\n<ul>\n<li>Caveat with using your current <code>RefTrait</code>. At the moment, <code>T bufferValue;</code> in your <code>interpolate</code> creates a locate T variable but doesn't initialize it. This poses a problem if T = const Vector&. Furthermore, it also means you're unable to <em>change</em> this T object later on should you need to. One possible way to fix it is to also add a valueType to your RefTraits policy. You would then use <code>typename T::valueType</code> to create any locates you would need inside <code>interpolate</code>.</li>\n<li>Using templates in this matter will reduce code clarity unless you're extra dilgent. The syntax has a matter of exploding in your face and could be difficult to get right especially if you're trying to cover the funny corner cases. Be sure to weight the tradeoffs.</li>\n</ul>\n\n<p>Edit: After thinking about my above code some more, I noticed it could be simplified a bit by just keeping the syntax the same as the OP. I've updated mines to reflect that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T01:55:21.953",
"Id": "715",
"ParentId": "706",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-09T15:46:57.603",
"Id": "706",
"Score": "9",
"Tags": [
"c++",
"serialization"
],
"Title": "Interpolating given value and legacy value from serialization buffer"
} | 706 |
<p>I am building up a basic folder tree with a list of strings in the form /root/node/node/node. Here is the basic algorithm I am using currently to build this collection and fill in my <code>TreeGridView</code>:</p>
<pre><code>// This method gets the list of folders and leaves, then trims out any folder paths
// that are already encompassed in a larger folder path, the idea is that it causes
// less work when adding the actual tree nodes (I may be wrong in this assumption)
List<string> BuildFinalList()
{
// This list is a collection of root folder paths and leaf folder names
// i.e. pair("/root/node/node", "node"), pair("/root/node", "node)
List<KeyValuePair<string, string>> folders = GetListOfFolders();
var paths = new List<string>();
foreach(var folder in folders)
{
var leaf = folder.Value;
var root = folder.Key;
paths.Add(string.Concat(root, "/", leaf);
}
paths.Sort(_INVERSE_LENGTH_COMPARE); // this sorts the list longest to shortest
// Iterate the computed paths from longest to shortest, if a path is not
// encompassed by an existing path in the final list, add it to the
// final list, otherwise just move to the next path
var finalList = new List<string>();
foreach(var path in paths)
{
bool found = false;
foreach(var item in finalList)
{
if (item.StartsWith(path, StringComparison.Ordinal))
{
found = true;
break;
}
}
if (!found)
{
finalList.Add(path);
}
}
return finalList;
}
</code></pre>
<p>Once I have the final list built, I then add the nodes to the tree (for simplification, I have removed the calls to end update and begin update of the tree that contains the root node):</p>
<pre><code>void FillTreeNodes(TreeNode root)
{
var rootText = root.Text;
var rootTextLength = rootText.Length;
var nodeStrings = BuildFinalList();
foreach(var nodeString in nodeStrings)
{
var roots = nodeString.Split(new char[] { '/' },
StringSplitOptions.RemoveEmptyEntries);
// The initial parent is the root node
var parentNode = root;
var sb = new StringBuilder(rootText, nodeString.Length + rootTextLength);
for(int rootIndex = 0; rootIndex < roots.Length; rootIndex++)
{
// Build the node name
var parentName = roots[rootIndex];
sb.Append("/");
sb.Append(parentName);
var nodeName = sb.ToString();
// Search for the node
var index = parentNode.Nodes.IndexOfKey(nodeName);
if (index == -1)
{
// Node was not found, add it
var temp = new TreeNode(parentName, 1, 1);
temp.Name = nodeName;
parentNode.Nodes.Add(temp);
parentNode = temp;
}
else
{
// Node was found, set that as parent and continue
parentNode = parentNode.Nodes[index];
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>One improvement that comes to mind is:</p>\n\n<pre><code>bool found = false;\nforeach(var item in finalList)\n{\n if (item.StartsWith(path, StringComparison.Ordinal))\n {\n found = true;\n break;\n }\n}\n</code></pre>\n\n<p>Finding out whether a condition is met for any item in a collection is a common enough problem that LINQ has a method for that: <code>Enumerable.Any</code>. Using that the above code can be written as just:</p>\n\n<pre><code>bool found = finalList.Any(item =>\n item.StartsWith(path,StringComparison.Ordinal);\n</code></pre>\n\n<p>Which is both shorter and simpler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T16:24:18.450",
"Id": "1288",
"Score": "0",
"body": "I have updated code based on the suggestion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T16:16:06.593",
"Id": "709",
"ParentId": "707",
"Score": "6"
}
},
{
"body": "<p>FillTreeNodes looks pretty much OK to me, I can't see any major ways to improve it. I would suggest, though, that the StringBuilder can be replaced with a simple <code>\"/\" + parentName</code>.</p>\n\n<p>I'n not convinced preprocessing the list is going to give you much. That said, we can remove the need to sort the list by removing any leaves we come across when trying to add the path to the list.</p>\n\n<p>Notice that by breaking the logic out into a separate function, we avoid the need for \"found\" flags.</p>\n\n<pre><code>List<string> BuildLeafList()\n{\n var leafList = new List<string>();\n foreach (var folder in GetListOfFolders())\n {\n var root = folder.Key;\n var leaf = folder.Value;\n string path = string.Concat(root, \"/\", leaf);\n AddPathToLeafList(path, leafList);\n }\n\n return leafList;\n}\n\nprivate void AddPathToLeafList(string path, List<string> leafList)\n{\n for (int i = 0; i < leafList.Count;)\n {\n string leaf = leafList[i];\n\n // If we have a leaf that already encompasses path, stop\n if (leaf.StartsWith(path, StringComparison.Ordinal))\n {\n return;\n }\n\n // If path encompasses leaf, remove leaf\n if (leaf.StartsWith(path, StringComparison.Ordinal))\n {\n leafList.RemoveAt(i);\n }\n else\n {\n i += 1;\n }\n }\n\n leafList.Add(path);\n}\n</code></pre>\n\n<p>I'm not too happy about the way the loop works though. It seems a little awkward to sometimes increment i, and other times not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T05:03:00.260",
"Id": "2627",
"Score": "0",
"body": "I think you meant path.StartsWith(leaf... in the second if block. I initially had something like this, but in the long run, I believe the sorting is more performative. This implementation would possibly require iterating the entire list each time I add a leaf. Also, removing from a list is and O(N) operation. In the implementation I presented, sorting should be O(NLogN) and then I make one more pass through the list so at worst case N^2LogN (if I am reading my code right that is)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T05:08:11.113",
"Id": "2628",
"Score": "0",
"body": "With regards to StringBuilder. The string is being appended to in each loop iteration. I know I am copying the string out, but it seemed like the preallocated StringBuilder set to the length that it will eventually end up should be more performative for the append. If I did something like nodeName += (\"/\" + parentName) then there would be at least 2 string allocations in each iteration of the loop. Using SB there should be only one, the sb.ToString() call. I can't say I looked at the IL though to verify that, my assumption is based on several articles regarding strings and StringBuilder."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T18:48:41.943",
"Id": "2656",
"Score": "0",
"body": "In your implementation you are also potentially iterating through the entire list for each leaf, after the sort. I /think/ in the worst case, in terms of number of iterations over the list, both implementations similar enough. However, you have the overhead of the sort. I did, however, forget to factor in the cost of remove, which does make mine more expensive :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T18:49:48.370",
"Id": "2657",
"Score": "0",
"body": "As for the StringBuilder, I missed that the initialisation was outside of the loop. I am obviously not on my game :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-30T13:39:09.307",
"Id": "2684",
"Score": "0",
"body": "No problem - I was writing my comments late at night, so not sure if I was correct or not. I think both implementations end up close enough as far as performance. The remove from the list was the place that I thought it might end up less performative. I appreciate the feedback though. At this point, my code is already in the \"wild\" so it will stay as it is for now :) When I get back to working on the next version, I am going to be redoing some of this framework so I am probably going to implement the code more along these lines. So thanks :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T17:50:45.190",
"Id": "1478",
"ParentId": "707",
"Score": "3"
}
},
{
"body": "<p>Not sure whether this is better for your application or not, but it is different. This is a pattern I used briefly a while back. It's works OK for sequentially dumping ordered hierarchies where each node's level is known. For typical or more complex recursive relationships I believe this to be a bad choice for maintainability and quality reasons.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n private void BuildFolderList(List<KeyValuePair<int, string>> folderInfoList, string entryPoint, int level)\n {\n try\n {\n foreach (string directory in Directory.GetDirectories(entryPoint))\n {\n folderInfoList.Add(new KeyValuePair<int, string>(level, Path.GetFileName(directory)));\n BuildFolderList(folderInfoList, directory, level + 1);\n }\n }\n catch (UnauthorizedAccessException ex)\n {\n // access to the folder was denied\n }\n }\n\n private void BuildFolderTree(object sender, EventArgs e)\n {\n List<KeyValuePair<int, string>> folderInfoList = new List<KeyValuePair<int, string>>();\n\n string rootLevelPath;\n\n // you can add multiple root-level paths whose subfolders can optionally be added recursively.\n\n rootLevelPath = @\"C:\\Projects\";\n folderInfoList.Add(new KeyValuePair<int, string>(0, Path.GetFileName(rootLevelPath)));\n BuildFolderList(folderInfoList, rootLevelPath, 1);\n\n rootLevelPath = @\"C:\\Temp\";\n folderInfoList.Add(new KeyValuePair<int, string>(0, Path.GetFileName(rootLevelPath)));\n // note: omitting subfolders for this item\n\n rootLevelPath = @\"C:\\Program Files\";\n folderInfoList.Add(new KeyValuePair<int, string>(0, Path.GetFileName(rootLevelPath)));\n BuildFolderList(folderInfoList, rootLevelPath, 1);\n\n tv.BeginUpdate();\n try\n {\n tv.Nodes.Clear();\n\n TreeNode tn = null;\n int cur_lvl = -1, new_lvl;\n string nodeText;\n\n for (int i = 0; i < folderInfoList.Count; i++)\n {\n new_lvl = folderInfoList[i].Key;\n nodeText = folderInfoList[i].Value;\n\n if (new_lvl == 0)\n {\n tn = tv.Nodes.Add(nodeText);\n }\n else\n {\n if (new_lvl == cur_lvl)\n {\n tn = tn.Parent.Nodes.Add(nodeText);\n }\n else if (new_lvl > cur_lvl)\n {\n tn = tn.Nodes.Add(nodeText);\n }\n else\n {\n while (tn.Level >= new_lvl)\n {\n tn = tn.Parent;\n }\n\n tn = tn.Nodes.Add(nodeText);\n }\n }\n cur_lvl = new_lvl;\n }\n }\n finally\n {\n tv.EndUpdate();\n }\n }\n\n public Form1()\n {\n InitializeComponent();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T18:14:21.013",
"Id": "2655",
"Score": "0",
"body": "I think this pattern would work if I was building a list of folders from a recursive directory search. In my case I am not doing that. The code in GetListOfFolders() is pulling together lists of folder/leaf nodes from multiple SharePoint sites."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T10:25:07.490",
"Id": "1497",
"ParentId": "707",
"Score": "1"
}
},
{
"body": "<p>I updated the code based on the LINQ answer that was provided and this is what ended up as my final production code. I felt it was a little cleaner and easier to read than the code that was posted originally.</p>\n\n<pre><code>List<string> BuildFinalList()\n{\n // This list is a collection of root folder paths and leaf folder names\n // i.e. pair(\"/root/node/node\", \"node\"), pair(\"/root/node\", \"node)\n List<KeyValuePair<string, string>> folders = GetListOfFolders();\n var paths = new List<string>();\n foreach(var folder in folders)\n {\n var leaf = folder.Value;\n var root = folder.Key;\n paths.Add(string.Concat(root, \"/\", leaf);\n }\n paths.Sort(_INVERSE_LENGTH_COMPARE); // this sorts the list longest to shortest\n\n // Iterate the computed paths from longest to shortest, if a path is not\n // encompassed by an existing path in the final list, add it to the\n // final list, otherwise just move to the next path\n var finalList = new List<string>();\n foreach(var path in paths)\n {\n if (!finalList.Any(item => item.StartsWith(path, StringComparison.Ordinal)))\n {\n finalList.Add(path);\n }\n }\n return finalList;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T23:19:05.970",
"Id": "62474",
"ParentId": "707",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "709",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-09T15:50:05.563",
"Id": "707",
"Score": "9",
"Tags": [
"c#",
"tree"
],
"Title": "Basic folder tree with a list of strings"
} | 707 |
<p>For interop purpose, this is something that I always do (C#):</p>
<pre><code> public static extern BigObject InteropWithCPlusPlus();
</code></pre>
<p>where <code>BigObject</code> is ( you guess it) a big object, it's not something small like <code>int</code>, or <code>double</code>.</p>
<p>Now, is this a good practice? Or is it better to do the interop in this way:</p>
<pre><code>public static extern void InteropWithCPlusPlus(ref BigObject bigObject);
</code></pre>
<p>I prefer the first one as it is easier to read and understand, but I afraid that it comes with performance penalty when the return object is a large, consuming memory one. </p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T16:28:11.123",
"Id": "1289",
"Score": "0",
"body": "This site is for reviewing code (which means we should see some code and implementation in the question). The question above is asking about best practices, which seems more in line with Programmers.SE."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T17:46:32.867",
"Id": "1290",
"Score": "1",
"body": "Mark may be right, though I think reviewing adherence to best practices in a block of code is part of the game this is more like a straight up question. Since we're all here: I don't believe there's any difference in the marshaling strategy .NET will use so there's likely no performance difference which makes your preference fit the pattern of .NET code more, but are the native libraries used by other stuff too? If so perhaps you should apply whatever the best practice is to your native library and handle the usage style differences in your managed wrapper."
}
] | [
{
"body": "<p>I don't think there would be too much of a difference. You have to use a reference anyway, because non-native types are stored as references. On x86 processors, returns are placed in register A, which is limited length. So, your C++ program would be either returning a reference to <code>BigObject</code> or modifying an existing instance of it.</p>\n\n<p>The area where I can see a performance hit is in memory allocation. If you are making that call, using the object, and then discarding it, it would be faster to create on single instance in your C# code and use that rather than allocating memory every time. You'll get diminishing returns for small numbers of calls, though; unless you have a couple thousand in a given program run, you probably won't notice the hit either way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T01:36:27.393",
"Id": "1298",
"Score": "0",
"body": "`On x86 processors, returns are placed in register A, which is limited length`-- I guess you are saying that my method 1 cannot return too big an object?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T13:51:09.863",
"Id": "1309",
"Score": "0",
"body": "Not by value. Objects bigger than the register have to be passed by reference, because while the register is too small for the value, it is big enough for a memory address."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T16:19:17.967",
"Id": "710",
"ParentId": "708",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "710",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T15:57:29.487",
"Id": "708",
"Score": "5",
"Tags": [
"c#",
"comparative-review"
],
"Title": "Interop: Return Parameter Method as Void"
} | 708 |
<p>Could this be made more efficient, and/or simpler? It's a path-finding function. It seems to work, but do you see any potential cases where it could fail?</p>
<pre><code>// Searches for a path from [start] to [end].
// Predicate [passable] should take an std::pair<int,int> and return true if the node is passable.
// Nodes in path are stored in [out].
// Return value is a pair. With first being a bool to indicate if a path was found,
// and second an iterator for the end of the path
template<typename OutputIterator, typename PassablePR>
std::pair<bool, OutputIterator> ShortestPath(std::pair<int,int> start, std::pair<int,int> end, PassablePR passable, OutputIterator out)
{
typedef std::pair<int,int> node;
std::pair<bool, OutputIterator> ret(false, out);
// queue of nodes expanding out from the starting point
std::queue<node> q;
// keep track of visited nodes so we don't visit them twice
std::vector<node> visited_nodes;
auto visited = [&visited_nodes] (node n) {
return std::find(visited_nodes.begin(), visited_nodes.end(), n) != visited_nodes.end();
};
// link child nodes to parents
std::map<node,node> path_tree;
q.push(start);
while(q.empty() == false)
{
auto parent = q.front();
if(passable(parent) && !visited(parent))
{
visited_nodes.push_back(parent);
if(parent == end)
{
ret.first = true;
std::vector<std::pair<int,int>> path;
auto i = path_tree.find(parent);
while(i != path_tree.end())
{
path.push_back(i->first);
parent = i->second;
path_tree.erase(i);
i = path_tree.find(parent);
}
// path is currently from end to start, so reverse it
std::copy(path.rbegin(), path.rend(), ret.second);
return ret;
}
auto child(parent);
// node to the left
--child.first;
q.push(child);
if(path_tree.find(child) == path_tree.end())
path_tree[child] = parent;
// right
child.first += 2;
q.push(child);
if(path_tree.find(child) == path_tree.end())
path_tree[child] = parent;
// above
--child.first;
--child.second;
q.push(child);
if(path_tree.find(child) == path_tree.end())
path_tree[child] = parent;
// and below
child.second += 2;
q.push(child);
if(path_tree.find(child) == path_tree.end())
path_tree[child] = parent;
}
q.pop();
}
return ret;
}
</code></pre>
<p>Testing it out:</p>
<pre><code>int main()
{
int grid[5][5] =
{ { 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 1, 0 } };
std::vector<std::pair<int,int>> path;
auto ret = ShortestPath(std::pair<int,int>(0,0), std::pair<int,int>(4,4),
[&grid] (std::pair<int,int> n) -> bool {
if(ben::WithinBoundsInclusive(std::pair<int,int>(0,0), std::pair<int,int>(4,4), n) == false)
return false;
return grid[n.first][n.second] == 0;
},
std::back_inserter(path));
if(ret.first)
{
std::cout << "Path found\n";
std::for_each(path.begin(), path.end(),
[](std::pair<int,int> n) {
std::cout << '(' << n.first << ',' << n.second << ")\n";
});
}
else
std::cout << "Path not found\n";
}
</code></pre>
| [] | [
{
"body": "<pre><code>// keep track of visited nodes so we don't visit them twice\nstd::vector<node> visited_nodes;\nauto visited = [&visited_nodes] (node n) {\n return std::find(visited_nodes.begin(), visited_nodes.end(), n) != visited_nodes.end();\n};\n</code></pre>\n\n<p>Every time you have to check whether a point has been visited, this is going to scan over the entire list of visited_nodes. Better to do a std::set</p>\n\n<pre><code>// path is currently from end to start, so reverse it\nstd::copy(path.rbegin(), path.rend(), ret.second);\n</code></pre>\n\n<p>Rather then constructing the path and reversing it, you could construct the path backwards.</p>\n\n<p>When it comes to constructing all of the child nodes, I think your approach is confusing. You'd be better of constructing a new node rather then reusing the node. As it is, its not clear what you are doing. That section of code is also repetitive. I'd do something like</p>\n\n<pre><code>int x_dir = {0, 0, 1, -1}\nint y_dir = {1, -1, 0, 0}\n\nfor(int pos = 0; pos < 4; pos++)\n{\n node child = parent;\n child.first += x_dir[pos];\n child.second += y_dir[pos];\n ...\n}\n</code></pre>\n\n<p>Other notes:</p>\n\n<p>The use of map is going to O(log), if you use a multidimensional array to hold the information for each point you can do it in O(1) time.</p>\n\n<p>Using pairs to hold co-ordinates is easy. However, I suggest that its better to have a point class with x and y members. I think it makes what is going on clearer. Additionally, the point class can encapsulate the neighboring cell logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T19:10:12.800",
"Id": "1387",
"Score": "1",
"body": "Iterating over a vector may be surprisingly quick compared to finding a node in a set, even if the former is O(n) and the latter is O(log n)... I'd rather test with realistic datasets..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T20:59:53.250",
"Id": "750",
"ParentId": "714",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "750",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-09T21:06:39.297",
"Id": "714",
"Score": "13",
"Tags": [
"c++",
"algorithm",
"c++11",
"pathfinding"
],
"Title": "Path finding function"
} | 714 |
<p>I've written this rather naïve branch-and-bound based IP solver.</p>
<p>Are there any obvious JavaScript optimisations that could speed it up? I am not looking for asymptotically better algorithms, just simple speed optimisations effective on problem sizes with 5-6 variables and <code>minSize</code> values up to about 500.</p>
<pre><code>/** Represents a simple 1-dimensional
* IP (Integer Programming) problem.
* @constructor
* @param {Array<size: Number, cost: Number>} priceList
* List of costs for given sizes.
* Note that this list will be sorted by this constructor.
*/
function Prices (priceList) {
this.prices = priceList;
this.prices.sort (PriceCompare);
this.minimise = PricesMinimise;
this.pricesBB = PricesBB;
}
/** Solves the simple 1-dimensional IP problem:
* Minimise Sum_i cost_i * x_i
* where Sum_i size_i * x_i >= minSize
* and cost_i, size_i are positive reals,
* and x_i is a nonnegative integer. (i = 0..prices.length - 1)
*
* cost_i = this.prices[i].cost and size_i = this.prices[i].size.
*
* @param {Number} minSize The minimum size that must be supplied.
* @return {xs: Array, cost: Number} [x_0, x_1, ...] and total cost.
*/
function PricesMinimise (minSize) {
this.minSize = minSize;
this.incumbent = Number.POSITIVE_INFINITY;
this.maxCost = Number.POSITIVE_INFINITY;
var xsCost = this.pricesBB (0, 0, 0, 0);
xsCost.xs.reverse ();
return xsCost;
}
/** Solves a sub problem using only price list elements with
* index >= i. It uses instance fields
* minSize: the minimum required size sum,
* incumbent: lowest full solution cost seen so far,
* maxCost: upper bound on full solution cost.
* @param {Number} i Minimum price list index.
* @param {Number} sizeSum Size sum already selected.
* @param {Number} costSum Cost sum already spent.
* @param {Number} minCost Lower bound on full solution cost in this
* subtree.
* @return {xs: Array, cost: Number} A minimum candidate
* solution, or null if none better than the incumbent were
* found.
*/
function PricesBB (i, sizeSum, costSum, minCost) {
var price = this.prices [i];
var size = price.size;
var cost = price.cost;
var xReal = (this.minSize - sizeSum) / size;
var x = Math.ceil (xReal);
var localCostSum;
if (size == Number.POSITIVE_INFINITY) {
x = 1;
size = 0; // Avoid NaN in recursive call
localCostSum = cost;
} else {
localCostSum = costSum + cost * x;
var localMinCost = costSum + cost * xReal;
minCost = Math.max (minCost, localMinCost);
if (localMinCost >= this.incumbent) return null;
}
this.maxCost = Math.min (this.maxCost, localCostSum);
var localMin = {'xs': [x], 'cost': localCostSum};
if (localCostSum < this.incumbent) this.incumbent = localCostSum;
if (localCostSum == minCost) return localMin;
if (i < this.prices.length - 1)
for (x--; x >= 0; x--) {
var xsCost =
this.pricesBB (i + 1, sizeSum + size * x, costSum + cost * x, minCost);
if (xsCost == null) continue;
xsCost.xs.push (x);
localMin = xsCost;
if (localMin.cost == minCost) return localMin;
}
if (localMin.cost == this.incumbent)
return localMin;
else
return null;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T22:56:04.070",
"Id": "1332",
"Score": "2",
"body": "I'll try to take a more serious look at this if it's still not answered when I have more time, but for starters, anywhere you can use \"===\" instead of \"==\" would be good. \"==\" performs type coercion in JS (which allows \"5\" == 5 to return true), whereas \"===\" does not."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T11:22:33.320",
"Id": "1401",
"Score": "0",
"body": "To be honest, that code looks horrible, either clean it up or provide some tests, otherwise chances are **very** high that any attempt by us to optimize it, will break it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T12:55:39.900",
"Id": "1402",
"Score": "0",
"body": "Please provide the definition of PriceCompare and context for the optimization: which methods do you call, what does the data look like..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T13:44:01.163",
"Id": "1405",
"Score": "0",
"body": "Ivo, I'd be happy to clean up the code if you explain me what you had in mind. Especially, of course, if it would speed it up :-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T13:52:23.043",
"Id": "1407",
"Score": "0",
"body": "TheXenocide, will type coercion also incur a cost in places where the types are already identical?\n\nEric, sorry for leaving out PriceCompare---it compares two prices by comparing their cost per size. Anyway, I wasn't really thinking of algorithmic optimisations, rather of JavaScript-related speedups.\nTo use this code, you first construct a Price object using new Price(...), then you call its minimise method."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T18:45:43.297",
"Id": "1408",
"Score": "0",
"body": "@Ame That code's comments is incredibly abstract and inline comments in the function would help. I second supplying test cases showing the blackbox functionality of the function. Most likely the best way to optimise is to have a high level understanding of what your doing and telling you a better O(foo) algorithm."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T10:22:03.897",
"Id": "1419",
"Score": "0",
"body": "@Ame it's hard to optimize JavaScript code out of the blue. Different browsers tend to be slow in different areas, and it rarely matters unless you repeat the same inefficient operation multiple times. So optimizing the algorithm is a safe way to optimize linearly in all browsers, and you need to benchmark in target browsers to identify specific bottlenecks."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-28T09:48:03.290",
"Id": "1850",
"Score": "0",
"body": "@Raynos: I see what you mean; however, what I was really looking for were places where I used obviously inefficient JavaScript constructions, rather than improving the general complexity of the algorithm. I would have thought this would not require understanding of the algorithm."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-28T09:51:00.540",
"Id": "1851",
"Score": "0",
"body": "@Eric I see. I didn't know that browsers are so different that there is no general advice on JavaScript constructions to avoid or to use. Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T16:57:21.063",
"Id": "2532",
"Score": "0",
"body": "Review your `for` loop and look at a negative `while` instead. Basis of my comment here: http://blogs.sun.com/greimer/entry/best_way_to_code_a"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T14:31:19.630",
"Id": "3295",
"Score": "0",
"body": "@Mark: Interesting. In your list I dont see any for loops using === or !==. How much slower than the negative while loop would the following be?\n\nfor (var i = 0, l = length; i !== l; i++) { }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T14:27:44.600",
"Id": "3322",
"Score": "0",
"body": "@Arne: not sure as I did not personally test all of his options. Might be worth it to compare it specifically in your browser of choice using development tools however."
}
] | [
{
"body": "<p>Nowadays we have great tools at our disposal, one of them is <a href=\"http://code.google.com/closure/compiler/\" rel=\"noreferrer\">The Closure Compiler</a> from Google, which is a tool for making JavaScript download and run faster. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.</p>\n\n<p>So, the <a href=\"http://closure-compiler.appspot.com\" rel=\"noreferrer\">web version of Closure Compiler</a> gave me the following recommendations for your snippet:</p>\n\n<ol>\n<li>Example, \n<code>this.incumbent = Number.POSITIVE_INFINITY;</code>\n<code>this.maxCost = Number.POSITIVE_INFINITY;</code>\n<strong>becomes</strong> <code>this.maxCost = this.incumbent = Number.POSITIVE_INFINITY;</code></li>\n<li>Other obvious speed enhancements that can be automated with minification: \n<ul>\n<li>Use parameters as a variable instead of another var:\n<strike><code>var</code></strike> <code>minSize = this.pricesBB(0, 0, 0, 0);</code></li>\n<li>Reuse var's when they are longer in user in a function instead of declaring new ones</li>\n<li>Shorten variable names (parsing speed issue)</li>\n<li><code>var price = this.prices [i];\nvar size = price.size;</code> <strong>becomes</strong> <code>var price = this.prices[i], g = price.size;</code></li>\n</ul></li>\n</ol>\n\n<p>The full result of the Closure Compiler for your piece Javascript: </p>\n\n<pre><code>function Prices(c) {\n this.prices = c;\n this.prices.sort(PriceCompare);\n this.minimise = PricesMinimise;\n this.pricesBB = PricesBB\n}\nfunction PricesMinimise(c) {\n this.minSize = c;\n this.maxCost = this.incumbent = Number.POSITIVE_INFINITY;\n c = this.pricesBB(0, 0, 0, 0);\n c.xs.reverse();\n return c\n}\nfunction PricesBB(c, i, h, f) {\n var e = this.prices[c], g = e.size;\n e = e.cost;\n var a = (this.minSize - i) / g, d = Math.ceil(a), b;\n if(g == Number.POSITIVE_INFINITY) {\n d = 1;\n g = 0;\n b = e\n }else {\n b = h + e * d;\n a = h + e * a;\n f = Math.max(f, a);\n if(a >= this.incumbent) {\n return null\n }\n }\n this.maxCost = Math.min(this.maxCost, b);\n a = {xs:[d], cost:b};\n if(b < this.incumbent) {\n this.incumbent = b\n }\n if(b == f) {\n return a\n }\n if(c < this.prices.length - 1) {\n for(d--;d >= 0;d--) {\n b = this.pricesBB(c + 1, i + g * d, h + e * d, f);\n if(b != null) {\n b.xs.push(d);\n a = b;\n if(a.cost == f) {\n return a\n }\n }\n }\n }\n return a.cost == this.incumbent ? a : null\n}\n;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T13:04:01.957",
"Id": "1365",
"ParentId": "716",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1365",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-10T00:34:51.283",
"Id": "716",
"Score": "6",
"Tags": [
"javascript",
"algorithm",
"optimization",
"integer"
],
"Title": "Branch-and-bound based IP solver"
} | 716 |
<p>I've got some legacy code which I need to maintain and its got this function which <strong>works perfectly fine</strong>, but I'm trying to understand if it is working using acceptable coding practices or not... I am trying to understand if it is safe and secure to operate the site with the function as-it-is.</p>
<p>The function would be called as:</p>
<pre><code>$this->editData('users',"activation_key",$_GET['key']);
</code></pre>
<p>The actual function (unedited):</p>
<pre><code>function editData($table_name,$fldname,$fldval,$other='',$lang_flag=0)
{
$link = $this->my_connect();
$this->my_select_db($this->DATABASE_NAME,$link);
$arr_types = array("TR_", "TN_", "TREF_", "PHR_", "PHN_", "IR_", "IN_", "MR_", "MN_", "TNEF_", "TRC_", "TNC_", "TRFN_", "TNFN_","TNURL_","TRURL_");
if (!empty($GLOBALS["HTTP_POST_VARS"])) {
reset($GLOBALS["HTTP_POST_VARS"]);
while (list($k,$v)=each($GLOBALS["HTTP_POST_VARS"]))
{
for($p=0;$p<count($arr_types);$p++)
{
if(stristr($k,$arr_types[$p])!="")
{
$k = str_replace($arr_types[$p],"",$k);
}
}
${strtolower($k)}=$v;
//echo "<br> k =$k -- v = $v";
}
}
if (!empty($_POST)) {
reset($_POST);
while (list($k,$v)=each($_POST))
{
for($p=0;$p < count($arr_types);$p++)
{
if(stristr($k,$arr_types[$p])!="")
{
$k = str_replace($arr_types[$p],"",$k);
}
}
${strtolower($k)}=$v;
//echo "<br> k =$k -- v = $v";
}
}
if (!empty($GLOBALS["HTTP_GET_VARS"])) {
reset($GLOBALS["HTTP_GET_VARS"]);
while (list($k,$v)=each($GLOBALS["HTTP_GET_VARS"]))
{
for($p=0;$p < count($arr_types);$p++)
{
if(stristr($k,$arr_types[$p])!="")
{
$k = str_replace($arr_types[$p],"",$k);
}
}
${strtolower($k)}=$v;
//echo "<br> k =$k -- v = $v";
}
}
if (!empty($_GET)) {
reset($_GET);
while (list($k,$v)=each($_GET))
{
for($p=0;$p < count($arr_types);$p++)
{
if(stristr($k,$arr_types[$p])!="")
{
$k = str_replace($arr_types[$p],"",$k);
}
}
${strtolower($k)}=$v;
//echo "<br> k =$k -- v = $v";
}
}
$result=$this->my_query("show fields from $table_name",$link);
$query="update $table_name SET ";
while ($a_row = $this->my_fetch_array($result)) {
$field="$a_row[Field]";
if($field!=$fldname)
{
if(isset($$field))
{
$query.="`".$field."`=";
$query.="'".$this->removeQuotes($$field,$lang_flag)."' , ";
}
else
{
if(isset($GLOBALS["$field"]))
{
//echo "<br> var ".$GLOBALS["$field"];
$query.="`".$field."`=";
$query.="'".$this->removeQuotes($GLOBALS["$field"],$lang_flag)."' , ";
}
}
}
}
$query = substr($query,0,-2);
$query.=" where `$fldname`='$fldval' $other";
$query ;
//echo $query;
$result=$this->my_query($query,$link);
$this->my_free_result($result);
$this->my_close($link);
return $result;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T09:10:57.147",
"Id": "1302",
"Score": "0",
"body": "is this code running on a php4 or php5 interpreter?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T10:37:20.730",
"Id": "1303",
"Score": "0",
"body": "@xzyfer - PHP Version 5.3.4"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-01T11:19:33.667",
"Id": "1870",
"Score": "0",
"body": "did you find my answer helpful?"
}
] | [
{
"body": "<p>Simply put, this code fails a lot best practices also contains massive security issues.\nSuggestion to improve for best practices:</p>\n\n<blockquote>\n <p><code>$GLOBALS[\"HTTP_POST_VARS\"]</code> is <strong>deprecated</strong> in favor of <code>$_POST</code></p>\n</blockquote>\n\n<p>So you looping over <code>$GLOBALS[\"HTTP_POST_VARS\"]</code> and <code>$_POST</code> is redundant and bad mojo. Just looping over <code>$_POST</code> will accomplish the same thing. Same goes for <code>$GLOBALS[\"HTTP_GET_VARS\"]</code> and <code>$_GET</code>.</p>\n\n<blockquote>\n <p>You should be passing in the $link object as parameter. </p>\n</blockquote>\n\n<p>Since there is no code intended to change the database connection conditionally (the connect parameters are always the same). This prevents your scripts creating multiple database connection resources and destroying them (more memory and time consuming). Also passing in the database resource as parameter to the function is a type of dependency injection which makes your code testable should you want to in the future. Since this also appears to be in a class, consider creating the database connection in the <code>__construct</code> and use that single instance.</p>\n\n<blockquote>\n <p>Using sessions in favor of $GLOBALS</p>\n</blockquote>\n\n<p>Pretty much any use of $GLOBALS is considered bad practice. I'm sure there are a few exceptions to the rule. But there you should definitely not be using is for storing data in a scopeless fashion. This is what sessions are for.</p>\n\n<blockquote>\n <p>removeQuotes() is never called on <code>$fldname</code> or <code>$fldval</code></p>\n</blockquote>\n\n<p>As you can imagine this a serious security issue leaving your script open to SQL Injection attacks.</p>\n\n<blockquote>\n <p>Use <a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php\">mysql_real_escape_string</a> in favor of home made sanitising functions i.e. <code>removeQuotes()</code></p>\n</blockquote>\n\n<p>There is a lot more to safe escaping query parameters that remove slashes. And in my experience home made sanitising functions often quietly fail when you have mixed string and number parameters.</p>\n\n<p><strong>As a matter of readability and style</strong> I would make to following suggestions, I know these are subject matters but there are common ways of doing things.</p>\n\n<blockquote>\n <p>Substitute the use of string concatenation</p>\n</blockquote>\n\n<pre><code>$query.=\"`\".$field.\"`=\";\n$query.=\"'\".$this->removeQuotes($$field,$lang_flag).\"' , \";\n... more concatenation ...\n$query = substr($query,0,-2);\n</code></pre>\n\n<p>for array joining</p>\n\n<pre><code>$queryParams[] = \"`\".$field.\"`='\".$this->removeQuotes($$field,$lang_flag).\"'\";\n... more array filling ...\n$query = join(',', $queryParams);\n</code></pre>\n\n<p><strong>General WTFs</strong></p>\n\n<blockquote>\n <p>This is doing nothing at all <code>$query ;</code></p>\n</blockquote>\n\n<p>And code that does nothing is very bad mojo.</p>\n\n<blockquote>\n <p>Call <code>count()</code> once.</p>\n</blockquote>\n\n<p>This is not really an issue, doing something like this </p>\n\n<p>for($p=0;$p\n\n<p>In actual fact calls <code>count()</code> on every iteration of the loop, even though the return value will never change. It causes the interpreter to do more work than necessary, although I suspect during compilation to byte code this would be optimised automatically. This could be substituted for:</p>\n\n<pre><code>// only call count() once\n$count = count($arr_types);\nfor($p=0;$p<$count;$p++)\n</code></pre>\n\n<blockquote>\n <p>Don't nest unnecessarily.</p>\n</blockquote>\n\n<p>Don't nest conditionals (if/else/switch) and loop(while/for) unnecessarily. It makes for messier code, code that's harder to read and follow mentally, and importantly difficult to test.</p>\n\n<pre><code>if(isset($$field))\n{\n $query.=\"`\".$field.\"`=\";\n\n $query.=\"'\".$this->removeQuotes($$field,$lang_flag).\"' , \";\n }\n else\n {\n if(isset($GLOBALS[\"$field\"]))\n {\n $query.=\"`\".$field.\"`=\";\n $query.=\"'\".$this->removeQuotes($GLOBALS[\"$field\"],$lang_flag).\"' , \";\n }\n }\n</code></pre>\n\n<p>The above code is exactly equal to the following, notice less nesting.</p>\n\n<pre><code>if(isset($$field))\n{\n $query.=\"`\".$field.\"`=\";\n\n $query.=\"'\".$this->removeQuotes($$field,$lang_flag).\"' , \";\n }\n else if(isset($GLOBALS[\"$field\"]))\n {\n $query.=\"`\".$field.\"`=\";\n $query.=\"'\".$this->removeQuotes($GLOBALS[\"$field\"],$lang_flag).\"' , \";\n }\n</code></pre>\n\n<p><strong>Personal preference</strong></p>\n\n<blockquote>\n <p>This is completely subjective, but something to think about.</p>\n</blockquote>\n\n<pre><code>if(stristr($k,$arr_types[$p])!=\"\")\n</code></pre>\n\n<p>equal to</p>\n\n<pre><code>if(stristr($k,$arr_types[$p]) == true)\n</code></pre>\n\n<p>equal to</p>\n\n<pre><code>if(stristr($k,$arr_types[$p]))\n</code></pre>\n\n<blockquote>\n <p>Considering the above, this:</p>\n</blockquote>\n\n<pre><code>while (list($k,$v)=each($_GET)) \n{\n for($p=0;$p < count($arr_types);$p++)\n {\n if(stristr($k,$arr_types[$p])!=\"\")\n {\n $k = str_replace($arr_types[$p],\"\",$k);\n }\n }\n ${strtolower($k)}=$v;\n}\n</code></pre>\n\n<p>Is exactly the same as:</p>\n\n<pre><code>while (list($k,$v)=each($_GET)) \n{\n $count = count($arr_types);\n for($p=0; $p<$count; $p++);\n {\n $k = str_replace($arr_types[$p],\"\",$k);\n }\n ${strtolower($k)}=$v;\n} \n</code></pre>\n\n<p><em>Which would you rather test and/or work with?</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T12:07:17.323",
"Id": "723",
"ParentId": "719",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T08:04:17.733",
"Id": "719",
"Score": "5",
"Tags": [
"php",
"mysql"
],
"Title": "Generalized PHP function for editing data in a table"
} | 719 |
<p>I'm going over the interview questions from "<a href="http://rads.stackoverflow.com/amzn/click/145157827X" rel="noreferrer">Cracking the Coding Interview</a>" and one of the chapters (Chapter 7) deals with Object Oriented Design (OOD). The requirements for one of the problems are as follows:</p>
<blockquote>
<p>Imagine you have a call center with
three levels of employees: fresher,
technical lead (TL), product manager
(PM). There can be multiple employees,
but only one TL or PM. An incoming
telephone call must be allocated to a
fresher who is free. If a fresher
can’t handle the call, he or she must
escalate the call to technical lead.
If the TL is not free or not able to
handle it, then the call should be
escalated to PM. Design the classes
and data structures for this problem.
Implement a method getCallHandler().</p>
</blockquote>
<p>I've written a solution in C#, it was not compiled (suggested by the author of the book) and it is currently not multithreaded. My solution is a bit long, but it should be really simple to understand. </p>
<p>Based on my understanding of the problem, I've established a "chain of command" where each employee knows who his/her superior is. Calls get handled in the following manner:</p>
<ul>
<li>If a fresher is given a call which he/she cannot handle, then the fresher escalates the call to his/her superior: a tech lead. </li>
<li>If there are no free freshers, then the tech lead automatically gets the call. </li>
<li>If the tech lead is busy or cannot service the call, then he/she escalates the call to the product manager. </li>
<li>If the product manager (PM) is busy, then the call gets queued on the PM's queue and dequeued once their current call is serviced.</li>
</ul>
<p><strong>NOTE: multithreading will be added in a later revision, so please ignore any multithreading issues.</strong></p>
<pre><code>enum EStatus{ HANDLING, ESCALATED, QUEUED }
enum ERank{ FRESHER, TECH_LEAD, PROD_MANAGER }
abstract class Employee
{
public ERank Rank{get; private set;}
public Employee(ERank rank)
{
Rank = rank;
}
public abstract EStatus ServiceCall(Call call);
}
class Fresher:Employee
{
private TechLead _superior;
public Fresher(TechLead superior):base(ERank.FRESHER)
{
_superior = superior;
}
public override EStatus ServiceCall(Call call)
{
if(CanService(call))
{
call.Service(this);
return EStatus.HANDLING;
}
else
{
_superior.ServiceCall(call);
return EStatus.ESCALATED;
}
}
private bool CanService(Call call)
{
// some logic to determine if the call can be serviced
}
}
class TechLead:Employee
{
private Call _activeCall;
private ProductManager _superior;
public TechLead(ProductManager superior):base(ERank.TECH_LEAD)
{
_activeCall = null;
_superior = superior;
}
public override EStatus ServiceCall(Call call)
{
if(_activeCall == null && CanService(call))
{
HandleCall(call);
return EStatus.HANDLING;
}
else
{
_superior.ServiceCall(call);
return EStatus.ESCALATED;
}
}
private bool CanService(Call call)
{
// some logic to determine if the call can be serviced
}
private HandleCall(Call call)
{
_activeCall = call;
call.OnCallServiced += new Call.CallServicedDelegate(OnCallServiced);
call.Service(this);
}
private void OnCallServiced(Call call)
{
if(call!=_activeCall)
{
// TODO: this call was never accepted
}
else
{
_activeCall = null;
}
}
}
class ProductManager:Employee
{
private Call _activeCall;
private Queue<Call> _callQueue;
public ProductManager():base(ERank.PROD_MANAGER)
{
_activeCall = null;
_callQueue = new Queue<Call>();
}
public override EStatus ServiceCall(Call call)
{
if(_activeCall == null)
{
HandleCall(call);
return EStatus.HANDLING;
}
else
{
_callQueue.Enqueue(call);
return EStatus.QUEUED;
}
}
private HandleCall(Call call)
{
_activeCall = call;
call.OnCallServiced += new Call.CallServicedDelegate(OnCallServiced);
call.Service(this);
}
private void OnCallServiced(Call call)
{
if(call!=_activeCall)
{
// TODO: this call was never accepted
}
else
{
if(_callQueue.Count==0)
{
_activeCall = null;
}
else
{
HandleCall(_callQueue.Dequeue());
}
}
}
}
class Call
{
public delegate void CallServicedDelegate(Call call);
public event CallServicedDelegate OnCallServiced;
public Employee CallHandler{get; private set;}
public Call()
{
CallHandler = null;
}
public void Service(Employee callHandler)
{
CallHandler = callHandler;
// Invoke the notification when the call is complete
OnCallServiced(this);
}
public void Disconnect()
{
// Disconnect the call
}
}
class CallCenter
{
private bool _running;
private BlockingQueue<Call> _callQueue;
private Queue<Employee> _freeFreshers;
private List<Employee> _busyFreshers;
private readonly TechLead _techLead;
public CallCenter(int numEmployees)
{
// create the tech lead and a supervising product manager
_techLead = TechLead(new ProductManager());
_callQueue = new BlockingQueue<Call>();
_freeFreshers = new Queue<Employee>();
_busyFreshers = new List<Employee>();
for(int i = 0; i < numEmployees; i++)
{
_freeFreshers.Enqueue(new Fresher(_techLead));
}
}
public void AcceptCall(Call call)
{
_callQueue.Enqueue(call);
}
// Assuming that threading will be handled
public void StartCallService()
{
_running = true;
while(_running)
{
Call call = _callQueue.Dequeue();
// Subscribe for the on call serviced delegate
call.OnCallServiced += new Call.CallServicedDelegate(OnCallServiced);
if(_freeFreshers.Count>0)
{
// Block until a fresher is available
Employee e = _freeFreshers.Dequeue();
// Assign the call to a free fresher
switch(e.ServiceCall(call))
{
case EStatus.HANDLING:
_busyFreshers.Add(e);
break;
case EStatus.ESCALATED:
_freeFreshers.Enqueue(e);
break;
case EStatus.QUEUED:
default:
break;
}
}
else
{
_techLead.ServiceCall(call);
}
}
}
// Assuming that threading will be handled
public void StopCallService()
{
_running = false;
}
private void OnCallServiced(Call call)
{
switch(call.CallHandler.Rank)
{
case ERank.FRESHER:
_busyFreshers.Remove(call.CallHandler);
_freeFreshers.Enqueue(call.CallHandler);
break;
case ERank.TECH_LEAD:
case ERank.PROD_MANAGER:
default:
// nothing to do if it's a tech lead or prod manager
break;
}
}
}
</code></pre>
<p>I was hoping to get some feedback since this question came from a book, there are many possible OOD solutions and I don't have an actual interviewer to comment on the solution. In addition, I do have the author's solution and I can post it if necessary.</p>
<p>Does this seem like a decent solution to the problem as stated? Is there something that I should definitely improve?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T14:15:18.533",
"Id": "1312",
"Score": "0",
"body": "I don't see a `getCallHandler`... :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T18:39:20.303",
"Id": "1321",
"Score": "0",
"body": "@Michael, it's a public property of `Call`: it's called `CallHandler` instead of `GetCallHandler`."
}
] | [
{
"body": "<p>In short, in my opinion, I think you've done too much.</p>\n\n<p>It seems like your design has gone beyond a design for the initial interview question and into an exercise of your own.</p>\n\n<p><strong>However</strong>, I don't have the book you're reading, so you may be going off more than just that snippet in your question.</p>\n\n<p>Based on the principle:</p>\n\n<blockquote>\n <p>Do the simplest thing that could\n possibly work.</p>\n</blockquote>\n\n<p>The basics I pulled from that question were:</p>\n\n<ul>\n<li>We need a way to represent the three different kinds of employees.</li>\n<li>We need a way of representing a call.</li>\n<li>We need a way of choosing an employee to handle a call (the getCallHandler method).</li>\n</ul>\n\n<p>i.e. I <em>think</em> the question is just after an implementation of <code>GetCallHandler</code> and some basic definitions of the types involved.</p>\n\n<p>I came up with the following:</p>\n\n<pre><code>public class Call\n{\n // TODO: Implement Call.\n}\n\npublic enum EmployeePosition\n{\n Fresher,\n TechnicalLead,\n ProductManager\n}\n\npublic class CallCentre\n{\n private IList<IEmployee> employees;\n\n public IEmployee GetCallHandler(Call call)\n {\n return employees.Where(e => e.CanHandle(call))\n .OrderBy(e => e.Position)\n .FirstOrDefault();\n }\n\n public CallCentre(IList<IEmployee> employees)\n {\n if (employees == null)\n {\n throw new ArgumentNullException(\"employees\");\n }\n\n this.employees = employees;\n }\n}\n\npublic interface IEmployee\n{\n EmployeePosition Position { get; }\n Boolean CanHandle(Call call);\n}\n\npublic class Fresher : IEmployee\n{\n public EmployeePosition Position { get { return EmployeePosition.Fresher; } }\n\n public Boolean CanHandle(Call call)\n {\n // TODO: Logic for handling a call.\n }\n}\n\n// Similar implementations of IEmployee for TechnicalLead and ProductManager.\n</code></pre>\n\n<p>That would be the starting point based on what the question says. After this would usually be a period of interaction between interviewee and interviewer(s) in which assumptions could be addressed and the design discussed/updated with more detail, such as employees being in a busy state etc.</p>\n\n<p>I think your design is a step beyond that.</p>\n\n<p>The combination of class and enumeration for the different employee types is something we both went for. However, I chose an interface over a base class. I don't think your base class provides a lot of value - just code to assign a <code>Rank</code> property. My proposal has the benefit that someone's not going to break implementation for some employees inadvertantly by altering the base class. The interface contains no implmentation. Using an interface also allows the employee classes to use a different base class in the future if needs be.</p>\n\n<p>One point for further discussion might be where it states:</p>\n\n<blockquote>\n <p>If a fresher can’t handle the call, he\n or she must escalate the call to\n technical lead.</p>\n</blockquote>\n\n<p>This may suggest that they want a fresher object to communicate directly with their superior like in your design (as opposed to my implementation, where employees don't need to know each other even exist - similar to many workplaces!). This could be clarified in the interview. However, I prefer my design because of the looser coupling between employees.</p>\n\n<p>As far as multithreading goes, I'd expect quite a bit of discussion on </p>\n\n<ul>\n<li>how it might be implemented</li>\n<li>potential issues with different threading models</li>\n<li>potential bottlenecks</li>\n<li>typical call volume </li>\n</ul>\n\n<p>before it got added to any code. But like I say, it does seem like your design is more than just an answer to the interview question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T22:31:49.877",
"Id": "1329",
"Score": "0",
"body": "On the point of \"further discussion\": it is only **my interpretation** that the fresher must escalate the call to a tech lead... so while I agree with the general idea that employees should not know about each-other, they should at least know who their supervisor is. I think I have some valid justification for my design, but `Employee` not being an interface is a very good point!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T22:33:57.143",
"Id": "1330",
"Score": "0",
"body": "Alex, I've also provided the author's solution as an answer for my question, I hope it's helpful to establish a frame of reference."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T22:42:28.650",
"Id": "1331",
"Score": "0",
"body": "@Alex, and the multithreading thing is not part of the question or the solution provided by the author, but I think it's inevitable with this type of system. I feel pretty comfortable with multithreading and my solution is pretty long as is, so I didn't bother to go any further."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:02:15.763",
"Id": "1333",
"Score": "0",
"body": "Finally, I think that going beyond the scope of the interview question is a bit excessive on my part, so that's definitely a huge issue that I need to think about!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T12:14:44.183",
"Id": "1351",
"Score": "0",
"body": "@Lirik - I think in summary, interview questions like this are intended to be leading. You can't ask a book questions or for clarification. I've done as much as I can above without that feedback. However, I understand why you've gone the extra mile here. Your writing the code you'd write after you'd discussed the requirements further. Just be aware that you're making assumptions - be careful of making up your own requirements in an actual interview."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T12:19:24.400",
"Id": "1352",
"Score": "0",
"body": "We ask a similar question at my place, and we might like to see what types you'd use and maybe a bit of pseudocode. But the main reason we use a question like this is to test requirements capture ability. The ability of the candidate to find holes/ambiguities in what's being requested and to ask us questions in order to resolve those ambiguities. The question then might progress from there until the candidate gets a much more solid idea of what's needed, and takes that into account as they design the system further."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T21:26:20.057",
"Id": "730",
"ParentId": "720",
"Score": "11"
}
},
{
"body": "<p>It looks like it may be a good idea to provide the solution from the book just to establish a frame of reference: </p>\n\n<pre><code>public class CallHandler \n{\n static final int LEVELS = 3; // we have 3 levels of employees\n static final int NUM_FRESHERS = 5; // we have 5 freshers\n ArrayList<Employee>[] employeeLevels = new ArrayList[LEVELS];\n\n // queues for each call’s rank\n Queue<Call>[] callQueues = new LinkedList[LEVELS];\n\n public CallHandler() { ... }\n\n Employee getCallHandler(Call call) \n {\n for (int level = call.rank; level < LEVELS - 1; level++) \n {\n ArrayList<Employee> employeeLevel = employeeLevels[level];\n for (Employee emp : employeeLevel) \n {\n if (emp.free) \n {\n return emp;\n }\n }\n }\n return null;\n }\n\n // routes the call to an available employee, or adds to a queue\n\n void dispatchCall(Call call) \n {\n // try to route the call to an employee with minimal rank\n Employee emp = getCallHandler(call);\n if (emp != null) \n {\n emp.ReceiveCall(call);\n } else {\n // place the call into queue according to its rank\n callQueues[call.rank].add(call);\n }\n }\n\n void getNextCall(Employee e) {...} // look for call for e’s rank\n}\n\nclass Call \n{\n int rank = 0; // minimal rank of employee who can handle this call\n public void reply(String message) { ... }\n public void disconnect() { ... }\n}\n\nclass Employee \n{\n CallHandler callHandler;\n int rank; // 0- fresher, 1 - technical lead, 2 - product manager\n boolean free;\n Employee(int rank) { this.rank = rank; }\n void ReceiveCall(Call call) { ... }\n void CallHandled(Call call) { ... } // call is complete\n void CannotHandle(Call call) \n { // escalate call\n call.rank = rank + 1;\n callHandler.dispatchCall(call);\n free = true;\n callHandler.getNextCall(this); // look for waiting call\n }\n}\n\nclass Fresher extends Employee \n{\n public Fresher() { super(0); }\n}\n\nclass TechLead extends Employee \n{\n public TechLead() { super(1); }\n}\n\nclass ProductManager extends Employee \n{\n public ProductManager() { super(2); }\n}\n</code></pre>\n\n<p>The solution of the book is similar similar in design and extent... there is no additional information besides what is provided by the quote above. My evaluation is that:</p>\n\n<ol>\n<li>I did not actually make a method called <code>GetCallHandler()</code>, I converted it to a property of the <code>Call</code>. </li>\n<li>There might have been a specific reason why a <code>GetCallHandler()</code> method is needed, i.e. necessary for another component of the system.</li>\n</ol>\n\n<p>I do have a justification for my design compared to the Author's design:</p>\n\n<ol>\n<li>It's more efficient to maintain a queue of free employees than to actually go through a list of employees and check which one is free every time a call comes through.</li>\n<li>The behavior in response to a call is defined by particular implementation of <code>Employee</code>, rather than an Employee \"expert\" (i.e. each employee knows what they're supposed to do, rather than the system telling each employee what to do).</li>\n<li>If a <code>GetCallHandler</code> method is needed in another system, then the question would have been more specific as to the signature of the method.</li>\n<li>Judging on the solution, <code>GetCallHandler</code> is only called by the <code>CallHandler</code> class itself, so that supports #3. Nobody outside of <code>CallHandler</code> seems to use it.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T12:25:28.030",
"Id": "1353",
"Score": "0",
"body": "in addition, I'd like to add that my and the author's implementations of GetCallHandler would probably be particularly unfair on the first few fresher employees - the 5th fresher would only answer a call if the first four were busy! I think the first fresher would get sick of their job pretty quickly :) If you queue them like you did, they'll be allocated calls in a round robin fashion."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T19:37:00.800",
"Id": "1375",
"Score": "0",
"body": "@Alex yes, the author's approach is a bit biased towards the first freshers, but it does get a little better when the call volume increases. I really appreciate your input on all of this :), thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T22:39:38.653",
"Id": "733",
"ParentId": "720",
"Score": "0"
}
},
{
"body": "<p>Sorry if there is a lack of pleasantries, but I am going to get down to it.</p>\n\n<p><strong>Source at time of review:</strong></p>\n\n<pre><code>enum EStatus{ HANDLING, ESCALATED, QUEUED }\nenum ERank{ FRESHER, TECH_LEAD, PROD_MANAGER }\n\nabstract class Employee\n{\n public ERank Rank{get; private set;}\n\n public Employee(ERank rank)\n {\n Rank = rank;\n }\n\n public abstract EStatus ServiceCall(Call call);\n}\n\nclass Fresher:Employee\n{\n private TechLead _superior;\n\n public Fresher(TechLead superior):base(ERank.FRESHER)\n {\n _superior = superior;\n }\n\n public override EStatus ServiceCall(Call call)\n {\n if(CanService(call))\n {\n call.Service(this);\n return EStatus.HANDLING;\n }\n else\n {\n _superior.ServiceCall(call);\n return EStatus.ESCALATED;\n }\n }\n\n private bool CanService(Call call)\n {\n // some logic to determine if the call can be serviced \n }\n}\n\nclass TechLead:Employee\n{\n private Call _activeCall;\n private ProductManager _superior;\n\n public TechLead(ProductManager superior):base(ERank.TECH_LEAD)\n {\n _activeCall = null;\n _superior = superior;\n }\n\n public override EStatus ServiceCall(Call call)\n {\n if(_activeCall == null && CanService(call))\n {\n HandleCall(call);\n return EStatus.HANDLING;\n }\n else\n {\n _superior.ServiceCall(call);\n return EStatus.ESCALATED;\n }\n }\n\n private bool CanService(Call call)\n {\n // some logic to determine if the call can be serviced \n }\n\n private HandleCall(Call call)\n {\n _activeCall = call;\n call.OnCallServiced += new Call.CallServicedDelegate(OnCallServiced);\n call.Service(this);\n }\n\n private void OnCallServiced(Call call)\n {\n if(call!=_activeCall)\n {\n // TODO: this call was never accepted\n }\n else\n {\n _activeCall = null;\n }\n }\n}\n\nclass ProductManager:Employee\n{\n private Call _activeCall;\n private Queue<Call> _callQueue;\n\n public ProductManager():base(ERank.PROD_MANAGER)\n {\n _activeCall = null;\n _callQueue = new Queue<Call>();\n }\n\n public override EStatus ServiceCall(Call call)\n {\n if(_activeCall == null)\n {\n HandleCall(call);\n return EStatus.HANDLING;\n }\n else\n {\n _callQueue.Enqueue(call);\n return EStatus.QUEUED;\n }\n }\n\n private HandleCall(Call call)\n {\n _activeCall = call;\n call.OnCallServiced += new Call.CallServicedDelegate(OnCallServiced);\n call.Service(this);\n }\n\n private void OnCallServiced(Call call)\n {\n if(call!=_activeCall)\n {\n // TODO: this call was never accepted\n }\n else\n {\n if(_callQueue.Count==0)\n {\n _activeCall = null;\n }\n else\n {\n HandleCall(_callQueue.Dequeue());\n }\n }\n }\n}\n\nclass Call\n{\n public delegate void CallServicedDelegate(Call call);\n public event CallServicedDelegate OnCallServiced;\n\n public Employee CallHandler{get; private set;}\n\n public Call()\n {\n CallHandler = null;\n }\n\n public void Service(Employee callHandler)\n {\n CallHandler = callHandler;\n\n // Invoke the notification when the call is complete\n OnCallServiced(this);\n }\n\n public void Disconnect()\n {\n // Disconnect the call\n }\n}\n\nclass CallCenter\n{\n private bool _running;\n private BlockingQueue<Call> _callQueue;\n private Queue<Employee> _freeFreshers;\n private List<Employee> _busyFreshers;\n private readonly TechLead _techLead;\n\n public CallCenter(int numEmployees)\n {\n // create the tech lead and a supervising product manager\n _techLead = TechLead(new ProductManager());\n\n _callQueue = new BlockingQueue<Call>();\n _freeFreshers = new Queue<Employee>();\n _busyFreshers = new List<Employee>();\n\n for(int i = 0; i < numEmployees; i++)\n {\n _freeFreshers.Enqueue(new Fresher(_techLead));\n }\n }\n\n public void AcceptCall(Call call)\n {\n _callQueue.Enqueue(call);\n }\n\n // Assuming that threading will be handled\n public void StartCallService()\n {\n _running = true;\n\n while(_running)\n {\n Call call = _callQueue.Dequeue();\n\n // Subscribe for the on call serviced delegate\n call.OnCallServiced += new Call.CallServicedDelegate(OnCallServiced);\n\n if(_freeFreshers.Count>0)\n {\n // Block until a fresher is available\n Employee e = _freeFreshers.Dequeue();\n\n // Assign the call to a free fresher\n switch(e.ServiceCall(call))\n {\n case EStatus.HANDLING:\n _busyFreshers.Add(e);\n break;\n case EStatus.ESCALATED:\n _freeFreshers.Enqueue(e);\n break;\n case EStatus.QUEUED:\n default:\n break;\n }\n }\n else\n {\n _techLead.ServiceCall(call);\n }\n }\n }\n\n // Assuming that threading will be handled\n public void StopCallService()\n {\n _running = false;\n }\n\n private void OnCallServiced(Call call)\n {\n switch(call.CallHandler.Rank)\n {\n case ERank.FRESHER:\n _busyFreshers.Remove(call.CallHandler);\n _freeFreshers.Enqueue(call.CallHandler);\n break;\n case ERank.TECH_LEAD:\n case ERank.PROD_MANAGER:\n default:\n // nothing to do if it's a tech lead or prod manager\n break;\n }\n }\n}\n</code></pre>\n\n<p><strong>Observation on chain of command.</strong></p>\n\n<p>First thing to address is that \"chain of command\" behaves in a way other then what is specified in the problem. The problem states:</p>\n\n<blockquote>\n <p>An incoming telephone call must be allocated to a fresher who is free.</p>\n</blockquote>\n\n<p>The defined \"chain of command\" behavior...</p>\n\n<blockquote>\n <p>If there are no free freshers, then the tech lead automatically gets the call.</p>\n</blockquote>\n\n<p>...stands in opposition to that. Additionally, in the way the solution is implemented it then follows that if the tech lead is busy then the call gets bumped to product manager. If the product manager is busy then the call is placed in his personal call queue, to wait until he is free.</p>\n\n<p>This behavior has the consequence of filling the PMs personal call queue with unscreened calls whenever all freshers and the tech is busy. This makes the PM responsible for screening all of those calls, even if at some point a fresher were to become free.</p>\n\n<p><strong>Suggested improvement.</strong></p>\n\n<p>Implement the base caller class in such a way that it have to it assigned a queue^ of calls to watch. This would allow for 2 things:</p>\n\n<ol>\n<li>All freshers could watch the same queue^ of new calls. When a new call is received, it then could be added to a common fresher queue^.</li>\n<li>The tech lead and project manager could each be assigned their own queues^ where escalated calls could wait for them to become available.</li>\n</ol>\n\n<p>This allows for all new calls to wait for a fresher to be free, and for the TL and PM to only have calls queued to them that they need answer.</p>\n\n<p>^Queues could be lists. Read on...</p>\n\n<p><strong>Observation on queuing behaviors.</strong></p>\n\n<p>In the implementation I counted 3 queues and a bonus list.</p>\n\n<ol>\n<li>_callQueue in CallCenter. Intended to contain new calls.</li>\n<li>_freeFreshers in CallCenter. Holds freshers without calls.</li>\n<li>_callQueue in ProductManager. Holds PMs calls or unserviced calls (see chain of command).</li>\n<li>_busyFreshers* in CallCenter. This is not really a queue but it holds freshers from the _freeFreshers queue when they are not free.</li>\n</ol>\n\n<p>Q1:</p>\n\n<p>In design, this queue holds the incoming calls. In practice, Q1 keeps the while(_running) loop in the StartCallService method from eating up as much cpu as possible. As soon as a call is added to Q1 it is <em>promptly</em> dequeued and handled by (A)a free caller, (B) the tech lead, (C) the project manager, or (D) thrown in the PMs queue. <em>Nothing ever stays in Q1</em>.</p>\n\n<p>Q2 & Q4:</p>\n\n<p>Q2 and Q4 are simply keeping track of the freshers busy state. Q4 only exists so that busy freshers are not lost? This also enforces a set behavior of choosing which free fresher takes a call. </p>\n\n<p>Q3:</p>\n\n<p>This queue behaves like a queue. Callers wait here for the attention of the project manager.</p>\n\n<p><strong>Suggested improvement.</strong></p>\n\n<p><em>I am struggling with what to write here because, minus a few design flaws in other places, these queues are perfectly functional.</em> But, what really should be asked is, <strong>is the function of a queue really wanted?</strong> </p>\n\n<p>In the case of Q2 & Q4, which are holding the free state and dictating who gets the next call. It makes more sense to add a IsBusy property to employee. That way CallCenter can simply have a _freshers list. To determine if a fresher is busy you just ask. To get a free fresher you are no longer stuck with whoever pops out of Q2. You may simply ask for the employee that fits the any criteria you like.</p>\n\n<p>In the same way Q1 could be replaced by a list. When a new call comes in it is assigned to the best free fresher. If no fresher is available it is added to the unanswered calls list. When a fresher finishes a call a check to the unanswered calls list is made. This allows for the elimination of the while(_running) loop, <em>and I love eliminating loops</em>, <strong>really love</strong>, <strong><em>really</em></strong>.</p>\n\n<p><strong>Observation on use of enums</strong></p>\n\n<p>The defined enums...</p>\n\n<pre><code>enum EStatus{ HANDLING, ESCALATED, QUEUED }\nenum ERank{ FRESHER, TECH_LEAD, PROD_MANAGER }\n</code></pre>\n\n<p>...really end up being just duplicated information. ERank can be determined by class, and EStatus can be determined by which queue or employee has the call.</p>\n\n<p><strong>Suggested improvement.</strong></p>\n\n<p>Just get rid of them.</p>\n\n<p><strong>OH, getCallHandler()</strong></p>\n\n<p>At this point this seems like a silly (and somewhat mysteriously defined) thing to implement. Maybe another user why this is a sensible thing to implement?</p>\n\n<p><em>But, a requirement is a requirement.</em> And, your Call.CallHandler, property has the right idea. I would just make it a method called getCallHandler() to play by the letter of the law, and null seems like a reasonable value to return if no one has handled the call yet.</p>\n\n<p>As always, I too welcome comments or criticisms. Cheers!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:45:09.720",
"Id": "1336",
"Score": "0",
"body": "I wish I had enough points to comment on some of the other solutions. :) There is some great input here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:58:53.263",
"Id": "1337",
"Score": "0",
"body": "VERY thorough review and it leaves me with very little to counter. I think the biggest issue here is that I've actually propagated the call up the chain-of-command if there is no free fresher. A call should only be propagated up if the fresher can't handle the call. I'm going to add another answer in which I update my solution based on your comments (of course I will not accept it). It seems that you've pointed out the most crucial issues here, thanks for the help!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:59:59.083",
"Id": "1338",
"Score": "0",
"body": "by the way, if you want to get 100 free points, just sign up for one of the other stack exchange sites and link your accounts. This will allow you to comment."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T00:31:46.030",
"Id": "1339",
"Score": "0",
"body": "@Lirik Sadly, I have linked the other stack exchange accounts I have and none of them must have enough points to award me a free 100."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T02:04:16.823",
"Id": "1340",
"Score": "0",
"body": "there are a couple of things that I disagree with: rank allows us to specify what is the minimum rank level that is necessary to service a given call; after looking further into the queue system, it looks like the author's solution makes the most sense. Other than that, I've pretty much done everything that you suggested in your answer :) Thanks!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:37:53.127",
"Id": "736",
"ParentId": "720",
"Score": "5"
}
},
{
"body": "<p>Here is a running revision of my solution (based on all the answers):</p>\n\n<pre><code>enum ERank{ FRESHER = 0, TECH_LEAD = 1, PROD_MANAGER = 2 }\n\nabstract class Employee\n{\n // Properties\n public ERank Rank{get; private set;}\n public bool Busy{get; priavte set;}\n\n // Fields\n protected static readonly CallService _callService = new CallService(SOME_GLOBAL_VALUE);\n\n // Constructors\n public Employee(ERank rank)\n {\n Rank = rank;\n Busy = false;\n }\n\n public void ServiceCall(Call call)\n {\n if(CanService(call))\n {\n Busy = true;\n call.Service(this);\n }\n else\n {\n // Only escalate if there is a superior rank available\n if(!Busy && (Rank != ERank.PROD_MANAGER))\n {\n call.Escalate();\n }\n\n // Put the call back onto the queue\n _callService.AcceptCall(call);\n }\n }\n\n public void OnCallServiced(Call call)\n {\n if(this != call.CallHandler)\n {\n // TODO: this call was never accepted\n // somebody is innapropriately calling this method\n }\n else\n {\n Call nextCall = _callService.GetNextCall();\n if(nextCall == null)\n {\n Busy = false;\n }\n }\n }\n\n protected abstract bool CanService(Call call);\n}\n\nclass Fresher:Employee\n{\n public Fresher():base(ERank.FRESHER){}\n private override bool CanService(Call call){ /*...*/ }\n}\n\nclass TechLead:Employee\n{ \n public TechLead():base(ERank.TECH_LEAD){}\n private override bool CanService(Call call){ /*...*/ }\n}\n\nclass ProductManager:Employee\n{ \n public ProductManager():base(ERank.PROD_MANAGER){}\n private override bool CanService(Call call){ /*...*/ }\n}\n\nclass Call\n{ \n public Employee CallHandler{get; private set;}\n public ERank AcceptableRank{get; private set;}\n\n public Call()\n {\n CallHandler = null;\n AcceptableRank = ERank.FRESHER;\n }\n\n public void Service(Employee callHandler)\n {\n CallHandler = callHandler;\n\n // notify the call handler when the call is serviced\n CallHandler.OnCallServiced(this);\n }\n\n public void Escalate()\n {\n if((in)AcceptableRank < (int)ERank.PROD_MANAGER)\n {\n AcceptableRank = ERank(((int)AcceptableRank)+1);\n }\n }\n}\n\nclass CallCenter\n{\n private Employee[][] _employees;\n private Queue<Call>[] _rankedCallQueue;\n\n public CallCenter(int numEmployees)\n {\n _prodManager = new ProductManager();\n _techLead = new TechLead();\n\n _rankedCallQueue = new Queue<Call>[((int)ERank.PROD_MANAGER)+1];\n _employees = new Employee[((int)ERank.PROD_MANAGER)+1][];\n\n for(int rank = 0; rank <= (int)ERank.PROD_MANAGER; rank++)\n {\n _rankedCallQueue[rank] = new Queue<Call>();\n switch((ERank)rank)\n {\n case ERank.Fresher:\n _employees[rank] = new Employee[numEmployees];\n for(int i = 0; i < numEmployees; i++)\n {\n _employees[rank][i] = new Fresher();\n }\n break;\n case ERank.TECH_LEAD:\n _emlpoyees[rank] = new Employee[]{new TechLead()};\n break;\n case ERank.PROD_MANAGER:\n _employees[rank] = new Employee[]{new ProductManager()};\n break;\n default:\n break;\n }\n }\n }\n\n public Employee GetCallHandler(Call call)\n {\n int rank = (int)call.AcceptableRank;\n for(int i = 0; i < _employees[rank].Length; i++)\n {\n if(!_employees[rank][i].Busy)\n {\n return _employees[rank][i];\n }\n }\n return null;\n }\n\n public void AcceptCall(Call call)\n {\n Employee employe = GetCallHandler(call);\n if(employee == null)\n {\n _rankedQueue[(int)call.AcceptableRank].Enqueue(call);\n }\n else\n {\n employee.ServiceCall(call);\n }\n }\n\n public Call GetNextCall(ERank rank)\n {\n if(_callQueue[(int)rank].Count == 0)\n {\n return null;\n }\n else\n {\n return _callQueue[(int)rank].Dequeue();\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T01:57:44.550",
"Id": "737",
"ParentId": "720",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "730",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T10:21:06.773",
"Id": "720",
"Score": "10",
"Tags": [
"c#",
"interview-questions"
],
"Title": "Review of object oriented design for a sample interview question"
} | 720 |
<p>I want my application to support multiple UI-languages (aka i18n). To do so, I have built the static class below, to automatically translate the form and all its contents to the desired language. It looks into a resource file for the user's Culture, and replaces the .Text properties of the controls with the strings it finds there, or falls-back to the initial strings, which is English.</p>
<p>Usage is calling TranslateForm(this) from each form's constructor.</p>
<p>Two concerns about my code:<br>
* The overloading of the "Translate" method. I didn't find any way to overcome this.<br>
* The special handling of different controls, which seems unnecessary.</p>
<p>I'm not a professional programmer, so any correction / enhancement / fix to my code is more than welcomed!</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Resources;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
namespace blahblah
{
static class TranslationHelper
{
static private ResourceManager rm = null;
static private CultureInfo default_ci = null;
static private CultureInfo lang_ci = null;
/// <summary>
/// translate control into the specific lang, or leave it untranslated if no translation string found
/// </summary>
/// <param name="ctrl"></param>
/// <param name="lang"></param>
static private void Translate(Control ctrl, string lang)
{
string str = TranslateString(ctrl.Name, lang);
if (str != null)
ctrl.Text = str;
}
static private void Translate(ToolStripMenuItem o, string lang)
{
string str = TranslateString(o.Name, lang);
if (str != null)
o.Text = str;
}
static private void Translate(ToolStripItem o, string lang)
{
string str = TranslateString(o.Name, lang);
if (str != null)
o.Text = str;
}
static private void Translate(Form o, string lang)
{
string str = TranslateString(o.Name, lang);
if (str != null)
o.Text = str;
}
/// <summary>
/// returns the <c>name</c> string from the <c>lang</c> resource
/// </summary>
/// <param name="name">string/key name</param>
/// <param name="lang">the language to translate to</param>
/// <returns>a translated string for <c>name</c></returns>
static public string TranslateString(string name, string lang)
{
if (lang_ci == null || !lang_ci.TwoLetterISOLanguageName.Equals(lang))
lang_ci = new CultureInfo(lang);
try
{
return rm.GetString(name, lang_ci);
}
catch (Exception)
{
// no translation yet
try
{
return rm.GetString(name, default_ci);
}
catch (Exception)
{
return null;
//MessageBox.Show(ex.Message.ToString(), name);
//System.Console.WriteLine(ex.Message.ToString());
}
}
}
static public void TranslateForm(string lang, Form parent)
{
if (rm == null)
rm = new ResourceManager("etimet.i18nResources.i18n", Assembly.GetExecutingAssembly(), null);
if (default_ci == null)
default_ci = new CultureInfo("en");
// handle direction
if (Program.conf.CurrentLang.Equals("he") || Program.conf.CurrentLang.Equals("ar") || Program.conf.CurrentLang.Equals("fa"))
{
parent.RightToLeft = RightToLeft.Yes;
}
else
{
parent.RightToLeft = RightToLeft.No;
}
// translate the form itself
Translate(parent, lang);
// translate all the children controls, recursively
Control.ControlCollection c = parent.Controls;
foreach (Control o in c)
{
// special handling for the menu
if (o.GetType() == typeof(MenuStrip))
{
foreach (ToolStripMenuItem it in ((MenuStrip)o).Items)
{
Translate(it, lang);
//MessageBox.Show(it.Text);
foreach (ToolStripItem f in it.DropDownItems)
{
if (typeof(ToolStripSeparator) != f.GetType())
Translate(f, lang);
}
}
}
RecursiveTranslateCtrl(lang, o);
}
}
static private void RecursiveTranslateCtrl(string lang, Control ctrl)
{
Translate(ctrl, lang);
foreach (Control c in ctrl.Controls)
{
RecursiveTranslateCtrl(lang, c);
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T11:13:50.567",
"Id": "1304",
"Score": "0",
"body": "Please, someone with >150 reputation should also create the tags translation or i18n and tag this question with them. Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T19:12:36.873",
"Id": "1323",
"Score": "1",
"body": "`Localization` seems to be a more correct word for me."
}
] | [
{
"body": "<p>You can avoid the overloading by using the common superclass on <code>ToolStripItem</code>:</p>\n\n<pre><code>static private void Translate(ToolStripItem o, string lang)\n{\n string str = TranslateString(o.Name, lang);\n if (str != null)\n c.Text = str;\n}\n</code></pre>\n\n<p>Unfortunately that only works for those two component types since it looks like <code>Component</code> does not have the <code>Name</code> and <code>Text</code> attributes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T19:51:43.417",
"Id": "729",
"ParentId": "721",
"Score": "2"
}
},
{
"body": "<p>There are built in mechanisms for automatically switching an entire form to use text from culture-specific resource files and it is more powerful than just setting the text property (ToolTips for example). The only times you should need to manually load from the resource file are for things like message boxes, but unless you need your application to block while displaying an alert you might as well use balloon tips which are localizable as well. <a href=\"http://msdn.microsoft.com/en-us/library/y99d1cd3%28v=VS.100%29.aspx\" rel=\"noreferrer\">This</a> is an easy place to start. It will also be more efficient as the controls themselves are localization aware so there's no need to loop through anything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T14:40:18.087",
"Id": "745",
"ParentId": "721",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "745",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T11:12:42.267",
"Id": "721",
"Score": "8",
"Tags": [
"c#",
".net"
],
"Title": "Automatic translation of forms"
} | 721 |
<p>I use named scopes all over the place. </p>
<p>When I have a named scope that deals with two different tables, I tend to query the second table in a sub-query. That way, if I mix and match with other tables I don't need to worry about reusing a table alias or having ambiguous column names that only appear in bizarre scenarios.</p>
<p>For example, suppose I have a <code>posts</code> table that is one-to-many related to a <code>tags</code> table. I might add a <code>with_tags</code> scope on my <code>Post</code> model like this:</p>
<pre><code>named_scope :with_tags, lambda { |tags|
tags = [tags] if tags.kind_of? String
{:conditions => ["id IN (SELECT post_id FROM tags WHERE name IN (?))", tags]}
}
</code></pre>
<p>However, that doesn't seem ideal. Many databases can use a join more efficiently than they can use a sub-query. A query that looks like this might perform better:</p>
<pre><code>SELECT DISTINCT posts.* FROM posts JOIN tags ON posts.id = tags.post_id WHERE tags.name IN (?)
</code></pre>
<p>How do other people do this? Do you use the <code>:include/:join</code> parameters cleverly to know what the aliases <code>ActiveRecord</code> will use?</p>
| [] | [
{
"body": "<p>You want to use what Rails calls eager loading. This is done with the <code>:include</code> parameter in your <code>AR</code> call. Add it to your lambda block.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-02T06:23:11.870",
"Id": "1074",
"ParentId": "731",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1074",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-10T21:47:11.813",
"Id": "731",
"Score": "8",
"Tags": [
"ruby",
"sql",
"mysql",
"ruby-on-rails"
],
"Title": "Avoiding sub-queries in named scopes"
} | 731 |
<p>I've implemented the <strong><code>GroupBy</code></strong> extension method for <strong><code>IEnumerable<T></code></strong> type as an excersise to deep a little more into <strong>LINQ</strong>.</p>
<p>What do you think about the source code?</p>
<p><strong>Code:</strong> </p>
<pre><code>static IEnumerable<IGrouping<TKey,TElement>> GroupBy<TKey,TElement>(this IEnumerable<TElement> source, Func<TElement,TKey> keySelector)
{
//Grouping elements in the dictionary according to the criteria
var dict = new Dictionary<TKey, List<TElement>>();
//Filling the dictionary. It will contain: [Key -> List<Values>]
foreach (var x in source)
{
var key = keySelector(x);
if (dict.Keys.Contains(key))
{
dict[key].Add(x);
}
else
{
dict.Add(key, new List<TElement> { x });
}
}
//For each group...
foreach (var x in dict)
{
yield return new Grouping<TKey, TElement>(x.Key, x.Value);
}
}
class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
private TKey _key;
private IEnumerable<TElement> _elements;
public Grouping(TKey key, IEnumerable<TElement> elements)
{
_key = key;
_elements = elements;
}
public IEnumerator<TElement> GetEnumerator()
{
return _elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public TKey Key
{
get { return _key; }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T08:57:10.373",
"Id": "1348",
"Score": "1",
"body": "Do not see anything related to `SortBy`, is your topic correct?"
}
] | [
{
"body": "<pre><code>foreach (var x in dict)\n{\n yield return new Grouping<TKey, TElement>(x.Key, x.Value);\n}\n</code></pre>\n\n<p>Could change to:</p>\n\n<pre><code>return dict.Select(x => new Grouping<TKey, TElement>(x.Key, x.Value));\n</code></pre>\n\n<p>It's a little thing, but I would make _key and _elements in Grouping readonly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:16:26.410",
"Id": "1334",
"Score": "0",
"body": "Nice. In fact, I implemented `Select` before `GroupBy` too, so it's valid ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T22:54:51.063",
"Id": "734",
"ParentId": "732",
"Score": "3"
}
},
{
"body": "<p>If you want to duplicate <code>GroupBy</code> semantics exactly, there are several things missing:</p>\n\n<ul>\n<li>Eager error checking on parameters instead of deferred</li>\n<li>The correct order of the groups (<code>GroupBy</code> guarantees that the groups are ordered by the relative order of the group's first element in the source)</li>\n<li>Allowing keys that are <code>null</code></li>\n</ul>\n\n<p>You may be interested in Jon Skeet's <a href=\"http://codeblog.jonskeet.uk/2011/01/01/reimplementing-linq-to-objects-part-21-groupby/\" rel=\"nofollow noreferrer\">recent blog postings</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T04:42:37.997",
"Id": "1341",
"Score": "0",
"body": "Thanks for your answer. Could you tell me why the order of the groups isn't correct?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T13:39:20.080",
"Id": "1356",
"Score": "1",
"body": "@Oscar Mederos: Dictionary does not guarantee the order that the pairs are returned in, and is usually heavily influenced by the hashing algorithm of the key."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T13:58:04.030",
"Id": "1359",
"Score": "0",
"body": "@Oscar: It's like this - if the keys of the original sequence are `5, 3, 5, 3`, then `GroupBy` produces two groups; the first one is guaranteed to be for key `5` and the second one is guaranteed to be for key `3`. Your implementation returns the groups in an unspecified order."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T15:53:23.577",
"Id": "1365",
"Score": "0",
"body": "As a quick solution, you can handle the ordering issue by storing the keys in the order you receive them in a separate List<TKey> though your final loop will be a little less efficient as you would loop through your List of keys and then yield return from the dictionary using its indexer which isn't as efficient as its enumerator if you're going to use every value."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T18:54:00.193",
"Id": "1374",
"Score": "0",
"body": "Thanks. Understood. For a moment I just forgot that a dictionary is just a HashTable ;-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-11T04:30:53.200",
"Id": "740",
"ParentId": "732",
"Score": "5"
}
},
{
"body": "<p>One thing that stands out is your Dictionary usage. When checking existence and using a value you should use TryGetValue like so:</p>\n\n<pre><code>List<TElement> tmpList;\nif (!dict.TryGetValue(key, out tmpList))\n{\n dict.Add(key, tmpList = new List<TElement>());\n}\ntmpList.Add(x);\n</code></pre>\n\n<p>Also, in regard to the LINQ change mentioned by mjcopple, there's no need to use Select; it's less efficient and provides no benefit over your yield return in this case. I could understand if it even promoted more readability, but in this case it doesn't and I would stick to your first solution for the sake of efficiency.</p>\n\n<p>No biggie, but since you're just decorating the enumeration of elements, you might as well use it's implementation of the non-generic IEnumerable which will save you a method on the call stack (not much). There's also a chance that the underlying implementation has a more efficient non-generic enumerator than wrapping the generic one (though this is generally uncommon and not the case for List)</p>\n\n<pre><code>IEnumerator IEnumerable.GetEnumerator()\n{\n return ((IEnumerable)_elements).GetEnumerator();\n}\n</code></pre>\n\n<p>Stephen Cleary makes relevant comments on the completeness of your implementation so I thought I'd just toss out code pointers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T18:51:02.820",
"Id": "1373",
"Score": "0",
"body": "Thank you for your reply. I will take in count the `TryGetValue`. I use dictionaries lots of time, and I always used `if (dict.Keys.Contains(...))` or `if (dict.ContainsKey(...))` for that purpose. About the `GetEnumerator()`, you're right, but I think that's not a big deal and it's more readable as it is now ;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T12:55:21.817",
"Id": "1490",
"Score": "0",
"body": "Agreed on the Enumerator front. TryGetValue is one of those things that slipped by a lot of people for a good while, but it's great in premise since it only searches once."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T15:50:27.547",
"Id": "748",
"ParentId": "732",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T22:28:31.387",
"Id": "732",
"Score": "8",
"Tags": [
"c#",
"linq"
],
"Title": "Implementation of GroupBy<TKey, TElement> in .NET"
} | 732 |
<p>The CMS I use uses the Xalan XSLT processor which is a XSLT version 1.0 processor. Editors who use WYSIWYG fields within the CMS can save content that will look like either:</p>
<pre><code><story>
<p>Story Text which may have <em>formatting</em>.</p>
</story>
</code></pre>
<p>or:</p>
<pre><code><story>Story Text which may have <em>formatting</em>.</story>
</code></pre>
<p>or even:</p>
<pre><code><story>
<div>Story Text which may<br /> have <em>formatting</em>.</div>
</story>
</code></pre>
<p>In order to handle those varying cases I've been using:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/system-index-block">
<xsl:for-each select="story">
<xsl:choose>
<!-- If wrapped in an element -->
<xsl:when test="./p|./div">
<!-- copy what is inside story, allow for text outside of elements -->
<xsl:copy-of select="./text()|./*"/>
</xsl:when>
<!-- wrap the content in a paragraph tag -->
<xsl:otherwise>
<p>
<!-- copy text and tags from inside story -->
<xsl:copy-of select="./text()|./*"/>
</p>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Is there a better way of producing well formed HTML from this data? Is there a way to simply this?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T10:13:37.173",
"Id": "1350",
"Score": "0",
"body": "I don't know how complex the \"real\" XML will be, but if you only have XHTML wrapped in `<story>` elements you could simply replace those with `<div>`s. If it's more complicated it would be useful to see an example (for example, could there be `<story>`s within `<story>`s?)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T16:17:37.023",
"Id": "1368",
"Score": "0",
"body": "The real XML is more complex. There are never nested `<story>` elements. The `<story>` element contains the post processed output of a TinyMCE instance and in most cases the editors are restricted from using the \"Edit HTML Source\" button within that editor."
}
] | [
{
"body": "<p>You should change your mindset when working with XSLT: look at it as a functional language, where you declare rules for the transformation of elements. Think about it in terms of events: when a p element is found in input, I expect this and that in the output.</p>\n\n<p>First, regarding the definition of your data. You should ask for (or create) a more formal description of the data. There are different formats available to describe the structure (grammar), <a href=\"https://secure.wikimedia.org/wikipedia/en/wiki/Document_Type_Definition\" rel=\"noreferrer\">DTD</a> and <a href=\"http://www.w3.org/TR/xmlschema-0/\" rel=\"noreferrer\">XML Schema</a> being the more common. There are more simple alternatives such as <a href=\"http://relaxng.org/\" rel=\"noreferrer\">RELAX NG</a> and <a href=\"http://www.schematron.com/\" rel=\"noreferrer\">Schematron</a>.</p>\n\n<p>My guess, from your stylesheet and your descriptions:</p>\n\n<ul>\n<li>there is always a <code><system-index-block></code> at the top</li>\n<li>there is a list of <code><story></code> elements in <code><system-index-block></code></li>\n<li>there is mixed HTML contents in <code><story></code>, with <code><p></code>,<code><div></code>,<code><br></code>,<code><em></code> and text allowed</li>\n</ul>\n\n<p>I am not sure about the last part: is it possible to have both text and div or paragraph at the top level in a story?</p>\n\n<pre><code><story>\n Text before a <p>Paragraph</p> in between or <div>Div</div> even after ?\n</story>\n</code></pre>\n\n<p>You should break your unique template rule into several template rules, one or several for each element. Then to direct the flow from rule to rule, do not use for-each but rather apply-templates:</p>\n\n<pre><code><xsl:template match=\"system-index-block\">\n <!-- Note:\n You probably need to create the basic HTML structure Here: html, head, body\n -->\n <xsl:apply-templates /> <!-- you can specify select=\"story\" but it is not required -->\n</xsl:template>\n\n<xsl:template match=\"story[p|div]\"> <!-- If wrapped in an element -->\n <xsl:apply-templates mode=\"copy\" />\n</xsl:template>\n\n<xsl:template match=\"story\"> <!-- wrap the content in a paragraph tag -->\n <p>\n <xsl:apply-templates mode=\"copy\" />\n </p>\n</xsl:template>\n</code></pre>\n\n<p>Note that I used the mode \"copy\" above: you can now create different rules for the same nodes depending on the mode, for example:</p>\n\n<pre><code><xsl:template match=\"text()\" /> <!-- ignore text in normal mode, probably whitespace -->\n\n<xsl:template match=\"text()\" mode=\"copy\">\n <xsl:copy />\n</xsl:template>\n</code></pre>\n\n<p>Also, you will probably get into trouble because you only declared a namespace for the xsl prefix. You typically need a prefix/namespace declaration for the input and output formats. You will then need to use the prefix in match/select expressions and in the tag names for the output, for example, with input prefix bound to your input namespace and html bound to the html namespace:</p>\n\n<pre><code><xsl:template match=\"input:story\"> <!-- wrap the content in a paragraph tag -->\n <html:p>\n <xsl:apply-templates mode=\"copy\" />\n </html:p>\n</xsl:template>\n</code></pre>\n\n<p>To go further, here are pointers that you will probably find useful:</p>\n\n<ul>\n<li><a href=\"http://www.xml.com/pub/a/2001/04/04/trxml/index.html\" rel=\"noreferrer\">Namespaces and XSLT Stylesheets</a></li>\n<li><a href=\"https://secure.wikimedia.org/wikipedia/en/wiki/Identity_transform\" rel=\"noreferrer\">Identity transformation</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T07:23:44.323",
"Id": "1395",
"Score": "0",
"body": "Good answer considering the degree to which I tried to simplify the example XML and XSL. I tried to boil the question down and see now that I left out useful information. I'll look at reworking things to include greater use of `mode=\"\"`. I'm going to review my use of `<xsl:for-each` throughout all of my code and see where I'm relying on it where it isn't needed. The namespace isn't an issue as the stylesheet is only generating a portion of a page."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T00:03:51.953",
"Id": "1432",
"Score": "0",
"body": "The only case this seems to break on the way it is layed out now is when `<story>` contains both unenclosed text and `<p>` tags."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T13:07:23.163",
"Id": "1491",
"Score": "0",
"body": "@Jason can you edit your answer to show your updated code?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T19:41:03.763",
"Id": "758",
"ParentId": "735",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "758",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:13:04.567",
"Id": "735",
"Score": "6",
"Tags": [
"html",
"xml",
"xslt"
],
"Title": "Using XSLT to turn content of WYSIWYG stored in XML into HTML"
} | 735 |
<p>I've written a lengthy procedure that I call a few times to apply filters defined by the customer to a table, as I didn't see how I could turn my <strong>column name string</strong> into a <strong>LINQ column</strong> and how I could turn my <strong>action string</strong> into an <strong>action on a string</strong> in such way that the function can be used in the LINQ query like:</p>
<pre><code>private void applyFilterAction(ref IQueryable<TempArticle> products, FilterAction action)
{
products = from p in products where MAGIC(p, action.Column).ToLower().MAGIC2(action.Action, action.Value) == action.AddOrKill select p;
}
</code></pre>
<p>I wrote this instead as a temporary solution:</p>
<pre><code>private void applyFilterAction(ref IQueryable<TempArticle> products, FilterAction action)
{
var actionValue = action.Value.ToLower();
var column = action.Column;
if (action.Action.Equals("StartsWith"))
{
if (column.Equals("Description")) products = from p in products where p.Description.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("LongDescription")) products = from p in products where p.LongDescription.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Provider")) products = from p in products where p.Provider.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("ProviderCode")) products = from p in products where p.ProviderCode.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Publisher")) products = from p in products where p.Publisher.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("PublisherCode")) products = from p in products where p.PublisherCode.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom1")) products = from p in products where p.Custom1.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom2")) products = from p in products where p.Custom2.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom3")) products = from p in products where p.Custom3.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("EanCode")) products = from p in products where p.EanCode.ToLower().StartsWith(actionValue) == action.AddOrKill select p;
}
else if (action.Action.Equals("EndsWith"))
{
if (column.Equals("Description")) products = from p in products where p.Description.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("LongDescription")) products = from p in products where p.LongDescription.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Provider")) products = from p in products where p.Provider.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("ProviderCode")) products = from p in products where p.ProviderCode.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Publisher")) products = from p in products where p.Publisher.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("PublisherCode")) products = from p in products where p.PublisherCode.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom1")) products = from p in products where p.Custom1.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom2")) products = from p in products where p.Custom2.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom3")) products = from p in products where p.Custom3.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
else if (column.Equals("EanCode")) products = from p in products where p.EanCode.ToLower().EndsWith(actionValue) == action.AddOrKill select p;
}
else if (action.Action.Equals("Contains"))
{
if (column.Equals("Description")) products = from p in products where p.Description.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("LongDescription")) products = from p in products where p.LongDescription.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("Provider")) products = from p in products where p.Provider.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("ProviderCode")) products = from p in products where p.ProviderCode.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("Publisher")) products = from p in products where p.Publisher.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("PublisherCode")) products = from p in products where p.PublisherCode.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom1")) products = from p in products where p.Custom1.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom2")) products = from p in products where p.Custom2.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom3")) products = from p in products where p.Custom3.ToLower().Contains(actionValue) == action.AddOrKill select p;
else if (column.Equals("EanCode")) products = from p in products where p.EanCode.ToLower().Contains(actionValue) == action.AddOrKill select p;
}
else if (action.Action.Equals("Exact"))
{
if (column.Equals("Description")) products = from p in products where p.Description.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("LongDescription")) products = from p in products where p.LongDescription.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("Provider")) products = from p in products where p.Provider.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("ProviderCode")) products = from p in products where p.ProviderCode.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("Publisher")) products = from p in products where p.Publisher.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("PublisherCode")) products = from p in products where p.PublisherCode.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom1")) products = from p in products where p.Custom1.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom2")) products = from p in products where p.Custom2.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("Custom3")) products = from p in products where p.Custom3.ToLower().Equals(actionValue) == action.AddOrKill select p;
else if (column.Equals("EanCode")) products = from p in products where p.EanCode.ToLower().Equals(actionValue) == action.AddOrKill select p;
}
}
</code></pre>
<p>It filters products based on an <code>action</code> object that contains:</p>
<ul>
<li><code>column</code>: Column of the product table that needs to be filtered.</li>
<li><code>action</code>: The action to perform on the strings coming from that column.</li>
<li><code>value</code>: The value to compare against using the action. </li>
</ul>
<p>Could I write this in a better way? I didn't get the switch statements in the MAGIC functions to LINQify.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T17:39:42.400",
"Id": "1386",
"Score": "0",
"body": "Is there any reason you went for a ref parameter rather than returning IQueryable<TempArticle>?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T21:57:25.073",
"Id": "1389",
"Score": "0",
"body": "Looked this up, seems I should avoid ref/out parameters, thanks."
}
] | [
{
"body": "<p>I don't see anything LINQ related that could be done here... but it looks to me like all the contents of all the IF statements are the same. Perhaps that should be extracted into a method?</p>\n\n<p>Also: </p>\n\n<pre><code>ToLower().StartsWith(actionValue) == action.AddOrKill\n</code></pre>\n\n<p>Should be</p>\n\n<pre><code>StartsWith(actionValue, StringComparison.CurrentCultureIgnoreCase) == action.AddOrKill \n</code></pre>\n\n<p>Using <code>ToLower</code> for case insensitive string comparisons doesn't respect the culture of the current system, and will give wrong results for several languages (particularly those with 3 cases rather than 2). Plus, it's slower, because you're converting the entire string, rather than simply running comparisons on the beginning of the string.</p>\n\n<hr>\n\n<p>EDIT: I see the difference between the IF blocks now. It's been a while since I've played with C#, so I'm not entirely sure this will compile out of the box, but it should give you the idea. Basically you pass around a functor rather than replicating the if block over and over again:</p>\n\n<pre><code>private void applyFilterAction(ref IQueryable<TempArticle> products, FilterAction action)\n{\n var actionValue = action.Value.ToLower();\n var column = action.Column;\n Func<string, string, bool> comparer;\n\n if (action.Action.Equals(\"StartsWith\"))\n {\n comparer = (a, b) => a.StartsWith(b, StringComparison.CurrentCultureIgnoreCase);\n }\n else if (action.Action.Equals(\"EndsWith\"))\n {\n comparer = (a, b) => a.EndsWith(b, StringComparison.CurrentCultureIgnoreCase);\n }\n else if (action.Action.Equals(\"Contains\"))\n {\n comparer = (a, b) => a.Contains(b, StringComparison.CurrentCultureIgnoreCase);\n }\n else if (action.Action.Equals(\"Exact\"))\n {\n comparer = (a, b) => a.Equals(b, StringComparison.CurrentCultureIgnoreCase);\n }\n\n if (column == \"Description\") products = from p in products where comparer(p.Description, actionValue) == action.AddOrKill select p;\n else if (column == \"LongDescription\") products = from p in products where comparer(p.LongDescription, actionValue) == action.AddOrKill select p;\n else if (column == \"Provider\") products = from p in products where comparer(p.Provider, actionValue) == action.AddOrKill select p;\n else if (column == \"ProviderCode\") products = from p in products where comparer(p.ProviderCode, actionValue) == action.AddOrKill select p;\n else if (column == \"Publisher\") products = from p in products where comparer(p.Publisher, actionValue) == action.AddOrKill select p;\n else if (column == \"PublisherCode\") products = from p in products where comparer(p.PublisherCode, actionValue) == action.AddOrKill select p;\n else if (column == \"Custom1\") products = from p in products where comparer(p.Custom1, actionValue) == action.AddOrKill select p;\n else if (column == \"Custom2\") products = from p in products where comparer(p.Custom2, actionValue) == action.AddOrKill select p;\n else if (column == \"Custom3\") products = from p in products where comparer(p.Custom3, actionValue) == action.AddOrKill select p;\n else if (column == \"EanCode\") products = from p in products where comparer(p.EanCode, actionValue) == action.AddOrKill select p;\n}\n</code></pre>\n\n<p>Like I said, it's been a while since I've messed with C#, so this might not work :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T16:23:51.440",
"Id": "1369",
"Score": "0",
"body": "-1 because extracting them into a method is LINQ related, as it would result in a method inside the LINQ query, the IFs you see determine the Column and the String Comparison Action in the LINQ query, I wanted to add the tag [extract-method] but I need 150 reputation for that. I want to know how to do it, because it usually gives a vague error that says that the method can't be converted to LINQ."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T16:26:33.497",
"Id": "1370",
"Score": "0",
"body": "+1 beceause of the unrelated hint; although its blazing fast as is, your suggestion makes it even faster. Still, the current code is ugly and prone to errors. :-("
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T21:18:32.037",
"Id": "1376",
"Score": "0",
"body": "@TomWij: What's different about the contents of the IF blocks? It looks to me like they are identical. EDIT: Oh, I see now. Give me a sec."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T21:24:10.423",
"Id": "1377",
"Score": "0",
"body": "+1 this seems a good approach and does take away lines without having me to go through the nasty LINQ compilation."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T00:17:30.330",
"Id": "2136",
"Score": "0",
"body": "Seems LINQ to Entities only allows this for `Equals`, using `ToUpper` at the moment and will look if another solution exists that can be EF4 LINQified."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T15:15:17.790",
"Id": "747",
"ParentId": "744",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p><strong>YOU HAVE A LOT OF CODE REPEATING ITSELF</strong> - it definitely means something. Basically you have two fields to consider - <code>action</code> and <code>column</code>. Since all your columns are considered to be strings so you can separate <strong>a)</strong> logic which determines which column to take and <strong>b)</strong> logic which determines how to filter columns. This will lead to dramatical changes in your code.</p>\n\n<p>Here is a sample: </p>\n\n<pre><code>private void applyFilterAction(ref IQueryable<TempArticle> products, FilterAction action)\n{\n var actionValue = action.Value.ToLower();\n var column = action.Column;\n\n Func<TempArticle, string> valueExtractor;\n // determining field\n if (column.Equals(\"Description\")) valueExtractor = p => p.Description;\n else if (column.Equals(\"LongDescription\")) valueExtractor = p => p.LongDescription;\n else if (column.Equals(\"Provider\")) valueExtractor = p => p.Provider;\n else if (column.Equals(\"ProviderCode\")) valueExtractor = p => p.ProviderCode;\n else if (column.Equals(\"Publisher\")) valueExtractor = p => p.Publisher;\n else if (column.Equals(\"PublisherCode\")) valueExtractor = p => p.PublisherCode;\n else if (column.Equals(\"Custom1\")) valueExtractor = p => p.Custom1;\n else if (column.Equals(\"Custom2\")) valueExtractor = p => p.Custom2;\n else if (column.Equals(\"Custom3\")) valueExtractor = p => p.Custom3;\n else if (column.Equals(\"EanCode\")) valueExtractor = p => p.EanCode;\n else throw new NotSupportedException(column);\n\n Predicate<string> filteringPredicate;\n\n // determining predicate\n if (action.Action.Equals(\"StartsWith\")) filteringPredicate = s => s.StartsWith(actionValue);\n else if (action.Action.Equals(\"EndsWith\")) filteringPredicate = s => s.EndsWith(actionValue);\n else if (action.Action.Equals(\"Contains\")) filteringPredicate = s => s.Contains(actionValue);\n else if (action.Action.Equals(\"Exact\")) filteringPredicate = s => s.Equals(actionValue);\n else throw new NotSupportedException(action.Action);\n\n products = from p in products where filteringPredicate(valueExtractor(p).ToLower()) == action.AddOrKill select p;\n}\n</code></pre>\n\n<p>This approach is much better but I would go even further. Instead of this <code>if</code> blocks I would use dictionaries which will map input string into corresponding delegates .<br>\nIt has nothing to do with LINQ yet, only common sense. This was the main part. My other points are: </p></li>\n<li><p><strong>UpperCamelCase</strong>? </p></li>\n<li><p><code>action.AddOrKill</code> looks very strange. It took me a while to understand what are you trying to achieve with it. It looks very weird and should be rewritten in some other, more developer-friendly way. </p></li>\n<li><p>I would not use such a method signature - void with ref parameter. It doesn't look solid with existing LINQ methods and there is no point in having such a signature. I would use regular LINQ <code>IQueryable MethodName(IQueryable<> source, ...other parameters)</code>. </p></li>\n<li><p>I believe in such cases you should create fluent interface - it will improve code readability a lot. Especially in implementing <code>NOT</code> functionality.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T21:29:52.820",
"Id": "1378",
"Score": "0",
"body": "+1 1) Didn't learned about functors in C# yet, pretty interesting and once you know it's indeed common sense. You were first so you most likely be accepted when I'm done reading. 2) Where did I go wrong? everything is private local so I think lowelCamelCase suffices in this case. 3) Well, the user can specify if he still wants to include or exclude the products that went through that filter; spares us both from having to create \"Doesn't Start With\" entries and such things. 4) Hmm, so as it is a reference type I don't need ref, I'll try. 5) How do you mean? I will extract the determining parts."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T22:06:50.513",
"Id": "1381",
"Score": "1",
"body": "2) In C# private methods are usually also named in UpperCC. 4) No, `ref` is needed if you are going to change products, but I believe you should return it instead of modifying that one which was passed as a parameter 5) If you are only started learning C# then maybe you should not do it, but I would prefer to see smth like `products.Where.Column(\"Description\").Equals(\"DDD\").And.Not.Column(\"LongDescription\").StartsWith(\"SSS\")` - this can be implemented"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T00:19:45.010",
"Id": "2137",
"Score": "0",
"body": "Got this working using a workaround by using `ToExpandable` and `Invoke`, as I'm using LINQ to Entities it started complaining about the different Func conversions that it had to do..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-11T20:39:59.887",
"Id": "749",
"ParentId": "744",
"Score": "7"
}
},
{
"body": "<p>If you can edit the <code>TempArticle</code> class, the best way would be to add an indexer to the class that switches on the column name and returns the value of that column. Your filter code would then be</p>\n\n<pre><code>private void applyFilterAction(ref IQueryable<TempArticle> products, FilterAction action)\n{\n if (action.Action == \"StartsWith\")\n {\n products = from p in products where p[action.Column].StartsWith(action.Value, StringComparison.CurrentCultureIgnoreCase) == action.AddOrKill select p;\n }\n else\n {\n products = from p in products where p[action.Column].EndsWith(action.Value, StringComparison.CurrentCultureIgnoreCase) == action.AddOrKill select p;\n }\n}\n</code></pre>\n\n<p>In case you can't change <code>TempArticle</code>'s definition and assuming <code>action.Column</code> equals the name of the corresponding property in <code>TempArticle</code>, you can use compiled Expressions as accessors:</p>\n\n<pre><code>static class PropertyAccessor<T>\n{\n static Dictionary<string, Func<T, object>> propGetters;\n static Dictionary<string, Func<T, object>> PropGetters\n {\n get\n {\n if (propGetters == null)\n {\n Initialize();\n }\n return propGetters;\n }\n }\n\n static Dictionary<string, Action<T, object>> propSetters;\n static Dictionary<string, Action<T, object>> PropSetters\n {\n get\n {\n if (propSetters == null)\n {\n Initialize();\n }\n return propSetters;\n }\n }\n\n static void Initialize()\n {\n propGetters = new Dictionary<string, Func<T, object>>();\n propSetters = new Dictionary<string, Action<T, object>>();\n\n var type = typeof(T);\n\n foreach (var pi in type.GetProperties(BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance))\n {\n if (pi.CanRead)\n {\n var parameter = Expression.Parameter(type, \"instance\");\n\n Expression<Func<T, object>> lambda;\n\n if (pi.PropertyType.IsValueType)\n {\n lambda = Expression.Lambda<Func<T, object>>(Expression.TypeAs(Expression.Property(parameter, pi.Name), typeof(object)), parameter);\n }\n else\n {\n lambda = Expression.Lambda<Func<T, object>>(Expression.Property(parameter, pi.Name), parameter);\n }\n\n propGetters.Add(pi.Name, lambda.Compile());\n }\n\n if (pi.CanWrite)\n {\n var paramExpT = Expression.Parameter(type, \"instance\");\n var paramExpObj = Expression.Parameter(typeof(object), \"value\");\n var setterLambda = Expression.Lambda<Action<T, object>>(Expression.Call(paramExpT, pi.GetSetMethod(), Expression.ConvertChecked(paramExpObj, pi.PropertyType)), paramExpT, paramExpObj);\n propSetters.Add(pi.Name, setterLambda.Compile());\n }\n }\n }\n\n public static object Get(T instance, string propName)\n {\n return PropGetters[propName](instance);\n }\n\n public static string[] GetAccessorKeys\n {\n get\n {\n return PropGetters.Keys.ToArray();\n }\n }\n\n public static void Set(T instance, string propName, object value)\n {\n PropSetters[propName](instance, value);\n }\n\n public static string[] SetAccessorKeys\n {\n get\n {\n return PropSetters.Keys.ToArray();\n }\n }\n}\n</code></pre>\n\n<p><code>applyFilterAction</code>:</p>\n\n<pre><code>private void applyFilterAction(ref IQueryable<TempArticle> products, FilterAction action)\n{\n if (action.Action == \"StartsWith\")\n {\n products = from p in products where ((string)PropertyAccessor<TempArticle>.Get(p, action.Column)).StartsWith(action.Value, StringComparison.CurrentCultureIgnoreCase) == action.AddOrKill select p;\n }\n else\n {\n products = from p in products where ((string)PropertyAccessor<TempArticle>.Get(p, action.Column)).EndsWith(action.Value, StringComparison.CurrentCultureIgnoreCase) == action.AddOrKill select p;\n }\n}\n</code></pre>\n\n<p>The accessors are compiled only once for each type, but are slightly slower than direct access, partly because of the type casting. (You can use <code>string</code> instead of <code>object</code> if you filter by <code>pi.PropertyType</code> in the initialize loop.)</p>\n\n<p>Other than that, I agree with Snowbear on the coding style and pattern use. This interface looks quite counterintuitive and it's definitely never a good idea to name a flag <code><Action>or<Opposite></code>.</p>\n\n<p>Part of the accessor code taken from:\n<a href=\"http://www.codeproject.com/KB/cs/fast_dynamic_properties.aspx\" rel=\"nofollow noreferrer\">Fast Dynamic Property Access with C# (Comments)</a></p>\n\n<p>Edit:</p>\n\n<p>If you want more speed, you should use <a href=\"http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx\" rel=\"nofollow noreferrer\">HyperDescriptor</a> instead: It writes IL directly and is really fast. In .NET 4, you need to <a href=\"https://stackoverflow.com/questions/3105763/does-hyperdescriptor-work-when-built-in-net-4/3105883#3105883\">fix the security permissions</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T21:32:51.790",
"Id": "1379",
"Score": "0",
"body": "+1 I'm using Code First, my guess is that the first thing will probably result in the LINQ problem. The second is a valid solution, still it looks like a dirty way to do it so I'm going for Snowbear's solution..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T21:36:58.947",
"Id": "1380",
"Score": "0",
"body": "Hmm, perhaps I can introduce a trimmed down version of your second solution for the dictionary in @Snowbear's solution. Thinking about it again your solution would allow code reuse if it works so you might as well be most likely accepted, I'll think about it... Worst case I'm going for bounties. I don't need rep here... :D"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T12:32:49.857",
"Id": "1384",
"Score": "0",
"body": "I added a link to HyperDescriptor, that way it's almost as fast as direct access but still reusable. It's a bit more hacky though..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T21:14:50.010",
"Id": "751",
"ParentId": "744",
"Score": "2"
}
},
{
"body": "<p>I would write some helper extension methods:</p>\n\n<pre><code>public static class FilterActionHelper {\n private static Dictionary<string, Func<string, Func<string, bool>>> actions = new Dictionary<string, Func<string, Func<string, bool>>>() {\n { \"StartsWith\", x => y => x.StartsWith(y) },\n { \"EndsWith\", x => y => x.EndsWith(y) },\n { \"Contains\", x => y => x.Contains(y) }\n };\n\n private static Dictionary<string, Func<TempArticle, string>> propertySelectors = new Dictionary<string, Func<TempArticle, string>>() {\n { \"Description\", x => x.Description },\n { \"LongDescription\", x => x.LongDescription },\n { \"Provider\", x => x.Provider },\n { \"ProviderCode\", x => x.ProviderCode },\n { \"Publisher\", x => x.Publisher },\n { \"PublisherCode\", x => x.PublisherCode },\n { \"Custom1\", x => x.Custom1 },\n { \"Custom2\", x => x.Custom2 },\n { \"Custom3\", x => x.Custom3 },\n };\n\n public static bool HasAction(string actionName) {\n return actions.ContainsKey(actionName);\n }\n\n public static Func<string, bool> GetAction(this string str, string actionName) {\n return actions[actionName](str);\n }\n\n public static bool HasProperty(string propertyName) {\n return propertySelectors.ContainsKey(propertyName);\n }\n\n public static string GetProperty(this TempArticle product, string propertyName) {\n return propertySelectors[propertyName](product);\n }\n}\n</code></pre>\n\n<p>which would allow the more succinct code:</p>\n\n<pre><code>private void ApplyFilterAction(ref IQueryable<TempArticle> products, FilterAction action) {\n var actionValue = action.Value.ToLower();\n var column = action.Column;\n\n if (!FilterActionHelper.HasAction(action.Action)) {\n return;\n }\n\n if (!FilterActionHelper.HasProperty(column)) {\n return;\n }\n\n products = from p in products\n where p.GetProperty(column).ToLower().GetAction(action.Action)(actionValue) == action.AddOrKill\n select p;\n}\n</code></pre>\n\n<p>The use of dictionaries makes it easy to add new properties and actions. The extension methods then make it a lot easier to use those dictionaries in a way that reads well.</p>\n\n<p>Another solution you may find easier is to make FilterAction generic:</p>\n\n<pre><code>public class FilterAction<T> {\n public string Value { get; set; }\n public Func<T, string> GetProperty { get; set; }\n public Func<string, string, bool> Action { get; set; }\n public bool AddOrKill { get; set; }\n\n public bool Matches(T t) {\n var filterValue = Value.ToLower();\n var propertValue = GetProperty(t).ToLower();\n return (Action(propertyValue, filterValue)) == AddOrKill);\n }\n}\n\n…\n\nFilterAction<TempArticle> filter = new FilterAction<TempArticle>();\nfilter.Value = \"foo\";\nfilter.GetProperty = x => x.Custom1;\nfilter.Action = x, y => x.StartsWith(y);\nfilter.AddOrKill = false;\n\nvar products = from p in products where filter.Matches(p) select p;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T21:44:20.117",
"Id": "1388",
"Score": "0",
"body": "+1 Thanks for working it out more, although generic won't work given that it is a Code First Entity."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T17:38:18.410",
"Id": "757",
"ParentId": "744",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "749",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-11T13:23:35.370",
"Id": "744",
"Score": "9",
"Tags": [
"c#",
"linq"
],
"Title": "Applying filters to a table"
} | 744 |
<p>The main view in my (toy!) Todo app is, of course, to display the list of tasks. These are grouped by some criterion, and the <code>tasks</code> structure below is actually a list of pairs (header, list of tasks).</p>
<pre><code>{% for tasks in tasks %}
<p class="list-header">{{ tasks.0 }}:</p>
<ul>
{% for t in tasks.1 %}
<li>
<span class="
{% if t.priority >= 1 %}prio-medium{% endif %}
{% if t.priority >= 2 %}prio-high{% endif %}
">
{{ t.description }}
</span>
{% if t.due_date %}
due,
<span class="
{% if t.days_to_due_date < 15 %}date-soon{% endif %}
{% if t.days_to_due_date < 3 %}date-very-soon{% endif %}
{% if t.days_to_due_date < 0 %}date-overdue{% endif %}
">
{{ t.relative_due_date }}
</span>
{% endif %}
-
{% if not t.done %}
<a href="/yata/{{ t.id }}/mark_done/">Done!</a>
{% else %}
<a href="/yata/{{ t.id }}/mark_not_done/">Not done!</a>
{% endif %}
-
<a href="/yata/{{ t.id }}/edit/">Edit</a>
</li>
{% endfor %}
</ul>
{% empty %}
<p class="list-header">Cool! Nothing to do...</p>
{% endfor %}
</code></pre>
<p>In particular, I'm wondering if deciding which CSS class to assign is considered to be the view function's role, or if it's correct to put it in the template.</p>
<p>Similarly, I'm also wondering about the presence of several URLs in the template. Would they be better in the <code>tasks</code> structure itself? Or should they be provided through some methods in the <code>Task</code> class? After all, <code>relative_due_date</code> is already a function that's only used for display (it returns a string like 'Yesterday', 'Tomorrow' or 'In 3 days'). And shouldn't I use <code>reverse()</code>?</p>
| [] | [
{
"body": "<p>I would move that conditional logic in the span tags to the view. Have your view pass the template a modified version of <code>tasks.1</code>, where each task instead of being the original datum is now the modified version that the template could use raw. For example, instead of passing your template <code>t.priority</code> as an integer, pass it as the actual CSS class that you'll be using. Same as <code>t.days_to_due_date</code>. </p>\n\n<p>Personally, I hate editing templates, because I haven't configured my text editor to play nice with them yet :-). As a consequence, I usually move everything out of the template and into the view that I can. Same situation with your URL's. I'm not sure if this is best practice, but I like to leave my template as clean as possible.</p>\n\n<p>As for your question about <code>reverse()</code>, I'd have to have more context to answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T00:13:11.017",
"Id": "753",
"ParentId": "746",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>I would suggest moving the CSS selection logic to a custom template tag or even a filter, e.g. <code><span class=\"{{ t|due_date_color }}\">{{ t.relative_due_date }}</span></code>. After that your templates will look much cleaner and that logic would still belong to the presentation part of MVT (Model, View, Template).</p></li>\n<li><p>You can split your tuple in the definition of the loop so that you don't redefine the <code>tasks</code> variable. <code>{% for header, task_list in tasks %} ...</code>. </p></li>\n<li><p>Use reverse URLs, no question about it. You'd hate the day you have to change them otherwise :) Go even further, use URL namespaces.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T00:46:59.047",
"Id": "754",
"ParentId": "746",
"Score": "5"
}
},
{
"body": "<p>I'd only add one thing to rassie's great list: while choosing which CSS class to assign to tasks that are due \"soon\" certainly belongs to the presentation layer (view or template), the fact that tasks due between 4 and 14 days from now are due \"soon\" belongs to the model. If each task here is an object, you can add <code>isDueSoon()</code>, <code>isDueVerySoon()</code>, and <code>isOverdue()</code> to encapsulate this logic in one logical place.</p>\n\n<p>You'll be happy you did this when you write unit tests for your task class and again when your boss asks you to build a REST API for working with tasks from a native iPhone app.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-12T02:08:52.640",
"Id": "755",
"ParentId": "746",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-11T14:54:59.473",
"Id": "746",
"Score": "5",
"Tags": [
"css",
"django",
"to-do-list",
"django-template-language"
],
"Title": "Todo app for displaying a list of tasks"
} | 746 |
<p>I need help to refactor my code. I usually had a hard time figuring out how to make my code reusable.</p>
<p>I have an XML file that hold the data for each Tag element. Tag element should have child nodes LastClocked, and TotalClocked. I first thought of creating Tag object and do serialization. But, I found Linq to XML is much easier. I would really appreciate if you guys can tell me what to improve for my code.</p>
<pre><code>namespace StopWatch.Models
{
public class TagCollection
{
private XElement doc;
private IEnumerable<XElement> tagElements;
public TagCollection()
{
if(File.Exists("TagsData.xml"))
{
doc = XElement.Load("TagsData.xml");
}
else
{
//TODO: Create XML
}
}
public void Save(TimeSpan clocked, string tags)
{
tagElements = from t in doc.Elements("Tag")
where (string)t.Attribute("Name") == tags
select t;
TimeSpan lastClocked = TimeSpan.Parse((string)
(from lc in tagElements.Descendants("LastClocked")
select lc).First());
lastClocked = lastClocked.Add(clocked);
if (!tagElements.Any())
{
Insert(clocked, tags);
}
else
{
Update(clocked, lastClocked);
}
doc.Save("TagsData.xml");
}
private void Update(TimeSpan clocked, TimeSpan lastClocked)
{
foreach(XElement tagElement in tagElements)
{
tagElement.SetElementValue("LastClocked", clocked.ToString());
tagElement.SetElementValue("TotalClocked", lastClocked.ToString());
}
}
private void Insert(TimeSpan clocked, string tags)
{
XElement newTag = new XElement("Tag",
new XAttribute("Name", tags),
new XElement("LastClocked", clocked.ToString()),
new XElement("TotalClocked", clocked.ToString()));
doc.Add(newTag);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-05T13:33:39.237",
"Id": "195374",
"Score": "0",
"body": "As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. For examples of good titles, check out [Best of Code Review 2014 - Best Question Title Category](http://meta.codereview.stackexchange.com/q/3883/23788) You may also want to read [How to get the best value out of Code Review - Asking Questions](http://meta.codereview.stackexchange.com/a/2438/41243)."
}
] | [
{
"body": "<p>Your code seems very procedural - you're worrying about implementing how things will be done before you think about what those things are and how you'd like to use them. You don't have any properties, just methods, which I don't particularly like.</p>\n\n<p>From what I understand you want to write a reusable wrapper from some XML, that's going to fit in a consistent format. Do you have a class that represents that object?</p>\n\n<pre><code>public TagElement\n{\n private XElement tagXml\n public string Name\n public DateTime LastClocked\n public DateTime TotalClocked\n}\n</code></pre>\n\n<p>Now I'd simply make each of those properties point into the private XML object get / set their values.</p>\n\n<pre><code>public TagElement(string name, DateTime initialValue)\n{ \n tagXml = new XElement(\"Tag\", \n new XAttribute(\"Name\", name),\n new XElement(\"LastClocked\", initialValue),\n new XElement(\"TotalClocked\", initialValue));\n}\n\npublic DateTime LastClocked\n{\n get\n {\n return tagXml.Descendents(\"LastClocked\").Single().Value;\n }\n set\n {\n tagXml.Descendents(\"LastClocked\").Single() = value;\n }\n}\n</code></pre>\n\n<p>You can still have a <code>Save</code> method that persists the XElement to a file. You probably also want a collection class that wraps the individual TagElements.</p>\n\n<pre><code>public TagCollection\n{\n public List<TagElement> TagElements { get; set; }\n}\n</code></pre>\n\n<p>So you can then use</p>\n\n<pre><code>var collection = new TagCollection(\"myFile.xml\");\n// constructor for TagCollection needs to parse the XML, and create TagElements\n\nvar fooElement = collection.TagElements.Single(tag => tag.Name == \"foo\");\nfooElement.LastClocked = DateTime.Now;\n\ncollection.TagElements.ForEach(tag => tag.TotalClocked = DateTime.Now);\n</code></pre>\n\n<p>In summary, prefer to use properties to get and set values than using methods. Abstract away the XML so that when you're using the class you do not know or care that it is being persisted to XML.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T09:52:07.733",
"Id": "1396",
"Score": "0",
"body": "I have those class that represent the object for TagElement, but I deleted it since I'm not really sure how it helps. I have little experience in OOP, so your factorization code does help. I'm trying to make a wrapper for XML as db, so I could query and save data. It should be a small file, so that's why I'm using XML. Thanks a lot for your input."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T10:04:56.910",
"Id": "1398",
"Score": "0",
"body": "Hopefully this will give you some ideas; there are other ways to do it but this is just what came to mind."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T07:36:34.803",
"Id": "760",
"ParentId": "759",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "760",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-13T03:37:56.223",
"Id": "759",
"Score": "4",
"Tags": [
"c#",
"linq",
"xml",
"wpf"
],
"Title": "Inserting and updating time spans in XML"
} | 759 |
<p>The code pretty much explains what I am doing here. Just wondering if anyone can think of a better way.</p>
<pre><code>public class AttachmentQuery
{
/// <summary>
/// Initializes a new instance of the <see cref="AttachmentQuery"/> class.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="status">The status.</param>
/// <param name="sort">The sort.</param>
/// <param name="order">The order.</param>
/// <param name="page">The page.</param>
public AttachmentQuery(string type, string status, SortAttachment sort, SortOrder order, int? page)
{
IAttachmentSpecification specification = null;
if (!string.IsNullOrEmpty(type))
{
specification = new AttachmentFileTypeSpecification(type);
}
if (!string.IsNullOrEmpty(status))
{
if (specification == null)
{
specification = new AttachmentStatusSpecification(status.AsEnum<AttachmentStatus>());
}
else
{
var spec = new AndSpecification<Attachment>(
specification,
new AttachmentStatusSpecification(status.AsEnum<AttachmentStatus>())
);
specification = spec as IAttachmentSpecification;
}
}
if (specification == null)
{
specification = new AttachmentSpecification();
}
specification.Page = page;
specification.Limit = Setting.AttachmentPageLimit.Value;
specification.Sort = sort;
specification.Order = order;
this.Specification = specification;
}
/// <summary>
/// Gets or sets the specification.
/// </summary>
/// <value>The specification.</value>
public IAttachmentSpecification Specification
{
get;
private set;
}
}
</code></pre>
<p><a href="https://github.com/Mike343/Netcoders/blob/master/Coders.Web/Controllers/Administration/Queries/AttachmentQuery.cs" rel="nofollow">Source</a>.</p>
<p><a href="https://github.com/Mike343/Netcoders/blob/master/Coders.Web/Controllers/Administration/AttachmentController.cs#L60" rel="nofollow">How it is used</a>.</p>
| [] | [
{
"body": "<p>How about adding an extension method to IAttachmentSpecification, such as</p>\n\n<pre><code>public static class AttachmentSpecificationExtensions\n{\n public static IAttachmentSpecification And(this IAttachmentSpecification orig, IAttachmentSpecification spec)\n {\n if (orig is NullAttachmentSpecification))\n {\n return spec ?? orig;\n }\n\n if (spec == null || spec is NullAttachmentSpecification)\n {\n return orig;\n }\n\n return (IAttachmentSpecification) new AndSpecification<Attachment>(specification, orig);\n }\n}\n\npublic class NullAttachmentSpecification : AttachmentSpecification\n{\n} \n</code></pre>\n\n<p>Now you can write your AttachmentQuery constructor as</p>\n\n<pre><code>public AttachmentQuery(string type, string status,\n SortAttachment sort, SortOrder order, int? page)\n{\n var statusSpec = string.IsNullOrEmpty(status) \n ? new NullAttachmentSpecification()\n : new AttachmentStatusSpecification(status.AsEnum<AttachmentStatus>())\n var typeSpec = string.IsNullOrEmpty(type) \n ? new NullAttachmentSpecification()\n : new AttachmentFileTypeSpecification(type)\n\n Specification = statusSpec.And(typeSpec);\n\n Specification.Page = page;\n Specification.Limit = Setting.AttachmentPageLimit.Value;\n Specification.Sort = sort;\n Specification.Order = order;\n}\n</code></pre>\n\n<p>It would seem more obvious to me what the intent was here. Plus it would seem more extensible if you add other types of <code>AttachmentSpecification</code> later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T00:17:59.807",
"Id": "767",
"ParentId": "762",
"Score": "3"
}
},
{
"body": "<p>I would definitely write it differently but exact result depends on whether your <code>AndSpecification</code> supports only two parameters or it can accept <code>IEnumerable</code> of attachments. </p>\n\n<p>If it has two parameters and you expect to nest those <code>AndSpecifications</code> if you will have more specs to compose then I would write something like this: </p>\n\n<pre><code>var typeSpecification = string.IsNullOrEmpty(type) ? null : new AttachmentFileTypeSpecification(type);\nvar statusSpecification = string.IsNullOrEmpty(status) ? null : new AttachmentStatusSpecification(status.AsEnum<AttachmentStatus>());\nvar specificationsToCompose = new IAttachmentSpecification[] {typeSpecification, statusSpecification};\n\nvar composedSpecification = specificationsToCompose\n .Aggregate((IAttachmentSpecification) null, (accumulator, currentSpec) =>\n {\n if (accumulator != null && currentSpec != null) return new AndSpecification<Attachment>(accumulator, currentSpec);\n return accumulator ?? currentSpec;\n })\n ?? new AttachmentSpecification();\n\n...\n\nthis.Specification = composedSpecification;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T09:23:06.533",
"Id": "1442",
"Score": "0",
"body": "Thats a good idea, I will probably end up trying this out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T10:24:37.447",
"Id": "769",
"ParentId": "762",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "769",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T21:56:47.670",
"Id": "762",
"Score": "6",
"Tags": [
"c#",
"linq"
],
"Title": "Better ways to build a linq specification for querying or is this the only way?"
} | 762 |
<p>Below are two solutions to the FizzBuzz problem in Python. Which one of these is more "Pythonic" and why is it more "Pythonic" than the other?</p>
<p>Solution One:</p>
<pre><code>fizzbuzz = ''
start = int(input("Start Value:"))
end = int(input("End Value:"))
for i in range(start,end+1):
if i%3 == 0:
fizzbuzz += "fizz"
if i%5 == 0:
fizzbuzz += "buzz"
if i%3 != 0 and i%5 != 0:
fizzbuzz += str(i)
fizzbuzz += ' '
print(fizzbuzz)
</code></pre>
<p>Solution Two:</p>
<pre><code>fizzbuzz = []
start = int(input("Start Value:"))
end = int(input("End Value:"))
for i in range(start,end+1):
entry = ''
if i%3 == 0:
entry += "fizz"
if i%5 == 0:
entry += "buzz"
if i%3 != 0 and i%5 != 0:
entry = i
fizzbuzz.append(entry)
for i in fizzbuzz:
print(i)
</code></pre>
| [] | [
{
"body": "<p>From my brief experience with Python, I would say the second is more Pythonic as it takes advantage of the Python lists and the first is just appending to strings which causes the output to be a wee bit ugly and clumped together. Although you could eliminate an entire extra iteration by appending to a temporary string within the first for loop, printing at the end of the loop and resetting the value so that the values don't need to be stored for more than one iteration.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T22:20:15.440",
"Id": "764",
"ParentId": "763",
"Score": "2"
}
},
{
"body": "<p>There is no difference in how \"Pythonic\" those solutions are. Both are perfectly acceptable. If the fizzbuzz string gets very long, using a list is preferable, as you don't have to make a copy of the string in every iteration, but that's a very minor issue.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T23:08:12.527",
"Id": "765",
"ParentId": "763",
"Score": "0"
}
},
{
"body": "<p>Most definitely solution two. However, you could further improve that solution by dumping the string concatenation altogether. Remember, string concatenation is expensive. Because strings are immutable, every time you concatenate, a new string is created. While the garbage collector can pick up the trash later, you're still having to go through the expense of copying a string. </p>\n\n<p>Instead, I'd recommend making a format string and then inserting the items in via string formatting, then appending them to your fizzbuzz list. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-09T12:53:17.980",
"Id": "245296",
"Score": "0",
"body": "can you please write an example for the laymen? :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-13T23:15:18.977",
"Id": "766",
"ParentId": "763",
"Score": "0"
}
},
{
"body": "<p>As has already been pointed out, creating a list is preferable as it avoids the concatenation of large strings. However neither of your solutions is the most pythonic solution possible:</p>\n\n<p>Whenever you find yourself appending to a list inside a for-loop, it's a good idea to consider whether you could use a list comprehension instead. List comprehensions aren't only more pythonic, they're also usually faster.</p>\n\n<p>In this case the body of the loop is a bit big to fit into a list comprehension, but that's easily fixed by refactoring it into its own function, which is almost always a good idea software design-wise. So your code becomes:</p>\n\n<pre><code>def int_to_fizzbuzz(i):\n entry = ''\n if i%3 == 0:\n entry += \"fizz\"\n if i%5 == 0:\n entry += \"buzz\"\n if i%3 != 0 and i%5 != 0:\n entry = i\n return entry\n\nfizzbuzz = [int_to_fizzbuzz(i) for i in range(start, end+1)]\n</code></pre>\n\n<p>However, while we're at it we could just put the whole fizzbuzz logic into a function as well. The function can take <code>start</code> and <code>end</code> as its argument and return the list. This way the IO-logic, living outside the function, is completely separated from the fizzbuzz logic - also almost always a good idea design-wise.</p>\n\n<p>And once we did that, we can put the IO code into a <code>if __name__ == \"__main__\":</code> block. This way your code can be run either as a script on the command line, which will execute the IO code, or loaded as a library from another python file without executing the IO code. So if you should ever feel the need to write a GUI or web interface for fizzbuzz, you can just load your fizzbuzz function from the file without changing a thing. Reusability for the win!</p>\n\n<pre><code>def fizzbuzz(start, end):\n def int_to_fizzbuzz(i):\n entry = ''\n if i%3 == 0:\n entry += \"fizz\"\n if i%5 == 0:\n entry += \"buzz\"\n if i%3 != 0 and i%5 != 0:\n entry = i\n return entry\n\n return [int_to_fizzbuzz(i) for i in range(start, end+1)]\n\nif __name__ == \"__main__\":\n start = int(input(\"Start Value:\"))\n end = int(input(\"End Value:\"))\n for i in fizzbuzz(start, end):\n print(i)\n</code></pre>\n\n<p>(Note that I've made <code>int_to_fizzbuzz</code> an inner function here, as there's no reason you'd want to call it outside of the <code>fizzbuzz</code> function.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T00:10:32.443",
"Id": "1469",
"Score": "0",
"body": "You could also take start end as command line arguments (as opposed to user input) so any future GUI can call the command line version in its present state without having to refactor any code. You'll probably need to add a --help argument so users have a way to look up what arguments are available."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T02:22:53.313",
"Id": "18110",
"Score": "0",
"body": "I think those last two lines could better be `print '\\n'.join(fizzbuzz(start, end))`. Also, refactored like this, the third `if` can be written `if not entry:`. Also, writing a bunch of Java may have made me hypersensitive, but `entry = str(i)` would make the list be of consistent type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-04T09:05:41.910",
"Id": "130912",
"Score": "0",
"body": "The list comprehension could be replaced with a generator."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-14T02:11:32.663",
"Id": "768",
"ParentId": "763",
"Score": "20"
}
},
{
"body": "<p>I have read a good solution with decorator, and I think it is a pythonic way to achieve a FizzBuzz solution:</p>\n\n<pre><code>@fizzbuzzness( (3, \"fizz\"), (5, \"buzz\") )\ndef f(n): return n\n</code></pre>\n\n<p>Generators are also a good pythonic way to get a list of numbers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-07T14:09:08.937",
"Id": "332165",
"Score": "0",
"body": "If you read python guide for beginners, you probably read about pep20. it says that \"Explicit is better than implicit.\" also YAGNI principle defines not to do anything if you need it only once. so there is no point to write decorator."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-14T11:24:12.343",
"Id": "770",
"ParentId": "763",
"Score": "4"
}
},
{
"body": "<p>I am not sure either solution has any 'Pythonic' elements. What I mean is, you have not used any features that are characteristic of Python. I think that for a beginner litmus test, you should demonstrate your ability to create functions and make some use of lambda, map, reduce, filter, or list comprehensions. Since output formatting is also an important fundamental skill, I would throw in some gratuitous use of it. Using comments before code blocks and using docstrings inside functions is always a good idea. Using the 'else' of iterators would also be more python-like, but this problem does not lend itself to such a solution.</p>\n\n<p>I would leave out the type casting on the user input. If you are using Python 2.X then it is redundant to cast the value since the print statement evaluates the input. If you are using 3.X then the point of type casting would be to force the value from a char to an int. The problem is, if the input included alphabetic characters then Python would throw an error. Also, since you do no bounds checking, casting to an int would not protect you from a negative integer screwing up you range.</p>\n\n<p>Here is what I would do in Python 2.x:</p>\n\n<pre><code># gather start and end value from user\nstart = input(\"Start value: \")\nend = input(\"End value: \")\n\ndef fizzbuzz(x):\n \"\"\" The FizzBuzz algorithm applied to any value x \"\"\"\n if x % 3 == 0 and x % 5 == 0:\n return \"FizzBuzz\"\n elif x % 3 == 0:\n return \"Fizz\"\n elif x % 5 == 0:\n return \"Buzz\"\n else:\n return str(x)\n\n# apply fizzbuzz function to all values in the range\nfor x in map(fizzbuzz, range(start,end+1)):\n print \"{0:>8s}\".format(x)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-26T06:37:01.823",
"Id": "78609",
"ParentId": "763",
"Score": "3"
}
},
{
"body": "<p>Not a decorator nor a function it's a right solution. Do some benchmarks and you will see. Call a function in Python is quite expensive, so try to avoid them.</p>\n\n<pre><code>for n in xrange(1, 101):\n s = \"\"\n if n % 3 == 0:\n s += \"Fizz\"\n if n % 5 == 0:\n s += \"Buzz\"\n print s or n\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code>for n in xrange(1, 101):\n print(\"Fizz\"*(n % 3 == 0) + \"Buzz\"*(n % 5 == 0) or n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-28T16:52:27.117",
"Id": "148975",
"Score": "0",
"body": "_Call a function in Python is quite expensive, so try to avoid them._ You do not pay money to call a function. You just wait a tiny bit of time. If a function is going to be called 100 or 10000 times, then you need not to worry. When writing in a high level language we should optimize for readability and maintainability, if you want rough speed use C, do not write highly obfuscated Python code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-01T17:56:12.810",
"Id": "149084",
"Score": "0",
"body": "I dont see any obfuscated code here, it's just a more pytonic way of writing.\nI am really worried that you don't understand what a function call is in Python."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-27T23:14:14.493",
"Id": "82785",
"ParentId": "763",
"Score": "1"
}
},
{
"body": "<p>Answering my own question: \"why noone uses <code>yield</code>?\"</p>\n\n<pre><code># the fizbuz logic, returns an iterator object that\n# calculates one value at a time, not all ot them at once\ndef fiz(numbers):\n for i in numbers:\n if i % 15 == 0:\n yield 'fizbuz'\n elif i % 5 == 0:\n yield 'buz'\n elif i % 3 == 0:\n yield 'fiz'\n else:\n yield str(i)\n\n# xrange evaluates lazily, good for big numbers\n# matches well with the lazy-eval generator function\nnumbers = xrange(1,2**20)\n\n# this gets one number, turns that one number into fuz, repeat\nprint ' '.join(fiz(numbers))\n\n# returns: 1 2 fiz 4 buz fiz [...] fiz 1048573 1048574 fizbuz\n</code></pre>\n\n<ul>\n<li>clearly separates fizbuz logic from concatenation</li>\n<li>is as plain and readeable as possible</li>\n<li><a href=\"https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/\" rel=\"nofollow\">generator iterator</a> does not keep all the array in memory</li>\n<li>so that you can do it on arbitrary numbers (see <a href=\"https://projecteuler.net/problem=10\" rel=\"nofollow\">Euler problem #10</a>)</li>\n</ul>\n\n<p>What I do not like in this solution is the three <code>if</code>s, whereas the problem can be solved with two.</p>\n\n<p><strong>Answer:</strong> because yield is efficient when you do not want to keep big arrays in memory just to iterate through them. But this question is not about big arrays.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-09T14:51:11.840",
"Id": "245332",
"Score": "2",
"body": "I was tempted to post a answer solely to explain that 3 and 5 are primes, and that you can check for 15 rather than 3 and 5 individually."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-25T10:01:55.103",
"Id": "248449",
"Score": "0",
"body": "And why is yield a better solution? Please explain so that the OP can learn from your thought process, instead of just saying \"Here's how I would do\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-07T14:13:36.030",
"Id": "332168",
"Score": "0",
"body": "Actually, you can do yeild only once, also you dont need to get remainder by 15. look \n\n\ndef fizzbuzz(count, step):\n for num in range(1, count, step):\n output = \"\"\n if not num % 3:\n output += \"fizz\"\n if not num % 5:\n output += \"buzz\"\n yield (output if output else str(num))\n\n\nprint(', '.join(fizzbuzz(count=100, step=2)))"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-09T12:45:13.367",
"Id": "131528",
"ParentId": "763",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "768",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-13T22:06:54.343",
"Id": "763",
"Score": "14",
"Tags": [
"python",
"comparative-review",
"fizzbuzz"
],
"Title": "Two FizzBuzz solutions"
} | 763 |
<p>Often I generate long lines of code such as the following...</p>
<pre><code>shippedItems.AddRange(OrderItem.Fetch(market: this.MARKET, shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE, orderPlacedAfter: serverTime.AddDays(-7), orderPlacedBefore: serverTime.AddHours(-85)));
</code></pre>
<p>... which adds the results of a method call to an existing list.</p>
<p>Adding white space to this line could improve readability. At one point in time or another have rationalized almost every possible behavior between:</p>
<ul>
<li>Leave everything on a single line and let the editor wrap where it feels is best.</li>
<li>Put even shippedItems.AddRange( on a line by itself.</li>
</ul>
<p>While over time I feel that the clarity and readability of the code that I write has improved -- and lets hope for reasons other then white space -- I have never come to peace with how to break long lines.</p>
<p>I will up vote any answer that does NOT include as the solution:</p>
<ul>
<li>shorter variable names.</li>
<li>disregarding named parameters (at least for this example).</li>
<li>creation of variables only used once.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T18:37:43.197",
"Id": "1428",
"Score": "2",
"body": "There's nothing wrong with creating a variable that is only used once. Sometimes, the required indentation is just too much."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T21:14:32.970",
"Id": "1601",
"Score": "0",
"body": "I am curious as to why you would not use a Pretty Print preprocessor to do this for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-17T05:03:35.193",
"Id": "24007",
"Score": "0",
"body": "What would StyleCop do?"
}
] | [
{
"body": "<p>I would break it up something like this:</p>\n\n<pre><code>shippedItems.AddRange(\n OrderItem.Fetch(market: this.MARKET,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85)));\n</code></pre>\n\n<p>Depending on previous indentation, some lines might flow over the \"max line length\", but I think that characters per line is more of a suggestion and there are good times to break that rule because breaking it leads to code that is more readable than code that doesn't.</p>\n\n<p>Rules that I find helpful:</p>\n\n<ul>\n<li>New line after an open paren.</li>\n<li>Line breaks after commas.</li>\n<li>Indent the inner method calls.</li>\n<li>Line up parameters to a method that are on new lines.</li>\n<li>Break \"max line length\" rules if it means the code is more readable.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T15:13:12.037",
"Id": "1637",
"Score": "0",
"body": "Top of the pile after 1 week. Accepted on the basis of most preferred."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T15:44:55.860",
"Id": "773",
"ParentId": "772",
"Score": "22"
}
},
{
"body": "<p>As a follow up to @Thomas Owens, another rule I personally like to follow is:</p>\n\n<ul>\n<li>Either put all parameters for a method on the same line, or put each parameter on its own line.</li>\n</ul>\n\n<p>So I would write the code as follows. I like this because it makes reading the parameters more consistent, and doesn't indent them quite as far.</p>\n\n<pre><code>shippedItems.AddRange(\n OrderItem.Fetch(\n market: this.MARKET,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85)));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:18:11.710",
"Id": "1423",
"Score": "0",
"body": "I sometimes do this, myself. I suppose it depends on how many parameters I have and how long each one is."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:40:23.173",
"Id": "1426",
"Score": "0",
"body": "I think this works well with named parameters, but without readability breaks down when a parameter is another function call."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T06:37:46.487",
"Id": "1434",
"Score": "2",
"body": "+1 as I find it annoying to have to fix the leading whitespace after a rename/refactor to keep things lined up. I might put `OrderItem.Fetch(` on the line above for compactness, and I put the ending `));` on its own line, outdented from the parameters (indented only one tab stop)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T19:42:53.393",
"Id": "1452",
"Score": "0",
"body": "This is definitely my preferred way of writing that kind of code"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:09:08.317",
"Id": "774",
"ParentId": "772",
"Score": "12"
}
},
{
"body": "<p>This is what I would do:</p>\n\n<pre><code>shippedItems.AddRange(\n OrderItem.Fetch(market: this.MARKET,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85))\n);\n</code></pre>\n\n<p>I feel that just as with brackets (<code>{}</code>) the closing parenthesis should be on its own line when a method call spans multiple lines. It seems more consistent to me.</p>\n\n<p>Alternatively, you could line up the <code>:</code>'s:</p>\n\n<pre><code>market: this.MARKET,\nshipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE\n</code></pre>\n\n<p>but that it difficult to maintain.</p>\n\n<p>Another option:</p>\n\n<pre><code>shippedItems.AddRange(OrderItem.Fetch(market: this.MARKET,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85)));\n</code></pre>\n\n<p>That uses fewer <em>lines</em>, but is longer horizontally. Also, at first glance it looks like the arguments are to <code>AddRange</code>, not <code>Fetch</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:15:16.440",
"Id": "1421",
"Score": "0",
"body": "I have been a fan in the past of the trailing ); as it makes a nice distinct \"block\" of code. But, I gave it up because I was ending up with multiple lines in a row of ) and }. For now, indent level is enough for me."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:16:02.930",
"Id": "1422",
"Score": "0",
"body": "Also, if you were willing to give AddRange its own level of ); why not a ) on a single line for Fetch?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:19:42.110",
"Id": "1424",
"Score": "0",
"body": "@jphofmann: It's a matter of style, really. My reasoning for placing `OrderItem.Fetch` on a new line was to prevent readers from thnking that the arguments were to `AddRange`. That does not apply in `Fetch`'s case, so I left them on the same line."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:21:09.660",
"Id": "1425",
"Score": "0",
"body": "@jphofmann first comment: There are limits, obviously. However, I've found that many times if you have calls that go that long you really need to do some refactoring anyway."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:09:19.673",
"Id": "775",
"ParentId": "772",
"Score": "2"
}
},
{
"body": "<p>Interesting to see the range of responses. I would tend towards a different answer from any of those so far:</p>\n\n<pre><code>shippedItems.AddRange(OrderItem.Fetch(\n market: this.MARKET,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85)\n));\n</code></pre>\n\n<p>This to me reads more intuitively as \"add the fetched order items to shippedItems, using the following block of arguments to fetch\".</p>\n\n<p>One piece of advice from someone who has been through the same dilemma for a while now: don't try to put rules on it. Take each example on its own merit and try to write it in the way that you would want it to be written if you were someone else trying to figure out what it does.</p>\n\n<p><strong>Sometimes</strong> it is a good idea to have a use-once variable to make something more readable. For example, if AddRange above had a second argument, where would you put it? Even this simple case reads badly</p>\n\n<pre><code>shippedItems.AddRange(\n OrderItem.Fetch(\n market: this.MARKET,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85)\n ),\n 2\n);\n</code></pre>\n\n<p>However, this reads just fine</p>\n\n<pre><code>var orderItems = OrderItem.Fetch(\n market: this.MARKET,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85)\n);\nshippedItems.AddRange(orderItems, 2);\n</code></pre>\n\n<p>Each case on its own merit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-26T00:47:59.993",
"Id": "110776",
"Score": "0",
"body": "+1, I use the One-True-Brace style [(1TBS)](http://en.wikipedia.org/wiki/1TBS#Variant:_1TBS), so all the answers where the closing parenthesis and semicolon are indented make me cringe. Can't match the semicolon with the opening of the statement to tell where the multi-line statement ends. This looks much better. That being said, the 2nd example with 2 as a second parameter looks fine to me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T00:24:42.460",
"Id": "785",
"ParentId": "772",
"Score": "8"
}
},
{
"body": "<p>This may be a sign you need to factor out the Fetch into a new method:</p>\n\n<pre><code>....\nshippedItems.AddRange( LastWeeksMarketItems() );\n....\n\nprivate OrderItems LastWeeksMarketItems ()\n{\n return OrderItem.Fetch(market: this.MARKET, \n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE, \n orderPlacedAfter: serverTime.AddDays(-7), \n orderPlacedBefore: serverTime.AddHours(-85));\n}\n</code></pre>\n\n<p>The method name gives you further clarity about what it is you are trying to add.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T21:32:15.060",
"Id": "1513",
"Score": "0",
"body": "For me, this just abstracts away what is actually being added to shippedItems. Also, this ends up defining in two places, to varying degrees, what items are being added. In the method name as \"last weeks\" and in the parameters being passed into fetch."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T21:56:20.133",
"Id": "1514",
"Score": "0",
"body": "It depends on the usage to determine how useful it is. Think of it like a drill down. If you are adding last weeks in one place, last months in another and last years in another then you can quickly see which is being achieved."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T21:56:57.497",
"Id": "1515",
"Score": "0",
"body": "Also if you add last weeks items in several places, this of course keeps the logic in one place."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T21:57:58.353",
"Id": "1516",
"Score": "0",
"body": "If you are adding arbitrary times in just this place, then it probably isn't so useful.."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T10:39:38.513",
"Id": "1632",
"Score": "0",
"body": "+1. +50 if I could. Abstraction is what it's all about, and you identified a very useful abstraction here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-26T00:51:19.947",
"Id": "110777",
"Score": "0",
"body": "-1 If I could, but I just opened this account. This doesn't seem to address the question of formatting a multi-line statement. You still have a multi-line statement in your new method. Is your whole answer just the example of formatted code? If it is, then it's identical to the accepted answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-26T07:42:09.557",
"Id": "110792",
"Score": "0",
"body": "@DCShannon the reason it is difficult to come up with an intuitive way to format that statement is because it is trying to do too many things all at once. By splitting it out so each line only does one thing the formatting becomes obvious. It also becomes easier to read."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T16:23:34.163",
"Id": "807",
"ParentId": "772",
"Score": "3"
}
},
{
"body": "<p>I think you are unwise to reject creation of variable used only once. The forced line breaks you seem to be requesting are difficult if not impossible to implement in an aesthetically satisfactory way in an automated formatter - and if you're not using an automated formatter, you're wasting time.</p>\n\n<pre><code>var state = ORDERITEMSHIPCONFIRMSTATE.NONE;\nvar start = serverTime.AddDays(-7);\nvar end = serverTime.AddHours(-85);\nvar range = OrderItem.Fetch(market: MARKET, shipConfirmState: state, orderPlacedAfter: start, orderPlacedBefore: end);\nshippedItems.AddRange(range);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T14:58:56.633",
"Id": "1596",
"Score": "0",
"body": "What automated formatter would you suggest?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T16:04:09.533",
"Id": "1598",
"Score": "0",
"body": "I'm afraid I'm from the Java world, not .net; I don't know what's available there, although I would hope Visual Studio would offer something like Eclipse's options for code formatting. If not, there must be some tool that will do the job."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T15:25:49.970",
"Id": "854",
"ParentId": "772",
"Score": "0"
}
},
{
"body": "<p>I really like <a href=\"https://codereview.stackexchange.com/questions/772/how-to-break-up-long-lines-of-code-example-line-results-of-method-call-added-t/807#807\">Mongus Pong's answer</a>, but I have a couple of things to add.</p>\n\n<ul>\n<li>The name of the extracted method should reflect the actual meaning of the <em><a href=\"https://stackoverflow.com/q/47882/11808\">magic numbers</a></em> (-7 and -85) inside the method.</li>\n<li>The magic numbers themselves should probably be turned into named constants, for added clarity.</li>\n<li>The extracted method should be put where it belongs. I would suggest using the <a href=\"http://martinfowler.com/eaaCatalog/repository.html\" rel=\"nofollow noreferrer\">repository pattern</a>, but in this specific case it would probably be a good idea to put it next to the <code>Fetch</code> method, inside the <code>OrderItem</code> class. (The <code>OrderItem</code> class looks like a domain entity to me, so this would break <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a>, but I digress.)</li>\n<li>If all usages of <code>Fetch</code> could be replaced by methods like this, <code>Fetch</code> could eventually be made non-public.</li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>shippedItems.AddRange(OrderItem.FetchLastWeeksOrderItems(MARKET, serverTime));\n\npublic class OrderItem\n{\n public static IEnumerable<OrderItem> FetchLastWeeksOrderItems(\n string market, DateTime serverTime)\n {\n return OrderItem.Fetch(\n market: market,\n shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,\n orderPlacedAfter: serverTime.AddDays(-7),\n orderPlacedBefore: serverTime.AddHours(-85));\n }\n\n private static IEnumerable<OrderItem> Fetch( ... )\n {\n ...\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T11:22:36.933",
"Id": "896",
"ParentId": "772",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "773",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T15:41:32.040",
"Id": "772",
"Score": "9",
"Tags": [
"c#"
],
"Title": "How to break up long lines of code. (Example Line: Results of method call added to list.)"
} | 772 |
<p>I've created and I manage a point of sale web application built in PHP which has thus far followed no clear guidelines or methodology for development; it's operation is completely procedural. In turn, because the department that's using it requests new and different features like it's a Las Vegas buffet, the software has become a mess which I'm terrified of (don't look it in the eyes). Thankfully, I'm the only developer and so no one else must feel the wrath of the beast I've created.</p>
<p>I've always had a hard time wrapping my head around OOP, but I think I'm finally beginning to understand the whole point behind encapsulating methods, protecting fields, and class inheritance. This brings me to my question: Given the object scheme posted below, am I doing this right? It works like it should and doesn't return any errors, but in terms of object design, I feel like a baby deer with wobbly legs, uncertain of the world around me.</p>
<p>To be a little more specific, should I have a separate class that encapsulates MySQL parameters - and where should it be included/inherited if many child classes, perhaps even on separate server requests, will need it?</p>
<p>Should these two classes be one? I thought to separate them for sake of file length - Is excessive file size a good indicator of when a class might need to be broken up?</p>
<p>Abstract, private, protected - I understand how this works in literal behavior, but in regard to use, I'm just swinging in the dark. Anyone care to shed a light on what I've done and whether it makes sense? I think that is the summation of my fears and concerns. Here is the code in question - Your replies will help guide my redesign/refactoring of everything I've spent the last 6 months on.</p>
<p>filterReports.class.php</p>
<pre><code>date_default_timezone_set('America/Chicago'); // For use by 'date()' and 'strtotime()'
/*
* First, we will create our appropriate file names for the dates in question,
* then we will determine if today is a day to run said reports. If today is in fact
* a fine day to create a report, we should then check to see if the desired
* report has already been created. If it has not, we will create and save it.
*/
abstract class filterReports
{
protected $reportFilenames = array(); // Store all file names in array, because it's fun
protected $reportDirs = array(
'daily-orders' => 'reports/daily/orders/',
'weekly-orders' => 'reports/weekly/orders/',
'monthly-orders' => 'reports/monthly/orders/',
'daily-volume' => 'reports/daily/volume/',
'weekly-volume' => 'reports/weekly/volume/',
'monthly-volume' => 'reports/monthly/volume/',
); // Folders where we plan to store these reports
protected function createFilenames()
{
// Comprehensive Order Data
$this->reportFilenames['daily-orders'] = 'store-report-'
. date('Ymd', strtotime('-1 day'))
. '.csv'; // Yesterday's Report
$this->reportFilenames['weekly-orders'] = 'store-report-'
. date('Ymd', strtotime('-8 days'))
. '-'
. date('Ymd', strtotime('-1 day'))
. '.csv'; // Last 7 Days
$this->reportFilenames['monthly-orders'] = 'store-report-'
. date('Ymd', strtotime('first day of last month'))
. '-'
. date('Ymd', strtotime('last day of last month'))
. '.csv'; // Last Month
// General Product Volume Data
$this->reportFilenames['daily-volume'] = 'store-volume-'
. date('Ymd', strtotime('-1 day'))
. '.csv'; // Yesterday's Report
$this->reportFilenames['weekly-volume'] = 'store-volume-'
. date('Ymd', strtotime('-8 days'))
. '-'
. date('Ymd', strtotime('-1 day'))
. '.csv'; // Last 7 Days
$this->reportFilenames['monthly-volume'] = 'store-volume-'
. date('Ymd', strtotime('first day of last month'))
. '-'
. date('Ymd', strtotime('last day of last month'))
. '.csv'; // Last Month
}
protected $reportsToCreate = array(); // Based on what day it is, a different report may need to be created
protected function chooseReports()
{
$this->reportsToCreate['daily-orders'] = TRUE; // Because 'every day' occurs every day.
$this->reportsToCreate['daily-volume'] = TRUE;
if (date('N', time()) == '1') { // If today is Monday, create weekly report
$this->reportsToCreate['weekly-orders'] = TRUE;
$this->reportsToCreate['weekly-volume'] = TRUE;
} else {
$this->reportsToCreate['weekly-orders'] = FALSE;
$this->reportsToCreate['weekly-volume'] = FALSE;
}
if (date('j', time()) == '1') { // If today is the first day of the month, create monthly report
$this->reportsToCreate['monthly-orders'] = TRUE;
$this->reportsToCreate['monthly-volume'] = TRUE;
} else {
$this->reportsToCreate['monthly-orders'] = FALSE;
$this->reportsToCreate['monthly-volume'] = FALSE;
}
}
protected $reportsExist = array(); // Now let's see which reports have already been created
protected function searchReports()
{
foreach ($this->reportsToCreate as $key => $val) {
if ($val != FALSE) {
if (!file_exists($this->reportDirs[$key] . $this->reportFilenames[$key])) {
$this->reportsExist[$key] = FALSE;
} else {
$this->reportsExist[$key] = TRUE;
}
}
}
}
}
</code></pre>
<p>manageReports.class.php</p>
<pre><code>include('filterReports.class.php');
/*
* As an extension of the previous class 'filterReports', if a desired report has
* not been found, we will create and save it.
*/
class manageReports extends filterReports
{
public $newReport;
private $dbConfig = array();
private $con;
private function dbParams() // This should all probably go somewhere else, but I haven't decided where just yet
{
$this->dbConfig = array(
'host' => 'hostname',
'user' => 'username',
'pass' => 'password',
'name' => 'database',
);
$this->con = mysql_connect(
$this->dbConfig['host'],
$this->dbConfig['user'],
$this->dbConfig['pass']
) or die('MySQL Error: ' . mysql_errno() . ' - ' . mysql_error());
}
private function createDailyOrdersReport() // Collect data and build the report body
{
// Do things to create $dataHeading and $dataContent strings
$this->newReport = $dataHeading . $dataContent;
}
private function createDailyVolumeReport()
{
$this->newReport = $dataHeading . $dataContent;
}
private function createWeeklyOrdersReport()
{
$this->newReport = $dataHeading . $dataContent;
}
private function createWeeklyVolumeReport()
{
$this->newReport = $dataHeading . $dataContent;
}
private function createMonthlyOrdersReport()
{
$this->newReport = $dataHeading . $dataContent;
}
private function createMonthlyVolumeReport()
{
$this->newReport = $dataHeading . $dataContent;
}
private function writeReport($key)
{
// Save the report to its appropriate folder
$writeReportName = $this->reportDirs[$key] . $this->reportFilenames[$key]; // I don't know why this works, seems to me to be out of scope for these array fields
$writeReportOpen = fopen($writeReportName, 'w');
fwrite($writeReportOpen, $this->newReport) or die('Unable to write file: ' . $writeReportName);
fclose($writeReportOpen);
}
public function createReports() // Finally, resolve which reports should be created - then create them.
{
parent::createFilenames(); // Create the report file names
parent::chooseReports(); // Decide whether a report should be run
parent::searchReports(); // Find out if the report exists already
foreach ($this->reportsExist as $key => $val) { // Any reports that should be created today, T or F for 'exists'
if ($val != TRUE) {
if ($key = 'daily-orders') {
$this->createDailyOrdersReport();
$this->writeReport($key);
}
if ($key = 'daily-volume') {
$this->createDailyVolumeReport();
$this->writeReport($key);
}
if ($key = 'weekly-orders') {
$this->createWeeklyOrdersReport();
$this->writeReport($key);
}
if ($key = 'weekly-volume') {
$this->createWeeklyVolumeReport();
$this->writeReport($key);
}
if ($key = 'monthly-orders') {
$this->createMonthlyOrdersReport();
$this->writeReport($key);
}
if ($key = 'monthly-volume') {
$this->createMonthlyVolumeReport();
$this->writeReport($key);
}
}
}
}
}
</code></pre>
<p>Finally, I do this to make it go.</p>
<pre><code>include('manageReports.class.php');
$initReports = new manageReports;
$initReports->createReports();
</code></pre>
<p>I preemptively appreciate any and all assistance you can provide as it will undoubtedly make me less bogus of a web developer.</p>
<p><strong>EDIT:</strong> Another question I just thought of in after-thought; Should I even bother declaring my fields and methods in <code>filterReports</code> as <code>protected</code>, seeing as though this class cannot be instantiated in the first place?</p>
<p><strong>EDIT:</strong> I have made some revisions to my code based on responses. For now, forget about the above two classes - Here is my new code. The first class instantiates each of my report generating sub-classes and executes a public function contained in each of them. The second class is a single report generation class.</p>
<p>manageReports.class.php</p>
<pre><code>include('store/library/reports/dailyOrdersReport.class.php');
/*
* Having included the desired reporting classes,
* we now need a uniform process for access and
* execution of these classes.
*/
class manageReports
{
private $reports = array();
public function __construct()
{
$this->createReports();
}
private function createReports()
{
$this->createReport('dailyOrdersReport');
}
private function createReport($class)
{
$this->reports[] = new $class;
}
public function go()
{
foreach ($this->reports as $report) {
$report->execReport();
}
}
}
</code></pre>
<p>dailyOrdersReport.class.php</p>
<pre><code>include('store/library/dbConfig.class.php'); // May need these parameters for dependent methods
/*
* Validates the need for specified report creation,
* and if true - does so.
*/
class dailyOrdersReport extends dbConfig
{
private $newReport; // Variable to store report data
private $reportPath;
private $reportName;
private $reportTestResult = FALSE;
public function __construct() // Preprocess validation answers, "Should we create this report?"
{
parent::__construct(); // MySQL Parameters
$this->reportPath = 'store/reports/daily/orders/';
$this->reportName = 'store-orders_'
. date('Ymd', strtotime('-1 day'))
. '.csv';
$this->reportTest();
}
private function reportTest() // We don't need to test against the date for this report, just if it's already been created
{
if (!file_exists($this->reportPath . $this->reportName)) {
$this->reportTestResult = TRUE;
} else {
return;
}
}
private function createReport()
{
// About 100 lines of csv report generating madness
$this->newReport = $dataHeading . $dataContent;
}
private function writeReport()
{
// Save the report to its appropriate folder
$writeReportName = $this->reportPath . $this->reportName;
$writeReportOpen = fopen($writeReportName, 'w');
fwrite($writeReportOpen, $this->newReport) or die('Unable to write file: ' . $writeReportName);
fclose($writeReportOpen);
}
public function execReport()
{
if ($this->reportTestResult) { // Evaluates to 'true' if report aught be generated and saved to file
$this->createReport();
$this->writeReport();
} else {
return;
}
}
}
</code></pre>
<p>Once again, the trigger.</p>
<pre><code>error_reporting(E_ALL);
date_default_timezone_set('America/Chicago'); // For use by 'date()' and 'strtotime()'
include('store/library/manageReports.class.php');
$manageReports = new manageReports;
$manageReports->go();
</code></pre>
<p>Is this perfect yet, or are there still miles to go before I sleep?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-27T04:02:54.270",
"Id": "1829",
"Score": "1",
"body": "Just a style thing, but it seems really weird having verbs for class names. Classes describe objects, which are inherently \"things\" (ie: nouns)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-28T13:04:43.993",
"Id": "1853",
"Score": "0",
"body": "So in effect, it would be more appropriate style to call `manageReports` -> `ReportsManager` and `filterReports` -> `ReportsFilter`? Good to know, and a helpful tool to stay in an _objects_ mindset."
}
] | [
{
"body": "<p>The first comment is that you have six functions in <code>manageReports</code> which are identical, which each call a seventh one, <code>createReports</code>. While I understand that you mean to have logical function naming, given that you have all the logic as to when each program should be made located in the <code>chooseReports</code> and <code>createReports</code> function, you might as well leave off all the unnecessary ones.</p>\n\n<p>For a more general answer, it doesn't seem like these two classes need to be separate. Class length isn't the main thing to consider here; you want to group things intelligently. Broadly speaking, you subclass only when you're making a more specific instance of the superclass. In your case, if you find that different types of reports require different functionality, could subclass different types of reports.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T19:23:45.453",
"Id": "1429",
"Score": "0",
"body": "`createDailyOrdersReport()` and `createDailyVolumeReport()`, etc... will contain different behavior (I just left out that behavior for sake of brevity). Should this class be rewritten to exclude the actual report creation, bringing that functionality into a subclass? If so, I think I would have to duplicate the decision/execution logic before instantiation."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T19:40:40.650",
"Id": "1430",
"Score": "0",
"body": "I would venture that this depends on the complexity of the \"different behavior\". If its just a few small changes, then go ahead and put each in its own function. If each is drastically different, I would combine the two current classes into the base class, and subclass each report type."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T20:19:17.700",
"Id": "1431",
"Score": "0",
"body": "Granted, it's the longest of the functions, but `createDailyOrdersReport()` is 147 lines. If I wanted to place this function in a `createDailyOrdersReport` class and combine the above classes into one, how would I go about extending/strapping my new class to the other?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T19:14:57.893",
"Id": "781",
"ParentId": "776",
"Score": "1"
}
},
{
"body": "<p>When I see a bunch of repeated <code>if</code> tests of a value against several constants, I think \"make these classes.\" You have a <code>Report</code> base class screaming to get out with one subclass per report type. If you think of each report in a general way, you'll start to see what operations it needs to support:</p>\n\n<ul>\n<li>Decide if it should be run given the date</li>\n<li>Check if it exists on disk</li>\n<li>Generate its file name and title</li>\n<li>Extract the data from MySQL into a text block</li>\n<li>Write itself to disk</li>\n</ul>\n\n<p>Here are the above requirements in an abstract base class, one designed to be extended by subclasses to fill out the specifics.</p>\n\n<pre><code>abstract class AbstractReport {\n private $directory;\n private $date;\n\n public function __construct($directory, $date) {\n $this->directory = 'reports/' . $directory;\n $this->date = $date;\n }\n\n public abstract function getTitle() ;\n public abstract function getFileName() ;\n public abstract function isNeeded() ;\n\n public function hasBeenRun() {\n return file_exists($this->key . $this->getFileName();\n }\n\n public function runIfNeeded() {\n if ($this->isNeeded() && !$this->hasBeenRun()) {\n $this->run();\n }\n }\n\n public function run() {\n $this->connectToDatabase();\n file_put_contents($this->getTitle(), $this->buildReport());\n }\n\n protected function connectToDatabase() {\n // ... mysql_connect() ...\n }\n\n protected abstract function buildReport() ;\n\n protected function formatDate($offset, $format='Ymd') {\n return date($format, strtotime($offset, $this->date));\n}\n</code></pre>\n\n<p>Here is an example subclass for one of the reports.</p>\n\n<pre><code>class DailyOrdersReport extends AbstractReport {\n public function __construct($date) {\n parent::__construct('daily/orders/', $date);\n }\n\n public function getTitle() {\n return 'Daily Orders';\n }\n\n public function getFileName() {\n return 'store-report-' . $this->formatDate('-1 day');\n }\n\n public function isNeeded() {\n return true; // or use $this->date to make determination\n }\n\n protected abstract function buildReport() {\n // ... pull data from database and return formatted text ...\n }\n}\n</code></pre>\n\n<p>Hopefully this gives you a start on some OOness. :) I highly recommend the book Clean Code as it's a great help as you work to answer these questions for yourself.</p>\n\n<p><strong>Edit</strong> As you write the report classes, you may find that all orders reports share some functionality in common that volume reports don't and vice versa. If it's significant you may want to create more abstract classes <code>AbstractOrdersReport</code> and <code>AbstractVolumeReport</code>. If the only difference between the time frames is the dates passed to the database queries, you could gain a lot from this.</p>\n\n<p>Of course what's missing now is a way to run the reports! The following is more procedural than OO, but it could be driven by a file or something similar.</p>\n\n<pre><code>class ReportManager {\n private $reports = array();\n\n public function __construct($date) {\n $this->date = $date;\n $this->createReports();\n }\n\n public function createReports() {\n // could read these from disk or a table\n $this->createReport('DailyOrders');\n $this->createReport('DailyVolume');\n $this->createReport('WeeklyOrders');\n $this->createReport('WeeklyVolumn');\n $this->createReport('MonthlyOrders');\n $this->createReport('MonthlyVolumn');\n }\n\n protected function createReport($class) {\n $this->reports[] = new $class($this->date);\n }\n\n public function runIfNeeded() {\n foreach ($this->reports as $report) {\n $report->runIfNeeded();\n }\n }\n\n public function run() {\n foreach ($this->reports as $report) {\n $report->run();\n }\n }\n}\n\n// ... and to kick it off ...\n\n$date = time();\n$manager = new ReportManager();\n$manager->runIfNeeded();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T21:07:54.287",
"Id": "1455",
"Score": "0",
"body": "+1 for pointing out my clear \"area for improvement\": Finding Objects. To verify I understand a few of your concepts, in createReport() you are creating an object for each report, then storing these in an array while the \"what day is today/should this report be generated\" logic is stored in each report class. When I created this thread, I had identified \"automated report creation\" as an object. Clearly from your response, this is too broad. What are the signs of an appropriately responsible class? What's too much or too little?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T21:08:45.690",
"Id": "1456",
"Score": "0",
"body": "Also, regarding protection - As a rule of thumb, should every field or method begin as private to then have restrictions loosened as the need arises? This question is more or less on common convention as I'm sure literal behavior changes from language to language. PS. I've edited my classes to reflect your suggested changes and posted them above."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T21:41:23.140",
"Id": "1458",
"Score": "0",
"body": "@65Fbef05 - Deciding class responsibilities takes practice, and often the classes tend to be abstract concepts like \"a regularly-run report\" that need subclasses to make them complete such as \"a weekly volume report\" and finally instances to make them useful such as \"the weekly volume report for January 12th, 2011\". One goal I try to follow is for each class to have a single major responsibility. Here `AbstractReport` is tasked with two: generate a report and manage its storage on disk. In this case I think it's okay, and you could always split them apart later."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T21:43:44.213",
"Id": "1459",
"Score": "0",
"body": "As for access level, any public method/property becomes part of the external contract (API) that client classes will use and becomes difficult to change over time. If you start with private, there are no external dependencies to fix if you need to change it or elevate it to public status. The same is true of protected with subclasses."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T21:55:39.517",
"Id": "1460",
"Score": "1",
"body": "I've just started reading 'Object Design: Roles, Responsibilities and Collaborations' - From reading the forward, the ability to define responsibility clearly seems to be an important skill to develop."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T05:56:19.753",
"Id": "787",
"ParentId": "776",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "787",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-14T16:55:21.320",
"Id": "776",
"Score": "10",
"Tags": [
"php",
"mysql",
"classes",
"object-oriented"
],
"Title": "Object Paradigm for PHP, Practice in Design"
} | 776 |
<p><a href="http://stackoverflow.com/tags/c%2b%2b/info">From the C++ tag wiki on Stack Overflow</a>:</p>
<h3>What is C++?</h3>
<p><a href="http://en.wikipedia.org/wiki/C++" rel="nofollow noreferrer">C++</a> is a statically-typed, free-form, (usually) compiled, multi-paradigm, intermediate-level, general-purpose programming language not to be confused with C. It was developed in the early 1980's by Bjarne Stroustrup as a set of extensions to the C programming language. Building on C, C++ improved type-safety and added support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.</p>
<h3>New to C++?</h3>
<p>Whether you are new to programming or are coming to C++ from another programming language, it is highly recommended to have a good book from which to learn the language. Stack Overflow keeps a detailed <a href="http://stackoverflow.com/q/388242">list of books</a>.</p>
<p>If you are looking for a good compiler, <a href="http://gcc.gnu.org/" rel="nofollow noreferrer">g++</a> is the most commonly used compiler on Linux and other platforms, <a href="http://clang.llvm.org/" rel="nofollow noreferrer">clang</a> is the official compiler on Mac and FreeBSD, and Microsoft <a href="http://msdn.microsoft.com/en-us/vstudio/hh386302" rel="nofollow noreferrer">Visual C++</a> is the most commonly used on Windows.</p>
<hr>
<h3>Online compilers</h3>
<ul>
<li><a href="http://coliru.stacked-crooked.com/" rel="nofollow noreferrer">Coliru</a></li>
<li><a href="https://wandbox.org/" rel="nofollow noreferrer">Wandbox</a></li>
<li><a href="http://ideone.com/" rel="nofollow noreferrer">IdeOne</a></li>
<li><a href="http://codepad.org/" rel="nofollow noreferrer">CodePad</a></li>
<li><a href="http://rextester.com/runcode" rel="nofollow noreferrer">rextester</a> (Can also compile with MSVC)</li>
<li><a href="http://ellcc.org/demo/" rel="nofollow noreferrer">ELLCC</a> (LLVM and more, can output assembly)</li>
</ul>
<h3>Other online tools</h3>
<ul>
<li><a href="https://godbolt.org/" rel="nofollow noreferrer">Godbolt Compiler Explorer</a> (compare machine code from a variety of compilers)</li>
<li><a href="http://quick-bench.com/" rel="nofollow noreferrer">Quick-bench</a> (benchmark C++ code using <a href="https://github.com/google/benchmark" rel="nofollow noreferrer">Google Benchmark</a>)</li>
</ul>
<h3>FAQs</h3>
<ul>
<li><a href="http://www.parashift.com/c++-faq-lite/" rel="nofollow noreferrer">C++ FAQ</a>: formerly C++ FAQ Lite</li>
<li><a href="http://womble.decadent.org.uk/c++/template-faq.html" rel="nofollow noreferrer">C++ Templates FAQ</a></li>
<li><a href="http://www.stroustrup.com/bs_faq2.html" rel="nofollow noreferrer">Bjarne Stroustrup's C++ Style and Technique FAQ</a></li>
</ul>
<h3>Other Resources</h3>
<ul>
<li><a href="https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md" rel="nofollow noreferrer">C++ Core Guidelines</a> - a semi-official project collecting many guidelines for coding practice, headed by Bjarne Stroustrup and Herb Sutter, but contributed to by many. Under active "development" as of 2017 (hence it's on GitHub).</li>
<li><a href="http://www.isocpp.org/" rel="nofollow noreferrer">ISO C++ website</a></li>
<li><a href="http://en.cppreference.com/w/cpp" rel="nofollow noreferrer">C++ Reference</a></li>
<li><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/" rel="nofollow noreferrer">ISO's C++ Standards Committee's Papers</a></li>
<li><a href="http://www.gotw.ca/gotw/" rel="nofollow noreferrer">Guru of the Week</a>: article series on high-quality, exception-safe C++ code</li>
<li><a href="http://herbsutter.com/gotw/" rel="nofollow noreferrer">Revised Guru of the Week (for C++14)</a></li>
<li>SGI's <a href="http://www.sgi.com/tech/stl/" rel="nofollow noreferrer">Standard Template Library Programmer's Guide</a></li>
<li><a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms" rel="nofollow noreferrer">More C++ Idioms</a></li>
<li><a href="http://www.boost.org/" rel="nofollow noreferrer">Boost C++ Libraries</a></li>
<li><a href="http://stackoverflow.com/q/81656/54262">Where do I find the current C or C++ standard documents?</a></li>
</ul>
<hr>
<h3>Code Review Snippets</h3>
<p>As an experiment I am starting to collect snippets of common Code Review things that happen repeatedly here: <a href="https://github.com/Loki-Astari/CodeReview" rel="nofollow noreferrer">Code Review</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-14T19:00:02.587",
"Id": "779",
"Score": "0",
"Tags": null,
"Title": null
} | 779 |
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. This tag should be used for any question which requires knowledge or expertise with the C++ programming language. This is a general tag which is used for any of the C++ language standards (C++98, C++11, C++17, etc.). The question should identify the compiler being used, the operating system, and which of the C++ standards is being targeted.
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-14T19:00:02.587",
"Id": "780",
"Score": "0",
"Tags": null,
"Title": null
} | 780 |
<p>I have a parser for CNF formulas in <a href="http://logic.pdmi.ras.ru/~basolver/dimacs.html" rel="nofollow">Dimacs format</a>, which is very slow. Any suggestion on how to improve its speed? I did some profiling and I might have to replace <code>Scanner</code>. Is there anything faster?</p>
<p>A possible input for the parser is:</p>
<blockquote>
<pre><code>c A sample .cnf file.
p cnf 3 2
1 -3 0
2 3 -1 0
</code></pre>
</blockquote>
<p>The code:</p>
<pre><code>/**
* Parses a stream for a CNF instance.
*
* @param source input stream
* @return read skeleton
* @throws ParseException if stream contains an invalid instance
*/
private static Skeleton parseStream(final InputStream source)
throws IOException, ParseException {
Scanner scanner = new Scanner(source);
// Skip comments
try {
String token = scanner.next();
while (token.equals("c")) {
scanner.nextLine();
token = scanner.next();
}
if (!token.equals("p")) {
throw new ParseException(
"Excepted 'p', but '" + token + "' was found");
}
} catch (NoSuchElementException e) {
throw new ParseException("Header not found");
}
// Reads header
int numVariables, numClauses;
try {
String cnf = scanner.next();
if (!cnf.equals("cnf")) {
throw new ParseException(
"Expected 'cnf', but '" + cnf + "' was found");
}
numVariables = scanner.nextInt();
numClauses = scanner.nextInt();
} catch (NoSuchElementException e) {
throw new ParseException("Incomplete header");
}
logger.debug("p cnf " + numVariables + " " + numClauses);
// Reads clauses
Skeleton skeleton = new Skeleton(numVariables);
try {
while (numClauses > 0) {
int literal = scanner.nextInt();
skeleton.cnf.add(literal);
if (literal == 0) {
numClauses--;
}
}
} catch (NoSuchElementException e) {
throw new ParseException(
"Incomplete problem: " + numClauses + " clauses are missing");
}
return skeleton;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-08T19:26:57.903",
"Id": "3021",
"Score": "0",
"body": "Are you sure it's the parsing that is the bottleneck here? Simply reading data from disk is an expensive operation, so, it could be just that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-08T07:51:11.307",
"Id": "194284",
"Score": "0",
"body": "I suggest you to use [ANTLR](http://www.antlr.org/) to generate parsers. It also provides you with some useful operations. You can find all you need. When you don't want to just learn how to write a parser from scratch then you should not reinvent the wheel."
}
] | [
{
"body": "<p>Use a <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedInputStream.html\"><code>BufferedInputStream</code></a> to speed up the disk access. If that's not enough, you can read the file line-by-line and use <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29\"><code>split()</code></a> to break it into individual numbers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T21:20:55.577",
"Id": "1512",
"Score": "0",
"body": "Same exact suggestion I was going to give"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T07:29:39.263",
"Id": "788",
"ParentId": "784",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "788",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-15T00:04:18.437",
"Id": "784",
"Score": "7",
"Tags": [
"java",
"parsing"
],
"Title": "Parser for CNF formulas"
} | 784 |
<p>The following is like the Unix "tail" program. It was assigned as an exercise in Chapter 5 of Kernighan & Ritchie's <em>The C Programming Language</em>. Because I've only read through most of Chapter 5, I'm still unfamiliar with certain topics, such as malloc(), which may have been more appropriate to use, I don't know.</p>
<p>I've done a little bit of programming before, but not enough to consider myself very experienced, so any kind of advice is welcome. : )</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define DEFLINES 10
#define MAXBUFF 20000
int findTail(char *lines[][2], int nlines, char buff[], int maxbuff);
/* main() processes optional cli argument '-n', where n is a number of lines.
* The default is 10. findTail finds the last n lines from the input so that
* they can be printed. */
main(int argc, char *argv[])
{
int nlines; char *endptr;
endptr = NULL;
nlines = DEFLINES;
if (argc > 2) {
printf("error: too many arguments.\n");
return EXIT_FAILURE;
}
else if (argc == 2) {
if (*argv[1] == '-') {
nlines = strtol(argv[1] + 1, &endptr, 10);
if (*endptr != '\0') {
printf("error: not a number of lines: %s\n", argv[1] + 1);
return EXIT_FAILURE;
}
}
else {
printf("error: malformed argument: %s\n", argv[1]);
return EXIT_FAILURE;
}
}
int i;
char *lines[nlines][2], buff[MAXBUFF];
findTail(lines, nlines, buff, MAXBUFF);
for (i=0; i < nlines; ++i) {
if (lines[i][0] != NULL)
printf(lines[i][0]);
if (lines[i][1] != NULL)
printf(lines[i][1]);
}
}
#define TRUE 1
#define FALSE 0
void shift(char *lines[][2], int nlines);
void testForRoom(char *lines[][2], int index, char *buffp);
/* findTail stores characters from stdin in the buffer 'buff'. When it finds
* the end of a line, it stores the pointer for the beginning of that line in
* 'lines'. once nlines have been found, pointers to previous lines are shifted
* off of the end of 'lines'. If there is space at the start of 'buff' not
* pointed to by 'lines', then the end of a line that hits the end of the
* buffer can continue its storage at the beginning of the buffer. This makes
* the best use of a fixed-sized buffer for long input. */
int findTail(char *lines[][2], int nlines, char buff[], int maxbuff)
{
char *buffp, *linestart;
int i, c, wrap, nfound;
for (i=0; i < nlines; ++i) {
lines[i][0] = NULL; // [0] for storing line, or beginning of wrapped line
lines[i][1] = NULL; // [1] for storing second half of a wrapped line
}
nfound = 0;
wrap = FALSE;
linestart = buffp = buff;
while ((c=getchar()) != EOF) {
if (buffp == linestart && wrap == FALSE) {
if (nfound < nlines)
++nfound;
shift(lines, nlines);
}
if (buffp - buff == maxbuff - 1) {
*buffp = '\0';
lines[nlines - 1][0] = linestart;
wrap = TRUE;
linestart = buffp = buff;
}
testForRoom(lines, nlines - nfound, buffp);
*buffp++ = c;
if (c == '\n') {
*buffp++ = '\0';
lines[nlines - 1][wrap] = linestart;
wrap = FALSE;
if (buffp - buff >= maxbuff - 1)
buffp = buff;
linestart = buffp;
}
}
// this is in case the input ended without a newline.
if (c == EOF && buffp != buff && buffp[-1] != '\0') {
testForRoom(lines, nlines - nfound, buffp);
*buffp = '\0';
lines[nlines - 1][wrap] = linestart;
}
}
/* shift is used upon finding a character that starts a new line. It shifts
* line pointers in the pointer array to the left, making room for new line
* pointer(s) and forgetting the pointer(s) for the oldest line in memory. */
void shift(char *lines[][2], int nlines)
{
int i;
for (i=0; i < nlines - 1; ++i) {
lines[i][0] = lines[i + 1][0];
lines[i][1] = lines[i + 1][1];
}
lines[nlines - 1][0] = NULL;
lines[nlines - 1][1] = NULL;
}
/* testForRoom tests to see if the location for (or the location following the)
* next character that would be placed in the buffer is pointed to by a line in
* the lines pointer array. */
void testForRoom(char *lines[][2], int index, char *buffp) {
if (buffp == lines[index][0]
|| buffp + 1 == lines[index][0]) {
printf("error: not enough room in buffer.\n");
exit(EXIT_FAILURE);
}
}
</code></pre>
| [] | [
{
"body": "<p>Interesting design. Performance could probably be improved by allocating a couple of large buffers, and reading large blocks of input alternately into the two buffers until EOF is encountered. At that point, count backward through the two blocks until the proper number of newlines have been found, and then print everything from there to the end.</p>\n\n<p>If the input happens to be a disk file, one could seek to a spot near the end and count the number of newlines from that point on; if there aren't enough, seek back some distance and count the number of newlines between that point to the previous seek point. This would allow \"tail\" to operate efficiently even if the input is a multi-gigabyte disk file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T17:51:48.500",
"Id": "1447",
"Score": "0",
"body": "The standard streams are already buffered. Buffering manually is counter productive."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T17:58:42.087",
"Id": "1448",
"Score": "0",
"body": "@Martin: The standard **C** streams are already buffered? I knew iostream did buffering but I was not aware C did so..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T19:21:50.710",
"Id": "1450",
"Score": "0",
"body": "@Billy: At several layers. [Hardware/OS/C-Runtime](http://stackoverflow.com/questions/1450551/buffered-i-o-vs-unbuffered-io) and check [fflush](http://www.manpagez.com/man/3/fflush/)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T20:39:31.023",
"Id": "1453",
"Score": "0",
"body": "@Martin: Ah -- knew somewhat about the OS caching, but not in the CRT."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T20:49:05.530",
"Id": "1454",
"Score": "0",
"body": "@Martin York: The streams are typically buffered, but the purpose of allocating the buffers in my suggested approach wouldn't just be to improve I/O throughput, but rather to avoid the need to scan the input for newlines until an EOF is detected. I suppose if one were doing character-at-a-time reads, one could guarantee that one would have the last N bytes of a file using a single buffer of size N, but I would expect that even with CRT buffering it would be faster to use two buffers of size N and request N bytes at a time."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T23:22:57.630",
"Id": "1462",
"Score": "0",
"body": "I wrote one years ago that started by seeking something like 8K from the end of the file, and started searching from there. If it couldn't find enough lines, it read another (previous) 8K -- but I'm not sure that ever happened except on files I synthesized for testing. For most practical purposes, it always produced instant results, regardless of file size."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T00:23:02.657",
"Id": "1470",
"Score": "0",
"body": "I like the idea of reading the end of the input and backtracking if necessary. It does sound way more efficient. Unfortunately, I haven't gotten to the part of the book that describes how to do that yet, so I won't be implementing it at this point."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T15:42:30.493",
"Id": "1498",
"Score": "0",
"body": "@sudoman: If the tail command is reading from a file, it's possible to seek directly to a spot near the end. If it's reading from a pipe, that won't be possible and the best the program can do is grab data as fast as possible and throwing out all but the last portion of it. I think the real 'tail' command can accept a filename as input; I don't know whether it can use the fseek method if it receives input redirected from a file."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T15:45:34.157",
"Id": "1500",
"Score": "0",
"body": "@Jerry Coffin: Whether you're likely to need more than 8K will depend upon how many lines you want from the end of the file. If the program is supposed to be able to output something like the last 10,000 lines of a 5MB file, reading back further than 8K could easily be necessary."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T16:41:11.577",
"Id": "1505",
"Score": "0",
"body": "@Supercat: that's certainly true. I guess now that logfile parsing is much more common, people might even need tens of thousands of liens much more often. I suppose if it was really interesting, you could estimate something like a kilobyte per line (max) and work from there. I never did that, because as I said, no need ever arose..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T17:48:08.033",
"Id": "1535",
"Score": "0",
"body": "@Jerry Coffin: If the program is reading from a pipe, it's probably best to have an argument for the buffer size in bytes, since whoever is invoking the program may know more about the expected line length than the author of the utility. When reading from disk, the optimal strategy will depend upon the file size and type of file system, but reading 8K at a time isn't apt to be horrible. My inclination would probably be to search back in 64K chunks, but I wouldn't expect it to matter too much."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T17:22:05.100",
"Id": "791",
"ParentId": "790",
"Score": "3"
}
},
{
"body": "<p>You are using some C99 features, such as declaring variables part way through a block of code and VLAs, but not obeying some C99 constraints, such as ensuring that the <code>main()</code> function has an explicit return type of <code>int</code>.</p>\n\n<p>Because you're using C99, you are allowed to leave off the <code>return(0);</code> (or <code>return 0;</code>) from the end of <code>main()</code>. I think that was one of the less good decisions in C++ that was then echoed in C, and don't take that liberty myself; but I can't criticize your code when the standard allows it.</p>\n\n<p>It might be better to use <code>enum</code> instead of <code>#define</code> for the constants; <code>enum</code> makes debugging easier because the values are in the symbol table, whereas <code>#define</code> constants are typically not.</p>\n\n<pre><code>enum { DEFLINES = 10 };\nenum { MAXBUFF = 20000 };\n</code></pre>\n\n<p>Your design only reads from standard input. That's not bad, though it is lightly limiting.</p>\n\n<p>Your code includes:</p>\n\n<pre><code>printf(lines[i][0]);\n</code></pre>\n\n<p>This is a very dangerous way to use <code>printf()</code> - it is the ultimate format string vulnerability. The trouble is that if my input to you contains:</p>\n\n<pre><code>%s%n%13$s\n</code></pre>\n\n<p>then <code>printf()</code> is going to be reading and writing values on the stack which you didn't put there, which leads to great unhappiness. At minimum, use:</p>\n\n<pre><code>printf(\"%s\", lines[i][0]);\n</code></pre>\n\n<p>Alternatively, use:</p>\n\n<pre><code>fputs(lines[i][0], stdout);\n</code></pre>\n\n<p>(Do not use <code>puts()</code> because it adds newlines to the end of your data - unless you remove the newlines from the input.)</p>\n\n<p>When I compile your code using my default options, I get two warnings about the <code>printf()</code> - confirmation of what I'd already observed - plus a warning that <code>findTail()</code> does not return a value even though it is declared to return an <code>int</code>. That's best fixed by making it into a <code>void</code> function.</p>\n\n<pre><code>/usr/bin/gcc -g -std=c99 -Wall -Wextra -Wmissing-prototypes \\\n -Wstrict-prototypes cr.c -o cr\n</code></pre>\n\n<p>That's a pretty stringent set of warning options, and your code is good to generate just those three. I wish all the code I dealt with was as clean.</p>\n\n<p>When I run the program on its own source code, it works fine. When I run it with:</p>\n\n<pre><code>$ perl -e 'for $i (1..12) { print \"A\" x 2047, \"\\n\"; }' | ./cr\nerror: not enough room in buffer.\n$\n</code></pre>\n\n<p>That's OK - you did say you weren't using <code>malloc()</code> to do dynamic memory allocation. As a general guideline, though, your error messages should include the name of the program, as found in <code>argv[0]</code>, so that if there are multiple processes in a pipeline, for instance, you can tell which of the processes generated the error. I do this by using a function call <code>err_setarg0(argv[0]);</code> at the start of <code>main()</code>. This records the program name for use in subsequent error messages. I then use function calls such as <code>err_error(\"error: not enough room in the buffer\\n\");</code> to report the messages. A minimal implementation of these two functions is:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdarg.h>\n\nstatic const char *err_arg0 = \"unknown\";\n\nvoid err_setarg0(const char *arg0)\n{\n err_arg0 = arg0;\n}\n\nvoid err_error(const char *fmt, ...)\n{\n va_list args;\n fprintf(stderr, \"%s: \", err_arg0);\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n va_end(args);\n exit(1);\n}\n</code></pre>\n\n<p>I have a fairly complex file with many variations on this theme that provides simple-to-use error reporting, including variations reporting on the system error (via <code>errno</code>) and including time stamps and process ID and ... all selectable based on program design.</p>\n\n<p>Closer scrutiny shows that at any one time, at most one line will be wrapped - it means that the line starts just before the end of the buffer and has to wrap around to the start of the buffer.</p>\n\n<p>Overall, a pretty good program. Well done (and I don't say that lightly).</p>\n\n<p>I'm not sure how easily it will adapt to handle dynamic memory allocation - my suspicion is that you will end up with a rather different scheme for managing memory. This would remove the issues with lots of very long lines at the end of the file overflowing your buffer. Depending on your platform, you might be able to use the POSIX <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html\"><code>getline()</code></a> function which will allocate memory for you as it reads lines. Or you might decide to write an emulation of that code. You then only need a simple circular buffer of character pointers to keep the last N lines, and you discard the old one (with <code>free()</code>) before storing the next line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T14:45:04.217",
"Id": "1494",
"Score": "0",
"body": "Thanks for the detailed analysis. : ) I didn't know that misuse of printf was a security risk! However, I didn't get the warning for that with the compilation flags you mentioned, I did with the -Wformat-security flag though. I've made changes to use argv[0] in error messages, and have applied your other helpful suggestions."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T03:47:38.057",
"Id": "1520",
"Score": "0",
"body": "@sudoman: I was using GCC 4.2.1 or 4.5.2 (I have and use both) on MacOS X 10.6.6. You may be using a 3.x version (perhaps on Linux) which may not have reported the `printf()` problem without the extra poking of `-Wformat-security`. The warning I get is 'warning: format not a string literal and no format arguments'. (I can also confirm that GCC 4.1.2 on RHEL5 does not generate the format warning with `-Wall -Wextra`.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T03:14:19.667",
"Id": "799",
"ParentId": "790",
"Score": "13"
}
},
{
"body": "<p>Since you're using C99, you may be interested in the <code><stdbool.h></code> header, this includes three macro definitions, similar to ones you've already defined. This header has at least the following macro definitions on any conforming implementation:</p>\n\n<pre><code>#define bool _Bool\n#define true 1\n#define false 0\n</code></pre>\n\n<p>In C99, <code>_Bool</code> is a native Boolean data type, it contains only 0, or 1. When converting any scalar type to <code>_Bool</code>, it will convert to 0 if the scalar type is equal to 0, otherwise it will convert to 1.</p>\n\n<p>Also, in C99, the “implicit <code>int</code>” has been removed, so you <em>must</em> give every function a return type, even <code>main</code>. In older C, functions without an explicit return type would “default” to <code>int</code> type (as would arguments, I think).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-06T16:17:19.497",
"Id": "189973",
"Score": "0",
"body": "Note that there is a fourth macro that's defined: `__bool_true_false_are_defined` which expands to 1. It allows you to detect that the other three have been defined by the standard header. Exceptionally: _Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then\nredefine the macros bool, true, and false.259)_ (and the footnote refers to the 'Future Directions' where it says (paraphrasing) \"this exceptional permission may be removed in the future\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T05:50:17.237",
"Id": "822",
"ParentId": "790",
"Score": "5"
}
},
{
"body": "<p>This example implements the -n option of the tail command.</p>\n\n<pre><code>#define _FILE_OFFSET_BITS 64\n#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <unistd.h>\n#include <getopt.h>\n\n#define BUFF_SIZE 4096\n\nFILE *openFile(const char *filePath)\n{\n FILE *file;\n file= fopen(filePath, \"r\");\n if(file == NULL)\n {\n fprintf(stderr,\"Error opening file: %s\\n\",filePath);\n exit(errno);\n }\n return(file);\n}\n\nvoid printLine(FILE *file, off_t startline)\n{\n int fd;\n fd= fileno(file);\n int nread;\n char buffer[BUFF_SIZE];\n lseek(fd,(startline + 1),SEEK_SET);\n while((nread= read(fd,buffer,BUFF_SIZE)) > 0)\n {\n write(STDOUT_FILENO, buffer, nread);\n }\n}\n\nvoid walkFile(FILE *file, long nlines)\n{\n off_t fposition;\n fseek(file,0,SEEK_END);\n fposition= ftell(file);\n off_t index= fposition;\n off_t end= fposition;\n long countlines= 0;\n char cbyte;\n\n for(index; index >= 0; index --)\n {\n cbyte= fgetc(file);\n if (cbyte == '\\n' && (end - index) > 1)\n {\n countlines ++;\n if(countlines == nlines)\n {\n break;\n }\n }\n fposition--;\n fseek(file,fposition,SEEK_SET);\n }\n printLine(file, fposition);\n fclose(file);\n}\n\nint main(int argc, char *argv[])\n{\n FILE *file;\n file= openFile(argv[2]);\n walkFile(file, atol(argv[1]));\n return 0;\n}\n</code></pre>\n\n<p>Note: keep in mind that i didn't write code to parse input options or arguments, nor code to check if the argument is really a number.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T05:23:19.117",
"Id": "27829",
"ParentId": "790",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "799",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-15T15:29:26.360",
"Id": "790",
"Score": "16",
"Tags": [
"beginner",
"c"
],
"Title": "Simple C Implementation for Unix \"tail\" Command"
} | 790 |
<p>I had a question about using the modulus operator in Python and whether I have used it in a understandable way. </p>
<p>This is how I've written the script:</p>
<pre><code>#sum numbers 1 to 200 except mults of 4 or 7
def main():
sum = 0
for x in range(200+1):
if (x % 4 and x % 7): #is this bad???
sum = sum + x
print sum
if __name__ == '__main__':
main()
</code></pre>
<p>So my questions are:</p>
<ul>
<li>Should I spell out the modulo more clearly? ie <code>if x % 4 != 0 and x % 7 != 0</code></li>
<li>Should I be approaching this in a very different way? </li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T02:45:46.707",
"Id": "1471",
"Score": "2",
"body": "Omitting the `!= 0` is fine, even preferable. Most everyone understands that non-zero numbers are `True` in most high-level languages, so you're not exploiting some tough-to-remember quirk that will trip you up later."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T06:07:25.803",
"Id": "1476",
"Score": "2",
"body": "@David: \"In most high-level languages\"? I'd assume that the number of high-level languages in which this is not true is greater than the number of low-level languages in which it is not true."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T06:11:40.040",
"Id": "1477",
"Score": "0",
"body": "@sepp2k I'm not sure I understand your comment. Could you explain further?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T06:16:10.570",
"Id": "1479",
"Score": "1",
"body": "@Kyle: You make it sound as if `0` being false (and the other numbers being true) was a concept introduced by high-level languages (otherwise why say \"most high-level languages\" instead of \"most languages\"). This is not true - 0 being false was a concept introduced by machine language. And as a matter of fact I believe there are more high-level languages in which 0 is not usable in place of `false` than there are low-level languages in which 0 can not be used as false."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T06:21:39.017",
"Id": "1480",
"Score": "0",
"body": "@ sepp2k, I got it now. I had originally submitted this code for a quick online test to qualify for an interview. And after I clicked submit I thought, \"geez, that's probably a crappy way to make code someone else could read.\" I really wanted a feel for how more experienced programmers would look at it. Especially using the modulo in the way I did, that a remainder = `True`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T06:38:02.827",
"Id": "1481",
"Score": "0",
"body": "@sepp2k - I wasn't denying the case for low-level languages, only speaking about most high-level languages that I know. As for machine language, in 65c02 (the one I know) you have BEQ and BNE which test for equality and inequality to zero, thus zero was neither `true` nor `false` by definition."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T07:46:08.110",
"Id": "1483",
"Score": "0",
"body": "I find `sum += x` more compact and elegant than `sum = sum + x`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T15:40:33.873",
"Id": "1497",
"Score": "0",
"body": "@ Ori, I got confused there, forgetting that python has the `+=` operator, but not the `++` increment operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-14T15:42:31.257",
"Id": "49790",
"Score": "0",
"body": "I just want to add that I also think the `!= 0` should be explicitly written out."
}
] | [
{
"body": "<p>I think your use of <code>%</code> is fine, but that could be simplified to:</p>\n\n<pre><code>def main():\n print sum([i for i in range(201) if i % 4 and i % 7])\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p><em>Edit:</em> Since I had a bug in there, that's a pretty clear indication that the <code>%</code> is a tripwire. Instead, I'd probably do:</p>\n\n<pre><code>def divisible(numerator, denominator):\n return numerator % denominator == 0\n\ndef main():\n print sum(i for i in range(201) if not(divisible(i, 4) or divisible(i, 7)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T23:39:19.340",
"Id": "1465",
"Score": "0",
"body": "Ahhh... seeing it in a generator expression makes me feel like I should make the comparison explicit, as a relative n00b, it confuses me what the comparison is doing exactly. I think that's bad since it's my code."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T00:00:21.360",
"Id": "1467",
"Score": "0",
"body": "What elegant looking code."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T02:50:28.603",
"Id": "1472",
"Score": "0",
"body": "@munificent - The `or` should be `and` to skip numbers that are multiples of 4 and/or 7. I thought Kyle had it wrong at first, but after careful consideration I'm 93.84% sure it should be `and`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T03:40:22.323",
"Id": "1473",
"Score": "0",
"body": "Thanks Munificent! I think you answer helped me a lot in understanding generator expressions too."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T04:44:47.903",
"Id": "1474",
"Score": "0",
"body": "@David - You're right. This is actually one of the things I don't like about how this uses `%`. `i % 4` means \"*not* divisible by four\" which is backwards from what you expect (but also what we want, which makes it hard to read."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T04:59:14.983",
"Id": "1475",
"Score": "0",
"body": "@munificent, this was really the essence of the question. I was really trying to figure out if my usage of the modulo operator was abusive, and I think it was. Because it looks like it should do one thing, but instead it does the other. Thanks for editing to the correct code."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T06:11:56.843",
"Id": "1478",
"Score": "0",
"body": "@Kyle: This is not a generator expression, it's a list comprehension. You can tell because it's surrounded by square brackets. However it *should* be a generator expression as there is no benefit to generating a list here. So you should remove the brackets."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T06:56:28.757",
"Id": "1482",
"Score": "0",
"body": "Updated to be clearer, I think."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T23:09:40.267",
"Id": "795",
"ParentId": "794",
"Score": "9"
}
},
{
"body": "<p>My program is the shortest possible:</p>\n\n<pre><code>print 12942\n</code></pre>\n\n<p>Use the formula of inclusion/exclusion.</p>\n\n<p>There should be <code>200-(200/4)-(200/7)+(200/28) (Using integer division) = 200-50-28+7 = 129</code> terms in the sum.</p>\n\n<p>The sum must be <code>s(200) - 4*s(200/4) - 7*s(200/7) + 28*s(200/28) where s(n) = sum from 1 till n = n*(n+1)/2</code>.</p>\n\n<p>This evaluates to <code>0.5* (200*201 - 4*50*51 - 7*28*29 + 28*7*8) = 0.5*(40200 - 10200 - 5684 + 1568) = **12942**</code>.</p>\n\n<p>Why write a program if you can use math?</p>\n\n<p>(I'll admit I used a calculator to multiply and add the numbers)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T05:54:22.990",
"Id": "1522",
"Score": "2",
"body": "Because just doing the maths doesn't teach you anything about the programming language you're using."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T11:51:05.470",
"Id": "1527",
"Score": "0",
"body": "@dreamlax I think that \"your piece of code is more complex than required. Use a bit of math to simplify it\" is a valid comment during code review. This is not learning-a-language.stackexchange.com."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T12:02:51.860",
"Id": "1528",
"Score": "2",
"body": "It's also not codegolf.stackexchange.com. We're reviewing the algorithm, not the result."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T19:15:02.570",
"Id": "1537",
"Score": "1",
"body": "I don't find this solution very helpful, but in code as an algorithm it would be."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T03:30:49.230",
"Id": "1578",
"Score": "0",
"body": "@KyleWpppd I don't know enough Python to turn this into correct Python code, that's why my answer has just one print statement. If anyone writes some Python code for the s() function, the integer divisions, and calling the s function, feel free to edit my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-14T16:26:04.627",
"Id": "49792",
"Score": "0",
"body": "I think `print(12942)` would be better, since it would run on both Python 2 and Python 3. :-P"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-17T05:07:10.877",
"Id": "821",
"ParentId": "794",
"Score": "3"
}
},
{
"body": "<p>This is a more generalised version of the answers already given:</p>\n\n<pre><code>def sum_excluding_multiples(top, factors):\n return sum(i for i in range(top + 1) if all(i % factor for factor in factors))\n\nprint sum_excluding_multiples(200, (4, 7))\nprint sum_excluding_multiples(200, (3, 5, 10, 9))\n</code></pre>\n\n<p>This is @Sjoerd's answer as Python code:</p>\n\n<pre><code>def sum_excluding_multiples2(top, factor1, factor2):\n def sum_of_multiples(m=1):\n return m * int(top / m) * (int(top / m) + 1) / 2\n return (sum_of_multiples() - sum_of_multiples(factor1) \n - sum_of_multiples(factor2) + sum_of_multiples(factor1 * factor2))\n\nprint sum_excluding_multiples2(200, 4, 7)\n</code></pre>\n\n<p>This is more complicated and harder to read, and I'm not sure how to generalise it to exclude multiples of more than two numbers. But it would be faster if very large numbers were involved, since it solves the problem mathematically instead of by iterating through a range.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-14T10:01:39.443",
"Id": "31274",
"ParentId": "794",
"Score": "4"
}
},
{
"body": "<p>I think <code>x % 4 != 0</code> is clearer than <code>x % 4</code>, because:</p>\n\n<ul>\n<li>The standard way to check if a number <strong>is</strong> divisible is <code>x % 4 == 0</code>. Of course that could also be written as <code>not x % 4</code>, but usually, it's not. <code>x % 4 != 0</code> is more in line with the standard way of writing tests for divisibility.</li>\n<li><code>x % 4</code> is probably more error-prone. <a href=\"https://codereview.stackexchange.com/questions/794/print-sum-of-numbers-1-to-200-except-mults-of-4-or-7-in-python#comment1474_795\">Quoting munificient</a>:\n\n<blockquote>\n <p>'i % 4 means \"not divisible by four\" which is backwards from what you expect (but also what we want, which makes it hard to read.</p>\n</blockquote></li>\n</ul>\n\n<p>It's not really a big deal though.</p>\n\n<hr>\n\n<p>A few more comments on your code:</p>\n\n<p>Don't shadow the built-in function <code>sum()</code> with your variable <code>sum</code>. Instead, use <code>total</code> or something similar.</p>\n\n<p>You don't need the parentheses in <code>if (x % 4 and x % 7):</code>.</p>\n\n<p>As has been mentioned in the comments, write <code>sum = sum + x</code> more concisely as <code>sum += x</code>.</p>\n\n<p>I would make <code>main()</code> return the number and then write <code>print main()</code> in the last line. This way, you could reuse the function in a different context.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-14T15:29:03.437",
"Id": "31277",
"ParentId": "794",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "795",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-15T22:37:23.323",
"Id": "794",
"Score": "10",
"Tags": [
"python"
],
"Title": "Print sum of numbers 1 to 200 except mults of 4 or 7 in Python"
} | 794 |
<p>Is there a way to do this using parameters so the value is automatically converted to whatever datatype the keyfield has in the datatable?</p>
<p>This code should be reusable for future bulk update applications hence the constant and the check on multiple datatypes.</p>
<pre><code>private const string DBKEYFIELDNAME = "CustomerNr";
...
for (int i = 1; i <= csvLines.Length - 1; i++) // i=1 => skip header line
{
string[] csvFieldsArray = csvLines[i].Split(';');
int indexKeyField = csvHeaders.IndexOf(CSVKEYFIELDNAME.ToLower());
object csvKeyValue = csvFieldsArray[indexKeyField];
// ... some more code here that is not relevant
// Find the matching row for our csv keyfield value
Type keyType = parameters.DataTableOriginal.Columns[DBKEYFIELDNAME].DataType;
DataRow[] rowsOriginal = null;
if (keyType.IsAssignableFrom(typeof(string)))
rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + "='" + csvKeyValue.ToString() + "'");
else if (keyType.IsAssignableFrom(typeof(Int16)) || keyType.IsAssignableFrom(typeof(Int32)) || keyType.IsAssignableFrom(typeof(Int64)) || keyType.IsAssignableFrom(typeof(bool)))
rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + "=" + csvKeyValue);
if (rowsOriginal != null && rowsOriginal.Length == 1)
{
// Do some processing of the row here
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T08:35:45.520",
"Id": "1484",
"Score": "0",
"body": "@Peter, where did csvKeyValue come from? Who generates it? Do you have control over it? From its name, it sounds like it was read from a csv file at some point, and whoever read it also converted it to a string, int, or bool. Is that correct? And how is it passed in to this chunk of code? As an object? Is this code in a separate method? If so, consider posting the signature of this method."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T08:50:03.387",
"Id": "1485",
"Score": "0",
"body": "It's quite a big method so I'd rather not as it takes the focus of the code I want reviewed, I'll update my question with more info on the csvKeyValue variable."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T08:55:56.110",
"Id": "1486",
"Score": "0",
"body": "Okay... The datatype is always going to be a string in the CSV... I still need to write some logic to get the datatype of the matching column in the DataTableOriginal."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T14:06:11.987",
"Id": "1492",
"Score": "0",
"body": "What is `DBSLEUTELVELDNAAM`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T14:25:28.187",
"Id": "1493",
"Score": "0",
"body": "Sorry it's DBKEYFIELDNAME. I forgot to replace it when copying my code over (which is partially in dutch), but forgot after an update..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T12:32:29.467",
"Id": "1583",
"Score": "3",
"body": "Is `i <= csvLines.Length - 1` idiomatic in this codebase? I think most people would consider `i < csvLines.Length` more idiomatic, and the fewer surprises the better."
}
] | [
{
"body": "<p>A few comments:</p>\n\n<ul>\n<li>This method does way too much. It is difficult to understand and will be difficult to debug and maintain. Break it down into smaller methods that each have a single responsibility.</li>\n<li>Use curly braces after your if and else statements. This improves readability of the code and makes it less likely for other code to sneak in there in the future.</li>\n<li>Can't your else statement just be a plain else with no if after it? It seems like you want to put quotes around a string, and use the plain value for everything else. Are there other requirements here?</li>\n<li>The type of csvKeyValue could just be string, since it's pulling a value out of a string[]</li>\n<li>No need for the call to .ToString() in your if branch</li>\n<li><p>I would try to write the call to <code>parameters.DataTableOriginal.Select</code> only once. Consider using your if/else to set a <code>delimeter</code> variable to either <code>string.Empty</code> or <code>'</code>, then write your query once like so:</p>\n\n<pre><code>DataRow[] rowsOriginal = parameters.DataTableOriginal.Select(\n DBSLEUTELVELDNAAM + \"=\" + delimeter + csvKeyValue + delimeter);\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T09:39:23.280",
"Id": "1487",
"Score": "0",
"body": "I agree on all point except for using brackets on the if statement. Especially when just using it to set a delimiter variable as you suggested. But that's personal opinion. Thanks for the pointers! I will split this method into different pieces as you are right, it is big and clunky. And you've only seen one 5th of it :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T09:29:46.640",
"Id": "801",
"ParentId": "800",
"Score": "7"
}
},
{
"body": "<p>Yup, that method does definitely need breaking down into smaller pieces.</p>\n\n<p>You may like to use an iterator method to loop through the lines. Something along the lines of :</p>\n\n<pre><code>IEnumerable<string> EachCSVKey(string[] csvLines)\n{\n int indexKeyField = csvHeaders.IndexOf(CSVKEYFIELDNAME.ToLower());\n\n for (int i = 1; i <= csvLines.Length - 1; i++) // i=1 => skip header line\n {\n string[] csvFieldsArray = csvLines[i].Split(';');\n yield return csvFieldsArray[indexKeyField];\n }\n}\n</code></pre>\n\n<p>Then in your method :</p>\n\n<pre><code>foreach ( var csvKeyValue in EachCSVKey ( csvLines) )\n{ \n ...\n</code></pre>\n\n<p>I find (in my opinion) that this makes the intent clearer.</p>\n\n<p>Note also you should get the indexKeyField value outside of the loop. This value won't change, and so it is unnecessary to keep getting it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T08:00:06.333",
"Id": "1525",
"Score": "0",
"body": "It looks cleaner but it can't be as performant because you are looping the entire csv twice?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T12:03:16.020",
"Id": "1529",
"Score": "2",
"body": "No, you only loop once - thats the clever part! Each time the EachCSVKey method hits the \"yield return\" statement it will transfer control to the calling methods foreach loop. When the calling foreach loop finishes an iteration, it returns control to the EachCSVKey method. This continues until EachCSVKey finishes its loop or the calling loop calls \"break\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T16:03:21.327",
"Id": "806",
"ParentId": "800",
"Score": "3"
}
},
{
"body": "<p>Just one small comment in addition to those provided by Saeed and Mongus, you have defined a constant called <code>CSVKEYFIELDNAME</code> but in the only place it is (shown to be) used, you call ToLower() on it. Should the constant be provided as lower case to begin with, or should you be doing a case insensitive search?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T07:26:44.643",
"Id": "1546",
"Score": "0",
"body": "Well, the thing is, the csvheaders array has received a tolower upon initialisation. I do a tolower on the constant to allow someone to change the value into a readable string without having to know it needs to be in lowercase always."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T10:08:38.573",
"Id": "1548",
"Score": "0",
"body": "@Peter, sounds like a case insensitive search is in order then :). Ultimately it's up to you, creating a new string and preforming multiple case insensitive string comparisons will both have performance impacts, though which is greater would probably depend on the number of columns you are comparing against. in any case, you might want to consider the effects of culture settings on your comparisons (http://stackoverflow.com/questions/2256453/using-invariantcultureignorecase-instead-of-toupper-for-case-insensitive-string-c/2256491#2256491)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T12:34:10.820",
"Id": "1584",
"Score": "0",
"body": "@Peter, this is C#, isn't it? So make the string a const and then wrap it in a property which does the ToLower() and you get the best of both worlds."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T01:07:58.557",
"Id": "833",
"ParentId": "800",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Is there a way to do this using\n parameters so the value is\n automatically converted to whatever\n datatype the keyfield has in the\n datatable?</p>\n</blockquote>\n\n<p>You could use something like this:</p>\n\n<pre><code>object csvKeyValue = Convert.ChangeType(csvKeyValue, keyType);\n</code></pre>\n\n<p>to convert a string to the type of the datatable column.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T23:02:15.850",
"Id": "847",
"ParentId": "800",
"Score": "1"
}
},
{
"body": "<p>I noticed this code: <code>parameters.DataTableOriginal.Select(DBKEYFIELDNAME + \"='\" + csvKeyValue.ToString() + \"'\")</code>. Just putting quotes around an user-input screams <strong>SQL Injection</strong> to me.</p>\n\n<p>The problem is that your code assumes that <code>csvKeyValue</code> has no quotes in it. That assumption is never checked anywhere, while csvKeyValue is read from an external file so cannot be trusted.</p>\n\n<p>Suppose the csvKeyValue equals \"a' or TRUE or 'x' ='x\". Do you really want to execute that select?</p>\n\n<p>Although I cannot judge whether this is a real danger, I thought I should mention it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T03:26:28.317",
"Id": "849",
"ParentId": "800",
"Score": "5"
}
},
{
"body": "<p><a href=\"https://msdn.microsoft.com/en-us/library/ff926074.aspx\" rel=\"nofollow\">Prefer <code>var</code> in <code>for</code> loop variable initializer</a>s:</p>\n\n<pre><code>for (int i = 1; i <= csvLines.Length - 1; i++)\n</code></pre>\n\n<p>Should be</p>\n\n<pre><code>for (var i = 1; i <= csvLines.Length - 1; i++)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-20T10:51:38.917",
"Id": "87415",
"ParentId": "800",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "801",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-16T08:07:25.013",
"Id": "800",
"Score": "6",
"Tags": [
"c#",
"csv"
],
"Title": "Strongly-typed reading values from CSV DataTable"
} | 800 |
<p>I have some small applications that I want to secure. I've been using the following setup that <em>I think</em> is fairly safe, but I've never been able to set my mind at ease that it really is. Could you give me some reviews on the security of this? It doesn't need super-security like credit card data, but I suppose secure is secure.</p>
<p>Cookie-based Sessions. User table is: </p>
<ul>
<li>Username field (cleartext) </li>
<li>Random/unique salt field (created with <code>mt_rand()</code> at signup </li>
<li>Password field (SHA256 hash)</li>
<li>(among other stuff)</li>
</ul>
<p>Login method takes username, looks for the DB row, gets the salt, adds it to the end of the posted password, calcs a SHA256 hash for that string, and compares that to the password field in the DB.</p>
<p><strong>auth.php include at beginning of app</strong></p>
<pre><code><?php
session_start();
if(!isset($_GET['logout']) && isset($_SESSION['user']) && $_SESSION['ipadd'] == $_SERVER['REMOTE_ADDR']) {
// currently logged in
// setup data
require_once('lib/functions.php');
$db = new ezSQL_sqlite('./','main.db');
$user = new user($db,$_SESSION['user']);
return;
}
// build login form
$head = '<html><head><title>Please login</title>
<style type="text/css">h2 { margin-top: 75px; margin-left: 100px; }</style>
</head><body>';
$form = '<form method="post" action="'.$_SERVER['PHP_SELF'].'" id="userLogin">
<table><tr>
<td>UserName:</td><td><input type="text" name="username" value="'.$_POST['username'].'"></td>
</tr><tr>
<td>Password:</td><td><input type="password" name="pass" /></td>
</tr><tr>
<td>Remember me on this computer</td>
<td><input type="checkbox" name="remember" value="1" /></td>
</tr><tr>
<td>&nbsp;</td>
<td><input type="hidden" name="loggingin" value="true" />
<input type="submit" value="login" />
</td></tr></table>
</form></body></html>';
$msg[1] = '<h2>You\'ve logged out.</h2>';
$msg[3] = '<h2>That username and password didn\'t match anything on record.</h2>';
$msg[4] = '<h2>You must login to use this application</h2>';
// used logout button
if($_GET['logout'] == 'true') {
setcookie('SaveMe','',time()-3600);
session_unset();
die($head.$msg[1].$form);
// trying to login from form or returning with 'save me' cookie
} elseif ($_POST['loggingin'] == 'true' || isset($_COOKIE['SaveMe'])) {
require_once('lib/functions.php');
$db = new ezSQL_sqlite('./','main.db');
$loginName = (isset($_POST['username'])) ? $_POST['username'] : $_COOKIE['worshipSaveMe'];
// ADDED: escaping of posted/cookie data;
$loginName = mysql_real_escape_string($loginName);
// try to create new user object, error on fail
try {
$user = new user($db,$_POST['username']);
} catch (Exception $e) {
die($head.'<h2>'.$e->getMessage().'</h2>'.$form);
}
// try to login with user object, die on fail
if( ! $user->login($_POST['pass']))
die($head.$msg[3].$form);
else {
// if remember me box was checked
if($_POST['remember'] == 1)
setcookie('worshipSaveMe',$_POST['username'],time()+60*60*24*365);
return;
}
// no post data, no save me cookie, just got here
} else {
die($head.$msg[4].$form);
}
</code></pre>
<p><strong>And the relevant part of the user class:</strong></p>
<pre><code>class user
{
private $username;
protected $ID;
private $created;
private $salt;
private $password;
private $db;
function __construct ( ezSQL_sqlite $db, $postedUsername ) {
if( !$user = $db->get_row("SELECT * FROM users WHERE uname = '$postedUsername';"))
throw new Exception ('That username didn\'t match anything on record.');
else {
$this->db = $db;
$this->username = $postedUsername;
$this->ID = $user->user_id;
$this->created = date('Y-m-d',$user->createdDate);
$this->salt = $user->salt;
$this->password = $user->pword;
}
}
/** check password for match
* @param user input from a posted form
* @return boolean
*/
private function verifyPassword($postedPass) {
$pHash = hash('sha256',$postedPass . $this->salt);
if($this->password != $pHash)
return FALSE;
else
return TRUE;
}
/** This relies on cookie based sessions, and so
* must be called before any output to browser.
* @return bool
*/
public function login($postedPassword) {
if( ! $this->verifyPassword($postedPassword) ) {
return FALSE;
} else {
if( isset( $_COOKIE["PHPSESSID"] )) { //be sure session was initialized
$_SESSION['user'] = $this->username;
$_SESSION['ipadd'] = $_SERVER['REMOTE_ADDR'];
return TRUE;
} else {
die('Session must be initialized before calling login method.');
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T19:35:07.273",
"Id": "64510",
"Score": "0",
"body": "This should be relevant: [How To Safely Store A Password](http://codahale.com/how-to-safely-store-a-password/ \"How To Safely Store A Password\") (bcrypt)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T15:02:45.430",
"Id": "64511",
"Score": "0",
"body": "Ah, interesting. So can I just sub out my `hash('sha256',$password)` function with `crypt($password,'$2a$12$1234567890123456789012$')` (obviously with a different salt string)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T16:26:01.613",
"Id": "64512",
"Score": "0",
"body": "crypt() might fall back to MD5 or something else if there is no support for blowfish, or if the salt isn't right. http://us.php.net/crypt To be sure, you could try phpass with PHP 5.3.0+ or the Suhosin patch: http://www.openwall.com/phpass/"
}
] | [
{
"body": "<p>Assuming that you also have user authenticated application behavior check against the open session before it executes, your security process appears reasonably solid. I would personally feel a little uncomfortable storing my salt in the user's cookie - though excluding it in your setup may prove problematic if each user has a unique string. From your description, it sounds like you are already retrieving the user's salt from the db during authentication and not from the cookie. Lastly, your variable <code>$postedUsername</code> kinda has me worried. You are escaping or removing unsafe (for MySQL) characters before your query, aren't you?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T14:53:36.770",
"Id": "1531",
"Score": "0",
"body": "The salt is _not_ in the cookie, it's in the db. The only thing stored in the cookie is the username. But as far as the unsafe characters, I guess there's a weak point. Is using `mysql_real_escape_string ()` good enough for this purpose? I've added that to the code."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T23:49:45.423",
"Id": "1542",
"Score": "0",
"body": "Right on. Beside keeping your database input clean (escaping characters) you script looks secure. Depending on how much time you have, `mysql_real_escape_string()` should do the trick. I know it's not solid either, but I also often like to implement some javascript controls on the input fields to keep apostrophes and quotation marks from being entered altogether (along with some other characters). It's not technically any more secure - but I figure while I'm at it..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T17:00:21.937",
"Id": "809",
"ParentId": "802",
"Score": "1"
}
},
{
"body": "<p>You're using a decent hash, with a unique salt per user. So it's pretty solid. You might consider adding some password stretching, but it is by no means necessary.</p>\n\n<pre><code>Step 1: Hash the password and salt.\nStep 2: Add the salt to the hash, and rehash\nStep 3: Repeat step 2 x number of times.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-01T03:47:43.220",
"Id": "279544",
"Score": "0",
"body": "One should not do these steps manually but use a predefined password hashing instead, e.g. bcrypt."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T12:49:54.133",
"Id": "897",
"ParentId": "802",
"Score": "1"
}
},
{
"body": "<p>I see you check for sql injection of the loginname: </p>\n\n<pre><code>$loginName = mysql_real_escape_string($loginName);\n</code></pre>\n\n<p>Do you filter bad content for the submitted password? </p>\n\n<p>Now that I look at it, you are sending the POSTed login name straight to the SQL, aren't you? </p>\n\n<p>This:</p>\n\n<pre><code>new user($db,$_POST['username']);\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code>new user($db,$loginName); \n</code></pre>\n\n<p>If I'm reading this correctly - you need to sanitize the password also!</p>\n\n<p>This is generally very important. You are also using MySQL functions to sanitize SQLite data. That's <em>probably</em> okay, but I wouldn't bet the farm on it!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:36:55.600",
"Id": "61881",
"Score": "1",
"body": "Be sure that you have communicated the locale to the MySQL function - otherwise you could still be SQL injected."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-22T18:31:40.307",
"Id": "925",
"ParentId": "802",
"Score": "6"
}
},
{
"body": "<p>Don't ever pass data directly into a query. You are just opening yourself to <a href=\"http://en.wikipedia.org/wiki/Sql_injection\" rel=\"noreferrer\">SQL Injection.</a> Always use <a href=\"http://php.net/manual/en/pdo.prepared-statements.php\" rel=\"noreferrer\">bind variables</a> when you can.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-22T22:02:42.383",
"Id": "932",
"ParentId": "802",
"Score": "5"
}
},
{
"body": "<p>Your code is crap.</p>\n\n<p>It contains the two most popular security holes, cross-site scripting and SQL injection. Read about them, learn them by heart and then try again.</p>\n\n<p>You may have heard somewhere that you should use <code>mysql_real_escape_string</code>, but you didn't get the context right. This function must only be used for MySQL databases, not for SQLite.</p>\n\n<p>Also, your password hashing function is too fast. Use bcrypt or PHP's CRYPT_SHA512 instead. With all your other security holes it's easy for a hacker to extract the password database, and after that, cracking the passwords will be really fast.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-01T03:57:18.870",
"Id": "148613",
"ParentId": "802",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "925",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-16T14:35:29.563",
"Id": "802",
"Score": "8",
"Tags": [
"php",
"mysql",
"security",
"authentication",
"session"
],
"Title": "Securely handling a password protected application"
} | 802 |
<p>Here's a method I made that's supposed to print out multiples of any numbers up to any quantity:</p>
<pre><code>def DisplayMultiples(multiplesOf, count)
i = multiplesOf
while i <= count
if i % multiplesOf == 0
puts i
end
i += 1
end
end
</code></pre>
<p>Any suggestions on how to improve the code to something more fitting to the Ruby style? I'm coming from a C# background so I'd like to switch things up a bit. </p>
| [] | [
{
"body": "<p>One important note regarding naming in ruby:</p>\n\n<p>The <strong>syntax</strong> in ruby is that constants (including class and module names) have to start with capital letters and local variables have to start with lower case letters. Instance, class and global variables must start with their respective sigil followed by a letter in any case. Method names must start with a letter in any case, but if they start with a capital letters, they must be called with <code>()</code> when there are no arguments.</p>\n\n<p>The naming <strong>convention</strong> in ruby is to use snake_case for method names and variables, PascalCase for class and module names and ALL_CAPS for constants other than class and module names.</p>\n\n<p>For method names the convention is to use <code>snake_case</code> for all methods except \"constructor\"-style functions (e.g. <code>Integer()</code>, <code>Array()</code>, <code>Hash()</code>) where the name of the function is the same as that of the constructed class.</p>\n\n<p>Generally using PascalCase for method names is a bad idea because:</p>\n\n<ul>\n<li>It's against convention and will make people think it's a constructor-style function</li>\n<li>If you define a method without arguments, you'll trip yourself up because you'll try to call it as <code>MyMethod</code> instead of <code>MyMethod()</code> which does not work if the method name starts with a capital letter.</li>\n</ul>\n\n<hr>\n\n<p>General notes on your code:</p>\n\n<p>Using a while loop is usually unidiomatic ruby. Using a while loop to iterate from one number to another number with a constant step-size is always unidiomatic ruby. If the step-size is 1, you can just use <code>each</code> on a range and if it is something else you can use <code>step</code>. So your code would just be written as:</p>\n\n<pre><code>def display_multples(multiples_of, count)\n (multiples_of .. count).each do |i|\n if i % multiples_of == 0\n puts i\n end\n end\nend\n</code></pre>\n\n<hr>\n\n<p>Now as pdr points out, this is not the optimal algorithm to do this. Instead of iterating between all integers between <code>multiples_of</code> and <code>count</code> and printing those which are divisible by <code>multiples_of</code>, you can just iterate between the numbers between <code>multiples_of</code> and <code>count</code> with a step size of <code>multiples_of</code>, i.e. only iterate over the multiples of <code>multiples_of</code>. However his code contains an unnecessary <code>each</code> (which will also make the code not work on ruby 1.8.6, though that's thankfully becoming less of an issue these days). So the code should just be:</p>\n\n<pre><code>def display_multiples(multiples_of, count)\n (multiplesOf..count).step(multiples_of) do |i|\n puts i\n end\nend\n</code></pre>\n\n<hr>\n\n<p>However this code still contains one major, non-ruby-specific design-smell: You're mixing the logic to generate the multiples with the code printing it. Generally IO and logic should be separated as much as possible. So what you should do is define a method <code>multiples</code> which generates the multiples and a method <code>print_multiples</code> which prints them.</p>\n\n<p>In ruby the best way to write a method which generates a sequence of values is to write an \"iterator method\", i.e. a method which yields the elements. That would look like this:</p>\n\n<pre><code>def multiples(multiples_of, count)\n (multiples_of .. count).step(multiples_of) do |i|\n yield i\n end\nend\n\ndef print_multiples(multiples_of, count)\n multiples(multiples_of, count) do |i|\n puts i\n end\nend\n</code></pre>\n\n<p>You can also define multiples as:</p>\n\n<pre><code>def multiples(multiples_of, count, &blk)\n (multiples_of .. count).step(multiples_of, &blk)\nend\n</code></pre>\n\n<p>In 1.8.7+ this also has the benefit of returning an Enumerator if no block is given. so if you don't just want to print it, you can also use Enumerable methods like <code>map</code>, <code>select</code> etc. on it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T16:31:29.823",
"Id": "1501",
"Score": "0",
"body": "Good, thorough, answer. Supercedes mine which I will delete, so no need to reference my answer here"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T03:56:28.643",
"Id": "1521",
"Score": "1",
"body": "By the way: literally everything you write, except for the specific naming conventions, has really nothing specifically to do with Ruby, it's just general good OO, or even just general good programming. Pretty much everything would apply 100% identically to C# as well, for example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T15:33:33.990",
"Id": "805",
"ParentId": "803",
"Score": "32"
}
},
{
"body": "<p>This is not actually an answer to your question, but since you mentioned that you come from C# to Ruby, I just wanted to point out that the idiomatic Ruby solution that @sepp2k presented is pretty much indentical to what an idiomatic C# solution would have looked like:</p>\n<pre><code>class Multiples : IEnumerable<int>\n{\n private readonly int _multiplesOf;\n private readonly int _limit;\n\n public static Multiples Of(int multiplesOf = 1, int limit = int.MaxValue) =>\n new Multiples(multiplesOf, limit)\n\n Multiples(int multiplesOf = 1, int limit = int.MaxValue)\n {\n _multiplesOf = multiplesOf;\n _limit = limit;\n }\n\n public IEnumerator<int> GetEnumerator()\n {\n var i = 0;\n while ((i += _multiplesOf) <= _limit) yield return i;\n }\n\n IEnumerator IEnumerable.GetEnumerator() =>\n GetEnumerator()\n}\n</code></pre>\n<p>It might not be immediately obvious that those two examples are the same, but they mostly are. The main difference is that .NET's libraries are much weaker than Ruby's, so we had to implement some stuff manually that was provided for us by the Ruby libraries.</p>\n<p>You would use both versions pretty much the same way:</p>\n<pre><code>// C#\nforeach (var n in Multiples.Of(7, 50)) Console.WriteLine(n);\nMultiples.Of(7, 50).ToList().ForEach(Console.WriteLine);\nConsole.WriteLine(Multiples.Of(7, 50).ToArray());\n\n# Ruby\nmultiples(7, 50) {|n| puts n }\nmultiples(7, 50, &method(:puts))\nputs *multiples(7, 50)\n</code></pre>\n<p>In fact, the C# version I presented here is slightly more powerful, since it allows the <em>client</em> to choose the termination condition more freely. For example, what if I don't want the multiples of 7 below 50, but rather the first 50 multiples? Easy:</p>\n<pre><code>Multiples.Of(7).Take(50)\n</code></pre>\n<p>Implementing this for the Ruby version is left as an exercise to the reader :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T18:12:34.010",
"Id": "1536",
"Score": "2",
"body": "I'd say that to be similar to my ruby version the C# code should use Enumerable.Range, not an iterative while-loop. Also I don't get your last point. You can do `multiples(7, Float::INFINITY).take(n)` in the ruby version as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-17T17:08:16.813",
"Id": "826",
"ParentId": "803",
"Score": "7"
}
},
{
"body": "<p>Inline way: <code>p (7..49).step(7).to_a</code></p>\n\n<p>Invocable way:</p>\n\n<pre><code>def multiples(of, through)\n (of..through).step of\nend\np multiples(7, 49).to_a\n</code></pre>\n\n<p>#=> [7, 14, 21, 28, 35, 42, 49]</p>\n\n<p>The biggest difference from your code is due to Ruby's library. Smalltalk was a major influence on Ruby.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-24T04:58:20.837",
"Id": "8242",
"ParentId": "803",
"Score": "5"
}
},
{
"body": "<p>As Ruby, like Perl, emphasizes that there is more than one way to do something, let me suggest my own. This is close to what I'd do in a functional programming language:</p>\n\n<pre><code>def multiples(n, count)\n 1.upto(count).map {|i| n * i}\nend\n\nmultiples(23, 5)\n=> [23, 46, 69, 92, 115]\n</code></pre>\n\n<p>It could also be added (via monkeypatching) to the Fixnum class, if you're willing to engage in that sort of thing. That would allow you to invoke it like this:</p>\n\n<pre><code>23.multiples(5)\n=> [23, 46, 69, 92, 115]\n</code></pre>\n\n<p>This will do the same thing as the <code>step</code> methods provided in other answers. I find it a bit more readable (though I wasn't familiar with the <code>step</code> function until today, so take that as you will).</p>\n\n<p>Edit</p>\n\n<p>While we're at it, let's look at something neat you can do with Ruby 2.0. With the new Enumerable.lazy class, you can easily express this as an infinite sequence, from which you can take small subsets:</p>\n\n<pre><code>def multiples(n)\n (1..Float::INFINITY).lazy.map {|x| x * n}\nend\n\n# Now we can get an infinite list, and defer operating on it until later\nmultiples(23).take(5).to_a\n=> [23, 46, 69, 92, 115]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-23T20:24:13.457",
"Id": "24289",
"ParentId": "803",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-16T14:43:54.687",
"Id": "803",
"Score": "12",
"Tags": [
"beginner",
"ruby"
],
"Title": "Displaying the multiples of a given number"
} | 803 |
<p>The below is \$O(n^3)\$. I'm sure there is a way to improve this..</p>
<pre><code>//vector<string> flight_path; given as parameter
//vector<int> flight_number; need to fill
//vector<segment> flight_segments; known, contains segments (dep, arr, flightnum)
//Purpose of the function is to take in a flight_path and give back a list of
// flight numbers for each segment
//
// Input: New York, London, Kolkata
// Output: 101 201 301, 102 939
vector<string> get_flight_numbers (vector<string> flight_path) {
vector<int> flight_number;
for (int i = 0; i < flight_path.size() - 1; i++) {
string dep = flight_path.at(i);
string arr = flight_path.at(i+1);
for (int j = 0; j < flight_segments.size(); j ++) {
if (flight_segments.at(j).departure == dep && flight_segments.at(j).arrival == arr) {
for (int k = 0; k < flight_segments.at(j).segment_numbers.size(); k++) {
flight_numbers.push_back(atoi(flight_segments.at(j).segment_numbers.at(k).c_str()));
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T03:20:58.107",
"Id": "1519",
"Score": "0",
"body": "Your inner loops don't seem to find segment chains correctly. The first `if()` tests if the flight covers the current path segment."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T23:58:50.837",
"Id": "1543",
"Score": "0",
"body": "If you use hash table instead of a vector of segments, you can make it much faster."
}
] | [
{
"body": "<p>If I understand this, you have a directed graph that consists of a series of flight segments. You are given a series of flight segments, say, A -> B -> C, that makes up a flight path.</p>\n\n<p>In addition, you have a group of flight numbers. The flight numbers correspond to paths. Flight number 1 will be tagged as [A,B,1], for example. Time is not an issue, all flights are assumed to be available at all times.</p>\n\n<p>Can you, in less than \\$O(n^3)\\$ time, figure out what flight numbers can take you from one segment to the next?</p>\n\n<p>Well, on approach might be to go through the array exactly once in order to separate out all the flights that depart from your first departure gate, your second departure gate, and so forth. That's order n.</p>\n\n<p>Then go through each of those lists (once) and remove all the flights that don't have the right destination gate. That's order n again. </p>\n\n<p>At that point, you're pretty much done. </p>\n\n<p>So think your big mistake here is going through your big loop (the flights) INSIDE your little loop (your flight path). You'd be much better off going through the small loop inside the big loop and breaking if you find a match. This loop only nests once, also, instead of twice. If you really really wanted to, you could check each departure as you find it to see if it matches an arrival.</p>\n\n<p>In psuedo-code:</p>\n\n<pre><code>for (i in each flight) do\n for (j in each pathpoint except the last one) do\n if flight[i][departure][i] == pathpoint[j] then\n if flight[j][arrival] == pathpoint[j+1]\n put flight in the good flights vector\n end if\n end if\n end for\nend for\n</code></pre>\n\n<p>That's \\$O(n*m)\\$, where \\$m\\$ is the length of the path and n is the number of flights. This should be, in any reasonable world, \\$O(n)\\$.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T03:19:58.590",
"Id": "1518",
"Score": "0",
"body": "I think you misunderstood the requirement. As I see it you need to find an ordered combination of segments for each neighboring pair of cities in the path. In the example, the first set of flights (101 201 301) takes you from New York to London, and the second set (102 939) takes you from London to Kolkata. If you will be checking multiple paths given the same segments you could preprocess the segments to build a directed graph. It would still be O(n^3), but one of those n's would be very small."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T13:40:51.263",
"Id": "1555",
"Score": "1",
"body": "If you use my method and create multiple arrays instead of a single array (one for each segment) than ANY selection of one choice from each array (or the point where all arrays are non-empty) solves the problem. This is still O(n*m) in the worst case. There is no need to go through the flights more than m times."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T13:56:47.050",
"Id": "1557",
"Score": "0",
"body": "thanks! I'll see if i can adapt your method correctly.\n@david: actually the flight numbers need not be ordered. i should have chosen better numbers..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-16T19:09:54.137",
"Id": "811",
"ParentId": "808",
"Score": "10"
}
},
{
"body": "<p>I've written the results in a common list, but you can use <code>vector<vector<string>></code>.</p>\n\n<pre><code>#include <vector>\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <iostream>\n\nclass Segment\n{\npublic:\n Segment(std::string const& departure, std::string const& arrival, int flighNum)\n :m_departure(departure)\n ,m_arrival(arrival)\n ,m_flightNumber(flighNum)\n {\n }\n std::string Departure() const { return m_departure; }\n std::string Arrival() const { return m_arrival; }\n int FlightNumber() const { return m_flightNumber; }\nprivate:\n std::string m_departure;\n std::string m_arrival;\n int m_flightNumber;\n};\n\nclass FillFlightNumbers\n{\npublic:\n FillFlightNumbers(std::vector<std::string> &flights, std::string const& departure, std::string const& arrival)\n :m_flights(flights)\n ,m_departure(departure)\n ,m_arrival(arrival)\n {\n }\n void operator()(Segment const& item) const\n {\n if (m_departure == item.Departure() && m_arrival == item.Arrival())\n {\n std::ostringstream oss;\n oss << item.FlightNumber();\n m_flights.push_back(oss.str());\n }\n }\nprivate:\n std::vector<std::string> &m_flights;\n std::string m_departure;\n std::string m_arrival;\n};\n\nvoid GetFlightNumbers(std::vector<Segment> const& segmentList, std::vector<std::string> const& roadList, std::vector<std::string> &result)\n{\n std::vector<std::string>::const_iterator iteratorPath = roadList.begin(), endPath = roadList.end();\n for ( ; iteratorPath != endPath; ++iteratorPath)\n {\n std::vector<std::string>::const_iterator nextIt = iteratorPath + 1;\n if (endPath == nextIt)\n {\n return;\n }\n std::for_each(segmentList.begin(), segmentList.end(), FillFlightNumbers(result, (*iteratorPath), (*nextIt)));\n }\n}\n\n// test solution\nvoid main()\n{\n std::vector<std::string> result;\n std::vector<Segment> segmentList;\n segmentList.push_back(Segment(\"New York\", \"London\", 101));\n segmentList.push_back(Segment(\"New York\", \"London\", 202));\n segmentList.push_back(Segment(\"New York\", \"London\", 909));\n segmentList.push_back(Segment(\"London\", \"Kolkata\", 2222));\n segmentList.push_back(Segment(\"London\", \"Kolkata\", 3333));\n segmentList.push_back(Segment(\"London\", \"Kolkata1\", 3344));\n std::vector<std::string> roadList;\n roadList.push_back(std::string(\"New York\"));\n roadList.push_back(std::string(\"London\"));\n roadList.push_back(std::string(\"Kolkata\"));\n GetFlightNumbers(segmentList, roadList, result);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T16:39:28.390",
"Id": "2070",
"ParentId": "808",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "811",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-16T16:49:59.310",
"Id": "808",
"Score": "14",
"Tags": [
"c++",
"optimization"
],
"Title": "Retrieving list of flight numbers from flight path"
} | 808 |
<p>I am primarily a Python programmer and have finally ditched the IDE in favour of vim and I will admit, I am loving it !</p>
<p>My <code>vimrc</code> file looks like this:</p>
<pre><code>autocmd BufRead,BufNewFile *.py syntax on
autocmd BufRead,BufNewFile *.py set ai
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,with,try,except,finally,def,class
set tabstop=4
set expandtab
set shiftwidth=4
filetype indent on
</code></pre>
<p>Any changes I should make to make my Python vim experience more pleasant? </p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T19:53:30.063",
"Id": "1646",
"Score": "0",
"body": "Hi Henry, welcome to the site. This really isn't a question for Code Review though, as this site is for reviewing working code. It is most likely better on Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-16T08:20:14.807",
"Id": "472003",
"Score": "0",
"body": "why would this be offtopic? this is working code"
}
] | [
{
"body": "<p>I like to add the following:</p>\n\n<pre><code>\" Allow easy use of hidden buffers.\n\" This allows you to move away from a buffer without saving\nset hidden\n\n\" Turn search highlighting on\nset hlsearch\n\n\" Turn on spelling\n\" This auto spell checks comments not code (so very cool)\nset spell\n\n\" tabstop: Width of tab character\n\" expandtab: When on uses space instead of tabs\n\" softtabstop: Fine tunes the amount of white space to be added\n\" shiftwidth Determines the amount of whitespace to add in normal mode\nset tabstop =4\nset softtabstop =4\nset shiftwidth =4\nset expandtab\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T19:34:31.727",
"Id": "1509",
"Score": "0",
"body": "Wonderful! Any suggestions for must-have vim plugins for enhanced Python support?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T16:58:54.873",
"Id": "1639",
"Score": "0",
"body": "@Henry You don't want to miss pyflakes (on-the fly syntax error reporting) and using pep8 as a compiler to see if you comply with the python style guide (PEP8). See my vim cfg files at (https://github.com/lupino3/config), it is fully commented and there also are some useful vim plugins."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T19:21:28.523",
"Id": "816",
"ParentId": "810",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T17:48:55.890",
"Id": "810",
"Score": "11",
"Tags": [
"python"
],
"Title": "Review the vimrc for a Python programmer"
} | 810 |
<p>I have a function that takes a column title, and a response.body from a urllib GET (I already know the body contains text/csv), and iterates through the data to build a list of values to be returned. My question to the gurus here: have I written this in the cleanest, most efficient way possible? Can you suggest any improvements?</p>
<pre><code>def _get_values_from_csv(self, column_title, response_body):
"""retrieves specified values found in the csv body returned from GET
@requires: csv
@param column_title: the name of the column for which we'll build a list of return values.
@param response_body: the raw GET output, which should contain the csv data
@return: list of elements from the column specified.
@note: the return values have duplicates removed. This could pose a problem, if you are looking for duplicates.
I'm not sure how to deal with that issue."""
dicts = [row for row in csv.DictReader(response_body.split("\r\n"))]
results = {}
for dic in dicts:
for k, v in dic.iteritems():
try:
results[k] = results[k] + [v] #adds elements as list+list
except: #first time through the iteritems loop.
results[k] = [v]
#one potential problem with this technique: handling duplicate rows
#not sure what to do about it.
return_list = list(set(results[column_title]))
return_list.sort()
return return_list
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T19:13:14.887",
"Id": "1508",
"Score": "1",
"body": "Tip: Don't use a blanket `except`, you will catch ALL exceptions rather than the one you want."
}
] | [
{
"body": "<p>My suggestions:</p>\n\n<pre><code>def _get_values_from_csv(self, column_title, response_body):\n # collect results in a set to eliminate duplicates\n results = set()\n\n # iterate the DictReader directly\n for dic in csv.DictReader(response_body.split(\"\\r\\n\")):\n # only add the single column we are interested in\n results.add(dic[column_title])\n\n # turn the set into a list and sort it\n return_list = list(results)\n return_list.sort()\n return return_list</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T19:19:04.433",
"Id": "814",
"ParentId": "812",
"Score": "0"
}
},
{
"body": "<p>Here's a shorter function that does the same thing. It doesn't create lists for the columns you're not interested in.</p>\n\n<pre><code>def _get_values_from_csv(self, column_title, response_body):\n dicts = csv.DictReader(response_body.split(\"\\r\\n\"))\n return sorted(set(d[column_title] for d in dicts))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T19:39:06.497",
"Id": "1510",
"Score": "0",
"body": "Thanks! This is brilliant! I'm still trying to wrap my head around how to use dictionaries in a comprehension context like this. So this is exactly what I was looking for. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T20:54:42.550",
"Id": "1511",
"Score": "0",
"body": "sorted() will return a list, so the list() bit isn't needed."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T08:12:37.030",
"Id": "1526",
"Score": "0",
"body": "Good point, Lennart -- Edited out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T19:24:29.407",
"Id": "817",
"ParentId": "812",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "817",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-16T19:08:41.697",
"Id": "812",
"Score": "9",
"Tags": [
"python",
"csv"
],
"Title": "Getting lists of values from a CSV"
} | 812 |
<p>I was playing around with LINQ and I came up with the following idea for composing locks taking advantage of C# Monadic syntax. It seems too simple, so I thought let me post it on StackExchange and see if anyone can quickly spot any major problems with this approach.</p>
<p>If you comment the lock inside the atomic implementation you'll see the accounts getting corrupted.</p>
<p>This idea is about being able to compose operations on the accounts without explicit locking.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace AtomicLinq
{
public static class AccountCombinators
{
public static IAtomic<Unit> TransferAndReverse(this Account accA,
Account accB,
double amount)
{
return from a in accA.TransferTo(accB, amount)
from b in accB.TransferTo(accA, amount)
select new Unit();
}
public static IAtomic<Unit> TransferTo(this Account accA,
Account accB,
double amount)
{
return from a in accA.Withdraw(amount)
from b in accB.Deposit(amount)
select new Unit();
}
public static IAtomic<double> Withdraw(this Account acc, double amount)
{
return Atomic.Create(() => acc.Amount -= amount);
}
public static IAtomic<double> Deposit(this Account acc, double amount)
{
return Atomic.Create(() => acc.Amount += amount);
}
}
static class Program
{
static void Main(string[] args)
{
var accA = new Account("John") { Amount = 100.0 };
var accB = new Account("Mark") { Amount = 200.0 };
var syncObject = new object();
Enumerable.Range(1, 100000).AsParallel().Select(_ => accA.TransferAndReverse(accB, 100).Execute(syncObject)).Run();
Console.WriteLine("{0} {1}", accA, accA.Amount);
Console.WriteLine("{0} {1}", accB, accB.Amount);
Console.ReadLine();
}
}
public class Account
{
public double Amount { get; set; }
private readonly string _name;
public Account(string name)
{
_name = name;
}
public override string ToString()
{
return _name;
}
}
#region Atomic Implementation
public interface IAtomic<T>
{
T Execute(object sync);
}
public static class Atomic
{
public static IAtomic<T> Create<T>(Func<object, T> f)
{
return new AnonymousAtomic<T>(f);
}
public static IAtomic<T> Create<T>(Func<T> f)
{
return Create(_ => f());
}
public static IAtomic<T> Aggregate<T>(this IEnumerable<IAtomic<T>> xs)
{
return xs.Aggregate((x, y) => from a in x
from b in y
select b);
}
public static IAtomic<K> SelectMany<T, V, K>(this IAtomic<T> m, Func<T, IAtomic<V>> f, Func<T, V, K> p)
{
return Create(sync =>
{
var t = m.Execute(sync);
var x = f(t);
return p(t, x.Execute(sync));
});
}
}
public class AnonymousAtomic<T> : IAtomic<T>
{
private readonly Func<object, T> _func;
public AnonymousAtomic(Func<object, T> func)
{
_func = func;
}
public T Execute(object sync)
{
lock (sync) // Try to comment this lock you'll see that the accounts get corrupted
return _func(sync);
}
}
#endregion Atomic Implementation
}
</code></pre>
| [] | [
{
"body": "<p>I'm trying to compile your code: </p>\n\n<ul>\n<li>What kind of class is Unit? Do I need to reference an additional assembly?</li>\n<li>Run at the end of <code>Enumerable.Range(1, 100000).AsParallel().Select(_ => accA.TransferAndReverse(accB, 100).Execute(syncObject)).Run();</code> seems to be unnecessary.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T08:29:19.640",
"Id": "1547",
"Score": "0",
"body": "System.Unit is defined in System.CoreEx.dll (Reactive Framework)\nhttp://msdn.microsoft.com/en-us/data/gg577609\nRun() is necessary because LINQ is lazy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T23:53:35.200",
"Id": "832",
"ParentId": "819",
"Score": "0"
}
},
{
"body": "<p>The disadvantage I see in your design is that you have decoupled the lock from the actual objects that should not be changed by another thread during the critical section.<br>\nIn your case only the two accounts of a transaction should be locked but you created a global lock <code>syncObject</code> that practically turns your parallel execution into a serial one. In other word if you had an <code>accC</code> and <code>accD</code> in Main you could not do a transfer between <code>accC</code> and <code>accD</code> in parallel with a transfer between <code>accA</code> and <code>accB</code>.<br>\nYou might be able to hack this by creating a series of lock objects and pass them somehow one-by-one in the proper order to <code>Execute</code> but if the call to the paralell execution is made from a much higher abstraction level then the manipulated objects are on you probably won't be able to pass the proper lock objects to <code>Execute</code>. Your only option would be to use a global lock for that <code>AsParallel()</code> \"session\" and that would defeat the purpose of using it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T22:14:48.823",
"Id": "846",
"ParentId": "819",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-16T21:07:12.450",
"Id": "819",
"Score": "3",
"Tags": [
"c#",
"linq",
"multithreading",
"locking"
],
"Title": "Composable Locks using LINQ. Can anyone see any problem with this ?"
} | 819 |
<p>I have created a small server program that encrypts text using a named pipe:</p>
<pre><code>#define UNICODE
#define WIN32_WINNT 0x0500
#include <stdio.h>
#include <windows.h>
#include <signal.h>
HANDLE hPipe;
DWORD WINAPI ServerProc(LPVOID lpVoid)
{
hPipe = CreateNamedPipe(L"\\\\.\\pipe\\testpipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |PIPE_WAIT, 1, 256, 256, 0, NULL);
if(!hPipe)
return wprintf(L"ERROR : Cannot create pipe.\n");
while(ConnectNamedPipe(hPipe, NULL))
{
WCHAR szText[80] = {0};
DWORD dwSize;
INT i;
ReadFile(hPipe, szText, 158, &dwSize, NULL);
for(i = 0; i < dwSize; i++)
szText[i] ^= '#';
WriteFile(hPipe, szText, 158, &dwSize, NULL);
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
}
CloseHandle(hPipe);
return 0;
}
void SignalHandler(int signal)
{
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
printf("Application closing...\n");
exit(0);
}
int wmain(void)
{
HANDLE hThread;
signal(SIGINT, SignalHandler);
hThread = CreateThread(NULL, 0, ServerProc, NULL, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
</code></pre>
<p>In this code I have created a <code>hPipe</code> handle as global because my program thread and the signal handler both need the handle.</p>
<p>Is this a correct way to handle signals?</p>
| [] | [
{
"body": "<p>It depends on what you want the server to do when an interrupt is sent.</p>\n\n<p>If you really want the program to stop when it is sent an interrupt, even though it is a service (Windows) or daemon (Unix), then what you did works. If, however, the program was run with settings to ignore interrupts, your code overrides that. The canonical sequence for setting a signal handler (for signal number <code>signum</code>) is:</p>\n\n<pre><code>if (signal(signum, SIG_IGN) != SIG_IGN)\n signal(signum, sighandler);\n</code></pre>\n\n<p>If the program was ignoring the signal, it continues to do so. Otherwise, it sets its own handler to handle the signal.</p>\n\n<p>On Unix, you usually use SIGTERM to do a controlled stop of a program, and for daemons, you typically use SIGHUP to indicate that the daemon should revisit its configuration.</p>\n\n<p>Also, in the POSIX world, it is generally recommended to use <code>sigaction()</code> rather than <code>signal()</code> because it gives different and better guarantees about what happens.</p>\n\n<p>If your program needed to continue after receiving the signal, you would have to reset the signal handler in the signal handler - and there's a small window of vulnerability which means that if two signals are sent fast enough, the program stops despite your handler. Using <code>sigaction()</code> avoids this timing vulnerability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T15:43:37.307",
"Id": "825",
"ParentId": "823",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-17T08:12:40.473",
"Id": "823",
"Score": "5",
"Tags": [
"c",
"file-system",
"windows",
"server",
"signal-handling"
],
"Title": "Handling SIGINT signal for a server program"
} | 823 |
<p>I am looking for any possible improvements on this tagging widget.</p>
<p>I ask for special attention to be paid to my <em>blur</em> handler in the event of a autocomplete option being specified but any optimizations or critiques are welcome.</p>
<pre>
Demo: <a href="http://webspirited.com/tagit">http://webspirited.com/tagit</a>
Js File: <a href="http://webspirited.com/tagit/js/tagit.js">http://webspirited.com/tagit/js/tagit.js</a>
Css File: <a href="http://webspirited.com/tagit/css/tagit.css">http://webspirited.com/tagit/css/tagit.css</a>
</pre>
<p>Code: </p>
<pre><code>(function($) {
$.widget("ui.tagit", {
// default options
options: {
tagSource: [],
triggerKeys: ['enter', 'space', 'comma', 'tab'],
initialTags: [],
minLength: 1
},
_keys: {
backspace: 8,
enter: 13,
space: 32,
comma: 44,
tab: 9
},
//initialization function
_create: function() {
var self = this;
this.tagsArray = [];
//store reference to the ul
this.element = this.element;
//add class "tagit" for theming
this.element.addClass("tagit");
//add any initial tags added through html to the array
this.element.children('li').each(function() {
self.options.initialTags.push($(this).text());
});
//add the html input
this.element.html('<li class="tagit-new"><input class="tagit-input" type="text" /></li>');
this.input = this.element.find(".tagit-input");
//setup click handler
$(this.element).click(function(e) {
if (e.target.tagName == 'A') {
// Removes a tag when the little 'x' is clicked.
$(e.target).parent().remove();
self._popTag();
}
else {
self.input.focus();
}
});
//setup autcomplete handler
this.options.appendTo = this.element;
this.options.source = this.options.tagSource;
this.options.select = function(event, ui) {
self._removeTag();
self._addTag(ui.item.value);
return false;
}
this.input.autocomplete(this.options);
//setup keydown handler
this.input.keydown(function(e) {
var lastLi = self.element.children(".tagit-choice:last");
if (e.which == self._keys.backspace)
return self._backspace(lastLi);
if (self._isInitKey(e.which)) {
e.preventDefault();
if ($(this).val().length >= self.options.minLength)
self._addTag($(this).val());
}
if (lastLi.hasClass('selected'))
lastLi.removeClass('selected');
self.lastKey = e.which;
});
//setup blur handler
this.input.blur(function(e) {
self._addTag($(this).val());
$(this).val('');
return false;
});
//define missing trim function for strings
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
this._initialTags();
},
_popTag: function() {
return this.tagsArray.pop();
}
,
_addTag: function(value) {
this.input.val("");
value = value.replace(/,+$/, "");
value = value.trim();
if (value == "" || this._exists(value))
return false;
var tag = "";
tag = '<li class="tagit-choice">' + value + '<a class="tagit-close">x</a></li>';
$(tag).insertBefore(this.input.parent());
this.input.val("");
this.tagsArray.push(value);
}
,
_exists: function(value) {
if (this.tagsArray.length == 0 || $.inArray(value, this.tagsArray) == -1)
return false;
return true;
}
,
_isInitKey : function(keyCode) {
var keyName = "";
for (var key in this._keys)
if (this._keys[key] == keyCode)
keyName = key
if ($.inArray(keyName, this.options.triggerKeys) != -1)
return true;
return false;
}
,
_removeTag: function() {
this._popTag();
this.element.children(".tagit-choice:last").remove();
}
,
_backspace: function(li) {
if (this.input.val() == "") {
// When backspace is pressed, the last tag is deleted.
if (this.lastKey == this._keys.backspace) {
this._popTag();
li.remove();
this.lastKey = null;
} else {
li.addClass('selected');
this.lastKey = this._keys.backspace;
}
}
return true;
}
,
_initialTags: function() {
if (this.options.initialTags.length != 0) {
for (var i in this.options.initialTags)
if (!this._exists(this.options.initialTags[i]))
this._addTag(this.options.initialTags[i]);
}
}
,
tags: function() {
return this.tagsArray;
}
,
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments); // default destroy
this.tagsArray = [];
}
});
})(jQuery);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T20:23:52.923",
"Id": "1572",
"Score": "0",
"body": "4 +votes and no answers/comments? Does that mean that this is almost max-optimized?"
}
] | [
{
"body": "<p>Cocky comment saying that this is almost max-optimized deserves a harsh review. </p>\n\n<p>I don't know anything about the <code>$.widget</code>, from my brief look of it none of my comments can be ignored because it's \"Something you need to do to play nicely with the $.widget\".</p>\n\n<p>Admittedly there are no obvious mistakes. Most of it is well structured and the code is readable. There are various nit picks all over the place though. Half of them can be ignored under the motto of that's a style specific comment.</p>\n\n<p>Over all the code was pretty good.</p>\n\n<p><strong>Here are the main points:</strong></p>\n\n<p><strong>Redundant:</strong></p>\n\n<p><code>this.element = this.element;</code></p>\n\n<p>That's just plain redundant.</p>\n\n<pre><code>if (lastLi.hasClass('selected'))\n lastLi.removeClass('selected');\n</code></pre>\n\n<p>jQuery is clever enough to not remove a class that doesn't exist. The hasClass check is just as expensive as the removeClass call.</p>\n\n<pre><code>_popTag: function() {\n return this.tagsArray.pop();\n}\n</code></pre>\n\n<p>That particular abstraction feels redundant when tagsArray is public aswell.</p>\n\n<pre><code>tags: function() {\n return this.tagsArray;\n}\n</code></pre>\n\n<p>again it feels like a redundant abstractions when tagsArray is public. You do know tagsArray is public right?</p>\n\n<p><strong>HTML Strings versus DOM manipulation</strong></p>\n\n<p><code>this.element.html('<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>');</code></p>\n\n<p>As mentioned in the comments I don't like messing with HTML directly. Use DOM manipulation methods instead.</p>\n\n<pre><code>this.input = $(document.createElement(\"input\"));\nthis.input.addClass(\"tagit-input\");\nthis.input[0].type = \"text\";\nvar li = $(\"<li></li>\");\nli.addClass(\"tagit-new\");\nli.append(this.input);\nthis.element.empty();\nthis.element.append(li);\n</code></pre>\n\n<p>This can actaully be improved on with jQuery 1.4</p>\n\n<pre><code>this.input = $(document.createElement(\"input\"), {\n \"class\": \"tagit-input\",\n \"type\": \"text\"\n});\nvar li = $(document.createElement(\"li\"), {\n \"class\": \"tagit-new\"\n});\nthis.element.empty().append(li.append(this.input));\n</code></pre>\n\n<p><strong>=== vs ==</strong></p>\n\n<p><code>if (e.target.tagName == 'A')</code></p>\n\n<p>Always use <code>===</code> end of.</p>\n\n<p><strong>name duplication</strong></p>\n\n<pre><code>this.options.appendTo = this.element;\nthis.options.source = this.options.tagSource;\n</code></pre>\n\n<p>Why do this? Why have the same thing mapped under different names? It's just hard to read and makes maintenance more of a pain. Also harder to refactor.</p>\n\n<p><strong>Return from a function or use if-else</strong></p>\n\n<pre><code>if (e.which == self._keys.backspace)\n return self._backspace(lastLi);\nif (self._isInitKey(e.which)) {\n</code></pre>\n\n<p>Might as well use <code>else if</code> here instead of returning. Avoid returning multiple times. There are some exceptions like guard statements or trivial functions.</p>\n\n<p><strong>Code smells</strong></p>\n\n<p><code>self.lastKey = e.which;</code></p>\n\n<p>Storing the last key that was pressed? That smells. Refactor or abstract this away. </p>\n\n<pre><code>_removeTag: function() {\n this._popTag();\n this.element.children(\".tagit-choice:last\").remove();\n}\n</code></pre>\n\n<p>You have both a remove and pop function. Refactor this so you only have one.</p>\n\n<p><strong>Caching</strong></p>\n\n<pre><code>self._addTag($(this).val());\n$(this).val('');\n</code></pre>\n\n<p>Really aught to cache it <code>var $this = $(this)</code>. Get into this habit some calls to <code>$</code> are really expensive. </p>\n\n<p><strong>Extending native prototypes</strong></p>\n\n<p><code>String.prototype.trim</code></p>\n\n<p>Don't do it. Simple as. You'll break everyone else's code. The problem is code like this:</p>\n\n<pre><code>for (var c in \"foo\") {\n console.log(someString[c]); \n}\n\"f\"\n\"o\"\n\"o\"\n\"function() { ... \"\n</code></pre>\n\n<p>This is why we check for hasOwnProperty in <code>for in</code> loops. Personally I prefer to just assume no-one extends native prototypes and shout anyone that does that rather then use hasOwnProperty. Not to mention there's lots of 3rd party code you use that doesn't check for it.</p>\n\n<p><strong>if (x) return true</strong></p>\n\n<pre><code>if (this.tagsArray.length == 0 || $.inArray(value, this.tagsArray) == -1)\n return false;\nreturn true;\n</code></pre>\n\n<p>Ignoring the fact that if statements without brackets make me rage. This really aught to be</p>\n\n<p><code>return this.tagsArray.length !== 0 && $.inArray(value, this.tagsArray) !== -1;</code></p>\n\n<p><strong>widget destroy function</strong></p>\n\n<pre><code>destroy: function() {\n $.Widget.prototype.destroy.apply(this, arguments); // default destroy\n this.tagsArray = [];\n}\n</code></pre>\n\n<p>The reason the widget makes call to <code>.destroy</code> is because there is no garbage collector for the DOM. Your supposed to clean up the dom. Your supposed to remove <code>this.element</code>, detach any event handlers. And whatever else needs cleaning up.</p>\n\n<p>You do not need to clean up javascript. JS has a garbage collector.</p>\n\n<p><strong>Here is the full code annotated:</strong></p>\n\n<p>just ctrl-f <code>//*</code></p>\n\n<pre><code>(function($) {\n $.widget(\"ui.tagit\", {\n\n // default options\n options: {\n tagSource: [],\n triggerKeys: ['enter', 'space', 'comma', 'tab'],\n initialTags: [],\n minLength: 1\n },\n\n _keys: {\n backspace: 8,\n enter: 13,\n space: 32,\n comma: 44,\n tab: 9\n },\n\n //initialization function\n _create: function() {\n\n var self = this;\n this.tagsArray = [];\n\n //store reference to the ul\n //* WTF? Seriously? you know theres only one this object right?\n this.element = this.element;\n\n //add class \"tagit\" for theming\n this.element.addClass(\"tagit\");\n\n //add any initial tags added through html to the array\n this.element.children('li').each(function() {\n self.options.initialTags.push($(this).text());\n });\n\n //add the html input\n //* Style issue. i don't like passing html strings around.\n /*\n this.input = $(\"<input></input>\");\n this.input.addClass(\"tagit-input\");\n this.input[0].type = \"text\";\n var li = $(\"<li></li>\");\n li.addClass(\"tagit-new\");\n li.append(this.input);\n this.element.empty();\n this.element.append(li);\n */\n this.element.html('<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>');\n\n this.input = this.element.find(\".tagit-input\");\n\n //setup click handler\n //*WTF this.element is already a jQuery object.\n $(this.element).click(function(e) {\n //*WTF use \"===\"\n if (e.target.tagName == 'A') {\n // Removes a tag when the little 'x' is clicked.\n //* Refactor this to ._popTag()\n /*\n self._popTag(e.target);\n */\n $(e.target).parent().remove();\n self._popTag();\n }\n else {\n self.input.focus();\n }\n });\n\n //setup autcomplete handler\n //*WTF Why map it to .appendTo. Feels like an annoying abstraction\n this.options.appendTo = this.element;\n //*WTF renaming it for no good reason\n this.options.source = this.options.tagSource;\n this.options.select = function(event, ui) {\n // Remove and add a tag? Feels like it could use a comment\n // or a swap/switch tags method\n self._removeTag();\n self._addTag(ui.item.value);\n return false;\n }\n this.input.autocomplete(this.options);\n\n //setup keydown handler\n this.input.keydown(function(e) {\n var lastLi = self.element.children(\".tagit-choice:last\");\n if (e.which == self._keys.backspace)\n //*WTF don't return use else if statements.\n return self._backspace(lastLi);\n\n if (self._isInitKey(e.which)) {\n e.preventDefault();\n //*WTF if the string in val is bigger then minLength?\n // Too code specific give a high level explanation.\n if ($(this).val().length >= self.options.minLength)\n self._addTag($(this).val());\n }\n //*WTF Why are you removing the selected class from the last\n // li on every key down press? This really could use a comment.\n if (lastLi.hasClass('selected'))\n lastLi.removeClass('selected');\n\n //*WTF storing the lastKey is a code smell. Reffactor this away\n self.lastKey = e.which;\n });\n\n //setup blur handler\n this.input.blur(function(e) {\n //*WTF always cache\n /*\n var $this = $(this);\n */\n self._addTag($(this).val());\n //* WTF duplication. The input is already cleared in the\n // addtag.\n $(this).val('');\n return false;\n });\n\n //define missing trim function for strings\n //*WTF don't extend native prototypes. Your evil. Evil evil evil.\n // Theres a perfectly good $.trim. Use it!\n String.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, \"\");\n };\n\n this._initialTags();\n\n },\n //*WTF Feels like a useless abstraction. _popTag is \"internal\" because\n // it starts with \"_\" but this.tagsArray is public. \n _popTag: function() {\n return this.tagsArray.pop();\n }\n ,\n\n _addTag: function(value) {\n this.input.val(\"\");\n value = value.replace(/,+$/, \"\");\n //*The extension! use var value = $.trim(value)\n value = value.trim();\n //* use \"===\" here. There's no reason why not to. \n if (value == \"\" || this._exists(value))\n return false;\n\n var tag = \"\";\n //* Ew more string generated HTML. use the jquery or native DOM \n // manipulation instead\n tag = '<li class=\"tagit-choice\">' + value + '<a class=\"tagit-close\">x</a></li>';\n $(tag).insertBefore(this.input.parent());\n //*WTF Sure. lets call it again? You know, just in case someone\n // managed to edit the input whilst where running IO blocking\n // javascript code.\n this.input.val(\"\");\n //* Personally I would take the tagsArray and overwrite it's \n // .push methods with the _addTag function. That way you can just\n // call this.tagsArray.push everywhere. Make sure to document it.\n // put it in the init function if you want.\n /*\n var _push = this.tagsArray.push;\n this.tagsArray.push = function(value) {\n _push.apply(this, arguments); \n // do stuff here.\n };\n */\n this.tagsArray.push(value);\n }\n ,\n\n _exists: function(value) {\n //* check with === !!! Replace this with\n /*\n return this.tagsArray.length !== 0 &&\n $.inArray(value, this.tagsArray) !== -1;\n */\n if (this.tagsArray.length == 0 || $.inArray(value, this.tagsArray) == -1)\n return false;\n return true;\n }\n ,\n\n _isInitKey : function(keyCode) {\n var keyName = \"\";\n for (var key in this._keys)\n //* Refactor this to \n /*\n if (this._keys[key] === keyCode) {\n return $.inArray(key, this.options.triggerKeys) !== -1;\n }\n */\n if (this._keys[key] == keyCode)\n keyName = key//*WTF don't forget that semi colon.\n //* unneccesary if refactored.\n if ($.inArray(keyName, this.options.triggerKeys) != -1)\n return true;\n return false;\n }\n ,\n //*WTF It feels so wrong from a design point of view to have both\n // a popTag and a removeTag function. What's the difference?\n // Why do you remove it from the tagList but not from the DOM?\n _removeTag: function() {\n this._popTag();\n this.element.children(\".tagit-choice:last\").remove();\n }\n ,\n //*WTF the whole backspace in lastKey things means you backspace has \n // two meanings when pressed byt eh user. It either selects it or\n // removes it. This just seems like bad design. Get rid of it.\n _backspace: function(li) {\n if (this.input.val() == \"\") {\n // When backspace is pressed, the last tag is deleted.\n if (this.lastKey == this._keys.backspace) {\n //*WTF why not just call _removeTag!!!\n this._popTag();\n li.remove();\n this.lastKey = null;\n } else {\n li.addClass('selected');\n this.lastKey = this._keys.backspace;\n }\n }\n return true;\n }\n ,\n\n _initialTags: function() {\n //*WTF use a > 0 check. checking for not 0 is just annoying,\n // Length can never be negative.\n if (this.options.initialTags.length != 0) {\n //*WTF avoid a for in loop on an array just use a standard\n /*\n var len = this.options.initialTags.length;\n for (var i=0;i < len;i++) {\n var tag = this.options.initialTags[i];\n if (!this._exists(tag)) {\n this._addTag(tag);\n }\n }\n */\n for (var i in this.options.initialTags)\n //*WTF you already check for existance in the addTag \n // function. Why do it here? Choose to do it either before\n // calling or in the function not both.\n if (!this._exists(this.options.initialTags[i]))\n this._addTag(this.options.initialTags[i]);\n }\n }\n ,\n\n //*WTF why have both a tags & a tagsArray. Why? There both public.\n // It just a useless abstraction\n tags: function() {\n return this.tagsArray;\n }\n ,\n //*WTF What is this? C++. We have a garbage collector. if tagsArray\n // is no longer referenced anywhere then we don't need to null it on\n // purpose. \n // From a $.widget point of view you want destroy to act as a garbage collector\n // for the DOM. Remove stuff from the DOM. The JS has it's own garbage\n // collector. \n destroy: function() {\n $.Widget.prototype.destroy.apply(this, arguments); // default destroy\n this.tagsArray = [];\n }\n\n });\n})(jQuery);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:50:07.333",
"Id": "1769",
"Score": "0",
"body": "Haha, you are correct. I was actually trying to extract an answer from people with that comment.\n\nI am going to comment on each point in a seperate comment for ease of readability."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:50:47.660",
"Id": "1770",
"Score": "0",
"body": "`this.element = this.element`.\n\nYeah... I think that was a typo...\nRemoved."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:51:43.273",
"Id": "1771",
"Score": "0",
"body": "`if (lastLi.hasClass('selected'))\n lastLi.removeClass('selected');`\n\nI honestly thought jQuery would throw a stink, removed the check."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:53:55.907",
"Id": "1772",
"Score": "0",
"body": "`_popTag: function() {\n return this.tagsArray.pop();\n}`\n\nYou make a good point. Its simply for future use incase I want to do something else while popping a tag. I dont have to add the code after every instance where I pop a tag."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:54:53.253",
"Id": "1773",
"Score": "0",
"body": "`self._addTag($(this).val());\n$(this).val('');`\n\nYeah, I normally do, I think I was just being lazy..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:55:44.797",
"Id": "1774",
"Score": "0",
"body": "`HTML Strings versus DOM manipulation` html string manipulation is a lot less expensive than dom manipulation. one paint event vs x paint events."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:56:38.930",
"Id": "1775",
"Score": "0",
"body": "`String.prototype.trim` yeah, again me being lazy, was a \"copy and paste\" job. Was planning on turning that into a function."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:57:20.973",
"Id": "1776",
"Score": "0",
"body": "`if (e.target.tagName == 'A')` whoops, I normally do, typo..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:58:10.553",
"Id": "1777",
"Score": "0",
"body": "`return this.tagsArray.length !== 0 && $.inArray(value, this.tagsArray) !== -1;` ah very useful. thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T08:58:43.233",
"Id": "1778",
"Score": "0",
"body": "`widget destroy function` whoops... knew I forgotten to write something, turns out it was that function ;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T09:00:04.480",
"Id": "1779",
"Score": "0",
"body": "`self.lastKey = e.which;` well, I guess I could always check if the previous tag has the _selected_ class, but would that not be more expensive? this is simply so we can check if backspace has been pressed twice in a row."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T09:01:25.633",
"Id": "1780",
"Score": "0",
"body": "`tags: function() {\n return this.tagsArray;\n}` This is so that you can call `$('#myUl').tagit('tags');` and get the array of tags, instead of having to do `$('#myUl').tagit('widget').tagsArray;`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-25T12:44:05.620",
"Id": "1787",
"Score": "0",
"body": "@Hailwood most of those are reasonable. Still I think `self.lastKey` needs some proper refactoring. `backspace` should be atomic. Hitting it twice shouldnt break anything. Also please provide a benchmark for string vs dom manipulation. I don't buy it."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T18:13:36.433",
"Id": "859",
"ParentId": "824",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "859",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T09:30:50.847",
"Id": "824",
"Score": "8",
"Tags": [
"javascript",
"optimization",
"jquery",
"jquery-ui"
],
"Title": "Looking for improvements on my jQuery-UI tagging widget"
} | 824 |
<p>I was writing a piece of code (a custom <code>EntityProcessor</code> for Solr, but that isn't too relevant) designed to break lines of input based on a string delimiter (<code>toMatch</code> below).</p>
<p>Characters are read from a stream and then passed to <code>addChar</code>.<br>
The assumption is that each character comes in a stream and look-ahead isn't allowed - the break needs to happen after the last character of a match is passed in.</p>
<p>I wrote two implementations below <code>addChar</code> and <code>addChar2</code>.<br>
The first is a simple, dumb, keep a buffer and compare it each iteration, the second is a simple state machine and the latter is slightly faster.</p>
<pre><code>import java.util.Iterator;
import java.util.LinkedList;
public class CharStreamMatcher {
protected char[] toMatch = null;
public MagicCharStreamMatcher(char[] match){
toMatch = match;
for(int i=0;i<match.length;i++) li.add((char)0);
}
public void clear(){
correspondences.clear();
}
LinkedList<Character> li = new LinkedList<Character>();
public boolean addChar2(char c){
li.addLast(c);
li.removeFirst();
int i=0;
for(Character ch : li){
if(ch.charValue() != toMatch[i++])
return false;
}
return true;
}
private class MutableInteger{
public int i;
public MutableInteger(int i){
this.i = i;
}
}
LinkedList<MutableInteger> correspondences = new LinkedList<MutableInteger>();
public boolean addChar(char c){
boolean result = false;
if(c == toMatch[0])
correspondences.add(new MutableInteger(-1));
Iterator<MutableInteger> it = correspondences.iterator();
while(it.hasNext()){
MutableInteger mi = it.next();
mi.i++;
// check the match
if(c != toMatch[mi.i]){
it.remove();
}
// are we done?
else if(mi.i == toMatch.length-1){
result = true;
it.remove();
}
}
return result;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T22:35:34.030",
"Id": "1577",
"Score": "1",
"body": "Depends on the statistics of toMatch. [Knuth-Morris-Pratt](http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) might be an improvement if the delimiters are fairly long."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-23T01:50:28.517",
"Id": "1688",
"Score": "1",
"body": "if performance is important you can't be adding one char at a time. Also prefer explicit int for loops to java 5 sugared iterator loops."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T06:33:22.277",
"Id": "2548",
"Score": "2",
"body": "A code style comment: your code will be more readable if you put the attribute declarations at the start of the class ... before the constructors and methods. That's where people expect to find them."
}
] | [
{
"body": "<p>There are more-sophisticated algorithms you can use, depending on the input and the search string. Even keeping the \"one character at a time\" interface though, there are optimizations to the implementation. Someone linked to KMP in a comment to your question - that's a good way to go if you can do some initial setup and buffer an arbitrary amount of the incoming stream.</p>\n\n<p>I think you're on the right track with a state machine, but the implementation in addChar2 looks kind of heavyweight, with the MutableInteger class and a linked list, and an iterator-driven loop, and all. If you want this to be fast, you'll likely want to use primitive types (ints and arrays of ints) rather than OO wrappers around the primitive types.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T20:32:17.730",
"Id": "1507",
"ParentId": "827",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-17T18:18:47.860",
"Id": "827",
"Score": "9",
"Tags": [
"java",
"stream"
],
"Title": "Implementing a fast 'split' function on a stream of characters in Java"
} | 827 |
<p>In my spare time I decided to write a program that would systematically identify prime numbers from 2 to 18,446,744,073,709,551,615. This is for fun and learning, as I know it will take too long to actually ever reach the upward value, but I'm using this to explore parallel processing. I know this is not a traditional question but I very much would like the critique of my peers. I know this can been torn apart, so please do, but if you do, do so constructively.</p>
<p>The program is designed to run until the user hits the <kbd>esc</kbd> key; at which time it will generate a file with all of the prime numbers discovered. The path to this file needs to be configured to a value for your directory structure. When I restart the program it will accept, as an argument, a primes text file, reading it in and starting from where it left off. The parallel processing portion and implementing the sieve for finding primes is what I was interested in woodshedding. </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace Prime
{
public class Program
{
public static void Main(string[] args)
{
List<UInt64> primes = new List<UInt64>();
primes.Add(2);
UInt64 numberToCheck = 3;
if (args.Count() > 0)
{
numberToCheck = ReadPrimesToList(args[0].ToString(), out primes) +2;
}
try
{
bool quit = false;
Console.WriteLine("Prime Number Search");
while (!quit)
{
if (Console.KeyAvailable)
quit = Console.ReadKey().Key == ConsoleKey.Escape;
Console.Write("Processing: " + numberToCheck);
if (CheckForPrime(numberToCheck, primes))
{
primes.Add(numberToCheck);
Console.WriteLine(" Prime Found!");
}
else
Console.WriteLine(" Not Prime :(");
if (numberToCheck < UInt64.MaxValue)
numberToCheck+=2;
else
break;
}
Console.WriteLine("Exiting");
WritePrimesToFile(primes);
Console.WriteLine("< Press Any Key To Exit >");
Console.ReadKey();
}
catch
{
if (primes.Count > 0)
WritePrimesToFile(primes);
}
}
private static UInt64 ReadPrimesToList(string fileName, out List<UInt64> primes)
{
primes = new List<UInt64>();
FileInfo file = new FileInfo(fileName);
StreamReader reader = new StreamReader(file.OpenRead());
String lineIn = String.Empty;
while (!reader.EndOfStream)
{
lineIn = reader.ReadLine();
String[] numberStrings = lineIn.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (String numberString in numberStrings)
{
primes.Add(UInt64.Parse(numberString));
}
}
return primes[primes.Count() - 1];
}
private static void WritePrimesToFile(List<UInt64> primes)
{
String dateAndTime = DateTime.Now.ToString("yyyyMMddhhmm");
String fileName = String.Format(@"<substitute your path here>\primes [{0}].txt", dateAndTime);
FileInfo file = new FileInfo(fileName);
using (StreamWriter writer = file.CreateText())
{
int maxLength = primes[primes.Count - 1].ToString().Length;
String line = String.Empty;
const int maxColumn = 16;
int column = 0;
foreach (UInt64 number in primes)
{
string numberString = number.ToString();
int numberLength = numberString.Length;
line += numberString.PadLeft(maxLength, ' ') + ((column < (maxColumn-1)) ? " " : String.Empty);
column++;
if (column == maxColumn)
{
writer.WriteLine(line);
line = string.Empty;
column = 0;
}
}
if (line.Length > 0)
writer.WriteLine(line);
writer.Flush();
writer.Close();
}
}
private static bool CheckForPrime(UInt64 numberToCheck, List<UInt64> primes)
{
if ((numberToCheck % 2) == 0)
return false;
UInt64 halfway = (UInt64)(Math.Ceiling((float)numberToCheck / 2F));
bool isprime = false;
UInt64 factor = 0;
Parallel.ForEach<UInt64>(primes, (prime, loopState) =>
{
if (prime > halfway)
{
isprime = true;
loopState.Stop();
}
if ((numberToCheck % prime) == 0)
{
factor = prime;
isprime = false;
loopState.Stop();
}
});
return (isprime && factor == 0);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Hmmmm... To speed it up, I'd look into alternate Prime Number tests, like <a href=\"http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test\" rel=\"nofollow\">Miller Rabin Test</a> or <a href=\"http://en.wikipedia.org/wiki/AKS_primality_test\" rel=\"nofollow\">AKS Test</a></p>\n\n<p>Here is a sample of code for the Miller Rabin algorithm written in C#. Maybe it can be parallelized and work faster than the method you currently have?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T21:12:17.397",
"Id": "1573",
"Score": "0",
"body": "Well I hit a ceiling last night, the combined memory usage of primes from 2 to 1339484197 pushed the runtime to throw a System.OutOfMemoryException. So I'll have to write the primes out to a file on the fly, perhaps in batches, and only keep enough primes around to test up the SqRt; or look into implementing one of the alternate tests you suggest."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T21:17:16.850",
"Id": "829",
"ParentId": "828",
"Score": "2"
}
},
{
"body": "<p>Console.Write is horribly slow. I mean it's not <em>that</em> bad, but it's worse than you might think.</p>\n\n<p>Try something like:</p>\n\n<pre><code>if((numberToCheck + 1) % 1000 == 0)\n Console.Write(\"Processing: \" + numberToCheck);\n</code></pre>\n\n<p>I've had many cases where updating the console less often resulted in a massive speed boost. A good rule is not to update the console more than a few times per second.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-02T13:33:36.707",
"Id": "1916",
"Score": "0",
"body": "Actually using the console too much can result in (afaik uncatchable) exceptions, especially when used in the main application thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T00:03:35.057",
"Id": "29589",
"Score": "0",
"body": "@Fge If that happens to you raise a bug. It should not be an assumption that you have to try to avoid using the console to avoid exceptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-14T08:55:46.973",
"Id": "87473",
"Score": "0",
"body": "maybe also interesting here: http://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-02T11:23:35.747",
"Id": "1081",
"ParentId": "828",
"Score": "23"
}
},
{
"body": "<p>For checking a the primeness of several numbers, you should use <a href=\"http://en.wikipedia.org/wiki/Sieve_of_eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a>. It is two simple loops you can parallelize, and the time complexity is just O(n log(n) log log (n)).</p>\n\n<p>Also, as Hannesh said, writing to the console is incredibly slow, I guess you should probably avoid writing \"Processing some number\" and just wrute the last number processed at the end.</p>\n\n<p>Console functions also create a bottleneck, specially if you check them after every number, I would check numbers in batches of 1000 or 10000 before asking if the user is pressing a key.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T18:29:33.567",
"Id": "1589",
"ParentId": "828",
"Score": "4"
}
},
{
"body": "<p>You could consider tweaking the prime test to bail out as soon as you reach a prime that is >= sqrt(numberToTest). The proof (very loosely) is that a composite number can always be written as the product of two integer factors, each > 1. Of the two factors, one must be necessarily <= the other. Thus you can stop testing when you reach the worst-case upper bound which is the square root of the test number. Other more efficient means exist for testing primes, but this tweak requires remarkably little code.</p>\n\n<p>Here's a summary of my tweaks:</p>\n\n<ul>\n<li>Removed \"halfway\" and \"factor\" variables & their use. They may have had value for debugging purposes, but they seem to detract from the overall goal of the method.</li>\n<li>Defaulted isprime to true - if we make it all the way through the candidate factors without finding one that is divisible, then isprime = true is the correct value to return.</li>\n<li>Avoided computing the square root of numberToCheck by changing the condition to first square the candidate factor and compare the result with numberToCheck in the LINQ Where call. This could eat up time when testing much larger numbers if the repeated multiplications outweigh the cost of computing an integer square root.</li>\n<li>The manner I chose to filter the primes using the LINQ Where could have a negative performance impact based on how the TPL parititions the work. I recall reading a post from the TPL team that they partition the work differently for indexable IEnumerables, and I wanted to provide the link here, but I am having trouble locating it. In short, this might offset the performance improvement bailing out earlier might provide.</li>\n</ul>\n\n<p>Regardless, here are the above tweaks (untested):</p>\n\n<pre><code>private static bool CheckForPrime(UInt64 numberToCheck, List<UInt64> primes)\n{\n if ((numberToCheck % 2) == 0)\n return false;\n\n bool isprime = true;\n\n Parallel.ForEach(primes.Where(prime => prime*prime < numberToCheck),\n (prime, loopState) =>\n {\n if ((numberToCheck % prime) == 0)\n {\n isprime = false;\n loopState.Stop();\n }\n });\n\n return isprime;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T22:10:30.090",
"Id": "29583",
"Score": "1",
"body": "You can replace `Where` with `TakeWhile` since the primes are ordered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-14T14:51:41.520",
"Id": "29624",
"Score": "0",
"body": "@CodesInChaos - `TakeWhile` is an excellent improvement. +1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-12T04:04:13.347",
"Id": "2373",
"ParentId": "828",
"Score": "1"
}
},
{
"body": "<p>Here is a super cute realization which I've seen in a book. If you wish you could optimize it. </p>\n\n<pre><code>IEnumerable<int> numbers = Enumerable.Range(3, 100000);\nvar parallelQuery =\n from n in numbers.AsParallel()\n where Enumerable.Range(2, (int)Math.Sqrt(n)).All(i => n % i > 0)\n select n;\n\nint[] primes = parallelQuery.ToArray();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T20:05:43.747",
"Id": "18561",
"ParentId": "828",
"Score": "3"
}
},
{
"body": "<p>Answers so far failed to inform you that this code is completely wrong:</p>\n\n<pre><code>if (prime > halfway)\n{\n isprime = true;\n loopState.Stop();\n}\n</code></pre>\n\n<p>You <strong><em>can't</em></strong> do that on <code>Parallel.Foreach</code> - there's no guarantee as to the order of execution. That's the whole point of the parallel loop!</p>\n\n<pre><code>if (prime > halfway)\n{\n loopState.Break(); // join all 'previous' jobs \n return; // terminate *this* job, not caring about others\n}\n</code></pre>\n\n<p>Another serious flaw is the condition itself - that fails as soon as checking 3. \nShould be:</p>\n\n<pre><code>if (prime >= halfway)\n</code></pre>\n\n<p>Another important thing, is that <strong><em>for this specific task, plain good ol` sequential for(...) is very likely to outperform the parallel version.</em></strong> </p>\n\n<p><del>My results for 1234567890, tested on Mono:</del> (stupid me)</p>\n\n<p>My results for 2^31 - 1, tested on Mono:</p>\n\n<pre><code>parallel: 5.3873 [ms], returned True\nsequential: 1.0157 [ms], returned True\n2147483647 : True\n</code></pre>\n\n<p><strong>EDIT</strong>: I see some reports suggesting the Parallel.ForEach implementation on Mono is exceptionally slow - would be nice to have some alternative results from win dudes. </p>\n\n<p><strong>Note about 'hitting memory boundry'</strong>:</p>\n\n<blockquote>\n <p>I hit the memory limits running from 2 to 1339484197</p>\n</blockquote>\n\n<p>Let's make a fun math game:</p>\n\n<ol>\n<li>The number of primes less than N is approximated by <code>N / ln(N)</code>. </li>\n<li>Our maximum list capacity is <code>2GB</code> (32/64 bit alike). If you run on 32 bit, your whole process available memory is <code>2GB</code> altogether. So you cannot even have that. </li>\n<li>We're using <code>long</code>, so each prime occupies <code>8 bytes</code>.</li>\n<li>And to add more evil, we didn't allocate list size in advance, so we're operating on doubling mode. That means every time we have 2^N elements, we're allocating space for 2*2^N <strong>more</strong>, thus momentarily using 3x the space needed for the actual list. So what happened here?</li>\n<li>We were at <code>N = 1339484197</code>, so the list had ~ <code>N/ln(N)</code> elements => ~ <code>64M primes</code></li>\n<li>Each prime takes 8 bytes, so we're eating <code>~500MB</code> of memory.</li>\n<li>Now we add on more item and need to double, so we have to allocate <code>1GB more</code>. That's <code>1.5GB</code> altogether. Too much.</li>\n<li>Now to the good news: We can get <code>x3</code> primes more just by passing a <code>MAX_SIZE</code> to the List c'tor. Indeed, we can get <code>x6</code>, as one side implication of the above math game, is that we can safely use <code>UInt32</code>. </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T22:58:50.430",
"Id": "29584",
"Score": "0",
"body": "You can use `AsOrdered()` though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T22:49:50.793",
"Id": "18565",
"ParentId": "828",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "18565",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-17T21:01:51.293",
"Id": "828",
"Score": "39",
"Tags": [
"c#",
"primes"
],
"Title": "Calculation of prime numbers making use of Parallel.ForEach"
} | 828 |
<p>The general idea of the code is that I have a <code>+</code> or <code>-</code> icon (<code>".trigger"</code>) that is click-able and will expand or collapse the content (<code>".cont"</code>) directly following it (there are many of there expand/collapse pairs). I also have a <code>span</code>(<code>"#expandAll"</code>) that, when clicked, will expand or collapse every block.</p>
<p>Please review my first usage of jQuery and help me put my head into a more jQuery state. Where can the code be improved? Are there any problems with it? Is there a better way to do it?</p>
<p>(To be perfectly honest, I have no idea what the <code>$()</code> function <em>really</em> does.)</p>
<pre><code>var expandAll = function () {
$(".cont").removeClass("hid");
$("#expandAll").html("Colapse All");
$("#expandAll").unbind("click", expandAll);
$(".trigger").html("-");
$("#expandAll").click(colapseAll);
}
var colapseAll = function () {
$(".cont").addClass("hid");
$("#expandAll").html("Expand All");
$("#expandAll").unbind("click", colapseAll);
$(".trigger").html("+");
$("#expandAll").click(expandAll);
}
$(document).ready(function () {
$(".trigger").click(function (event) {
$this = $(this);
$this.html($this.text() == '+' ? '-' : '+');
$($this.nextAll(".cont").get(0)).toggleClass("hid");
});
$("#expandAll").click(expandAll);
});
</code></pre>
<p>Please let me know if you need more/less info.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T13:34:24.267",
"Id": "1552",
"Score": "0",
"body": "@Jonathan, ha, nothing really. It just seems that everyone these days starts 'programming' with html, css, and JQuery."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T16:42:56.313",
"Id": "1585",
"Score": "0",
"body": "@zzz Yeah, I know, thanks. I have fixed it in my code."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T21:13:37.743",
"Id": "1600",
"Score": "0",
"body": "You should run your first jQuery in the Firebug Console."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T01:56:18.670",
"Id": "6114",
"Score": "0",
"body": "\"To be perfectly honest, I have no idea what the $() function really does.\" Don't worry, nobody knows everything it does. I've heard it can create world peace. [Hey, John Resig wrote it, right?](http://benalman.com/news/2009/12/john-resig-javascripts-chuck-norris/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-15T02:04:04.767",
"Id": "6116",
"Score": "0",
"body": "@alpha, haha that's good to know."
}
] | [
{
"body": "<p>I've refactored your code and added comments to explain certain things.</p>\n\n<pre><code>// We can shorten this from document.ready(...) to $(...) \n// Internally, jQuery will add the passed in function to a list\n// of handlers that will be invoked when the document is ready.\n$(function() {\n // Since the $ function will query the document with the \n // specified selector we want to cache these.\n // Doing this from within the ready callback allows us \n // to keep these references hidden.\n // I've also added the 2 function variables to keep them\n // hidden as well.\n var expandAll, colapseAll,\n expandAllElement = $(\"#expandAll\"),\n contElements = $(\".cont\"),\n triggerElements = $(\".trigger\");\n\n expandAll = function() {\n contElements.removeClass(\"hid\");\n triggerElements.html(\"-\");\n // Notice how we can chain these calls together?\n // jQuery was designed with a fluent interface.\n expandAllElement.html(\"Colapse All\").one(\"click\", colapseAll);\n };\n\n colapseAll = function() {\n contElements.addClass(\"hid\");\n triggerElements.html(\"+\");\n expandAllElement.html(\"Expand All\").one(\"click\", expandAll);\n };\n\n triggerElements.click(function(event) {\n // Always define a variable so the 'name' \n // is not defined in the global object,\n var $this = $(this);\n $this.html($this.text() == '+' ? '-' : '+');\n $($this.nextAll(\".cont\").get(0)).toggleClass(\"hid\");\n });\n\n // Using the one function allows you to skip \n // unbinding the event handler for each click.\n expandAllElement.one(\"click\", expandAll);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T22:22:13.447",
"Id": "1540",
"Score": "0",
"body": "Why do you declare `expandAll` and `colapseAll` outside of the `doc.ready()` function?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T22:37:05.343",
"Id": "1541",
"Score": "0",
"body": "@Justin - You know I wasn't sure if you were manually calling those functions from other places. If your not using the functions anywhere else then that is definitely a good idea. See my latest changes."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T12:36:27.943",
"Id": "1549",
"Score": "1",
"body": "Hm there's no need for making `expandAll` and `colapseAll` expressions, declarations would do just fine here. Also both functions are extremely similar in their workings, refactoring the code out into a more generic helper would be a good idea here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T17:01:10.900",
"Id": "1566",
"Score": "0",
"body": "OCD alert: `collapse` has two Ls (yes, I know the OP has the same typo)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T18:34:57.547",
"Id": "1571",
"Score": "0",
"body": "@Matt, yeah I didn't notice that spelling fail until after I posted the code. Didn't feel like fixing it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T22:23:06.307",
"Id": "1574",
"Score": "0",
"body": "For portability/extendability purposes you should use `jQuery(function($){});` to alias `jQuery` to `$` whether or not `noConflict` is called."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-23T14:35:17.227",
"Id": "1698",
"Score": "0",
"body": "Accepting this answer because it was first and helped me make the most improvements."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-17T21:45:53.470",
"Id": "831",
"ParentId": "830",
"Score": "15"
}
},
{
"body": "<pre><code>// If you use selectors multiple times, always cache them into variables, else jQuery has to search for them multiple times.\nvar $cont = $('.cont'),\n $expandAll = $('#expandAll'),\n $trigger = $('.trigger');\n\nfunction expandAll() {\n $cont.removeClass('hid');\n $trigger.text('-');\n // Use .text() instead of .html().\n // You can chain these calls together.\n // If you use .one(), you don't have to unbind the previous event handler next time, jQuery does it for you.\n $expandAll.text('Collapse All').one('click', collapseAll);\n}\nfunction collapseAll() {\n $cont.addClass('hid');\n $trigger.text('-');\n $expandAll.text('Expand All').one('click', expandAll);\n}\n\n// You can pass a function to jQuery itself – it's a shorthand for $(document).ready().\n$(function() {\n // There's no need to pass the event argument, because\n // 1. You didn't use it there\n // 2. jQuery “normalizes” the event object, so you don't have to pass it as an argument. If you want a shorthand for it, do it inside the function:\n // var e = event;\n $trigger.click(function() {\n // Always use var to declare variables, to prevent polluting the global scope.\n var $this = $(this);\n // Again: use .text() instead of .html().\n $this.text($this.text() == '+' ? '-' : '+');\n // There's no need to do this:\n // $($this.nextAll(\".cont\").get(0)).toggleClass(\"hid\");\n // You can simply do this:\n $this.nextAll('.cont').toggleClass('hid');\n });\n $expandAll.one('click', expandAll);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-23T17:07:22.643",
"Id": "1706",
"Score": "0",
"body": "One question, why do you use `html` and `text` in different scenarios?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-23T17:07:51.067",
"Id": "1707",
"Score": "0",
"body": "`$this.nextAll('.cont:first').toggleClass('hid');` was what worked."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-23T17:10:07.587",
"Id": "1708",
"Score": "0",
"body": "@Justin **1.** It was a mistake. Fixed. **2.** I don't get what are you trying to say…"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-23T18:25:15.493",
"Id": "1712",
"Score": "0",
"body": "the way my dom was `nextAll('.cont')` didn't work. I needed to add the `:first`. Not really important info for you."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-20T19:52:55.877",
"Id": "865",
"ParentId": "830",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "831",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-17T21:19:39.140",
"Id": "830",
"Score": "14",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "Clickable icon for expanding/collapsing content"
} | 830 |
<p>I'm trying to apply <code>string.strip()</code> to all the leafs that are strings in a multidimensional collection, but my Python is a bit rusty (to say the least). The following is the best I've come up with, but I suspect there's a much better way to do it.</p>
<pre><code>def strip_spaces( item ):
if hasattr( item, "__iter__" ):
if isinstance( item, list ):
return [strip_spaces( value ) for value in item]
elif isinstance( item, dict ):
return dict([(value,strip_spaces(value)) for value in item])
elif isinstance( item, tuple ):
return tuple([ strip_spaces( value ) for value in item ])
elif isinstance( item, str ) or isinstance( item, unicode ):
item = item.strip()
return item
</code></pre>
| [] | [
{
"body": "<pre><code>elif isinstance( item, dict ):\n return dict([(value,strip_spaces(value)) for value in item])\n</code></pre>\n\n<p>This will transform <code>{ ' a ': ' b ' }</code> into <code>{' a ': 'a' }</code>, which I suspect is not what you want. How about:</p>\n\n<pre><code> return dict([(key, strip_spaces(value)) for key, value in item.items()])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T19:44:12.957",
"Id": "843",
"ParentId": "834",
"Score": "5"
}
},
{
"body": "<p>I don't understand why you are checking for an <code>__iter__</code> attribute, as you don't seem to use it. However I would recommend a couple of changes:</p>\n\n<ul>\n<li>Use Abstract Base Classes in the <code>collections</code> module to test duck types, such as \"Iterable\"</li>\n<li>Use <code>types.StringTypes</code> to detect string types</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>import collections\nimport types\n\ndef strip_spaces( item ):\n if isinstance( item, types.StringTypes ):\n return item.strip()\n\n if isinstance( item, collections.Iterable ):\n if isinstance( item, list ):\n return [ strip_spaces( value ) for value in item ]\n\n elif isinstance( item, dict ):\n return dict([ ((strip_spaces(key), strip_spaces(value)) \\\n for key, value in item.iteritems() ])\n\n elif isinstance( item, tuple ):\n return tuple( [ strip_spaces( value ) for value in item ] )\n\n return item\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T21:49:51.253",
"Id": "844",
"ParentId": "834",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "844",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-18T02:52:08.510",
"Id": "834",
"Score": "12",
"Tags": [
"python",
"strings"
],
"Title": "Traversing a multidimensional structure and applying strip() to all strings"
} | 834 |