body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I want to teach about "encapsulation" and chose <code>Date</code> with <code>Year</code>, <code>Month</code> and <code>Day</code> as an example -- because it demonstrates type-safety w.r.t. preventing accidental swapping of parameters. I want to demonstrate encapusulation to the extreme, meaning I want to hide the <code>int</code>-values of the <code>Year</code>, <code>Month</code> and <code>Day</code> completely and instead define the operations in them as required.</p>
<p>Disregarding if it's good to go to this extreme when encapsulating, does anyone have any comments about my demonstration code?</p>
<h2>Intro section</h2>
<pre><code>// #!cpp filename=33a-dateplus.cpp
#include <iostream>
#include <iomanip>
using std::ostream; using std::setfill; using std::setw;
</code></pre>
<h2>Helper value classes</h2>
<h3>Helper value class <code>Year</code></h3>
<pre><code>class Year {
int value_; // eg. 2014
public:
explicit Year(int v) : value_{v} {}
Year& operator+=(const Year& other) {
value_ += other.value_;
return *this;
}
friend ostream& operator<<(ostream& os, const Year&x) {
return os << setfill('0') << setw(4) << x.value_;
}
bool isLeap() const;
};
</code></pre>
<h3>Helper value class <code>Month</code></h3>
<pre><code>class Day;
class Month {
int value_; // 1..12
public:
// v may be invalid month-number, to be normalized later, but >0 .
explicit Month(int v) : value_{v} {}
Month& operator+=(const Month& other) {
value_ += other.value_;
return *this;
}
friend ostream& operator<<(ostream& os, const Month&x) {
return os << setfill('0') << setw(2) << x.value_;
}
void normalize(Year &year);
// precond: month must be normalized; value_ in [1..12]
Day days(const Year& inYear) const;
friend bool operator<(const Month &l, const Month& r) {
return l.value_ < r.value_;
}
};
</code></pre>
<h3>Helper value class <code>Day</code></h3>
<pre><code>class Day {
int value_; // 1..31
public:
// v may be invalid day-of-month, to be normalized later, but >0 .
explicit Day(int v) : value_{v} {}
Day& operator+=(const Day& other) {
value_ += other.value_;
return *this;
}
Day& operator-=(const Day& other) {
value_ -= other.value_;
return *this;
}
friend bool operator<(const Day& l, const Day& r) {
return l.value_ < r.value_;
}
void normalize(Month& month, Year& year);
friend ostream& operator<<(ostream& os, const Day&x) {
return os << setfill('0') << setw(2) << x.value_;
}
};
</code></pre>
<h2><code>Date</code>, the class we are mainly designing</h2>
<pre><code>class Date {
Year year_;
Month month_ {1};
Day day_ {1};
public:
explicit Date(int y) : year_{y} {} // year-01-01
Date(Year y, Month m, Day d) : year_{y}, month_{m}, day_{d} {}
friend ostream& operator<<(ostream& os, const Date&x) {
return os << x.year_ << "-" << x.month_ << "-" << x.day_;
}
// add an arbitrary number of days to a date; normalizez afterwards
friend Date operator+(Date date, const Day& day) {
date.day_ += day;
date.normalize(); // handle overflows
return date;
}
void normalize();
};
</code></pre>
<h2>Implementing member functions</h2>
<pre><code>bool Year::isLeap() const {
return ( (value_%4==0) && (value_%100!=0) ) || (value_%400==0);
}
Day Month::days(const Year& inYear) const {
switch(value_) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
return Day{31};
case 4: case 6: case 9: case 11:
return Day{30};
case 2:
return inYear.isLeap() ? Day{29} : Day{28};
}
return Day{0}; // invalid value_
}
</code></pre>
<h2>Normalization functions</h2>
<pre><code>void Month::normalize(Year &year) {
if(12 < value_ || value_ < 1) {
auto ival = value_-1; // -1: for [1..12] to [0..11]
year += Year{ ival / 12 };
value_ = value_ % 12 + 1; // +1: back to [1..12]
}
}
void Day::normalize(Month& month, Year& year) {
// normalize month, adjusting year
month.normalize(year);
// normalize day; adjusting month and year
while(month.days(year) < *this) {
*this -= month.days(year);
month += Month{1};
if(Month{12} < month) {
month = Month{1};
year += Year{1};
}
}
}
// afterwards contains valid values
void Date::normalize() {
day_.normalize(month_, year_);
}
</code></pre>
<h2>A test: <code>main</code></h2>
<pre><code>int main() {
using std::cout;
Date d1 { Year{2013}, Month{15}, Day{199} };
cout << d1 << " = ";
d1.normalize();
cout << d1 << "\n";
for(auto yi : {1898, 1899, 1900, 1901,
1998, 1999, 2000, 2001, 2002, 2003, 2004}) {
Date d { Year{yi}, Month{3}, Day{366} };
cout << d << " = ";
d.normalize();
cout << d << "\n";
}
for(auto yi : {2011, 2012, 2013, 2014}) {
Date d { Year{yi}, Month{2}, Day{1} };
cout << d << " +28d = " << d+Day{28} << "\n";
}
}
</code></pre>
<h2>Notes</h2>
<p>The code is supposed to follow a "modern" programming style, which here means:</p>
<ul>
<li>C++11: use of <code>{...}</code> for initialization in most cases, <code>auto</code></li>
<li>type-safety, esp. no evil casts</li>
<li>a bit more use of class-instances a values, i.e. "value-semantics"</li>
</ul>
<h2>Output</h2>
<blockquote>
<pre class="lang-none prettyprint-override"><code>2013-15-199 = 2014-10-16
1898-03-366 = 1899-03-01
1899-03-366 = 1900-03-01
1900-03-366 = 1901-03-01
1901-03-366 = 1902-03-01
1998-03-366 = 1999-03-01
1999-03-366 = 2000-02-29
2000-03-366 = 2001-03-01
2001-03-366 = 2002-03-01
2002-03-366 = 2003-03-01
2003-03-366 = 2004-02-29
2004-03-366 = 2005-03-01
2011-02-01 +28d = 2011-03-01
2012-02-01 +28d = 2012-02-29
2013-02-01 +28d = 2013-03-01
2014-02-01 +28d = 2014-03-01
</code></pre>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T01:17:13.997",
"Id": "77314",
"Score": "3",
"body": "I would avoid naming anything with just the lowercase letter `l`, as this code does in `operator<`, due to its common visual similarities with the number `1` or capital letter `I`. I prefer other letters such as `a`, `b`, or short strings such as `lhs`, `rhs`, to avoid the potential ambiguities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T08:51:45.463",
"Id": "77322",
"Score": "0",
"body": "@MichaelUrman `lhs`, `rhs` it is."
}
] | [
{
"body": "<blockquote>\n <p>because it demonstrates type-safety w.r.t. preventing accidental swapping of parameters</p>\n</blockquote>\n\n<p>It does that: because the constructors which take an <code>int</code> parameter are marked <code>explicit</code>.</p>\n\n<blockquote>\n <p>has anyone comments about my demonstration code?</p>\n</blockquote>\n\n<p>I'm unsure why you mark member methods as <code>friend</code>.</p>\n\n<p>Perhaps the Date constructor should implicitly invoke <code>Date::normalize</code> (because I don't like two-stage construction, where user code should remember to invoke normalize on a newly-constructed Date).</p>\n\n<p>Sometimes you pass by const reference e.g. <code>Day& operator+=(const Day& other)</code> and sometimes you pass by value e.g. <code>Date(Year y, Month m, Day d)</code>.</p>\n\n<p>Check a good reference book for the right way to define <code>operator+</code> and <code>operator+=</code>. Instead of ...</p>\n\n<pre><code>friend Date operator+(Date date, const Day& day) {\n date.day_ += day;\n date.normalize(); // handle overflows\n return date;\n}\n</code></pre>\n\n<p>... I suspect that the right way to define it is something like this ...</p>\n\n<pre><code>Date operator+(const Day& day) {\n Date date = *this; // make a copy\n date.day_ += day; // alter the copy\n date.normalize(); // handle overflows\n return date; /// return the copy\n}\n</code></pre>\n\n<p>The comment <code>precond: month must be normalized; value_ in [1..12]</code> implies something tricky or wrong in the public API. Maybe months should always be normalized; if they can't be, maybe this trickery needs to be private and accessible to friend Date (or something like that). Maybe all the normalize methods should be private.</p>\n\n<p>This statement <code>return Day{0}; // invalid value_</code> should perhaps be a thrown exception. Are you able to construct test/user code which triggers that condition?</p>\n\n<p>Whitespace is unconventional e.g. in <code>( (value_%4==0) && (value_%100!=0) )</code> ... I would have expected <code>((value_ % 4 == 0) && (value_ % 100 != 0))</code>. Maybe your code editor/IDE has a \"format document\" command to auto-format such things.</p>\n\n<p>Instead of this trickery ...</p>\n\n<pre><code>void Month::normalize(Year &year) {\n if(12 < value_ || value_ < 1) {\n auto ival = value_-1; // -1: for [1..12] to [0..11]\n year += Year{ ival / 12 };\n value_ = value_ % 12 + 1; // +1: back to [1..12]\n }\n}\n</code></pre>\n\n<p>... maybe Month values could be stored internally as 0 .. 11, converted from 1 .. 12 in the constructor, and converted to 1 .. 12 in the stream output. Maybe that would be a good demonstration of encapsulation.</p>\n\n<p>Maybe you should throw if a negative int is passed to a constructor, or use an unsigned int type (though you should perhaps allow negative years, but then again things like the Gregorian calendar change makes early dates meaningless).</p>\n\n<p>Perhaps you should also be able to subtract days from a Date.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T13:52:14.640",
"Id": "77233",
"Score": "0",
"body": "\"methods as friend.\" I am accessing private `value_` from a global function. Oh, I see that you meant that `operator+()` could be a member function; hrm... I'll check. \"call Date::normalize in c'tor\" -- yes, true. \"normalize methods should be private\" good point. I guess I did that public for demo-reasons. \"Month values 0..11\", like other implementations? Yeah well, that I consider a matter of taste, since everything is hidden anyway. \"Maybe you should throw\" yes, I didn't because I have not covered Exceptions yet. Point very well taken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T14:53:11.023",
"Id": "77237",
"Score": "0",
"body": "operators can be defined as members or as free functions but I think there's a preferred way to do it; IIRC there's a chapter (\"Item 19\") in _Effective C++_ which suggests they should be members, the rationale being \"Whenever you can avoid friend functions, you should, because, much as in real life, friends are often more trouble than they're worth.\" Maybe not a great rationale, but it does mean that IMO there are more- and less-canonical ways to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T15:08:57.500",
"Id": "77243",
"Score": "0",
"body": "I concur with the trickery. You shouldn't be able to construct an object with an invalid state so I believe throwing from the constructor should be done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:56:57.557",
"Id": "77269",
"Score": "0",
"body": "@EmilyL. I totally agree. When I use this example in a later course stage I will be using exceptions. At this specific stage I will keep the \"contractional comments\". On your both behalf I will add a note at the end about \"one should move use exceptions there\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:07:59.350",
"Id": "77273",
"Score": "0",
"body": "\"friend\": I can get rid of `friend` for `<` by moving from free functions `bool operator<(T lhs,T rhs)` to member functions `bool T::operator<(T rhs)`. I can not do that for `operator<<` because its first argument is `ostream&`, not `T`. I think using the member-variant here makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:11:04.230",
"Id": "77274",
"Score": "0",
"body": "@towi Yes the stream operators need to be free (not member) functions, for that reason: I expect/know that. It's the arithmetic operators that I'm used to seeing as member methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:18:56.177",
"Id": "77276",
"Score": "0",
"body": "@ChrisW like I just commented on EmilyL, I would discourage using member functions in the general case. But In this teaching example for \"encapsulation\" I think it makes more sense. Not need to overly use `friend`. As a matter of fact, I will get rid of the `friend` for `operator<<` too, by adding a public method `print` and calling that from `operator<<`. Fruitful discussion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:29:53.190",
"Id": "77279",
"Score": "2",
"body": "@towi There are some \"rules of thumb\" in the C++ Operator overloading FAQ on StackOverflow: [The Decision between Member and Non-member](http://stackoverflow.com/a/4421729/49942)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:46:19.457",
"Id": "77282",
"Score": "0",
"body": "@ChrisW _that_ is a good link (esp. that answer), +1 for that. I am not quite sure what he means by \"treating equally\" or \"changing left argument\". Probably some unusual applications of `<` or `+`. I will use the comment \"Item 44 in C++ Coding Standards (Sutter) Prefer writing nonmember nonfriend functions,\" as my general rule, except in todays case :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:57:42.400",
"Id": "77297",
"Score": "0",
"body": "@towi \"Changing left argument\" probably means `operator+=`. The ones which I was used to seeing as methods instead of as friends were `friend bool operator<(const Month &l, const Month& r)` and `friend Date operator+(Date date, const Day& day)` ... which (apart from the friend issue) are candidates for being non-members (as you wrote them), because both parameters are \"treated equally\" i.e. they change neither operand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T22:10:17.143",
"Id": "77298",
"Score": "0",
"body": "@ChrisW Oh, of course. See, `+=` I so much assume to be a member that I did not think of that it could be a free function, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T15:23:43.027",
"Id": "77357",
"Score": "0",
"body": "@towi If you had a public, named method e.g. `int compare(const Date& rhs) const` then that could be used to implement many operators (`==`, `<`, etc.) ... with such a named method in the public API, the operators needn't be friends and could be mere decoration ('syntactic sugar') defined as functions outside the class."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T13:34:43.193",
"Id": "44507",
"ParentId": "44505",
"Score": "8"
}
},
{
"body": "<p>I have recently earned my M.Sc. in Comp.Sci. and one of the things that was my main gripes with any examples given to use during programming classes was the lack of consistency. So I'll say this, please be consistent and if you implement one arithmetic or relational operator you need to implement all of them that make sense.</p>\n\n<p>And show them how to implement arithmetic and relational operators properly, some thing like this:</p>\n\n<pre><code>T operatpr -() const{\n T(*this) t;\n ...\n return t;\n}\n\nT operator += (const T& rhs){\n ...\n return *this;\n}\n\nT operator + (const T& rhs) const{\n return T(*this) += rhs;\n}\n\nT operator -= (const T& rhs){\n return *this += (-rhs); \n}\n\nT operator - (const T& rhs) const{\n return *this + (-rhs);\n}\n\nbool operator < (const T& rhs) const{\n return ...;\n}\n\nbool operator > (const T& rhs) const{\n return rhs < *this;\n}\n\nbool operator <= (const T& rhs) const{\n return !(*this > rhs);\n}\n\nbool operator >= (const T& rhs) const{\n return !(*this < rhs);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T14:56:15.877",
"Id": "77239",
"Score": "3",
"body": "+1 for pleasing, textbook-like correctness; but note that the OP is adding Days to Date (not adding Date to Date); and that if he weren't, IMO Date-and-Date operators should be avoided (I would prefer Date-and-Timespan operations)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T15:02:50.297",
"Id": "77240",
"Score": "1",
"body": "Yeah of course, I prefer date+timespan too. Date+date has no semantic meaning as opposed to date+timespan. I just gave example on how to implement all operators based on just a few of them. For the arithmetic operators it's just a matter of swapping T for a timespan and implementing. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:51:38.533",
"Id": "77267",
"Score": "0",
"body": "\"if you implement one arithmetic or relational operator you need to implement all of them that make sense\"... hrm, good point. But as @ChrisW says, with these date-things one needs to take special brain-care \"what _makes_ sense\". But you are right, I evaded that question by only implementing what I needed. I agree, I should implement more of them: I will add `-` for most classes. I will implement `<` and `==` for all of them. Note that I will \"be consistent\" by only providing `<` and `==` like the stdlib requires at several points. My guess is that one rarely need more -- using the stdlib."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:53:54.463",
"Id": "77268",
"Score": "0",
"body": "True, `date+timespan` would make sense. I use `Day` as member in `Date` as well as a timespan for arithmetics. That's semantically not very nice. I'll mull that over, but I guess I will keep this for my \"simple\" teaching example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:15:08.303",
"Id": "77275",
"Score": "1",
"body": "You are using member functions for all your implementations, i.e. `T T::operator+(T& rhs)`. I would discourage that and would use free functions `T operator+(T& lhs, T& rhs)`. It will allow you to be more *consistent* when the left and right arguments are different. Note that this is also the case when you have more heavy-weight types and want to offer Move-Semantics with `&&`-overloads. Then you have to provide implementations for *all* variants of `T&/T&`, `T&/T&&`, `T&&/T&` and `T&&/T&&`. That can not be done as member functions. (I left out the `const`s in the signatures)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T09:59:35.177",
"Id": "77329",
"Score": "0",
"body": "Of course, as stated in my first comments: the example is only to show that you only need to implement `operator <`, `operator +` and `unary operator -` to get all other arithmetic and relational operators for free. (I didn't do == and != but I consider that trivial with the hints from the above.)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T14:35:20.067",
"Id": "44509",
"ParentId": "44505",
"Score": "11"
}
},
{
"body": "<blockquote>\n <p>comments about my demonstration code?</p>\n</blockquote>\n\n<p>A few notes:</p>\n\n<ul>\n<li><p>try defining Day and Month in terms of <code>unsigned int</code>, not <code>int</code>;</p></li>\n<li><p>Do not use <code>Date{0}</code> as an invalid value.</p></li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>Day Month::days(const Year& inYear) const {\n // instead of this:\n // return Day{0}; // invalid value_\n // use this:\n throw std::runtime_error{\"invalid month value\"};\n}\n</code></pre>\n\n<p>This way, the error cannot be ignored and the code cannot fail silently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:34:27.860",
"Id": "77536",
"Score": "0",
"body": "Because I mix two semantics for the date elements, I'll keep the `int`. But you are right, it would be better to have a separate \"timespan/diffence\" type -- which should support signedness, and the date elements should not. You are right `Day{0}` is bad, but I haven't introduced exceptions yet."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:48:42.363",
"Id": "44579",
"ParentId": "44505",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T12:03:20.427",
"Id": "44505",
"Score": "16",
"Tags": [
"c++",
"c++11",
"datetime",
"type-safety"
],
"Title": "Type-safe Date class with total encapsulation"
} | 44505 |
<p>I am the <a href="https://codereview.stackexchange.com/users/27623/syb0rg">half-robot side of syb0rg</a> that will be posting the recent answers of Code Review to the <a href="http://chat.stackexchange.com/rooms/12723/cr-answers">CR Answers chatroom</a>. <strong>Here is the list of review suggestions I would like, in order of preference:</strong></p>
<ol>
<li>Efficiency (with API requests, speed of login and posting answers, etc.)</li>
<li>Security issues</li>
<li>Best practices</li>
</ol>
<p><em>For feature requests regarding the chat bot, please see <a href="https://codereview.meta.stackexchange.com/questions/1633/chat-bot-feature-requests">this meta post</a>.</em></p>
<p>Any and all reviews are acceptable however. Don't be too harsh please, this is one of my first times using Ruby.</p>
<pre><code>ACCESS_TOKEN = '<insert key>'
# get your access token here:
# https://stackexchange.com/oauth/dialog?client_id=2666&redirect_uri=http://keyboardfire.com/chatdump.html&scope=no_expiry
$root = 'http://stackexchange.com'
$chatroot = 'http://chat.stackexchange.com'
$room_number = 12723
site = 'codereview'
email = '<insert email>'
password = '<insert password>'
require 'rubygems'
require 'mechanize'
require 'json'
require 'net/http'
loop
{
begin
$agent = Mechanize.new
$agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
login_form = $agent.get('https://openid.stackexchange.com/account/login').forms.first
login_form.email = email
login_form.password = password
$agent.submit login_form, login_form.buttons.first
puts 'logged in with SE openid'
meta_login_form = $agent.get($root + '/users/login').forms.last
meta_login_form.openid_identifier = 'https://openid.stackexchange.com/'
$agent.submit meta_login_form, meta_login_form.buttons.last
puts 'logged in to root'
chat_login_form = $agent.get('http://stackexchange.com/users/chat-login').forms.last
$agent.submit chat_login_form, chat_login_form.buttons.last
puts 'logged in to chat'
$fkey = $agent.get($chatroot + '/chats/join/favorite').forms.last.fkey
puts 'found fkey'
def send_message text
loop
{
begin
resp = $agent.post("#{$chatroot}/chats/#{$room_number}/messages/new", [['text', text], ['fkey', $fkey]]).body
success = JSON.parse(resp)['id'] != nil
return if success
rescue Mechanize::ResponseCodeError => e
puts "Error: #{e.inspect}"
end
puts 'sleeping'
sleep 3
}
end
puts $ERR ? "An unknown error occurred. Bot restarted." : "Bot initialized."
last_date = 0
loop
{
uri = URI.parse "https://api.stackexchange.com/2.2/events?pagesize=100&since=#{last_date}&site=#{site}&filter=!9WgJfejF6&key=thqRkHjZhayoReI9ARAODA((&access_token=#{ACCESS_TOKEN}"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
data = JSON.parse http.get(uri.request_uri).body
events = data['items']
data['items'].each do |event|
last_date = [last_date, event['creation_date'].to_i + 1].max
if ['answer_posted'].include? event['event_type']
send_message "[tag:rob0t] New answer detected:"
send_message event['link']
puts "Answer posted."
end
end
puts "#{data['quota_remaining']}/#{data['quota_max']} quota remaining"
sleep(40 + (data['backoff'] || 0).to_i) # add backoff time if any, just in case
}
rescue => e
$ERR = e
p e
end
}
</code></pre>
<p><sub>(<a href="https://github.com/KeyboardFire/stackexchange-chatdump" rel="noreferrer">Attribution to original author, code above is a modified version of it.</a>)</sub></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T15:03:16.857",
"Id": "77241",
"Score": "8",
"body": "Have an upvote: you'll be wanting to use the chatroom!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:29:18.470",
"Id": "77265",
"Score": "7",
"body": "I can't believe I'm talking to a robot. This is awesome!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T13:14:17.467",
"Id": "84145",
"Score": "9",
"body": "*Ahem*, I believe [I licensed that under MIT](https://github.com/KeyboardFire/stackexchange-chatdump), meaning you have to give attribution to me. ;) I'd prefer \"The Supreme Overlordly Knob of the Door, Superior to Mankind in All Ways,\" but anything goes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-20T19:40:54.153",
"Id": "192544",
"Score": "0",
"body": "Related: [Chat bot feature requests](http://meta.codereview.stackexchange.com/q/1633/31562) on meta."
}
] | [
{
"body": "<p>For starters, indent your code consistently — the standard in Ruby is two spaces. That includes indenting the contents of your <code>begin-rescue-end</code> blocks.</p>\n\n<p>Normally, I don't like to make such a huge fuss about indentation, but in this case I think it's highly important, because:</p>\n\n<ol>\n<li>Your program has a highly unusual outline (infinite loops and a function definition(!) inside an infinite loop)</li>\n<li>The stakes are high: if you misbehave, you could make a lot of people upset. Therefore, good software engineering practices should be used.</li>\n</ol>\n\n<p>An outline like this would be more idiomatic for Ruby:</p>\n\n<pre><code>class AnswerBot\n ROOT = 'http://stackexchange.com'\n CHAT_ROOT = 'http://chat.stackexchange.com'\n\n def initialize(options)\n @agent = Mechanize.new\n @options = options\n end\n\n def login\n # Do stuff with @agent\n login_form = $agent.get('https://openid.stackexchange.com/account/login').forms.first\n login_form.email = @options[:email]\n # ...\n @fkey = @agent.get(CHAT_ROOT + '/chats/join/favorite').forms.last.fkey\n end\n\n def fetch_answers\n # Make request to api.stackexchange.com\n # ...\n data['items'].each { |event| yield event }\n return (data['backoff'] || 0).to_i\n end\n\n def send_message(text, retries=5, backoff=40)\n # ...\n end\nend\n\nbot = AnswerBot.new(:access_token => ...,\n :room_number = 12723,\n :site => 'codereview',\n :email => ...,\n :password => ...)\nloop {\n begin\n bot.login\n\n do\n backoff = bot.fetch_answers do |event|\n if ['answer_posted'].include?(event['event_type']) # <-- Is that right?\n bot.send_message(...)\n end\n end\n while sleep(40 + backoff)\n rescue => e\n puts \"An error occurred.\"\n p e\n end\n puts \"Bot restarted.\"\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T17:03:24.527",
"Id": "77255",
"Score": "0",
"body": "Thanks for the review! In response to your comment in the code, take a look at the [SE API here](http://api.stackexchange.com/docs/types/event)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T16:37:17.213",
"Id": "44515",
"ParentId": "44511",
"Score": "22"
}
},
{
"body": "<p>Some low-level style issues:</p>\n\n<ul>\n<li>Although parentheses around parameter lists are optional, there is <a href=\"https://stackoverflow.com/q/14703024/1157100\">consensus that they should not be omitted</a>.</li>\n<li>I don't see any consist pattern in your use the <code>$</code> sigil for variables. I suggest not using them at all.</li>\n<li>You use both <code>Mechanize</code> and raw <code>Net::HTTP</code> requests. I suggest using <code>Mechanize</code> for everything.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:01:30.533",
"Id": "77262",
"Score": "1",
"body": "There is, I agree, pretty good consensus that parentheses should not be omitted in method declarations. What about method calls?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T16:56:18.970",
"Id": "44516",
"ParentId": "44511",
"Score": "8"
}
},
{
"body": "<h1>Block syntax</h1>\n\n<p>This:</p>\n\n<pre><code>loop\n{\n ...\n}\n</code></pre>\n\n<p>Causes a syntax error in MRI 2.1. This would fix the syntax error:</p>\n\n<pre><code>loop {\n ...\n}\n</code></pre>\n\n<p>However, the use of <code>{...}</code> is normally reserved for single-line blocks. Prefer:</p>\n\n<pre><code>loop do\n ..\nend\n</code></pre>\n\n<h1>Methods</h1>\n\n<p>Use many more methods. It should be possible to figure out what the script does, in broad strokes, by looking only at its main method. Find lines of code that <em>do one thing</em> and put them in their own method. For example:</p>\n\n<pre><code>def login_to_se\n login_form = $agent.get('https://openid.stackexchange.com/account/login').forms.first\n login_form.email = email\n login_form.password = password\n $agent.submit login_form, login_form.buttons.first\n puts 'logged in with SE openid'\nend\n\n...\n\nlogin_to_se\n</code></pre>\n\n<p>and so on. Your methods should, when possible, have these properties:</p>\n\n<ul>\n<li>The method does one thing</li>\n<li>The name says what it does</li>\n<li>All of the code in the method is at the <em>same level of abstraction</em></li>\n</ul>\n\n<p>You want code, at the higher levels such as the main loop, to look more like this:</p>\n\n<pre><code>loop do\n continue_on_error do\n login_to_se\n login_to_meta\n login_to_chat\n loop do\n copy_new_post_to_chat\n wait\n end\n end\nend\n</code></pre>\n\n<p>A method should read like a story. Abstract away--in methods, classes, etc--details that make the story hard to follow.</p>\n\n<h1>Abstract out rescue, too</h1>\n\n<p>You may notice the call to <code>continue_on_error</code> above. It can be very useful to abstract out your rescue blocks, too. In this case, it gives us a method name that documents <em>why</em> we are doing the rescue:</p>\n\n<pre><code>def continue_on_error\n yield\nrescue => e\n $ERR = e\n p e\nend\n</code></pre>\n\n<h1>$ERR</h1>\n\n<p>We can get rid of $ERR by having #continue_on_error say that we're restarting:</p>\n\n<pre><code>def continue_on_error\n yield\nrescue => e\n puts e\n puts \"Restarting\"\nend\n</code></pre>\n\n<p>and in the main loop, instead of:</p>\n\n<pre><code>puts $ERR ? \"An unknown error occurred. Bot restarted.\" : \"Bot initialized.\"\n</code></pre>\n\n<p>simply</p>\n\n<pre><code>puts \"Initialized\"\n</code></pre>\n\n<p>The script's log output will be just as clear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:25:26.817",
"Id": "77289",
"Score": "0",
"body": "Thanks for the review! I guess I was too used to my C-syntactical ways. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:28:35.233",
"Id": "77291",
"Score": "0",
"body": "@syb0rg It seems to be accepted, in C, to write long methods. I've never understood the practice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T18:22:12.157",
"Id": "44522",
"ParentId": "44511",
"Score": "22"
}
},
{
"body": "<p>Adding to the existing answers:</p>\n\n<ol>\n<li>You don't need to require <code>rubygems</code> as you are not using it at all. It is usually unnecessary. See here <a href=\"https://stackoverflow.com/questions/2711779/require-rubygems\">https://stackoverflow.com/questions/2711779/require-rubygems</a> .</li>\n<li><p>When you have many requires you can do this trick to group them into one line:</p>\n\n<pre><code>require 'rubygems'\nrequire 'mechanize'\nrequire 'json'\nrequire 'net/http'\n</code></pre>\n\n<p>Into</p>\n\n<pre><code>%w{rubygems mechanize json net/http}.each{|gem| require gem}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-15T16:30:43.343",
"Id": "54312",
"ParentId": "44511",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44515",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T14:59:36.733",
"Id": "44511",
"Score": "59",
"Tags": [
"performance",
"ruby",
"security",
"stackexchange",
"chat"
],
"Title": "Chat bot for posting recent answers"
} | 44511 |
<p>Is there any way to make this more efficient?</p>
<pre><code>.386 ; assembler use 80386 instructions
.MODEL FLAT ; use modern standard memory model
INCLUDE io.h ; header file for input/output
cr EQU 0dh ; carriage return
Lf EQU 0ah ; line feed
maxArr EQU 5 ; constant for array size
ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD
EXTERN SEARCH:near32
.STACK 4096 ; reserve 4096-byte stack
.DATA ; reserve storage for data
prompt0 BYTE cr, Lf, 'Please enter 5 numbers.', cr, Lf
BYTE 'This program will then search the array for a specific '
BYTE 'value: ', 0
array DWORD maxArr DUP (?) ; array variable, size: maxArr
elemCount DWORD ? ; number of elements entered
valToSearch DWORD ? ; value to search for
prompt1 BYTE cr, Lf, 'Which value would you like to search for?: ', 0
dwinput BYTE 16 DUP (?) ; for input
poslabel BYTE cr,Lf,Lf, 'The value was found at position (0 if not found): '
dwoutput BYTE 16 DUP (?), cr, Lf, 0 ; for output
noPos BYTE cr, Lf, 'The value entered is not present in the array.', 0
.CODE ; program code
_start: ; program entry point
output prompt0 ; output directions and prompt input
mov ecx, maxArr ; initialize ECX with the array capacity value
lea ebx, array ; place address of array in EBX
xor edx, edx ; initialize EDX
getArrayInput:
input dwinput, 16 ; get input
atod dwinput ; convert to DWORD, place in EAX
jo subroutine ; if any overflow, end number entry
mov [ebx], eax ; store number in address pointed to by EBX (array ; index position)
inc edx ; increment counter if number entered so far
add ebx,4 ; get address of next item of array (4 bytes away)
loop getArrayInput ; loop back (up to 5 times)
subroutine:
output prompt1 ; get value to search for
input dwinput, 16 ; get input
atod dwinput ; convert to DWORD, place in EAX
mov valToSearch, eax ; store value to search for
mov elemCount, edx ; move no. of elements to elemCount
lea eax, array ; get starting address of array again
push eax ; Parameter 1: push address of array (4 bytes)
push elemCount ; Parameter 2: push elemCount by value (4 bytes)
push valToSearch ; Parameter 3: push address of valToSearch (4 bytes)
call SEARCH ; search for value, return eax
add esp, 12 ; remove arguments from stack
dtoa dwoutput, eax ; convert to ASCII
cmp eax, 0 ; check if eax(position) = 0
je zeroPosition ; if position=0, go to error message
output poslabel ; output the position
jmp exitSeq ; exit the program
zeroPosition:
output noPos ; output error & exit
exitSeq:
INVOKE ExitProcess, 0 ; exit with return code 0
PUBLIC _start
END
SUBROUTINE:--------------------------------------------------
.386 ; assembler use 80386 instructions
.MODEL FLAT ; use modern standard memory model
PUBLIC SEARCH ; make SEARCH proc visible
.CODE ; program code
SEARCH PROC NEAR32
push ebp ; save base pointer
mov ebp,esp ; establish stack frame
push ebx ; save registers
push ecx
push edx
pushf ; save flags
mov eax, [ebp+8] ; move value to search for to eax
mov ebx, [ebp+16] ; move array address to EBX
mov ecx, [ebx] ;move first element to ECX
cmp ecx, eax ;comparing search number to the first value in the array
je first ;If equal return the position.
mov ecx, [ebx+4] ;move first element to ECX
cmp ecx, eax ;comparing search number to the second value in the array
je second ;If equal return the position.
mov ecx, [ebx+8]
cmp ecx, eax ;comparing search number to the third value in the array
je third ;If equal return the position.
mov ecx, [ebx+12]
cmp ecx, eax ;comparing search number to the fourth value in the array
je fourth ;If equal return the position.
mov ecx, [ebx+16]
cmp ecx, eax ;comparing search number to the fifth value in the array
je fifth ;If equal return the position.
jmp none
first: ;returns position 1
mov eax, 1
jmp done
second: ;returns position 2
mov eax, 2
jmp done
third: ;returns position 3
mov eax, 3
jmp done
fourth: ;returns position 4
mov eax, 4
jmp done
fifth: ;returns position 5
mov eax, 5
jmp done
none: ;returns 0 if the search value is not found.
mov eax, 0
jmp done
done:
retpop:
popf ; restore flags
pop edx ; restore registers
pop ecx
pop ebx
pop ebp ; restore base pointer
ret ; return to main
SEARCH ENDP
PUBLIC SEARCH
END
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-28T22:29:54.590",
"Id": "142958",
"Score": "0",
"body": "The *SEARCH* routine doesn't use its 2nd parameter *elemCount*."
}
] | [
{
"body": "<p>There are some opcodes I haven't seen before: <code>output</code>, <code>input</code>, and <code>atod</code>; are these new opcodes, macros, or what?</p>\n\n<p>\"if any overflow, end number entry\" might not be correct behaviour: perhaps you should prompt again for correct input, or abend the program.</p>\n\n<p>I don't know whether \"loop getArrayInput\" will work because I don't know whether <code>input</code> and <code>atod</code> will preserve the contents of the <code>ecx</code> register.</p>\n\n<p>\"add esp, 12\" implies that SEARCH is using <code>__cdecl</code> calling convention, in which case you could name it _SEARCH with an underscore. Alternatively SEARCH could pop its own parameters using <code>ret 12</code> instead of <code>ret</code>.</p>\n\n<p>There is a way to make the search more \"efficient\": use the <code>scasd</code> opcode with the <code>repnz</code> prefix, i.e. <code>repnz scasd</code>. That would be many fewer instructions. It would be faster too, on '386 processors (I don't know about Pentium+ processors which prefer more, RISC-like opcodes).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T17:03:58.337",
"Id": "44517",
"ParentId": "44513",
"Score": "6"
}
},
{
"body": "<p>It's been a while since my assembler days but your <code>SEARCH</code> routine should really use a loop to check the array. Basically it should accept the start address of the array, the number of entries and the number to search for. Right now if the requirement changes to lets say have an array of 10 numbers you are in to do a lot of copy and paste and bound to make mistakes. You have already used a loop for the input so why not for the search as well?</p>\n\n<p>Also some of the names like <code>prompt0</code> could be a tiny bit more descriptive.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T18:55:41.650",
"Id": "44523",
"ParentId": "44513",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T15:25:37.850",
"Id": "44513",
"Score": "7",
"Tags": [
"homework",
"assembly"
],
"Title": "Search procedure to find inputted DWORD in MASM Array"
} | 44513 |
<p>I just wrote this gem <a href="https://github.com/glebm/order_query" rel="nofollow">order_query</a> to find next or previous records relative to the record assuming a (possibly complex) <code>ORDER BY</code> over the records. For example, this is needed to show a link to the next result from the current search result page.</p>
<blockquote>
<p>The gem is used like so:</p>
<pre><code>class Issue < ActiveRecord::Base
include OrderQuery
order_query :order_display, [
[:priority, %w(high medium low)],
[:valid_votes_count, :desc, sql: '(votes - suspicious_votes)'],
[:updated_at, :desc],
[:id, :desc]
]
def valid_votes_count
votes - suspicious_votes
end
end
Issue.order_display #=> ActiveRecord::Relation<...>
Issue.reverse_order_display #=> ActiveRecord::Relation<...>
p = Issue.find(31).order_display(scope) # scope default: Issue.all
p.items_before #=> ActiveRecord::Relation<...>
p.prev_item #=> Issue<...>
p.position #=> 5
p.next_item #=> Issue<...>
p.items_after #=> ActiveRecord::Relation<...>
</code></pre>
<p><a href="https://github.com/glebm/order_query" rel="nofollow">Read more</a></p>
</blockquote>
<p>The code gets a <a href="https://codeclimate.com/github/glebm/order_query/OrderQuery%3a%3aRelativeOrder" rel="nofollow">complex method warning from CodeClimate</a>, and I agree: it does not look easy to comprehend.</p>
<p>Can this be done better?</p>
<p>This is <a href="https://github.com/glebm/order_query/blob/master/lib/order_query/relative_order.rb#L60" rel="nofollow">the code</a> that constructs the query:</p>
<pre><code># @param [:before or :after] mode
def build_query(mode)
# The next element will be the first one among elements with lesser order
build_query_factor(
order.map { |o| where_relative(o, mode) },
order.map { |o| where_eq(o) }
)
end
# @param [Array] x query conditions
# @param [Array] y query conditions
# @return [query, query_args] The resulting query is as follows:
# x0 | y0 &
# (x1 | y1 &
# (x2 | y2 &
# (x3 | y3 & ... )))
#
# Explanation:
#
# To narrow the result to only the records that come before / after the current one, build_query passes
# the values of x and y so that:
#
# x matches order criteria with values that come after the current record.
# y matches order criteria with values equal to the current record's value, for resolving ties.
#
def build_query_factor(x, y, i = 0, n = x.length)
q = []
x_cond = [x[i][0].presence, x[i][1]]
q << x_cond if x_cond[0]
if i >= 1
q << ['AND'] << y[i - 1]
end
if i < n - 1
q << ['OR'] if x_cond[0]
nested = build_query_factor(x, y, i + 1)
q << ["(#{nested[0]})", nested[1]]
end
[q.map { |e| e[0] }.join(' '),
q.map { |e| e[1] }.compact.reduce(:+) || []]
end
EMPTY_FILTER = ['', []]
def where_eq(spec)
["#{spec.col_name_sql} = ?", [values[spec.name]]]
end
# @param [:before or :after] mode
def where_relative(spec, mode)
ord = spec.order
value = values[spec.name]
if ord.is_a?(Array)
# ord is an array of values, ordered first to last, e.g.
# all up to current
pos = ord.index(value)
values = mode == :after ? ord.from(pos + 1) : ord.first(pos) if pos
# if current not in result set, do not apply filter
return EMPTY_FILTER unless values.present?
["#{spec.col_name_sql} IN (?)", [values]]
else
# ord is :asc or :desc
op = {before: {asc: '<', desc: '>'}, after: {asc: '>', desc: '<'}}[mode][ord || :asc]
["#{spec.col_name_sql} #{op} ?", [value]]
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:06:18.433",
"Id": "77263",
"Score": "0",
"body": "I believe it would be better if you pasted in your question the actual code you want us to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:22:26.667",
"Id": "77264",
"Score": "0",
"body": "I have updated the question"
}
] | [
{
"body": "<p>I will stick to reviewing the code you've posted, although it seems tied to other code.</p>\n\n<p>First of all: Use descriptive variable names. <code>x</code>, <code>y</code>, <code>q</code>, and so forth aren't great for legibility. Use <code>query</code>, <code>position</code> and similar full words. Especially since you're dealing with complex nested arrays.</p>\n\n<p>There also seems to be some logical issues/dangerous assumptions. I don't know if you check/sanitize your input elsewhere, but if you don't things will get weird. E.g.:</p>\n\n<pre><code># This will fail if x[i] is nil\nx_cond = [x[i][0].presence, x[i][1]]\n\nq << x_cond if x_cond[0]\n\nif i >= 1\n # 1. This *may* append [\"AND\"] etc. directly to an empty array,\n # if x_cond[0] was nil above, resulting in a nonsense query.\n # 2. This will fail if y.count < i - 1\n q << ['AND'] << y[i - 1]\nend\n</code></pre>\n\n<p>In other words, if <code>x_cond[0]</code> isn't present, you don't append anything to the array. Yet the following <code>if</code> block assumes that something definitely was appended. And there's no check for the length of <code>y</code> so <code>y[i - 1]</code> may fail. And <code>x[i][0].presence</code> will fail if <code>x[i]</code> is nil to begin with.</p>\n\n<p>I also see some (dangerous) redundancy, like the <code>n = x.length</code> method parameter. There's no reason for this to be a method parameter. In fact, it's detrimental, because the <code>n</code> value is never checked, so you can pass any value like <code>n = -42</code> which wouldn't make sense.</p>\n\n<p>Moreover, <strong>the code doesn't actually match its description</strong>: Your comment for <code>build_query_factory</code> states that the result should be something like:</p>\n\n<pre><code>x0 OR y0 AND (x1 OR y1 AND (x3 OR y3))\n</code></pre>\n\n<p>but the method returns:</p>\n\n<pre><code>x1 OR (x2 AND y1 OR (x3 AND y2))\n</code></pre>\n\n<p>Notice that a) the structure is very different, and b) <code>y3</code> doesn't even appear.</p>\n\n<hr>\n\n<p>Now, assuming that you want the result you give as an example in the comment (and not the result the method actually returns), I would do something like this:</p>\n\n<pre><code>def build_nested_query(x, y)\n # zip the two arrays (x, y, x, y, x, y, ...)\n ordered = x.zip(y)\n\n # split into conditions and parameters\n ordered = ordered.map do |x, y|\n [ [x.first, y.first], [x.second, y.second] ] # still confusing, to be honest\n end\n\n conditions = ordered.map(&:first)\n parameters = ordered.map(&:second).flatten # thanks to ActiveSupport for Array#second, by the way\n\n [ nest_conditions(conditions) , parameters ]\nend\n\ndef nest_conditions(conditions)\n # create \"x OR y\" string\n branch = conditions.first\n branch = branch.join(\" OR \")\n\n # nest the remaining recursively, appending them with \" AND \"\n remaining = conditions[1..-1]\n if remaining.any?\n nested = nest_conditions(remaining)\n branch += \" AND (#{nested})\"\n end\n\n branch\nend\n</code></pre>\n\n<p>That'll do something like this:</p>\n\n<pre><code>x = [[\"x1\", [:x1]], [\"x2\", [:x2]], [\"x3\", [:x3]]]\ny = [[\"y1\", [:y1]], [\"y2\", [:y2]], [\"y3\", [:y3]]]\n\nquery = build_nested_query(x, y)\nquery[0] #=> \"x1 OR y1 AND (x2 OR y2 AND (x3 OR y3))\"\nquery[1] #=> [:x1, :y1, :x2, :y2, :x3, :y3]\n</code></pre>\n\n<p>Which I believe is what you want. You'll want to do some sanity-checking/sanitizing of <code>x</code> and <code>y</code> beforehand, to make sure they make sense.</p>\n\n<p>Of course, if you find a better way to supply the method parameters in the first place, the code can be cleaned up even more.</p>\n\n<p>I would also consider encapsulating conditions and parameters somehow to avoid the non-descriptive <code>[0]</code> and <code>[1]</code> (or <code>first</code>/<code>second</code>) stuff in favor of something more descriptive (Rails no doubt already has an internal class for this structure. Otherwise, a simple <code>Struct</code>-based class should do.)</p>\n\n<hr>\n\n<p>I haven't looked closely at <code>where_relative</code>, but again I see some strange logic:</p>\n\n<pre><code>def where_relative(spec, mode)\n ord = spec.order\n\n # I assume `values` is an instance variable?\n # Anyway, why assign `value` here? It's only used in\n # the else-block, and so should be assigned there\n value = values[spec.name]\n\n if ord.is_a?(Array)\n\n # ...\n\n # Wait, now you're assigning something to `values`?\n values = mode == :after ? ord.from(pos + 1) : ord.first(pos) if pos\n\n # and apparently, that something can be nil, since you're\n # checking for that here - but you didn't check for that\n # before you called `values[spec.name]` above\n return EMPTY_FILTER unless values.present?\n\n # ...\n\n else\n\n # ...\n\n # And here you use `value` (i.e. values[spec.name])\n [\"#{spec.col_name_sql} #{op} ?\", [value]]\n\n end\nend\n</code></pre>\n\n<p>Now, I admit I don't know the exact sequence of events, but the above looks/smells like dangerous assumptions and nasty side effects. If the method is called several times per object instantiation, results get unpredictable. First time it's called, I assume <code>values</code> is set to something. But it might get set to <code>nil</code> by the method. This will cause the next call to the method to crash on <code>values[spec.name]</code>. If the method is so completely dependent on <code>values</code>, it should be a parameter.</p>\n\n<p>Lastly, this line should really be reworked:</p>\n\n<pre><code>values = mode == :after ? ord.from(pos + 1) : ord.first(pos) if pos\n</code></pre>\n\n<p>Don't use a ternary and postfixed <code>if</code> on the same line - it's very confusing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:17:00.933",
"Id": "77752",
"Score": "0",
"body": "Zipping arrays before `nest_conditions` is a clever move that simplifies everything greatly, thanks :) Refactoring for now, will get back when done"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:11:26.720",
"Id": "77762",
"Score": "0",
"body": "I've refactored, and you can see the result [here](https://github.com/glebm/order_query/commit/cf545212a75ec237a5cfcd9649b57df1ab9bfa9d). CodeClimate now reports A (4.0, highest score) too!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:41:26.083",
"Id": "77779",
"Score": "0",
"body": "@glebm Neat! Glad it helped"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T10:28:11.387",
"Id": "77782",
"Score": "0",
"body": ":D By the way, I have another question about this gem's relevance [on StackOverflow](http://stackoverflow.com/questions/22440601/given-a-record-and-order-conditions-find-records-after-or-before)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-06T03:53:03.313",
"Id": "113093",
"Score": "0",
"body": "Recognized a `foldr` and reduced the method down to just a few lines of code https://github.com/glebm/order_query/blob/e3522f061036a172a24f70e8882a616e2cd315be/lib/order_query/sql/where.rb#L41-L48"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:45:05.593",
"Id": "44719",
"ParentId": "44520",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44719",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T18:19:23.120",
"Id": "44520",
"Score": "7",
"Tags": [
"ruby",
"sql",
"ruby-on-rails",
"active-record"
],
"Title": "ActiveRecord extension to find next / previous record(s) in one query"
} | 44520 |
<p>I've written some python code to solve the <a href="http://en.wikipedia.org/wiki/Four_color_theorem" rel="nofollow">map coloring problem</a>. In my code, I represent the problem using <code>Territory</code> and <code>MapColor</code> objects:</p>
<pre><code>class Territory:
def __init__(self, name, neighbors, color = None):
self.name = name
self.neighbors = neighbors
self.color = color
def __str__(self):
return str((self.name, self.neighbors, self.color))
class MapColor:
def __init__(self, graph, colors):
self.map = graph
self.colors = colors
self.vars = list(self.map.keys())
self.domains = { var: set(self.colors) for var in self.vars }
</code></pre>
<p>Here, <code>MapColor.map</code> represents a <code>{str: Territory}</code> mapping and <code>MapColor.vars</code>, the string keys of the the dictionary (my solve function visits the territories in the dictionary iteratively; once we've exhausted this list, we have know the problem has been solved). Here's an example how this problem can be instantiated:</p>
<pre><code>WA = 'western australia'
NT = 'northwest territories'
SA = 'southern australia'
Q = 'queensland'
NSW = 'new south wales'
V = 'victoria'
T = 'tasmania'
colors = {'r', 'g', 'b'}
australia = { T: Territory(T, [V] ),
WA: Territory(WA, [NT, SA] ),
NT: Territory(NT, [WA, Q, SA] ),
SA: Territory(SA, [WA, NT, Q, NSW, V] ),
Q: Territory(Q, [NT, SA, NSW] ),
NSW: Territory(NSW, [Q, SA, V] ),
V: Territory(V, [SA, NSW, T] ) }
problem = MapColor(australia, colors)
</code></pre>
<p>Notice that <code>MapColor.domains</code> is used to keep track of the possible colors a <code>Territory</code> can take. My <code>solve</code> function in fact adds some optimization to the standard backtracking method by reducing the domains of neighboring territories. In this function, the variable <code>i</code> is used to iterate through the keys of <code>MapColor.map</code>. </p>
<p>As I write in the comments, this code adapts the approach typically used to solve puzzles: the idea is to make a move and then continue solving the rest of the puzzle, moving to the next open spot on the board. Since we can't iterate over a "board" with explicit indices, I iterate over the keys of <code>MapColor.map.</code></p>
<pre><code>def solve(self, i):
if i == len(self.vars):
return True
# discussion on why we keep track of old domain is in comments
old = {var: set(self.domains[var]) for var in self.vars}
var = self.vars[i]
print 'domain for ' + var + ': ' + str(self.domains[var])
if self.map[var].color != None:
return self.solve(i + 1)
for color in self.domains[var]:
if self.is_valid(var, color):
self.set_map(var, color)
self.remove_from_domains(var, color)
if self.solve(i + 1):
return True
self.set_map(var, None)
self.domains = old
return False
</code></pre>
<p><strong>My question</strong>: How can I use a heap (python has <code>heapq</code>) to choose to visit the <code>Territory</code> with the smallest domain next? Should I pass the heap along with each recursive call? </p>
<p>Or should I try to make this method iterative? Would that require using both a stack and a heap? Advice on how to do this would be much appreciated! </p>
<p>For reference, here are the other functions used in my code:</p>
<pre><code>def is_valid(self, var, color):
territory = self.map[var]
for neighbor in territory.neighbors:
if color == self.map[neighbor].color:
return False
return True
def set_map(self, key, color):
self.map[key].color = color
def remove_from_domains(self, key, color):
territory = self.map[key]
for var in territory.neighbors:
if self.map[var].color != None:
continue
if color in self.domains[var]:
self.domains[var].remove(color)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:03:03.153",
"Id": "77284",
"Score": "0",
"body": "Welcome to CodeReview.SE ! Your question seems interesting and properly ask (nice description and example). However, could you give more information about the `i` parameter to the `solve` method ? Also the expected output and an brief explanation would be welcome. Thanks in advance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:12:41.040",
"Id": "77285",
"Score": "0",
"body": "@Josay: The goal of the map color problem is to assign a color to each territory such that a given territory does not have the same color as its neighbors. `i` is used to iterate through the the keys in the `MapColor.map`. Typically, in depth first search, we push the adjacent nodes onto the stack (or recursively continue with the children). In the kind of backtracking used to solve puzzles, the idea is to make a move and then continue solving the rest of the puzzle, moving to the next open spot on the board. Since we can't iterate over a \"board\", I iterate over the keys of `MapColor.map`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:17:18.843",
"Id": "77286",
"Score": "0",
"body": "Thanks for the additional explanation (feel free to edit your answer to incorporate it). Related question (and without trying to go to far in the code review already) : what value should I give if I just want to solve the problem ? 0 ? Can it be a default value ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:18:48.257",
"Id": "77288",
"Score": "0",
"body": "@Josay Yes, 0 is fine, and you're right, the header for `solve` should be `def solve(self, i = 0)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T22:12:41.807",
"Id": "77299",
"Score": "0",
"body": "Method `cp_solve` is used but I cannot find the definition. Have I missed something ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T22:26:19.433",
"Id": "77301",
"Score": "0",
"body": "@Josay: sorry that should be `solve`. I had written another solve method (without lookahead filtering) for comparison. Thanks!"
}
] | [
{
"body": "<p>Your code looks good but I think you should have a look at <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> which is the Style Guide for Python Code. Among other things, it says :</p>\n\n<blockquote>\n <p>Comparisons to singletons like None should always be done with is or is not, never the equality operators.</p>\n</blockquote>\n\n<p>Also, you should probably add documentation especially as the solve method takes a parameter for no obvious reason. <a href=\"http://legacy.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">PEP 257</a> describes the Docstring Conventions.</p>\n\n<p>Finally, the name you give to your variables and members can be quite confusing.</p>\n\n<hr>\n\n<p>Your <code>Territory</code> class describes a territory by its name, its neighbours and its colors. The association from territory to color is valid only in the context of a <code>MapColor</code>. Thus, Territories could be described just by their name and neighbours. Instead of defining Australia with :</p>\n\n<pre><code>australia = { T: Territory(T, [V] ),\n WA: Territory(WA, [NT, SA] ),\n NT: Territory(NT, [WA, Q, SA] ),\n SA: Territory(SA, [WA, NT, Q, NSW, V] ),\n Q: Territory(Q, [NT, SA, NSW] ),\n NSW: Territory(NSW, [Q, SA, V] ),\n V: Territory(V, [SA, NSW, T] ) }\n</code></pre>\n\n<p>one could get rid of the <code>Territory</code> class alltogether and remove the duplicated values by defining a mapping from name to containers of neighbours. Because neighbours do not need to be in a given order, a set will do the trick :</p>\n\n<pre><code>australia = { T: {V },\n WA: {NT, SA },\n NT: {WA, Q, SA },\n SA: {WA, NT, Q, NSW, V},\n Q: {NT, SA, NSW },\n NSW: {Q, SA, V },\n V: {SA, NSW, T } }\n</code></pre>\n\n<p>I also took this chance to add a function to check that the graph is properly defined :</p>\n\n<pre><code>def check_valid(graph):\n for node,nexts in graph.iteritems():\n assert(nexts) # no isolated node\n assert(node not in nexts) # # no node linked to itself\n for next in nexts:\n assert(next in graph and node in graph[next]) # A linked to B implies B linked to A\n</code></pre>\n\n<p>Then, in the <code>MapColor</code> class, you can add a dictionnary to map nodes to their colors (if any).</p>\n\n<hr>\n\n<p>You don't need to store <code>colors</code> in your <code>MapColor</code> class as you don't reuse it afterward.\nAlso, the <code>nodes</code> member is not required neither.</p>\n\n<hr>\n\n<p>The <code>is_valid</code> method can be rewritten in a more concise way using the function <a href=\"http://docs.python.org/2.7/library/functions.html#all\" rel=\"nofollow\">all</a>.</p>\n\n<hr>\n\n<p>The biggest problem in your code is probably the fact that most interesting function takes a parameter for no obvious reason. Easiest solution would be to make it a default parameter with value 0. A more interesting solution would be to try to understand when we want to stop which is when all nodes have been given a color. In order to do so, get the list of nodes with no color and consider we have a valid solution if this list is empty :</p>\n\n<pre><code> uncolored_nodes = [n for n,c in self.node_colors.iteritems() if c is None]\n if not uncolored_nodes:\n print self.node_colors\n return True\n</code></pre>\n\n<p>Then, in order to know what is the next node to consider, just take the first of the list (at this stage, we know that the list cannot be empty):</p>\n\n<pre><code> node = uncolored_nodes[0]\n</code></pre>\n\n<p>(This also makes obvious the fact that condition <code>if self.map[var].color != None:</code> (which would be written <code>self.node_colors[node] is not None</code> in my code) cannot be true by definition of <code>node</code>.</p>\n\n<hr>\n\n<p>Once comments have been taken into account (except for the comments because I can't be bothered), the code looks like :</p>\n\n<pre><code>#!/usr/bin/python\n\n\ndef check_valid(graph):\n for node,nexts in graph.iteritems():\n assert(nexts) # no isolated node\n assert(node not in nexts) # # no node linked to itself\n for next in nexts:\n assert(next in graph and node in graph[next]) # A linked to B implies B linked to A\n\nclass MapColor:\n\n def __init__(self, graph, colors):\n check_valid(graph)\n self.graph = graph\n nodes = list(self.graph.keys())\n self.node_colors = { node: None for node in nodes }\n self.domains = { node: set(colors) for node in nodes }\n\n\n def solve(self):\n uncolored_nodes = [n for n,c in self.node_colors.iteritems() if c is None]\n if not uncolored_nodes:\n print self.node_colors\n return True\n\n node = uncolored_nodes[0]\n print 'domain for ' + node + ': ' + str(self.domains[node])\n for color in self.domains[node]:\n if all(color != self.node_colors[n] for n in self.graph[node]):\n self.set_color(node, color)\n self.remove_from_domains(node, color)\n\n if self.solve():\n return True\n\n self.set_color(node, None)\n self.add_to_domains(node, color)\n\n return False\n\n def set_color(self, key, color):\n self.node_colors[key] = color\n\n def remove_from_domains(self, key, color):\n for node in self.graph[key]:\n if color in self.domains[node]:\n self.domains[node].remove(color)\n\n def add_to_domains(self, key, color):\n for node in self.graph[key]:\n self.domains[node].add(color)\n\n\n\nWA = 'western australia'\nNT = 'northwest territories'\nSA = 'southern australia'\nQ = 'queensland'\nNSW = 'new south wales'\nV = 'victoria'\nT = 'tasmania'\n\ncolors = {'r', 'g', 'b'}\n\naustralia = { T: {V },\n WA: {NT, SA },\n NT: {WA, Q, SA },\n SA: {WA, NT, Q, NSW, V},\n Q: {NT, SA, NSW },\n NSW: {Q, SA, V },\n V: {SA, NSW, T } }\n\nproblem = MapColor(australia, colors)\n\nproblem.solve()\n</code></pre>\n\n<hr>\n\n<p>Once all of this has been done, one can notice that the <code>node_colors</code> and <code>domains</code> contain somewhat duplicated information : a node <code>n</code> has color <code>c</code> if and only if <code>domains[n] == {c}</code>. I have no time to get rid of node_colors but that would be my next suggestion. Also, there might be a problem with the way you add/remove colors because when calling <code>self.add_to_domains(node, color)</code> we might re-add a color that has been removed at an earlier stage. I am not able to find an example right now but it might be something to consider. Please let me know if you think I am wrong.</p>\n\n<hr>\n\n<p><strong>Problem in your code</strong> (and in mine) : trying to make the test case a bit more interesting (at the moment, your example does not encounter any problem), I've discovered a problem.</p>\n\n<p>Indeed, I was adding Queensland as a neighboor of Victoria (which <a href=\"http://www.flagsaustralia.com.au/images/Australian-States.jpg\" rel=\"nofollow\">is still possible</a> in a planar graph if the Sunshine State decided to invade the West Coast of NSW) and I got the following error :</p>\n\n<pre><code>Traceback (most recent call last):\n File \"./colors_original.py\", line 99, in <module>\n problem.solve(0)\n File \"./colors_original.py\", line 43, in solve\n if self.solve(i + 1):\n File \"./colors_original.py\", line 43, in solve\n if self.solve(i + 1):\n File \"./colors_original.py\", line 36, in solve\n for color in self.domains[var]:\nRuntimeError: Set changed size during iteration\n</code></pre>\n\n<p>Before trying to go for better perf, I think you should try to make this correct. Because maintaining a consistent state whilst calling recursive method can be quite hard, I guess you should try to make things as simple as possible. I'll try to update this answer if I think of anything interesting but it is quite unlikely.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:45:49.230",
"Id": "77364",
"Score": "0",
"body": "Thank you for your thoughtful comments. Regarding using the variable `i`: we want to be efficient, so I think it would be better to take this approach than getting an uncolored list. Also, I think we're not quite okay with how I add/remove colors from the domains. I think you're right that I should only add/remove from domains if the item has not been set. Forward checking only eliminates from the domains along tentative paths: if we return `True` our domain elimination survives and we keep it for the next path. If not, we should backup, but only reset nodes that remain unsolved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:47:37.380",
"Id": "77365",
"Score": "0",
"body": "Also, this question was more about optimizing my existing algorithm. Can you please refer to the **bolded** part where I explicitly define my question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:27:48.557",
"Id": "77371",
"Score": "0",
"body": "I think I've found an error. Please have a look at my edited answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:49:09.057",
"Id": "77494",
"Score": "0",
"body": "Please see my edit. If you the code on your example, you'll get false (this is because Victoria _can't_ be a neighbor to Queensland with New South Wales in the way. J\n\nJust like in regular backtracking, we have to revert to the last known solution. The easiest way to do this is to make a copy of the old domain before recursing, and use that if we actually make a mistake. Please correct me if I'm wrong!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:53:33.540",
"Id": "77496",
"Score": "0",
"body": "I have also added a check in the remove function to skip over colors that have already been set (elimination isn't needed, here). Again, please correct me if you think I'm wrong. Also, thank you for taking the time to review this code. It's great to have the support and it means a lot that you've taken the time to read over my work!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T09:48:50.790",
"Id": "44557",
"ParentId": "44521",
"Score": "4"
}
},
{
"body": "<p>Not really a code-review but more like a complete rewriting.</p>\n\n<pre><code>#!/usr/bin/python\n\ndef check_valid(graph):\n for node,nexts in graph.iteritems():\n assert(node not in nexts) # # no node linked to itself\n for next in nexts:\n assert(next in graph and node in graph[next]) # A linked to B implies B linked to A\n\ndef check_solution(graph, solution):\n if solution is not None:\n for node,nexts in graph.iteritems():\n assert(node in solution)\n color = solution[node]\n for next in nexts:\n assert(next in solution and solution[next] != color)\n\ndef find_best_candidate(graph, guesses):\n if True: #optimised\n # Optimisations are to be put here. Ideas would be to take the node with the most uncolored neighboors or the one with the smallest possible number of colors or both\n candidates_with_add_info = [\n (\n -len({guesses[neigh] for neigh in graph[n] if neigh in guesses}), # nb_forbidden_colors\n -len({neigh for neigh in graph[n] if neigh not in guesses}), # minus nb_uncolored_neighbour\n n\n ) for n in graph if n not in guesses]\n candidates_with_add_info.sort()\n candidates = [n for _,_,n in candidates_with_add_info]\n else:\n candidates = [n for n in graph if n not in guesses]\n candidates.sort() # just to have some consistent performances\n if candidates:\n candidate = candidates[0]\n assert(candidate not in guesses)\n return candidate\n assert(set(graph.keys()) == set(guesses.keys()))\n return None\n\nnb_calls = 0\n\ndef solve(graph, colors, guesses, depth):\n global nb_calls\n nb_calls += 1\n n = find_best_candidate(graph, guesses)\n if n is None:\n return guesses # Solution is found\n for c in colors - {guesses[neigh] for neigh in graph[n] if neigh in guesses}:\n assert(n not in guesses)\n assert(all((neigh not in guesses or guesses[neigh] != c) for neigh in graph[n]))\n guesses[n] = c\n indent = ' '*depth\n print \"%sTrying to give color %s to %s\" % (indent,c,n)\n if solve(graph, colors, guesses, depth+1):\n print \"%sGave color %s to %s\" % (indent,c,n)\n return guesses\n else:\n del guesses[n]\n print \"%sCannot give color %s to %s\" % (indent,c,n)\n return None\n\n\ndef solve_problem(graph, colors):\n check_valid(graph)\n solution = solve(graph, colors, dict(), 0)\n print solution\n check_solution(graph,solution)\n\n\nWA = 'western australia'\nNT = 'northwest territories'\nSA = 'southern australia'\nQ = 'queensland'\nNSW = 'new south wales'\nV = 'victoria'\nT = 'tasmania'\n\naustralia = { T: {V },\n WA: {NT, SA },\n NT: {WA, Q, SA },\n SA: {WA, NT, Q, NSW, V},\n Q: {NT, SA, NSW },\n NSW: {Q, SA, V },\n V: {SA, NSW, T } }\n\n\nAL = \"Alabama\"\nAK = \"Alaska\"\nAZ = \"Arizona\"\nAR = \"Arkansas\"\nCA = \"California\"\nCO = \"Colorado\"\nCT = \"Connecticut\"\nDE = \"Delaware\"\nFL = \"Florida\"\nGA = \"Georgia\"\nHI = \"Hawaii\"\nID = \"Idaho\"\nIL = \"Illinois\"\nIN = \"Indiana\"\nIA = \"Iowa\"\nKS = \"Kansas\"\nKY = \"Kentucky\"\nLA = \"Louisiana\"\nME = \"Maine\"\nMD = \"Maryland\"\nMA = \"Massachusetts\"\nMI = \"Michigan\"\nMN = \"Minnesota\"\nMS = \"Mississippi\"\nMO = \"Missouri\"\nMT = \"Montana\"\nNE = \"Nebraska\"\nNV = \"Nevada\"\nNH = \"NewHampshire\"\nNJ = \"NewJersey\"\nNM = \"NewMexico\"\nNY = \"NewYork\"\nNC = \"NorthCarolina\"\nND = \"NorthDakota\"\nOH = \"Ohio\"\nOK = \"Oklahoma\"\nOR = \"Oregon\"\nPA = \"Pennsylvania\"\nRI = \"RhodeIsland\"\nSC = \"SouthCarolina\"\nSD = \"SouthDakota\"\nTN = \"Tennessee\"\nTX = \"Texas\"\nUT = \"Utah\"\nVT = \"Vermont\"\nVA = \"Virginia\"\nWA = \"Washington\"\nWV = \"WestVirginia\"\nWI = \"Wisconsin\"\nWY = \"Wyoming\"\n\nunited_stated_of_america = {\n AL: {GA, FL, TN, MS},\n AK: {},\n AZ: {CA, NV, UT, CO, NM},\n AR: {MO, OK, TX, LA, TN, MS},\n CA: {OR, NV, AZ},\n CO: {WY, NE, KS, OK, NM, AZ, UT},\n CT: {},\n DE: {},\n FL: {AL, GA},\n GA: {SC, NC, TN, AL, FL},\n HI: {},\n ID: {WA, MT, OR, WY, UT, NV},\n IL: {WI, IA, MO, KY, IN, MI},\n IN: {MI, WI, IL, KY, OH},\n IA: {MN, SD, NE, MO, WI, IL},\n KS: {NE, CO, OK, MO},\n KY: {IN, IL, MO, TN, OH, WV, VA},\n LA: {AR, TX, MS},\n ME: {},\n MD: {},\n MA: {},\n MI: {IL, WI, IN, OH},\n MN: {ND, SD, IA, WI},\n MS: {TN, AR, LA, AL},\n MO: {IA, NE, KS, OK, AR, IL, KY, TN},\n MT: {ID, WY, SD, ND},\n NE: {SD, WY, CO, KS, MO, IA},\n NV: {OR, ID, UT, AZ, CA},\n NH: {},\n NJ: {},\n NM: {AZ, UT, CO, OK, TX},\n NY: {},\n NC: {GA, TN, SC, VA},\n ND: {MT, SD, MN},\n OH: {MI, IN, KY, WV},\n OK: {KS, CO, NM, TX, AR, MO},\n OR: {WA, ID, NV, CA},\n PA: {},\n RI: {},\n SC: {GA, NC},\n SD: {ND, MT, WY, NE, MN, IA},\n TN: {KY, MO, AR, MS, MO, AL, GA, NC},\n TX: {OK, NM, AR, LA},\n UT: {ID, NV, WY, CO, AZ, NM},\n VT: {},\n VA: {WV, KY, NC},\n WA: {OR, ID},\n WV: {OH, VA, KY},\n WI: {MN, IA, IL, MI, IN},\n WY: {MT, SD, NE, CO, UT, ID},\n}\n\n# Can't be bothered to complete the East part of the map - removing unused nodes (keeping them is also a good way to test your algorithm and see if still works)\nunited_stated_of_america = {n:neigh for n,neigh in united_stated_of_america.iteritems() if neigh}\n\ncolors = {'r', 'g', 'b', 'y'}\n\nsolve_problem(australia, colors)\nsolve_problem(united_stated_of_america, colors)\nprint nb_calls\n</code></pre>\n\n<p>A few comments :</p>\n\n<ul>\n<li><code>graph</code> is not updated during the process. The only object we update is <code>guesses</code>. Because of the way we do so, changes can be easily reverted.</li>\n<li>I've added quite a lot of assertions</li>\n<li>Optimisations to pick a better candidate should be easy to add.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:45:35.637",
"Id": "77577",
"Score": "0",
"body": "Did you see my comments to the original post?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T17:31:07.093",
"Id": "77647",
"Score": "2",
"body": "I didn't get a chance to look at it yet. However, just to that you know, the usage is not to update the code in your question (because it makes the answer irrelevant and/or hard to understand). You can revert you change and add a part \"Edit after taking into account <whatever> from <whoever> about <stuff>\". In the meantime, I've updated my code to have some more interesting test case, a way to measure performance and some ideas of optimisation tested and approved :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:38:47.023",
"Id": "44669",
"ParentId": "44521",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44669",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T18:21:10.743",
"Id": "44521",
"Score": "5",
"Tags": [
"python",
"algorithm",
"recursion",
"graph",
"heap"
],
"Title": "Constraint Programming: Map color problem"
} | 44521 |
<p>I'm new to Python and want to make sure I'm not developing bad habits. If you could please review this code below and give me any tips, practice ideas or critiques you might have. Any ideas on which aspects of the language I should focus on early would also be appreciated.</p>
<pre><code>#!usr/env/python
#Modeling a soccer team with substitutions
#Players stored in dictionary {Name:Numbers}
players = {}
# Player positions stored in a list
forward = []
midfield = []
defense = []
goalie = []
class Team(object):
def __init__(self, name):
self.name = name
class Players(object):
def __init__(self):
pass
#creates a player list with names, numbers, and preferred positions
def addPlayer(self, name, number, position):
self.name = name
self.number = number
self.position = position
players[name] = number
if position == 'forward':
forward.append(name)
return forward
elif position == 'midfield':
midfield.append(name)
return midfield
elif position == 'defense':
defense.append(name)
return defense
elif position == 'goalie':
goalie.append(name)
return goalie
else:
print 'Only forward, midfield, defense, goalie accepted'
print "Added %s to the team!" % name
#Should list the players currently on the field. Only 3 player sample data
players_on_field = []
class OnField(object):
def __init__(self):
pass
def sub_in(self, sub_name):
self.sub_name = sub_name
if len(players_on_field) == 3:
print "Field is full, sub_out first!"
#testing some options
#x = raw_input('Which player would you like to sub out?')
#OnField.sub_out(x)
else:
players_on_field.append(sub_name)
print "%s entering the game" % sub_name
return
def sub_out(self, sub_name):
for i in range(3):
if players_on_field[i] == sub_name:
del players_on_field[i]
print "%s has been removed from the game" % sub_name
return
#testing some options
#x = raw_input('Who would you like to sub in?')
#OnField.sub_in(x)
else:
print "That player is not on the field"
return
def list_players_on_field(self):
print players_on_field
#Testing
Barcelona = Team('Barcelona')
this = Players()
game = OnField()
this.addPlayer('Messi', 10, 'forward')
this.addPlayer('Neymar', 11, 'forward')
this.addPlayer('Song', 9, 'midfield')
this.addPlayer('Valdes', 1, 'goalie')
this.addPlayer('Pique', 25, 'defense')
this.addPlayer('Pedro', 8, 'forward')
print players
print 'Forward Players'
print forward
print 'Midfield Players'
print midfield
print 'Defense Players'
print defense
print 'Goalies'
print goalie
#Subsitution testing
print "Players currently on the field"
print players_on_field
game.sub_in('Messi')
game.sub_in('Pedro')
game.sub_in('Song')
game.list_players_on_field()
game.sub_out('Pedro')
print players_on_field
game.sub_in('Neymar')
print players_on_field
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T22:16:37.517",
"Id": "77300",
"Score": "0",
"body": "Your `Team` class is useless, no? It has no use (a player is not assigned to a team), so I don't think you need it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T01:17:09.220",
"Id": "77313",
"Score": "0",
"body": "True, at this point it is useless. I think I had intentions of using it later on. Thanks."
}
] | [
{
"body": "<p>The idea of a class in python is to keep track of a state. Your OnField class does nothing else than appending and removing players from <code>players_on_field</code>(which is outside the class). Therefor, <code>sub_in</code> and <code>sud_out</code> could be defined outside the class.</p>\n\n<pre><code>players_on_field = []\nclass OnField(object):\n def __init__(self):\n pass\n def sub_in(self, sub_name):\n self.sub_name = sub_name\n if len(players_on_field) == 3:\n print \"Field is full, sub_out first!\"\n #testing some options\n #x = raw_input('Which player would you like to sub out?')\n #OnField.sub_out(x)\n else:\n players_on_field.append(sub_name)\n print \"%s entering the game\" % sub_name\n return\n\n def sub_out(self, sub_name):\n for i in range(3):\n if players_on_field[i] == sub_name:\n del players_on_field[i]\n print \"%s has been removed from the game\" % sub_name\n return\n else:\n print \"That player is not on the field\"\n return\n\n def list_players_on_field(self):\n print players_on_field\n</code></pre>\n\n<p>Could become</p>\n\n<pre><code>players_on_field = []\n\ndef sub_in(sub_name):\n if len(players_on_field) == 3:\n print \"Field is full, sub_out first!\"\n #testing some options\n #x = raw_input('Which player would you like to sub out?')\n #OnField.sub_out(x)\n else:\n players_on_field.append(sub_name)\n print \"%s entering the game\" % sub_name\n return\n\ndef sub_out(sub_name):\n for i in range(3):\n if players_on_field[i] == sub_name:\n del players_on_field[i]\n print \"%s has been removed from the game\" % sub_name\n return\n #testing some options\n #x = raw_input('Who would you like to sub in?')\n #OnField.sub_in(x)\n else:\n print \"That player is not on the field\"\n return\n</code></pre>\n\n<p>I would avoid to print errors. You should raise errors. Ex: <code>raise PlayerNotOnFieldError()</code></p>\n\n<p>You are also using some 'magic values'. Ex: <code>if len(players_on_field) == 3:</code>. I would suggest that you define a constant <code>MAX_NUMBER_OF_PLAYER_ON_THE_FIELD = 3</code> so that the if statement alone is verbose. The same apply to the player positions. This way you could re-use the constants and only maintain then in one place.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T15:07:35.223",
"Id": "44580",
"ParentId": "44525",
"Score": "4"
}
},
{
"body": "<p>You naming convention does not follow <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>. Try to follow it as much as you can as it helps having same consistent guidelines all over Python code.</p>\n\n<hr>\n\n<p>I do not quite understand how the <code>on field</code> thingy is supposed to work so I'll skip on that part.</p>\n\n<hr>\n\n<p>Try to avoid global variables. Try to think how things would be affected if you were trying to handle multiple teams. Most probably things would go wrong.</p>\n\n<p>I guess your different lists should be part of the team class. Also, there is not much point for having a <code>Player</code> class as a player on its own is nothing but a name. As far as I understand soccer, the number is for a given player in a given team. Thus, the team should be some kind of containers of pairs name/number.</p>\n\n<p>Also, it seems like your are doing the same things for different teams of players that could be handled the same way. Instead of write code, it's easier to use smart data structures and make them work for you. In your case, it seems like a dictionnary from position to list of (player name + player number) is good idea. Default composition is to have empty lists and to fill them later on.</p>\n\n<p>Here's what my code looks like :</p>\n\n<pre><code>class Team(object):\n def __init__(self, name):\n self.name = name\n self.composition = {\n 'forward' : [],\n 'midfield': [],\n 'defense': [],\n 'goalie': []\n }\n\n def add_player(self, name, number, position):\n if position not in self.composition:\n print 'Only %s accepted' % ', '.join(self.composition.keys())\n else:\n self.composition[position].append((name,number))\n print 'Added %s to the team!' % name\n\nbcn = Team('Barcelona')\nbcn.add_player('Messi', 10, 'forward')\nbcn.add_player('Neymar', 11, 'forward')\nbcn.add_player('Song', 9, 'midfield')\nbcn.add_player('Valdes', 1, 'goalie')\nbcn.add_player('Pique', 25, 'defense')\nbcn.add_player('Pedro', 8, 'forward')\nbcn.add_player('Josay', 10, 'invalid')\n\n# It could be a good idea to create a method to do this :-) \nfor pos, players in bcn.composition.iteritems():\n print pos\n for p in players:\n print p\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T04:28:37.083",
"Id": "77502",
"Score": "0",
"body": "not in .keys() is a much better way to handle that check. I wasn't aware of it before. Thank you! On_Field was supposed to be kind of a snapshot of the available players if the coach were looking at options to sub players in / out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:22:55.127",
"Id": "77653",
"Score": "1",
"body": "It's more idiomatic to write `position not in self.composition` rather than `position not in self.composition.keys()`. Moreover, in Python 2, `.keys()` generates a separate `list` that needs to be inefficiently searched."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:30:37.757",
"Id": "44590",
"ParentId": "44525",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T19:43:39.493",
"Id": "44525",
"Score": "6",
"Tags": [
"python",
"beginner"
],
"Title": "Modeling a soccer team with substitutions"
} | 44525 |
<p>A friend of mine dabbles in lua, and he recently sent me a code which applies an equation we were discussing. I personally am very mediocre with lua, but my Python senses are tingling - I feel as though this code could almost certainly be shortened. Any thoughts?</p>
<pre><code>print("Choose what you want to find:")
print("Health")
print("Size")
print("Speed")
print("Average Damage")
print("")
chosen = io.read()
if chosen == 'Health' then
print("Input The Damage")
Da = io.read()
print("Input The Size")
Sz = io.read()
print("Input The Speed")
Sp = io.read()
local m = 70 * ((Da * Sz) / Sp)
print(m)
elseif chosen == 'Size' then
print("Input the Health")
h = io.read()
print("Input the Damage")
Da = io.read()
print("Input the Speed")
Sp = io.read()
local n = (h*Sp) / (70*Da)
print(n)
elseif chosen == 'Speed' then
print("Input the Health")
h = io.read()
print("Input the Damage")
Da = io.read()
print("Input The Size")
Sz = io.read()
local o = (70*Da*Sz) / h
print(o)
elseif chosen == 'Average Damage' then
print("Input the Health")
h = io.read()
print("Input The Size")
Sz = io.read()
print("Input The Speed")
Sp = io.read()
local p = (h * Sp) / (70 * Sz)
print(p)
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:21:24.173",
"Id": "77277",
"Score": "4",
"body": "We can only review code that you have written *yourself*. Has your friend given you permission to post this code here? (There is a rather banal reason for this restriction: all user content on the Stack Exchange networked is licensed under [CC-BY-SA](http://creativecommons.org/licenses/by-sa/3.0/), and nobody but the copyright holder can issue a license)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:22:47.487",
"Id": "77278",
"Score": "0",
"body": "@amon Thanks for your concern! I asked him before I posted and he was all right with it."
}
] | [
{
"body": "<p>I have never written any Lua code before, but a short view in a tutorial at <a href=\"http://www.lua.org/\">http://www.lua.org/</a> let me come up with this:</p>\n\n<p>Extract a method which returns 3 values:</p>\n\n<pre><code>print(\"Choose what you want to find:\")\nprint(\"Health\")\nprint(\"Size\")\nprint(\"Speed\")\nprint(\"Average Damage\")\nprint(\"\")\nchosen = io.read()\nif chosen == 'Health' then\n Da,Sz,Sp = read3values(\"Input The Damage\",\"Input The Size\",\"Input The Speed\")\n print((70 * ((Da * Sz) / Sp)))\nelseif chosen == 'Size' then\n h,Da,Sp= read3values(\"Input the Health\",\"Input the Damage\",\"Input the Speed\")\n print(((h*Sp) / (70*Da)))\nelseif chosen == 'Speed' then\n h,Da,Sz = read3values(\"Input the Health\",\"Input the Damage\",\"Input The Size\")\n print(((70*Da*Sz) / h))\nelseif chosen == 'Average Damage' then\n h,Sz,Sp = read3values\"Input the Health\",\"Input The Size\",\"Input The Speed\")\n print(((h * Sp) / (70 * Sz)))\nend\n\nfunction read3values(text1,text2,text3)\n local value1 = readValue(text1)\n local value2 = readValue(text1)\n local value3 = readValue(text1)\n return value1,value2,value3\nend\n\n\nfunction readValue(text)\n print(text)\n return io.read()\nend\n</code></pre>\n\n<p>You may also want to extract the repeating string constants.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:35:31.383",
"Id": "77292",
"Score": "0",
"body": "I was not learning the hole language, only the syntax of functions. And I was pleased to see the possibility to return more than one value. I would love to have this directly build in the language in java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:41:13.510",
"Id": "77293",
"Score": "0",
"body": "Shhhh... Just pretend :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:44:42.073",
"Id": "77294",
"Score": "0",
"body": "@KnightOfNi: I think to write an answer I do not have to know all about the language. Just the parts I want to apply."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:53:55.717",
"Id": "77296",
"Score": "1",
"body": "I was joking/being friendly... the clue was in the emoticon. I agree that you don't need to be an expert to answer the question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:54:38.277",
"Id": "44531",
"ParentId": "44527",
"Score": "8"
}
},
{
"body": "<p>Possibly not exactly how I'd write it if I was writing this myself but given the example code and the lack of any other context it works and is reasonably clean.</p>\n\n<pre><code>local choicetab = {\n Health = {\"Damage\", \"Size\", \"Speed\", cb = function(Da, Sz, Sp) return 70 * ((Da * Sz) / Sp) end},\n Size = {\"Health\", \"Damage\", \"Speed\", cb = function(h, Da, Sp) return (h * Sp) / (70 * Da) end},\n Speed = {\"Health\", \"Damage\", \"Size\", cb = function(h, Da, Sz) return (70 * Da * Sz) / h end},\n [\"Average Damage\"] = {\"Health\", \"Size\", \"Speed\", cb = function(h, Sz, Sp) return (h * Sp) / (70 * Sz) end},\n}\n\nprint([[Choose what you want to find:\nHealth\nSize\nSpeed\nAverage Damage\n]])\nlocal chosen = io.read()\nlocal tab = choicetab[chosen]\nif not tab then\n error(\"Not a valid choice\")\nend\n\nlocal argtab = {}\nfor i, v in ipairs(tab) do\n print(\"Input The \"..v)\n argtab[i] = io.read()\nend\nprint(tab.cb(unpack(argtab)))\n</code></pre>\n\n<p>This might be better for the choice printing loop if you aren't concerned about the order possibly changing (it should be stable but isn't guaranteed to be) since it shows you all the valid choices (even if you remove one or add more).</p>\n\n<pre><code>print(\"Choose what you want to find:\")\nfor name in pairs(choicetab) do\n print(name)\nend\n</code></pre>\n\n<p>Additionally, if you didn't care about the order of the information prompted for either you could do away with storing that information in the sub-tables of <code>choicetab</code> and do something like this instead:</p>\n\n<pre><code>local choicetab = {\n Health = function(args) return 70 * ((args[\"Average Damage\"] * args.Size) / args.Speed) end,\n Size = function(args) return (args.Health * args.Speed) / (70 * args[\"Average Damage\"]) end,\n Speed = function(args) return (70 * args[\"Average Damage\"] * args.Size) / args.Health end,\n [\"Average Damage\"] = function(args) return (args.Health * args.Speed) / (70 * args.Size) end,\n}\n\nprint(\"Choose what you want to find:\")\nfor name in pairs(choicetab) do\n print(name)\nend\nprint()\nlocal chosen = io.read()\nlocal fun = choicetab[chosen]\nif not fun then\n error(\"Not a valid choice\")\nend\n\nlocal argtab = {}\nfor name, v in pairs(choicetab) do\n if name ~= chosen then\n print(\"Input The \"..name)\n argtab[name] = io.read()\n end\nend\nprint(fun(argtab))\n</code></pre>\n\n<p>But that depends on the set of choices always being one more than the arguments that the calculation functions need which may or may not be a valid assumption in any broader case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T14:34:25.743",
"Id": "83399",
"Score": "0",
"body": "I think I understand this program pretty well, (although I never would have come up with it) but why do you have the double brackets for your print function? And why no quotes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T18:37:40.217",
"Id": "83425",
"Score": "0",
"body": "`[[...]]` is a lua `long string`. See the `mutliline quotes` section of [this page](http://lua-users.org/wiki/StringsTutorial). But basically it just allowed for the literal newlines to be in the string instead of needing to use `\\n` or multiple calls to `print`. (Also described in [the manual](http://www.lua.org/manual/5.1/manual.html#2.1).)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T23:21:25.723",
"Id": "83460",
"Score": "0",
"body": "OK, thanks. This was a very innovative approach."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T08:23:49.093",
"Id": "47552",
"ParentId": "44527",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "44531",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:14:15.833",
"Id": "44527",
"Score": "8",
"Tags": [
"lua"
],
"Title": "Lua Formula Code"
} | 44527 |
<p>I'm setting up a Django development environment using Vagrant to run an Ubuntu virtual machine on VirtualBox. As this is a student project run mostly by very amateur coders and I want everyone to be able to contribute, I want the environment to be as convenient as possible.</p>
<p>What I'm trying to achieve:</p>
<ul>
<li>LESS-files would be compiled to CSS automatically whenever they are changed</li>
<li>This automation would be run immediately on vagrant up, without any need to SSH the virtual machine.</li>
</ul>
<p>I'm using django-pipeline (as it is supports Python3, unlike some other similar plugins) to manage my static files and compile LESS. Getting the files to compile automatically has proven a bit problematic though, since changing files in the shared folder from the host machine <a href="https://www.virtualbox.org/ticket/10660" rel="noreferrer">does not trigger inotify events on the VirtualBox guest machine</a>. This rules out the most commonly used options for watching a folder for changes.</p>
<p>One option that I considered was using the Guard-gem with the -p (polling) option, but this would have required setting up Ruby, that I don't use elsewhere in the project, so I abandoned it as too complicated an option.</p>
<p>Inspired somewhat by Django's server's <a href="https://github.com/django/django/blob/master/django/utils/autoreload.py#L147" rel="noreferrer">way of monitoring files in the absence of inotify</a>, I decided to write my own script for watching for changes in a folder and then run that script on screen in Vagrant's provisioning script. <strong>I got it to work</strong>, but since I feel like I have no idea what I'm doing, I want to ask:</p>
<ol>
<li>Does this solution make any sense at all or would there have been an insanely easy solution to the original problem that I just missed?</li>
<li>I'm a newbie to Python. Does my code comply to the best practices of using Django and Python?</li>
<li>Did I just crack an enigmatic riddle puzzling millions worldwide or should I just be embarrassed about ever spending time on such a petty problem?</li>
</ol>
<h2>The code</h2>
<p><strong>myapp/management/commands/watchstatic.py:</strong></p>
<pre><code>from django.core.management.base import NoArgsCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from pipeline.exceptions import CompilerError
import os
import sched
import time
class Command(NoArgsCommand):
help = 'Watches the static folder for changes, and runs the collectstatic-command if something is changed'
def handle_noargs(self, **options):
def get_time(filename):
stat = os.stat(filename)
mtime = stat.st_mtime
return mtime
def files_and_times(directory):
files = []
files_dict = {}
for (dirpath, dirname, filenames) in os.walk(directory):
for name in filenames:
files.append(dirpath + '/' + name)
for filename in files:
files_dict[filename] = get_time(filename)
return files_dict
def read_all():
all_files = {}
for key, sets in settings.WATCH_STATIC_FOLDERS.items():
folder_dict = files_and_times(sets['folder'])
all_files[key] = folder_dict
return all_files
def files_changed(sc, old_files={}):
# Read new files and their modification times
new_files = read_all()
if new_files != old_files:
print('Files changed!')
try:
call_command('collectstatic', interactive=False)
# Delete the useless files created by django-pipeline
# See: https://github.com/cyberdelia/django-pipeline/issues/202
for key, sets in settings.WATCH_STATIC_FOLDERS.items():
for filename in sets['delete']:
filepath = sets['folder'] + '/' + filename
os.remove(filepath)
print('Deleted ' + filepath)
except CompilerError:
print('Failed to compile!')
# Just try again when the code is changed next time
pass
old_files = read_all()
sc.enter(settings.WATCH_INTERVAL, 1, files_changed, (sc, old_files))
s = sched.scheduler(time.time, time.sleep)
# The files are always compiled on the first run
s.enter(settings.WATCH_INTERVAL, 1, files_changed, (s,))
s.run()
</code></pre>
<p><strong>settings.py:</strong></p>
<pre><code>WATCH_INTERVAL = 5 # Seconds
WATCH_STATIC_FOLDERS = {
'myapp': {
'folder': 'myapp/static',
'delete': (
'bootstrap_less/bootstrap.css',
'style.css'
)
}
}
</code></pre>
<p><strong>In Vagrant provisioning shell script:</strong></p>
<pre><code>su - vagrant -c "cd /vagrant && screen -S watcher -d -m python manage.py watchstatic"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T00:53:19.297",
"Id": "78230",
"Score": "1",
"body": "I'd recommend you look at using https://github.com/seb-m/pyinotify or similar for this; it's the \"corrrect\" way to do it (certainly far more correct than walking through every single file ;))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T05:38:22.803",
"Id": "78245",
"Score": "0",
"body": "pyinotify relies on inotify, that does not work in this scenario, as I explained."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-27T06:04:11.883",
"Id": "354915",
"Score": "0",
"body": "I would avoid reinventing the wheel and use proven technology, in this case compass . Yes, it's ruby, but that's a one-line install so isn't too complex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T17:12:29.293",
"Id": "492982",
"Score": "1",
"body": "Watchdog ( https://github.com/samuelcolvin/watchgod ) is Python changes watcher without utilizing inotify, I'd use that instead of reinventing a wheel and encountering various bugs during that. For example in here `files_changed(sc, old_files={})` you have a dictionary as a default value which might cause issues, see https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-16T20:25:28.303",
"Id": "44528",
"Score": "14",
"Tags": [
"python",
"beginner",
"django",
"less-css"
],
"Title": "Django on virtual machine - watching changes in static files and autocompiling LESS without inotify"
} | 44528 |
<p>This is loosely based on one of W3_School samples:</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates forEach() function</p>
<script>
var x=Array.prototype.slice.call(document.getElementsByTagName("p"));
x.forEach(function(value, index)
{
document.write(value.innerHTML);
document.write("<br>");
});
</script>
</body>
</html>
</code></pre>
<p>Please let me know if any improvements need (could) be done to the script.</p>
| [] | [
{
"body": "<p>The only purpose of this script appears to be to illustrate the use the <code>Array.prototype.slice.call</code> \"idiom\" and the <code>forEach</code> function. So it's hard to make \"improvements\" when the purpose of the code isn't its actual result (which is trivial).</p>\n\n<p>What the code actually <em>does</em> can be done in a number of ways, some of which won't (directly) use <code>forEach</code> and/or <code>NodeList</code> and/or <code>slice.call</code>. In that case, is it still an improvement? Conversely, sticking to <code>forEach</code> etc. doesn't leave much room for change, since the code seems designed as a minimal example of those things.</p>\n\n<p>I'm hesitant to write any code, because I'm not sure what the point would be.</p>\n\n<p>With that said,</p>\n\n<ul>\n<li>Don't rely on W3 Schools (<a href=\"http://www.w3fools.com/\" rel=\"nofollow noreferrer\">this site</a> lists several reasons and better alternatives)</li>\n<li>Avoid <code>document.write()</code> - or use it with open eyes (see why <a href=\"https://stackoverflow.com/a/802943/167996\">here</a>)</li>\n<li>I'd also avoid <code>forEach</code> in favor of a standard <code>for</code> loop, since <code>forEach</code> is not universally supported in browsers (see <a href=\"http://caniuse.com/#search=foreach\" rel=\"nofollow noreferrer\">caniuse.com</a>)</li>\n<li>The page's text appears to betray some confusion. Yes, the DOM is useful, and yes, the code demonstrates <code>forEach</code>. But <code>forEach</code> isn't part of the DOM. The whole point is that a <code>NodeList</code> object is a DOM object and not a normal array. It must therefore be converted to one by way of <code>Array.prototype.slice.call</code>. <em>Then</em> one can use <code>forEach</code> which is an array function but which, in and of itself, has nothing to do with the DOM.</li>\n</ul>\n\n<hr>\n\n<p>Update after reading @PM77-1's comment:</p>\n\n<p>There's nothing inherently wrong with this code. It is true, that<br>\nA) <code>for...in</code> doesn't behave like it does in Java and shouldn't be used here, and that<br>\nB) <code>getElementsByTagName</code> doesn't return a \"real\" array. The <code>slice.call</code> trick is indeed the \"standard\" way of converting an \"array-like\" object (which you find a lot of, unfortunately) to a real array. A very useful trick to know.</p>\n\n<p>So all in all, the code is basically fine. Yes, improvements can be made, <a href=\"https://codereview.stackexchange.com/questions/44529/foreach-and-nodelist/44532#44534\">as @Palacsint points out in his answer</a>, but there's nothing terrible going on.</p>\n\n<p>However, while a <code>NodeList</code> object isn't a real array, one can still use a regular old <code>for</code> loop:</p>\n\n<pre><code>var nodes, i;\n\nnodes = document.getElementsByTagName(\"p\");\nfor(i = 0 ; i < nodes.length ; i++) {\n document.write(nodes[i].innerHTML);\n document.write(\"<br>\");\n}\n</code></pre>\n\n<p>This removes the need for the <code>slice.call</code> trick, and it works on old browsers (where <code>forEach</code> doesn't exist).</p>\n\n<p>In general, though, when working with the DOM, it's useful to use a library to iron out the otherwise frustrating differences between browsers. jQuery is the king of the hill these days, and with that, you'd do something like this to find and iterate over some elements:</p>\n\n<pre><code>$(\"p\").each(function () {\n document.write(this.innerHTML);\n document.write(\"<br>\");\n});\n</code></pre>\n\n<p>(Of course, jQuery also makes it easy to do \"proper\" DOM insertion without resorting to <code>document.write</code>, but this is just for illustration)</p>\n\n<p>However, I do think it very wise to learn the nitty-gritty of JS, and not just run straight for jQuery or its ilk. And dealing with those \"array-like\" is one of those nitty-gritty things indeed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T22:31:00.350",
"Id": "77302",
"Score": "0",
"body": "It was actually my first `JavaScript` code. Originally I wanted to use `for-in` (assuming that it's similar to one in Java) instead of the *regular* `for` loop in one of W3 samples. After I realized that it's a completely different animal and does not iterate through a collection, I tried to apply `forEach()` function to the return of `getElementsByTagName()` assuming (wrongly again) that it returns an array. At the end I had to use `Array.prototype.slice.call` to convert the list to array. The resulting code looks somewhat convoluted, so I asked this question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T23:22:40.523",
"Id": "77303",
"Score": "1",
"body": "@PM77-1 Well, your code is about as good as it gets given what you aimed for. I know it looks convoluted, but, well, that's because the DOM is an odd beast. I've added some more to my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:35:55.323",
"Id": "44532",
"ParentId": "44529",
"Score": "11"
}
},
{
"body": "<p>Just two minor notes to add <em>@Flambino</em>'s great answer:</p>\n\n<ol>\n<li><p>Instead of <code>x</code> use intention-revealing names. What's the purpose of this variable? Name according to that. <code>paragraphs</code> would be a better name here, it explains the purpose of the variable and avoids mental mapping (readers/maintainers don't have to decode it every time). (It's just a minor thing here, everyone has one slot of short-term memory for <code>x</code> but having a couple of abbreviations in a larger project could make understanding code really hard.)</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Use Intention-Revealing Names</em>, p18; <em>Avoid Mental Mapping</em>, p25)</p></li>\n<li><p><a href=\"http://validator.w3.org/check\" rel=\"nofollow\">W3C Validator</a> founds one error and at least one warning. You could fix those by setting a <code>title</code> and an encoding:</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n<head>\n <title>DOM test page</title>\n <meta charset=\"UTF-8\">\n</head>\n<body>\n...\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:52:55.133",
"Id": "44534",
"ParentId": "44529",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44532",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T20:26:09.393",
"Id": "44529",
"Score": "4",
"Tags": [
"javascript",
"html",
"dom"
],
"Title": "forEach and NodeList"
} | 44529 |
<p>I am still working on A Z80 CPU emulator and I have decided to prototype it in javascript and then translate it into a faster language, It might be ported to C but more likely is Java - this means I cannot use pointers or jump-tables. It both compiles assembly and interprets it however both are giant nested switch-case statements with over 200 cases because I cant think of a more elegant way, is this the best way?</p>
<p>This is also the format of all emulator's source code I can find, one giant nested switch-case!</p>
<p>Here is an example of one tiny part of the compiler:</p>
<pre><code> switch(opcode) {
case "NOP":
RAM[byte++] = 0x00;
break;
case "HALT":
RAM[byte++] = 0x10;
break;
case "LD":
switch (parts[1]) {
case "A":
switch (parts[2]) {
case "A":
RAM[byte++] = 0x7F; break;
case "B":
RAM[byte++] = 0x78; break;
case "C":
RAM[byte++] = 0x81; break;
case "D":
RAM[byte++] = 0x82; break;
case "E":
RAM[byte++] = 0x83; break;
case "H":
RAM[byte++] = 0x84; break;
case "L":
RAM[byte++] = 0x85; break;
// LD A, n
default:
RAM[byte++] = 0x3E;
RAM[byte++] = parseInt(parts[2]);
}
break;
case "B":
switch (parts[2]) {
case "A":
RAM[byte++] = 0x47; break;
case "B":
RAM[byte++] = 0x40; break;
case "C":
RAM[byte++] = 0x41; break;
case "D":
RAM[byte++] = 0x42; break;
case "E":
RAM[byte++] = 0x43; break;
case "H":
RAM[byte++] = 0x44; break;
case "L":
RAM[byte++] = 0x45; break;
// LD B, n
default:
RAM[byte++] = 0x06;
RAM[byte++] = parseInt(parts[2]);
}
break;
case "C":
...
</code></pre>
<p>For some of these opcodes there is a format of the bits making up the number however I think it is more readable, reliable, faster and smaller to hard-code them all.</p>
<p>This is part of the interpreter:</p>
<pre><code> switch(RAM[PC++]) {
// NOP
case 0x00:
break;
// STOP
case 0x10:
terminate();
break;
// LD A, A
case 0x7F:
// Pointless
break;
// LD A, B
case 0x78:
Registers[0] = Registers[1]; break;
// LD A, C
case 0x79:
Registers[0] = Registers[2]; break;
// LD A, D
case 0x7A:
Registers[0] = Registers[3]; break;
...
</code></pre>
<p>Bytes are both wrote and read in hex because it has more of a pattern than decimal, plus ease of use with a hex editor.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T00:47:45.347",
"Id": "77307",
"Score": "3",
"body": "You say you ultimately want to implement this in C or Java, which makes this tricky to answer. I have some ideas but they are solely for a JavaScript version, and they won't translate well to those other languages. I'll be happy to post an answer, but if what you want is actually a different language, I'd say you should simply prototype in that other language directly"
}
] | [
{
"body": "<blockquote>\n <p>I cant think of a more elegant way, is this the best way?</p>\n</blockquote>\n\n<p>It's quite a good way: it's clear; and it's simple, so perhaps it's easily extended when you have a complicated bit.</p>\n\n<p>The copy-and-paste duplication in the compiler is the repeated <code>RAM[byte++] =</code> expression. You might get around this with a subroutine ...</p>\n\n<pre><code>switch(opcode) {\n case \"NOP\":\n return [ 0x00 ]; // return an array of bytes\n break;\n case \"HALT\":\n ... etc ...\n</code></pre>\n\n<p>... so that the caller invokes the subroutine, gets an array of bytes back, and writes the array of bytes into RAM (so there's only one statement which writes to RAM).</p>\n\n<p>Another possibility is to define the whole switch statement using a JSON dictionary:</p>\n\n<pre><code>{\n { \"NOP\": 0x00 },\n { \"HALT\": 0x10 },\n { \"LD\": {\n { \"A\": {\n { \"A\": 0x7f },\n { \"B\": 0x78 },\n ... etc ...\n { \"!default!\": [ 0x06, \"parseInt(2)\" ]\n</code></pre>\n\n<p>That's theoretically good:</p>\n\n<ul>\n<li>Separates data from the code (perhaps you can define a compiler for a different assembly language just by using a different dictionary)</li>\n<li>Fewer lines of code (enough to load and then read the dictionary)</li>\n</ul>\n\n<p>Whether this is faster (at run-time) than a switch statement may depend on the JavaScript engine: <a href=\"http://davidbcalhoun.com/2010/is-hash-faster-than-switch-in-javascript/\" rel=\"nofollow\">according to this article</a> some do and some don't make a dictionary faster than a switch statement.</p>\n\n<p>The JSON seems able to deal with special cases, but not very elegantly: for example I used strings with special meanings, <code>\"!default!\"</code> (I wondered about using <code>null</code> instead) and <code>\"parseInt(2)\"</code> (could that be a named function instead?).</p>\n\n<p>The interpreter can also use a dictionary of opcode values. Javascript and C both support function pointers (as the dictionary or array/jump-table values).</p>\n\n<hr>\n\n<blockquote>\n <p>\"however the compiler\"</p>\n</blockquote>\n\n<p>Yes. I only reviewed the code you posted. :-) You are right: that's what I meant (one of the complications I was thinking of) in my first sentence when I said, \"it's easily extended when you have a complicated bit\".</p>\n\n<p>Still, one possibility is for the subroutine to return several types of data simultaneously, as different properties of a returned object, e.g.: 1) an array of bytes 2) and whether it's a jmp, call, or label.</p>\n\n<p>Another possibility is to have more than one parser: one which returned encoded bytes for every opcode, and another (much shorter) with special-case handling for the relatively few branch and label instructions.</p>\n\n<p>A third possibility is to pass one or more callback functions as parameters into the subroutine: a callback function which the subroutine should call when it detects a jump or call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:29:24.757",
"Id": "77398",
"Score": "0",
"body": "Nice idea of returning byte arrays however the compiler sometimes needs to make note of certain instructions (jmp, call) to come back to, which means the switch-case replacement needs to be able to do instructions. I don't know about JSON dictionaries (and will look into them) but wouldn't this conclusion include it too if it can only store values?.. otherwise it'll have to be a function table which is messier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:54:33.917",
"Id": "77406",
"Score": "0",
"body": "I edited my answer to try to address your comment"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T08:31:28.370",
"Id": "44552",
"ParentId": "44537",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T23:40:00.920",
"Id": "44537",
"Score": "8",
"Tags": [
"javascript",
"assembly",
"simulation"
],
"Title": "Switch-case Monstrosity for CPU Emulator"
} | 44537 |
<p>I am writing a python script that will call mandrills export activity api for every blog on a worpress mu install except for the main site. The script is designed to be called from a cron job on a regular schedule. The code I have is here.</p>
<pre><code>__author__ = 'Taylor'
import datetime
import mandrill
import phpserialize
import mysql.connector
class BlogReporter(object):
blog_id = None
table_name = 'wp_%s_options'
notify_email = None
sender_email = None
date_to = None
date_from = None
def __init__(self, blog_id_, database_config_, mandrill_client_):
self.blog_id = blog_id_
self.mandrill_client = mandrill_client_
self.table_name = 'wp_' + str(blog_id_) + '_options'
try:
cnx_ = mysql.connector.connect(**database_config_)
except mysql.connector.Error as err:
print(err)
else:
query_ = "SELECT option_value FROM " + self.table_name + " WHERE option_name=%s"
try:
cursor_ = cnx_.cursor()
cursor_.execute(query_, ('admin_email',))
result = cursor_.fetchone()
except Exception as err:
print(err)
else:
# set notify email from cursor
self.notify_email = result
cursor_.close()
try:
cursor_ = cnx_.cursor()
cursor_.execute(query_, ('wysija',))
encoded_result = cursor_.fetchone()[0]
except Exception as err:
print(err)
else:
decoded_result = phpserialize.unserialize(encoded_result.decode('base64', 'strict'))
self.sender_email = decoded_result['from_email']
cursor_.close()
cnx_.close()
self.date_to = datetime.datetime.now()
# if it monday lets get activity since saturday
if self.date_to.weekday() is 0:
self.date_from = self.date_to - datetime.timedelta(days=2)
# else just get the activity from the past day
else:
self.date_from = self.date_to - datetime.timedelta(days=1)
def export_activity(self):
self.mandrill_client.exports.activity(self.notify_email, self.date_from, self.date_to, None,
self.sender_email,'Sent')
# database name and credentials
# these should eventually be parsed from command line arguments
database_config = {
'user': 'root',
'password': 'password',
'database': 'wpmudb'
}
# Mandrill API Key
# this should also be parsed from command line
mandrill_api_key = 'xxxxx_xxxxxxxxxxxxxxxx'
mandrill_client = mandrill.Mandrill(mandrill_api_key)
try:
cnx = mysql.connector.connect(**database_config)
except mysql.connector.Error as err:
print(err)
else:
try:
cursor = cnx.cursor()
# Get all blogs but blog_id 1 since the main site needs no report
query = "SELECT blog_id FROM wp_blogs WHERE blog_id != '1'"
cursor.execute(query)
except Exception as err:
print(err)
else:
for blog_id in cursor:
blog = BlogReporter(blog_id[0], database_config, mandrill_client)
blog.export_activity()
del blog
cursor.close()
cnx.close()
</code></pre>
<p>I wrote it like this because it is the first program I have written in python and I was unsure of how to structure it and wanted to learn more about classes in python. However, recognizing that in the programs current state <code>Class BlogReporter</code>'s constructer and method <code>export_activity</code> could be refactored into one function that accepts the arguments of class <code>BlogReporter</code>'s constructor and is simply the class's constructor plus the method <code>export_activity</code>; I was curious if doing so would be beneficial to the program in any way.</p>
<p>I would also like to welcome comments as to whether the mandrill client should be reinstantiated for each instance of <code>BlogReporter</code> or whether it is better to pass the same client to each instance.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:10:03.517",
"Id": "77530",
"Score": "0",
"body": "Rather than hard coding API keys and passwords (or passing them as command line arguments), you could look at the [`keyring`](https://pypi.python.org/pypi/keyring) module instead."
}
] | [
{
"body": "<p>Here are some points:</p>\n\n<blockquote>\n <p>and wanted to learn more about classes in python</p>\n</blockquote>\n\n<p>If you write some piece of code to learn something, delete it and rewrite it.</p>\n\n<blockquote>\n <p>construct[o]r and method <code>export_activity</code> could be refactored into one function</p>\n</blockquote>\n\n<p>If you have <strong>a class with a single method</strong> converting to a function is what you should do <em>by default</em>. By <code>by default</code> I mean unless you have a really solid reason to do otherwise.</p>\n\n<blockquote>\n <p>I was curious if doing so would be beneficial to the program in any way.</p>\n</blockquote>\n\n<p>Simplicity is second only to (actually needed) functionality. (As XP people say <a href=\"http://xp.c2.com/DoTheSimplestThingThatCouldPossiblyWork.html\">Do the simplest thing that could possibly work</a>.) You do not have to justify making your program simpler by appealing to a higher value. </p>\n\n<p>Some more specific points:</p>\n\n<p>The sections of code where you read an option from the database is the same almost word for word. If you find yourself writing the same code twice or more tellingly *Copy&Paste*ing some snippet you should put it in a function and call it instead. This way you will save yourself a lot of effort. As a general rule you should write everything <a href=\"http://c2.com/cgi/wiki?OnceAndOnlyOnce\">once and only once</a>.</p>\n\n<p>Your constructor does too much. <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\">Anything other that assigning fields should not be done in a constructor</a>. But your constructor is too long even for a method. <a href=\"http://c2.com/cgi/wiki?ExtractMethod\">Extract every snippet of code that is doing something in a function</a> so that when you (or someone else) read it again instead of trying to guess what you are trying to do by reading how you do it you would just read what you are trying to do. This way you (or others) may skip reading the extracted function altogether if they are not interested.</p>\n\n<p>Clean up of resources (files, connections, cursors etx) are usually done by initializing them in <code>with</code> blocks. If the resource does not support <code>with</code> blocks out-of-the box but cleaning-up consists of calling <code>.close()</code> on it, you can wrap the resource in <code>contextlib .closing</code> The clean-up should otherwise be done in <code>finally</code> blocks to ensure they are executed even if an exception is thrown; at least in long running programs, server or desktop applications.</p>\n\n<p>When you decide to catch an exception, catch the most specific exception you expect. Look <a href=\"http://docs.python.org/2/library/exceptions.html#exception-hierarchy\">what else are you catching</a> when you say <code>catch Exception</code>. Here root exception of all <code>mysql.connector</code> errors (apparently <code>mysql.connector.Error</code>) is more suitable.</p>\n\n<p>If you are not going to do anything useful (recover, wrap&rethrow etc) do not catch exceptions. You can do <code>print(err)</code> somewhere else.</p>\n\n<p>In a script put your code in a function, for example <code>main</code>, and call it <code>if __name__ == \"__main__\": main()</code>. That way you can debug your code in repl, or import it in other scripts/programs as a module. This also allows further refactorings, which I won't elaborate but you can see in the code below.</p>\n\n<p>If a method has many parameters and you are calling it many times with same parameters you can use <code>functools.partial</code> to reduce the noise. (see below)</p>\n\n<p>Also <code>cursor.fetchone()</code> apparently returns tuple and I'm assuming you do not want to pass a tuple as <code>notify_email</code> parameter so you are probably missing a <code>[0]</code> after the <code>fetchone()</code> when reading the <code>admin_email</code>.</p>\n\n<p>Caveat: I am not a python programmer. And haven't tried the program below.\nAlso the refactored code still needs some <strong>Inversion of control</strong> refactoring, but ignore this if you do not already know what that means from other languages.</p>\n\n<pre><code>def get_option(cnx, blog_id, option_name):\n table_name = 'wp_' + str(blog_id) + '_options'\n query_ = \"SELECT option_value FROM \" + table_name + \" WHERE option_name=%s\"\n with closing( cnx.cursor() ) as cursor_:\n cursor_.execute(query_, (option_name,))\n return cursor_.fetchone()[0]\n\ndef get_timespan():\n date_to = datetime.datetime.now()\n # if it monday lets get activity since saturday\n if date_to.weekday() is 0:\n date_from = date_to - datetime.timedelta(days=2)\n # else just get the activity from the past day\n else:\n date_from = date_to - datetime.timedelta(days=1)\n return (date_from, date_to)\n\ndef export_blog_activity(blog_id, cnx, mandrill_client):\n notify_email = get_option(cnx, blog_id, 'admin_email')\n encoded_result = get_option(cnx, blog_id, 'wysija')\n decoded_result = phpserialize.unserialize(encoded_result.decode('base64', 'strict'))\n sender_email = decoded_result['from_email']\n date_from, date_to = get_timespan()\n mandrill_client.exports.activity(notify_email, date_from, date_to, None, sender_email,'Sent')\n\ndef main():\n # database name and credentials\n # these should eventually be parsed from command line arguments\n database_config = {\n 'user': 'root',\n 'password': 'password',\n 'database': 'wpmudb'\n }\n # Mandrill API Key\n # this should also be parsed from command line\n mandrill_api_key = 'xxxxx_xxxxxxxxxxxxxxxx'\n mandrill_client = mandrill.Mandrill(mandrill_api_key)\n with closing(mysql.connector.connect(**database_config)) as cnx:\n export_activity = functools.partial(export_blog_activity, mandrill_client = mandrill_client, cnx=cnx)\n with closing( cnx.cursor() ) as cursor_:\n # Get all blogs but blog_id 1 since the main site needs no report\n query = \"SELECT blog_id FROM wp_blogs WHERE blog_id != '1'\"\n cursor_.execute(query)\n for row in cursor_:\n export_activity(row[0])\n\nif __name__ == \"__main__\":\n try:\n main()\n except mysql.connector.Error as e:\n print \"Sql error:\", e\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T08:32:29.160",
"Id": "44650",
"ParentId": "44539",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44650",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T00:09:48.723",
"Id": "44539",
"Score": "12",
"Tags": [
"python",
"object-oriented",
"functional-programming"
],
"Title": "Refractoring OOP vs. Functional Programming Approach"
} | 44539 |
<p>I built a simple Node app, and the code "works", with no failures, no syntax errors, and does not break, but one component doesn't work right. I showed a snippet <a href="https://stackoverflow.com/questions/22444848/function-failing-silently-with-perfect-syntax-how-should-i-debug?noredirect=1#comment34136300_22444848">on Stack Overflow, in this question</a>, but viewers found no issue. So, I think the infrastructure, the method, in which I put this app together must be problematic, and I'd like to have it reviewed.</p>
<p>I put everything into a single source file to eliminate the headache of debugging whilst keeping track of modules. </p>
<p><a href="https://gist.github.com/anonymous/9592099" rel="nofollow noreferrer">Here is the code</a></p>
<p>Here's my relevant script:</p>
<pre><code>var connection = createConnection();
connection.connect(function (err) {
if (err) return callback(new Error('Failed to connect'), null);
console.log('[Post]Connection with the officeball MySQL database opened...');
connection.query(
'INSERT INTO `officeball`.`sales_entries` SET category = ?, `group` = ?, date = ?, price = ?, customer = ?, seller = ?, commission = ?',
salesData),
function (err, rows, fields) {
if (err) console.log(err);
connection.destroy();
console.log('[Post]...Connection with the officeball MySQL database closed.');
}
});
</code></pre>
<p>And here's my console output:</p>
<pre><code>Application initializing...
Application successfully initialized!
Server running at http://127.0.0.1:8080/
User username1 is attempting to validate for a hit...
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
User username1 validated and is ready!
[Post] Connection with the officeball MySQL database opened...
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T00:56:06.533",
"Id": "77309",
"Score": "2",
"body": "Code review is a site for posting code to be reviewed, not for posting links to code you want reviewed. While it's okay to post a link to the full project, at a minimum, you should include the code you most want reviewed in your question, for numerous reasons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T01:00:24.260",
"Id": "77310",
"Score": "0",
"body": "Sure, sorry, I'm new. I'll add the snippet. @nhgrif"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T01:12:01.413",
"Id": "77311",
"Score": "0",
"body": "Also, I'd like to add that this is my first non-tutorial node app, and while I understand the efficiency and power of Node's callback functions, I'm focusing on a working application more than I am on one that can handle a billion users right now. Please keep that in mind when performing your review. Also, thank you ahead of time. I appreciate this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T01:14:39.043",
"Id": "77312",
"Score": "0",
"body": "And Jamal, thank you for that edit. I've seen you around the exchange more than a few times so far."
}
] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Your <code>console.log</code> statement should be wrapped in a condition so that you can turn off all logging to the console. Node can really slow down because of logging to the console.</p></li>\n<li><p>If you are going to log to the console, then it would make more sense to log your query and <code>salesData</code> as well. </p></li>\n<li><p>Opening and closing a connection every time you want to post a sale is (very) bad practice, check out <code>mysql.createPool</code></p></li>\n<li><p>Calling <code>connection.end();</code> will kill a connection gracefully. calling <code>connection.destroy()</code>, not so much..</p></li>\n</ul>\n\n<p>All in all, I would always be sensitive to performance and established best practice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:45:30.737",
"Id": "77380",
"Score": "0",
"body": "Thanks Konijn, those are very good points. I did not know that console logs could slow the execution down. Mainly though, I need to look into that connection pooling."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T12:57:30.503",
"Id": "44564",
"ParentId": "44541",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T00:50:34.063",
"Id": "44541",
"Score": "3",
"Tags": [
"javascript",
"mysql",
"node.js"
],
"Title": "My node app with valid syntax is failing silently, but not breaking. Infrastructure problem?"
} | 44541 |
<p>I recently gave an interview and was asked the following question. I posted this here
<a href="https://stackoverflow.com/questions/22445688/finding-path-in-maze">Finding path in Maze</a> also, and someone suggested I should try Code Review. So here it goes.</p>
<p>A maze is a group of linked Places. Each Place has a North, South, East, and West Place adjacent to it. There are two special pre-defined Place's: Place Wall represents a wall - the mouse can't go there. Place Cheese is ... cheese! The connections between Places are symmetrical - if you start from any Place and go North and then South, you return to where you were.</p>
<p>To simplify things, the maze has no closed loops - that is, if you start in any Place and follow any path, you eventually either hit a wall or find cheese - you never come back to the Place you started unless you actually retrace your steps.</p>
<p>A mouse starts off in some Place and searches around for Cheese. When it finds Cheese, it returns a set of directions - a string of the letters NSEW that lead from where it started to the Cheese.</p>
<p>The following framework defines the classes and functions. Some other code not included here generates a maze by creating a bunch of Place's and linking them. It then calls mouse(), passing some starting Place from the maze:</p>
<pre><code>interface Place {
// Return the adjacent Place in the given direction
public Place goNorth();
public Place goSouth();
public Place goEast();
public Place goWest();
// Returns true only for the special "Wall" place
public bool isWall();
// Returns true only for the special "Cheese" place
public bool isCheese();
};
class Mouse {
public Mouse() {}
// Return a string of the letters NSEW which, if used to traverse the
// the maze from startingPoint, will reach a Place where isCheese() is
// true. Return null if you can't find such a path.
public String findCheese(Place startingPoint) {
... fill this in ...
}
}
</code></pre>
<p>Implement findCheese(). You can add any fields or helper methods you need to Mouse. Extra credit: Eliminate the "no closed loops" restriction. That is, change your code so that it works correctly even if there might be a path like SSNEEW that leads the mouse back to the Place it started from.</p>
<p>This is what I tried. I understand this won't be the best or optimized solution, and wanted feedback as to what I else I could try. I have not considered the extra credit part</p>
<pre><code>public String findCheese(place startingPoint)
{
//Call helper function in all 4 directions;
return findCheeseHelper(startingPoint,new StringBuilder("N")).append(
findCheeseHelper(startingPoint,new StringBuilder("S"))).append(
findCheeseHelper(startingPoint,new StringBuilder("E"))).append(
findCheeseHelper(startingPoint,new StringBuilder("W"))).toString();
}
public StringBuilder findCheeseHelper(place startingPoint, StringBuilder direction)
{
StringBuilder nDir=new StringBuilder("");
StringBuilder sDir=new StringBuilder("");
StringBuilder eDir=new StringBuilder("");
StringBuilder wDir=new StringBuilder("");
//Rerturn which direction this step came from if cheese found
if(startingPoint.isCheese())
{
return direction;
}
//Specify this is not a correct direction by returning an empty String
else if(startingPoint.isWall())
{
return "";
}
//Explore all other 3 directions (except the one this step came from)
if(direction=="N")
{
sDir=findCheeseHelper(startPoint.goSouth(), new StringBuilder("N"));
eDir=findCheeseHelper(startPoint.goEast(), new StringBuilder("E"));
wDir=findCheeseHelper(startPoint.goWest(), new StringBuilder("W"));
}
else if(direction=="E")
{
nDir=findCheeseHelper(startPoint.goNorth(), new StringBuilder("N"));
sDir=findCheeseHelper(startPoint.goSouth(), new StringBuilder("S"));
wDir=findCheeseHelper(startPoint.goWest(), new StringBuilder("E"));
}
else if(direction=="W")
{
nDir=findCheeseHelper(startPoint.goNorth(), new StringBuilder("N"));
sDir=findCheeseHelper(startPoint.goSouth(), new StringBuilder("S"));
eDir=findCheeseHelper(startPoint.goEast(), new StringBuilder("W"));
}
else if(direction=="S")
{
nDir=findCheeseHelper(startPoint.goNorth(), new StringBuilder("S"));
eDir=findCheeseHelper(startPoint.goEast(), new StringBuilder("E"));
wDir=findCheeseHelper(startPoint.goWest(), new StringBuilder("W"));
}
//If I hit wall in every direction, I will get empty string and so specify to calling
//function that this is not a correct direction
if(nDir.equals("") && sDir.equals("") && eDir.equals("") && wDir.equals(""))
return new StringBuilder("");
//If Cheese was found in even 1 direction, return direction to come to this step, appended with the path
// forward to the calling function
return direction.append(nDir).append(sDir).append(eDir).append(wDir);
}
</code></pre>
| [] | [
{
"body": "<p>I'm sorry, but that code is really convoluted. </p>\n\n<p>First off, does this actually work? The comparisons <code>direction == \"N\"</code>(etc.) should fail at compile time due to incomparable types (<code>String</code> and <code>StringBuilder</code>) and <code>nDir.equals(\"\")</code> would always return <code>false</code>.</p>\n\n<p>Generally you can't use use <code>==</code> to compare strings in Java. You have to use <code>equals</code> (for strings. <code>StringBuilder</code> doesn't have an implemention of <code>equals</code>).</p>\n\n<p>You really are overdoing it with the <code>StringBuilder</code>s. You should only need a single one (one <code>new StringBuilder()</code> call in the entire code) to which you append <code>String</code>s. </p>\n\n<p>To be honest in practice code like this, you don't need use a <code>StringBuilder</code> at all. Just use string concatenation. It's slow and a memory hog, so it's not something you should do in real life code, but it would make this code much more simpler and easier to read.</p>\n\n<p>There is much more, but I believe that would be good for a first step in the right direction.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T15:06:25.310",
"Id": "77356",
"Score": "0",
"body": "If I'm not mistaken, except in loop, concatenating `String`s is the way to go, since the compiler will optimize everything for you. `StringBuilder` is optimize things in loops, but be aware that I could be wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T06:05:49.670",
"Id": "77744",
"Score": "0",
"body": "@RoToRA - I actually made the code first with Strings but then thought there would be too much memory consumption. So shifted to StringBuilder. As for the part that I StringBuilder doesn't override equals(), my bad, should have realized that. Thanks for your inputs."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T10:39:27.940",
"Id": "44558",
"ParentId": "44544",
"Score": "6"
}
},
{
"body": "<p>@RoToRa has some good points. Creating so many <code>StringBuilder</code>s while recursing is really an overkill, and assuming even if the algorithm works (albeit inefficiently), I will be more inclined to use <code>enums</code> representing the direction instead of <code>StringBuilder</code>s.</p>\n\n<p>Also, the logic needs more clarification in the example below... if I'm heading/headed(?) north of my starting point, then I'll head in the opposite direction but with my direction \"North\" still...?</p>\n\n<pre><code>if(direction==\"N\")\n{\n sDir=findCheeseHelper(startPoint.goSouth(), new StringBuilder(\"N\"));\n eDir=findCheeseHelper(startPoint.goEast(), new StringBuilder(\"E\"));\n wDir=findCheeseHelper(startPoint.goWest(), new StringBuilder(\"W\"));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T09:55:38.480",
"Id": "77528",
"Score": "0",
"body": "I wanted to suggest using an enum, too, however with the given `Place` interface it would require some anonymous classes to map the enums to the method class and I don't think the OP is ready for that :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T00:35:54.053",
"Id": "44629",
"ParentId": "44544",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T02:22:55.643",
"Id": "44544",
"Score": "10",
"Tags": [
"java",
"recursion",
"pathfinding",
"backtracking"
],
"Title": "Finding path in Maze"
} | 44544 |
<blockquote>
<p>Excel column letters to actual numbers, if you recall, Excel names its columns with letters from A to Z, and then the sequence goes AA, AB, AC... AZ, BA, BB, etc.
You have to write a function that accepts a string as a parameter (like "AABCCE") and returns the actual column number. And then do the exact reverse, given column number return the column name.</p>
</blockquote>
<p>Also verify complexity: \$O(\log n)\$, where \$n\$ is the input number while \$\log\$ is to base the base being considered (hexa, decimal or binary etc.).</p>
<pre><code>public final class Excel {
private Excel() {}
public static int getExcelColumnNumber(String column) {
int result = 0;
for (int i = 0; i < column.length(); i++) {
result *= 26;
result += column.charAt(i) - 'A' + 1;
}
return result;
}
public static String getExcelColumnName(int number) {
final StringBuilder sb = new StringBuilder();
int num = number - 1;
while (num >= 0) {
int numChar = (num % 26) + 65;
sb.append((char)numChar);
num = (num / 26) - 1;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
Assert.assertEquals(53, getExcelColumnNumber("BA"));
Assert.assertEquals("BA", getExcelColumnName(53));
Assert.assertEquals(703, getExcelColumnNumber("AAA"));
Assert.assertEquals("AAA", getExcelColumnName(703));
Assert.assertEquals(26, getExcelColumnNumber("Z"));
Assert.assertEquals("Z", getExcelColumnName(26));
Assert.assertEquals(702, getExcelColumnNumber("ZZ"));
Assert.assertEquals("ZZ", getExcelColumnName(702));
}
}
</code></pre>
| [] | [
{
"body": "<p>Your code is basically fine, and your unit tests are good. All I have is nitpicks.</p>\n\n<p>\"Excel\" in the method names are a bit redundant.</p>\n\n<p>In <code>getExcelColumnNumber()</code>, group <code>- 'A' + 1</code> with parentheses as <code>- ('A' - 1)</code>. Then the compiler can generate <code>64</code> as a constant.</p>\n\n<p>In <code>getExcelColumnName()</code>, the similarly named variables <code>number</code>, <code>num</code>, and <code>numChar</code> are confusing.</p>\n\n<p>The complexity O(log <em>n</em>) is correct. (With Big-O notation, the base of the logarithm is an unimportant detail, since the base just scales the logarithm by a constant factor, and constant factors are conventionally discarded with Big-O. For example, O(log_26 <em>n</em>) = O(ln <em>n</em> / ln 26) = O(ln <em>n</em>).)</p>\n\n<pre><code>public final class ExcelColumn {\n\n private ExcelColumn() {}\n\n public static int toNumber(String name) {\n int number = 0;\n for (int i = 0; i < name.length(); i++) {\n number = number * 26 + (name.charAt(i) - ('A' - 1));\n }\n return number;\n }\n\n public static String toName(int number) {\n StringBuilder sb = new StringBuilder();\n while (number-- > 0) {\n sb.append((char)('A' + (number % 26)));\n number /= 26;\n }\n return sb.reverse().toString();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T00:36:45.527",
"Id": "77480",
"Score": "0",
"body": "\"In `getExcelColumnNumber()`, group `- 'A' + 1` with parentheses as `- ('A' - 1)`\". Good point."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T07:02:24.173",
"Id": "44549",
"ParentId": "44545",
"Score": "22"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T02:54:42.250",
"Id": "44545",
"Score": "19",
"Tags": [
"java",
"algorithm",
"number-systems"
],
"Title": "Excel column string to row number and vice versa"
} | 44545 |
<p>I've been messing with metaprogramming and variadic templates in C++, and I came up with this very primitive implementation of a tuple:</p>
<pre><code>constexpr bool GreaterThanZero(int N)
{
return N > 0;
}
template <int, typename...>
struct Helper;
template <int N, typename Head, typename... Tail>
struct Helper<N, Head, Tail...>
{
typedef typename Helper<N-1, Tail...>::type type;
};
template <typename Head, typename... Tail>
struct Helper<0, Head, Tail...>
{
typedef Head& type;
};
template <int, typename...>
class TupleImpl;
template <>
class TupleImpl<-1>
{
};
template <typename Head>
class TupleImpl<0, Head>
{
protected:
Head head;
public:
template <int Depth>
Head& get()
{
static_assert(Depth == 0, "Requested member deeper than Tuple");
return head;
}
template <int Depth>
const Head& get() const
{
static_assert(Depth == 0, "Requested member deeper than Tuple");
return head;
}
};
template <int N, typename Head, typename... Tail>
class TupleImpl<N, Head, Tail...>
{
protected:
Head head;
TupleImpl<N-1, Tail...> tail;
public:
template <int M>
typename std::enable_if<M == 0, Head&>::type get()
{
return head;
}
template <int M>
typename std::enable_if<GreaterThanZero(M), typename Helper<M, Head, Tail...>::type>::type get()
{
return tail.get<M-1>();
}
template <int M>
typename std::enable_if<M == 0, const Head&>::type get() const
{
return head;
}
template <int M>
typename std::enable_if<GreaterThanZero(M), typename Helper<M, Head, Tail...>::type>::type get() const
{
return tail.get<M-1>();
}
};
template <typename... Elements>
class Tuple : public TupleImpl<sizeof...(Elements)-1, Elements...>
{
public:
static constexpr std::size_t size()
{
return sizeof...(Elements);
}
};
int main()
{
using namespace std;
Tuple<int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int> test;
Tuple<> test2;
test.get<0>() = 1;
test.get<1>() = 2;
cout << test.size() << endl;
cout << test.get<0>() << endl;
cout << test.get<1>() << endl;
}
</code></pre>
<p>Being template metaprogramming, of course it looks terrible. Are there any ways I can clean it up? I've been picking up the nitty-gritty details of how templates work by messing around with stuff like this, but I'm sure I'm missing something that would simplify this.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T12:48:30.713",
"Id": "77336",
"Score": "2",
"body": "Your implementation does not handle empty tuples :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:55:25.250",
"Id": "77425",
"Score": "0",
"body": "@Morwenn Ah good point :) what is acceptable behavior for that? Perhaps just an empty specialized class? I mean, there's nothing to get from it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T08:42:02.127",
"Id": "77520",
"Score": "0",
"body": "I actually tried to find a use case for it, but the only I could find was for some variadic metafunctions using tuples where there was a specialization for an empty parameter pack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T06:31:10.837",
"Id": "77746",
"Score": "3",
"body": "First obvious point: `GreaterThanZero` might as well just use: `return N > 0;` as its body."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T01:20:48.680",
"Id": "77986",
"Score": "0",
"body": "@JerryCoffin Wow, I can't believe I did that. The code has been updated for both fixes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-16T19:26:49.870",
"Id": "204418",
"Score": "0",
"body": "This code compiles with gcc, but clang 3.5 gives \"error: expected expression\" error for the line `return tail.get<M-1>();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-17T00:38:39.487",
"Id": "204482",
"Score": "0",
"body": "@BuğraGedik have you tried with the latest Clang? It looks well-formed to me but I'm not sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-18T21:47:11.010",
"Id": "204881",
"Score": "0",
"body": "@chbaker It needs to be tail.template get<M-1>(); See http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords"
}
] | [
{
"body": "<p>Below is how I would clean this up, or maybe partially re-write [<a href=\"http://coliru.stacked-crooked.com/a/ac1e7947152acd6a\">live example</a>]:</p>\n\n<pre><code>// helpers\ntemplate <typename T>\nstruct id { using type = T; };\n\ntemplate <typename T>\nusing type_of = typename T::type;\n\ntemplate <size_t... N>\nstruct sizes : id <sizes <N...> > { };\n\n// choose N-th element in list <T...>\ntemplate <size_t N, typename... T>\nstruct Choose;\n\ntemplate <size_t N, typename H, typename... T>\nstruct Choose <N, H, T...> : Choose <N-1, T...> { };\n\ntemplate <typename H, typename... T>\nstruct Choose <0, H, T...> : id <H> { };\n\ntemplate <size_t N, typename... T>\nusing choose = type_of <Choose <N, T...> >;\n\n// given L>=0, generate sequence <0, ..., L-1>\ntemplate <size_t L, size_t I = 0, typename S = sizes <> >\nstruct Range;\n\ntemplate <size_t L, size_t I, size_t... N>\nstruct Range <L, I, sizes <N...> > : Range <L, I+1, sizes <N..., I> > { };\n\ntemplate <size_t L, size_t... N>\nstruct Range <L, L, sizes <N...> > : sizes <N...> { };\n\ntemplate <size_t L>\nusing range = type_of <Range <L> >;\n\n// single tuple element\ntemplate <size_t N, typename T>\nclass TupleElem\n{\n T elem;\npublic:\n T& get() { return elem; }\n const T& get() const { return elem; }\n};\n\n// tuple implementation\ntemplate <typename N, typename... T>\nclass TupleImpl;\n\ntemplate <size_t... N, typename... T>\nclass TupleImpl <sizes <N...>, T...> : TupleElem <N, T>...\n{\n template <size_t M> using pick = choose <M, T...>;\n template <size_t M> using elem = TupleElem <M, pick <M> >;\n\npublic:\n template <size_t M>\n pick <M>& get() { return elem <M>::get(); }\n\n template <size_t M>\n const pick <M>& get() const { return elem <M>::get(); }\n};\n\ntemplate <typename... T>\nstruct Tuple : TupleImpl <range <sizeof...(T)>, T...>\n{\n static constexpr std::size_t size() { return sizeof...(T); }\n};\n</code></pre>\n\n<p>Comments:</p>\n\n<ul>\n<li><p>With a bit more infrastructure (helper structs that are typically reused here and there) at the beginning, the main tuple implementation becomes just 20 lines.</p></li>\n<li><p>Instead of a recursive implementation, I have switched to multiple (variadic) inheritance of single tuple elements <code>TupleElem</code>, each with its own id <code>N</code> (so that each element is of unique type) and its own function <code>get()</code>. Hence <code>Tuple</code>'s function <code>get()</code> just redirects to the appropriate base class.</p></li>\n<li><p>Now a specialization of <code>TupleElem</code> for empty types can bring easily the desired <a href=\"http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Empty_Base_Optimization\">empty base optimization</a> without affecting the main tuple implementation.</p></li>\n<li><p>No specialization is needed for empty tuple. This definition includes empty tuple as a special case.</p></li>\n<li><p>No static assertions needed, an out-of-range index will give an error anyway (but you can add for better messages of course).</p></li>\n</ul>\n\n<p>Now, there are so many things missing. I would start from support for rvalue references and, of course, constructors. If you want to get an idea, you can have a look at <a href=\"https://github.com/iavr/ivl2/tree/master/include/ivl/root/core/tuple\">my own tuple implementation</a> (of which this one here is a miniature) including tuple views, expression templates for lazy evaluation, loops, algorithms, integration with all C++ operators, and much more.</p>\n\n<p>Template metaprogramming does not have to look terrible!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T11:02:40.370",
"Id": "78044",
"Score": "0",
"body": "Kudos for the non-recursive implementation :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T23:05:21.317",
"Id": "78220",
"Score": "0",
"body": "Agreed, that's cool. Not to mention, saves me from the unlikely case that the entire tuple won't be inlined with the recursive implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:05:32.590",
"Id": "44832",
"ParentId": "44546",
"Score": "12"
}
},
{
"body": "<p>This currently probably won't compile:</p>\n\n<pre><code>const Tuple<int, int> t{};\nt.get<1>();\n</code></pre>\n\n<p>Your recursive const version of <code>get</code> returns a non-const reference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:23:05.297",
"Id": "78072",
"Score": "0",
"body": "Yes, I had noticed too that a `const` was missing, but one couldn't see that easily among all the template, `enable_if` and `Helper` stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T23:06:11.473",
"Id": "78221",
"Score": "0",
"body": "Good point, that's pretty important."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:05:52.930",
"Id": "44855",
"ParentId": "44546",
"Score": "4"
}
},
{
"body": "<p>In C++14, it's possible to implement a tuple in a very concise way. However, you lose some functionality of <code>std::tuple</code> (<code>constexpr</code>ness and some perfect forwarding) because of some limitations of lambdas. The basic idea is to use a lambda capture as a fast compiler-generated struct. Here's a naive implementation just to give you the idea, but you should look at <a href=\"http://github.com/ldionne/hana\" rel=\"noreferrer\">Hana</a> to see the actual implementation:</p>\n\n<pre><code>#include <cstddef>\n#include <utility>\n\n\ntemplate <typename ...Xs>\nauto make_tuple(Xs&& ...xs) {\n // No perfect forwarding in the capture: maybe C++17?\n return [=](auto&& f) mutable -> decltype(auto) {\n return std::forward<decltype(f)>(f)(&xs...);\n };\n}\n\ntemplate <std::size_t n, typename = std::make_index_sequence<n>>\nstruct get_impl;\n\ntemplate <std::size_t n, std::size_t ...ignore>\nstruct get_impl<n, std::index_sequence<ignore...>> {\n template <typename Nth>\n constexpr decltype(auto) operator()(decltype(ignore, (void const*)0)..., Nth nth, ...) const\n { return nth; }\n};\n\ntemplate <std::size_t N, typename Tuple>\ndecltype(auto) get(Tuple& tuple) {\n return *tuple(get_impl<N>{});\n}\n</code></pre>\n\n<p>You can then use it like:</p>\n\n<pre><code>#include <cassert>\n\nint main() {\n auto xs = make_tuple('0', 1, 2.2);\n assert(get<0>(xs) == '0');\n assert(get<1>(xs) == 1);\n assert(get<2>(xs) == 2.2);\n\n get<2>(xs) = 2.2222222;\n assert(get<2>(xs) == 2.2222222);\n}\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/6bf7255384c2c297\" rel=\"noreferrer\">Here's the live example</a>. Of course, it's not exactly clear how one would then have a <code>std::tuple<...></code> type using this technique, but it can be done (see slide 33 of <a href=\"http://ldionne.github.io/hana-cppcon-2014/\" rel=\"noreferrer\">this</a>).</p>\n\n<p>The largest advantages of this technique are:</p>\n\n<ol>\n<li>Clarity. Once you get it, it's very simple and terse.</li>\n<li>Opens new avenues for implementing many algorithms on tuples. For example, implementing <code>std::tuple_cat</code> is rather easy with this representation, while it's <em>very</em> hard with the usual <code>std::tuple</code> implementation.</li>\n<li>Compile-time performance: I've done several benchmarks, and this implementation technique really improves on the usual <code>std::tuple</code> implementation in terms of compilation time.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-04T12:56:18.253",
"Id": "280043",
"Score": "0",
"body": "Tried to implement it as a proof-of-concept: https://bitbucket.org/johannes_gerd_becker/pmt/src"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-22T15:51:18.247",
"Id": "67572",
"ParentId": "44546",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "44832",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T04:53:23.577",
"Id": "44546",
"Score": "16",
"Tags": [
"c++",
"c++11",
"template",
"template-meta-programming",
"variadic"
],
"Title": "Very basic tuple implementation"
} | 44546 |
<p>I am writing a new web service that will be performing a lot of large data load operations. To do so I am moving the data to a temporary table then merging the data in to the live data via a stored procedure.</p>
<p>That part I have down and working and am very confident in. What I am doing now is trying to optimize the loading code to help take the load off of the IIS server that will be performing these operations.</p>
<p>Here is what I am currently doing synchronously and works fine.</p>
<pre><code>public void BulkLoadData(IDataReaderWithMappings reader,
string createTempTableStatement,
string loadingStoredProcedureName)
{
using (var connection = new SqlConnection(_connectionString))
using (var bulkCopy = new SqlBulkCopy(connection))
using (var command = new SqlCommand(createTempTableStatement, connection))
{
connection.Open();
command.ExecuteNonQuery();
bulkCopy.DestinationTableName = "#temp";
var mappings = reader.GetMappings();
foreach (var sqlBulkCopyColumnMapping in mappings)
{
bulkCopy.ColumnMappings.Add(sqlBulkCopyColumnMapping);
}
bulkCopy.WriteToServer(reader);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = loadingStoredProcedureName;
command.ExecuteNonQuery();
}
}
</code></pre>
<p>And here is my attempt at translating that in to asynchronous code.</p>
<pre><code>public async Task BulkLoadDataAsync(IDataReaderWithMappings reader,
string createTempTableStatement,
string loadingStoredProcedureName)
{
using (var connection = new SqlConnection(_connectionString))
using (var bulkCopy = new SqlBulkCopy(connection))
using (var command = new SqlCommand(createTempTableStatement))
{
var firstStage = connection.OpenAsync()
.ContinueWith(async delegate
{
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
});
bulkCopy.DestinationTableName = "#temp";
var mappings = reader.GetMappings();
foreach (var sqlBulkCopyColumnMapping in mappings)
{
bulkCopy.ColumnMappings.Add(sqlBulkCopyColumnMapping);
}
//Wait for the connection opening and the create table task to finish.
await firstStage.ConfigureAwait(false);
await bulkCopy.WriteToServerAsync(reader).ConfigureAwait(false);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = loadingStoredProcedureName;
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
</code></pre>
<p>The part I am not sure of my self about is that <code>.ContinueWith(</code> section. I thought it would be good to start opening the connection and creating the temporary table while I populate the bulk copy column mappings, and I have used async/await many times before but this is the first time I have used <code>.ContinueWith(</code> in conjunction with the async/await syntax.</p>
<p>Did I do it correctly, or should that <code>await firstStage;</code> be <code>await firstStage.Unwrap();</code>? I still do not exactly understand when I should be using <code>Unwrap()</code>. <strong>EDIT</strong>: Ok, <code>Unwrap()</code> is not listed so I could not use it even if I wanted to, but if anyone wants to include a explanation in their answer of when I should I would appreciate it.</p>
<p>(P.S. Do not worry about SQL injection from <code>createTempTableStatement</code> the strings being passed in are hard-coded resource strings with no user input.)</p>
<hr>
<p>With the suggestions from svick and some other tweaks I made while waiting for an answer here is the final version</p>
<pre><code>public async Task BulkLoadDataAsync(IDataReader reader,
string createTempTableStatement,
string loadingStoredProcedureName,
params SqlParameter[] args)
{
using (var connection = new SqlConnection(_connectionString))
using (var bulkCopy = new SqlBulkCopy(connection))
using (var command = new SqlCommand(createTempTableStatement))
{
Func<Task> firstStageFunc = async () =>
{
await connection.OpenAsync().ConfigureAwait(false);
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
};
var firstStage = firstStageFunc();
bulkCopy.DestinationTableName = "#temp";
var mappedReader = reader as IDataReaderWithMappings;
if (mappedReader != null)
{
var mappings = mappedReader.GetMappings();
foreach (var sqlBulkCopyColumnMapping in mappings)
{
bulkCopy.ColumnMappings.Add(sqlBulkCopyColumnMapping);
}
}
//Wait for the connection opening and the create table task to finish.
await firstStage.ConfigureAwait(false);
var bulkCopyTask = bulkCopy.WriteToServerAsync(reader);
command.CommandType = CommandType.StoredProcedure;
command.CommandText = loadingStoredProcedureName;
if (args != null)
command.Parameters.AddRange(args);
//Wait for the bulk copy to finish.
await bulkCopyTask.ConfigureAwait(false);
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
</code></pre>
| [] | [
{
"body": "<p>If you want to combine <code>ContinueWith()</code> and <code>async</code> this way, then you <strong>need</strong> to use <code>Unwrap()</code>. (And it <em>is</em> available, though my ReSharper doesn't seem to think so, maybe you use that too?) If you don't do that, you're not actually waiting for <code>ExecuteNonQueryAsync()</code> to complete.</p>\n\n<p>But using <code>ContinueWith()</code> is usually not a good idea when you can use <code>await</code>. Instead, you can use a helper method:</p>\n\n<pre><code>private static async Task FirstStageAsync(SqlConnection connection, SqlCommand command)\n{\n await connection.OpenAsync().ConfigureAwait(false);\n await command.ExecuteNonQueryAsync().ConfigureAwait(false);\n}\n</code></pre>\n\n<p>And then in the main method:</p>\n\n<pre><code>var firstStage = FirstStageAsync(connection, command);\n\n…\n\n//Wait for the connection opening and the create table task to finish.\nawait firstStage.ConfigureAwait(false);\n</code></pre>\n\n<p>Another option would be use a lambda instead of the helper method:</p>\n\n<pre><code>Func<Task> firstStageFunc = async () =>\n{\n await connection.OpenAsync().ConfigureAwait(false);\n await command.ExecuteNonQueryAsync().ConfigureAwait(false);\n};\n\nvar firstStage = firstStageFunc();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:49:14.063",
"Id": "77384",
"Score": "0",
"body": "I do use resharper, and actually I ended up re-writing the code to use a helper method anyway since I asked the question because I thought it looked \"cleaner\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T13:21:55.970",
"Id": "44569",
"ParentId": "44547",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44569",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T04:55:41.173",
"Id": "44547",
"Score": "9",
"Tags": [
"c#",
"asynchronous",
"task-parallel-library",
"async-await"
],
"Title": "Writing highly asynchronous code"
} | 44547 |
<p>I find sometimes it is useful to capture the notion of invertible functions.</p>
<p>The idea is that if two functions <code>f :: a -> b</code> and <code>g :: b -> a</code> are the inverse function of each other, and if there is another function <code>h :: b -> b</code>, then <code>h</code> can also work on values of type <code>a</code>.</p>
<p>Moreover, if there <code>f'</code> and <code>g'</code> are another pair of functions that are the inverse function of each other, <code>(f,g)</code> and <code>(f',g')</code> can actually be composed to <code>(f' . f, g . g')</code> and the invertibility still holds.</p>
<p>The following is my attempt to implement this in Haskell, and I'm wondering if an existing library can do the same thing (or even more general thing) for me.
Also advice and comments about my code are appreciated.</p>
<h1>Implementation</h1>
<p>First I use records to store two functions:</p>
<pre><code>data Invertible a b = Invertible
{ into :: a -> b
, back :: b -> a
}
</code></pre>
<p><code>into</code> means "convert a into b" while <code>back</code> means "convert b back to a".</p>
<p>And then few helper functions:</p>
<pre><code>selfInv :: (a -> a) -> Invertible a a
selfInv f = Invertible f f
flipInv :: Invertible a b -> Invertible b a
flipInv (Invertible f g) = Invertible g f
borrow :: Invertible a b -> (b -> b) -> a -> a
borrow (Invertible fIn fOut) g = fOut . g . fIn
liftInv :: (Functor f) => Invertible a b -> Invertible (f a) (f b)
liftInv (Invertible a b) = Invertible (fmap a) (fmap b)
</code></pre>
<p>In the above code <code>borrow</code> will use the pair of functions to make its last argument <code>g</code>
available to values of type <code>a</code>. And changing <code>borrow f</code> to <code>borrow (flipInv f)</code> will make <code>g</code> available to values of type <code>b</code>. Therefore <code>borrow</code> captures my initial idea of making a function of type <code>b -> b</code> available for values of <code>a</code> if <code>a</code> and <code>b</code> can be converted to each other.</p>
<p>In addition, <code>Invertible</code> forms a monoid-like structure, I use <code>rappend</code> and <code>rempty</code> to suggest a similiarity between it and <code>Monoid</code>:</p>
<pre><code>rempty :: Invertible a a
rempty = selfInv id
rappend :: Invertible a b
-> Invertible b c
-> Invertible a c
(Invertible f1 g1) `rappend` (Invertible f2 g2) =
Invertible (f2 . f1) (g1 . g2)
</code></pre>
<h1>Examples</h1>
<p>Here I have two examples to demonstrate that <code>Invertible</code> might be useful.</p>
<h2>Data Encryption</h2>
<p>It is natural that <code>Invertible</code> can be used under scenario of symmetric encryption. <code>Invertible (encrypt key) (decrypt key)</code> might be one instance if:</p>
<pre><code>encrypt :: Key -> PlainText -> CipherText
decrypt :: Key -> CipherText -> PlainText
</code></pre>
<p>To simplify a little, I make an example of <a href="https://en.wikipedia.org/wiki/Caesar_Cipher">Caesar cipher</a> and assume that plain text contains only uppercase letters:</p>
<pre><code>-- constructor should be invisible from outside
newtype OnlyUpper a = OnlyUpper
{ getOU :: [a]
} deriving (Eq, Ord, Show, Functor)
ouAsList :: Invertible (OnlyUpper a) [a]
ouAsList = Invertible getOU OnlyUpper
onlyUpper :: String -> OnlyUpper Char
onlyUpper = OnlyUpper . filter isAsciiUpper
upperAsOrd :: Invertible Char Int
upperAsOrd = Invertible ord' chr'
where
ord' x = ord x - ord 'A'
chr' x = chr (x + ord 'A')
</code></pre>
<p>And Caesar Cipher is basically doing some modular arithmetic:</p>
<pre><code>modShift :: Int -> Int -> Invertible Int Int
modShift base offset = Invertible f g
where
f x = (x + offset) `mod` base
g y = (y + (base - offset)) `mod` base
caesarShift :: Invertible Int Int
caesarShift = modShift 26 4
caesarCipher :: Invertible (OnlyUpper Char) (OnlyUpper Char)
caesarCipher = liftInv (upperAsOrd
-- Char <-> Int
`rappend` caesarShift
-- Int <-> Int
`rappend` flipInv upperAsOrd)
-- Int <-> Char
</code></pre>
<p>One way to use <code>Invertible</code> is just using its <code>into</code> and <code>back</code> as <code>encrypt</code> and <code>decrypt</code>, and <code>Invertible</code> also gives you the power of manipulating encrypyed data as if it was plain text:</p>
<pre><code>exampleCaesar :: IO ()
exampleCaesar = do
let encF = into caesarCipher
decF = back caesarCipher
encrypted = encF (onlyUpper "THEQUICKBROWNFOX")
decrypted = decF encrypted
encrypted' = borrow (flipInv caesarCipher
`rappend` ouAsList) (++ "JUMPSOVERTHELAZYDOG") encrypted
decrypted' = decF encrypted'
print encrypted
-- OnlyUpper {getOU = "XLIUYMGOFVSARJSB"}
print decrypted
-- OnlyUpper {getOU = "THEQUICKBROWNFOX"}
print encrypted'
-- OnlyUpper {getOU = "XLIUYMGOFVSARJSBNYQTWSZIVXLIPEDCHSK"}
print decrypted'
-- OnlyUpper {getOU = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"}
</code></pre>
<h2>Matrix manipulation</h2>
<p>Sometimes it's convenient to write some code that manipulates matrices using <code>Invertible</code>.</p>
<p>Say there is a list of type <code>[Int]</code> in which <code>0</code> stands for an empty cell, and we want every non-zero element move to their leftmost possible position while preserving the order:</p>
<pre><code>compactLeft :: [Int] -> [Int]
compactLeft xs = nonZeros ++ replicate (((-) `on` length) xs nonZeros) 0
where nonZeros = filter (/= 0) xs
</code></pre>
<p>Now consider 2D matrices, we want to "gravitize" the matrix so that every non-zero element in it falls to {left,right,up,down}-most possible position while preserving the order.</p>
<pre><code>data Dir = DU | DD | DL | DR deriving (Eq, Ord, Enum, Show, Bounded)
gravitizeMat :: Dir -> [[Int]] -> [[Int]]
gravitizeMat dir = borrow invertible (map compactLeft)
where mirrorI = selfInv (map reverse)
diagonalI = selfInv transpose
invertible = case dir of
DL -> rempty
DR -> mirrorI
DU -> diagonalI
DD -> diagonalI `rappend` mirrorI
</code></pre>
<p>here <code>Invertible</code> comes into play by the observation that <code>transpose</code> and <code>map reverse</code> are all invertible (moreover, they are inverse functions of themselves).
So that we can transform matrices and pretend the problem is only "gravitize to the left".</p>
<p>Here is one example:</p>
<pre><code>print2DMat :: (Show a) => [[a]] -> IO ()
print2DMat mat = do
putStrLn "Matrix: ["
mapM_ print mat
putStrLn "]"
exampleMatGravitize :: IO ()
exampleMatGravitize = do
let mat = [ [1,0,2,0]
, [0,3,4,0]
, [0,0,0,5]
]
print2DMat mat
let showExample d = do
putStrLn $ "Direction: " ++ show d
print2DMat $ gravitizeMat d mat
mapM_ showExample [minBound .. maxBound]
</code></pre>
<p>And the result will be:</p>
<pre><code>Matrix: [
[1,0,2,0]
[0,3,4,0]
[0,0,0,5]
]
Direction: DU
Matrix: [
[1,3,2,5]
[0,0,4,0]
[0,0,0,0]
]
Direction: DD
Matrix: [
[0,0,0,0]
[0,0,2,0]
[1,3,4,5]
]
Direction: DL
Matrix: [
[1,2,0,0]
[3,4,0,0]
[5,0,0,0]
]
Direction: DR
Matrix: [
[0,0,1,2]
[0,0,3,4]
[0,0,0,5]
]
</code></pre>
<h1>Complete code</h1>
<p>Since code review's policy requires complete code (you can also find it from my <a href="https://gist.github.com/Javran/9593215">gist</a>):</p>
<pre><code>{-# LANGUAGE DeriveFunctor #-}
import Data.Char
import Data.Function
import Data.List
data Invertible a b = Invertible
{ into :: a -> b
, back :: b -> a
}
selfInv :: (a -> a) -> Invertible a a
selfInv f = Invertible f f
rempty :: Invertible a a
rempty = selfInv id
rappend :: Invertible a b
-> Invertible b c
-> Invertible a c
(Invertible f1 g1) `rappend` (Invertible f2 g2) =
Invertible (f2 . f1) (g1 . g2)
flipInv :: Invertible a b -> Invertible b a
flipInv (Invertible f g) = Invertible g f
borrow :: Invertible a b -> (b -> b) -> a -> a
borrow (Invertible fIn fOut) g = fOut . g . fIn
liftInv :: (Functor f) => Invertible a b -> Invertible (f a) (f b)
liftInv (Invertible a b) = Invertible (fmap a) (fmap b)
-- examples
-- constructor should be invisible from outside
newtype OnlyUpper a = OnlyUpper
{ getOU :: [a]
} deriving (Eq, Ord, Show, Functor)
ouAsList :: Invertible (OnlyUpper a) [a]
ouAsList = Invertible getOU OnlyUpper
onlyUpper :: String -> OnlyUpper Char
onlyUpper = OnlyUpper . filter isAsciiUpper
upperAsOrd :: Invertible Char Int
upperAsOrd = Invertible ord' chr'
where
ord' x = ord x - ord 'A'
chr' x = chr (x + ord 'A')
modShift :: Int -> Int -> Invertible Int Int
modShift base offset = Invertible f g
where
f x = (x + offset) `mod` base
g y = (y + (base - offset)) `mod` base
caesarShift :: Invertible Int Int
caesarShift = modShift 26 4
caesarCipher :: Invertible (OnlyUpper Char) (OnlyUpper Char)
caesarCipher = liftInv (upperAsOrd
-- Char <-> Int
`rappend` caesarShift
-- Int <-> Int
`rappend` flipInv upperAsOrd)
-- Int <-> Char
exampleCaesar :: IO ()
exampleCaesar = do
let encF = into caesarCipher
decF = back caesarCipher
encrypted = encF (onlyUpper "THEQUICKBROWNFOX")
decrypted = decF encrypted
encrypted' = borrow (flipInv caesarCipher
`rappend` ouAsList) (++ "JUMPSOVERTHELAZYDOG") encrypted
decrypted' = decF encrypted'
print encrypted
-- OnlyUpper {getOU = "XLIUYMGOFVSARJSB"}
print decrypted
-- OnlyUpper {getOU = "THEQUICKBROWNFOX"}
print encrypted'
-- OnlyUpper {getOU = "XLIUYMGOFVSARJSBNYQTWSZIVXLIPEDCHSK"}
print decrypted'
-- OnlyUpper {getOU = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"}
-- gravitize
compactLeft :: [Int] -> [Int]
compactLeft xs = nonZeros ++ replicate (((-) `on` length) xs nonZeros) 0
where nonZeros = filter (/= 0) xs
data Dir = DU | DD | DL | DR deriving (Eq, Ord, Enum, Show, Bounded)
gravitizeMat :: Dir -> [[Int]] -> [[Int]]
gravitizeMat dir = borrow invertible (map compactLeft)
where mirrorI = selfInv (map reverse)
diagonalI = selfInv transpose
invertible = case dir of
DL -> rempty
DR -> mirrorI
DU -> diagonalI
DD -> diagonalI `rappend` mirrorI
print2DMat :: (Show a) => [[a]] -> IO ()
print2DMat mat = do
putStrLn "Matrix: ["
mapM_ print mat
putStrLn "]"
exampleMatGravitize :: IO ()
exampleMatGravitize = do
let mat = [ [1,0,2,0]
, [0,3,4,0]
, [0,0,0,5]
]
print2DMat mat
let showExample d = do
putStrLn $ "Direction: " ++ show d
print2DMat $ gravitizeMat d mat
mapM_ showExample [minBound .. maxBound]
main :: IO ()
main = do
exampleCaesar
exampleMatGravitize
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T08:49:16.403",
"Id": "77321",
"Score": "11",
"body": "By no means I claim that they theoretically fit here, but somehow, I suspect that by using [lens isomorphisms](http://hackage.haskell.org/package/lens-4.0.7/docs/Control-Lens-Iso.html), you may be able to abstract much of what you are trying to do here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T01:55:52.557",
"Id": "77988",
"Score": "2",
"body": "`rempty` and `rappend` form a `Category` instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T14:31:57.010",
"Id": "78752",
"Score": "3",
"body": "http://hackage.haskell.org/package/TypeCompose-0.6.4/docs/Data-Bijection.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-05T23:10:24.503",
"Id": "118684",
"Score": "0",
"body": "The 4th revision of your [gist](https://gist.github.com/codecurve/cddfcdc03bf25d319c15/8d51a5bd30b14e550e120fa84410a908b5bf07e5) illustrates using lens isomorphisms as per the suggestion from @DannyNavarro. I'd suggest posting that as the answer. In combination with your original code, both show a good way of working with a pair of invertible functions. Your original code is nice because it is self contained, and then after that, the lens code is easier to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-06T16:48:35.017",
"Id": "118889",
"Score": "0",
"body": "@figmentum thanks for the suggestion, will do it this week."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-17T02:25:42.357",
"Id": "121994",
"Score": "1",
"body": "Not sufficient for an answer, but in `modShift`, `g` can be simplified to ``g y = (y - offset) `mod` base``."
}
] | [
{
"body": "<p><strong>Naming:</strong></p>\n<p>There are a lot of names I'd change. Some of them matter more than others (local names in a let are not that big a deal even if they're terrible, but a name for a widely used function should be suggestive, if possible). Some of them I'm more sure of than others.</p>\n<p>I'd change <code>borrow</code> to <code>within</code>. The old name isn't bad, but I think the new one is suggestive in the right way. I'd change <code>Invertible</code> to <code>Transform</code>, since an invertible function is just the one function, and we're talking about a pair of related functions. <code>Bijection</code> is the mathematical name for it, and it would make a good name too, but it seems (to me at least) to suggest that the domain and range are the entire input and output types, and not every function we'd want to use with this fits that.</p>\n<p>I'd change the local <code>invertible</code> to <code>transform</code> to match, so <code>borrow invertible (map compactLeft)</code> becomes <code>within transform (map compactLeft)</code>.</p>\n<p>I'd change <code>mirrorI</code> -> <code>mirror</code> and <code>diagonalI</code> -> <code>diagonal</code>; the I doesn't add anything, it just looks as if you're using roman numerals at first. I'd also change <code>DD, DL, DR, DU -> DOWN, LEFT, RIGHT, UP</code>, as it's just clearer.</p>\n<p>The <code>Inv</code> suffix doesn't help. Not all of the functions have it, and it isn't spelled out enough to be suggestive. Also, if we change it from <code>Invertible</code>, it no longer makes sense. So, <code>selfInv</code> -> <code>involution</code>, <code>liftInv</code> -> <code>lift</code>, <code>flipInv</code> -> <code>backwards</code>. An <code>involution</code> is the mathematical name for a function that is its own inverse (and if you didn't know that, don't feel bad, I was only guessing there <em>might</em> be a name for it until I googled it). <code>flip</code> is already taken, and I think <code>backwards</code> is more suggestive (<code>reverse</code> would have been nice too, but it's also taken). <code>lift</code> isn't taken as far as I know, but it's the sort of thing that seems like it might be. If so, <code>liftT</code> or <code>liftTr</code> might work (or <code>liftB</code> if we're using <code>Bijection</code>).</p>\n<p>I'd change <code>fIn</code>, <code>fOut</code> -> <code>f</code>, <code>f'</code>. Using <code>f'</code> doesn't quite say "I'm an inverse", but it suggests it somewhat if we know how <code>Transform</code> is defined/meant to be used.</p>\n<p>I can see why you named <code>rempty</code> and <code>rappend</code> as you did, but the names made me (and would probably make other people) want to try to make it a Monoid instance, and that doesn't work. I'd change <code>rempty</code> -> <code>idT</code>, <code>rappend</code> -> <code>>>></code>. <code>>>></code> matches the <code>Category</code> class, and is nicely intuitive (and doesn't need backquotes). I'm not really sure about <code>idT</code>, and it could probably be improved, but it still seems a bit nicer than <code>rempty</code> to me.</p>\n<p>I'd also change <code>into</code>, <code>back</code> -> <code>fwd</code>, <code>rev</code>, but I don't have much justification here. It seems a little more suggestive of a thing that can go both ways, instead of a box that you can go into and come out of, but can't be flipped inside out. The original names here are good.</p>\n<p><strong>All Namechanges in One Spot:</strong></p>\n<blockquote>\n<p>DD, DL, DR, DU -> DOWN, LEFT, RIGHT, UP</p>\n<p>Invertible -> Transform</p>\n<p>invertible -> transform</p>\n<p>mirrorI -> mirror</p>\n<p>diagonalI -> diagonal</p>\n<p>selfInv -> involution</p>\n<p>liftInv -> lift</p>\n<p>flipInv -> backwards</p>\n<p>into, back -> fwd, rev</p>\n<p>fIn, fOut -> f, f'</p>\n<p>rempty -> idT</p>\n<p>rappend -> >>></p>\n</blockquote>\n<p><strong>Instances that don't work:</strong></p>\n<p>Monad, Applicative, and Functor don't work because <code>fmap :: (a -> b) -> f a -> f b</code> and that doesn't fit.</p>\n<p>Monoid doesn't work because <code>mappend :: a -> a -> a</code>, and our composition takes 2 different types and returns yet another different type.</p>\n<p>Arrow seems like it should work at first, but <code>arr :: (b -> c) -> a b c</code>. The types match nicely, but we'd need a way that makes sense to take an arbitrary function and find its inverse. Functions and Arrows go one way, but we want to go both ways.</p>\n<p>Category fits perfectly, but when I tried to get it to work, the compiler complained about all the uses of <code>.</code> in the program being ambiguous. There may be a way to make it work, but looking at <a href=\"http://hackage.haskell.org/package/base-4.7.0.1/docs/Control-Category.html\" rel=\"noreferrer\">Control.Category</a>, the gains were almost nonexistent, so I abandoned the attempt. The interface (<code>>>></code> and <code><<<</code> for forward and backward composition), was nice, though, so I kept it.</p>\n<p><strong>Instances that do work:</strong></p>\n<p>None?</p>\n<p><strong>Non-Naming Changes:</strong></p>\n<p>The suggestion in the comments by mjolka is correct, and the resulting code:</p>\n<pre><code>modShift base offset = Transform f g\n where\n f x = (x + offset) `mod` base\n g y = (y - offset) `mod` base\n</code></pre>\n<p>looks nicer and is clearer.</p>\n<p>This:</p>\n<pre><code>compactLeft xs = nonZeros ++ replicate (((-) `on` length) xs nonZeros) 0\n where nonZeros = filter (/= 0) xs\n</code></pre>\n<p>is a bit ugly, and can be simplified to this:</p>\n<pre><code>compactLeft xs = take (length xs) $ nonZeros ++ repeat 0\n where nonZeros = filter (/= 0) xs\n</code></pre>\n<p>I'd introduce a new function that abstracts the pattern in the parentheses in</p>\n<pre><code>caesarCipher = liftInv (upperAsOrd\n -- Char <-> Int\n `rappend` caesarShift\n -- Int <-> Int\n `rappend` flipInv upperAsOrd)\n -- Int <-> Char\n</code></pre>\n<p>making my suggested namechanges, it becomes:</p>\n<pre><code>caesarCipher = lift (upperAsOrd >>> caesarShift >>> backwards upperAsOrd)\n</code></pre>\n<p>and the new function I'd suggest is:</p>\n<pre><code>nest :: Transform a b -> Transform b b -> Transform a a\nnest ab bb = backwards ab <<< bb <<< ab\n</code></pre>\n<p>The reason I'm using <code><<<</code> is that it composes in the same order as <code>.</code>, and this way, the <code>nest</code> function looks very similar to <code>within</code> (the function formerly known as <code>borrow</code>), which its type signature strongly resembles.</p>\n<p>Here they (both) are, with type signatures:</p>\n<pre><code>within :: Transform a b -> (b -> b) -> a -> a\nwithin (Transform f f') g = f' . g . f\n\nnest :: Transform a b -> Transform b b -> Transform a a\nnest ab bb = backwards ab <<< bb <<< ab\n</code></pre>\n<p>I can't be sure, based on only one example, that this will end up commonly used, but it would make some sense if it did, based on the fact that it showed up once in a small set of examples and on the type signature resemblance. Also, <code>nest</code> may not be the best possible name, but it seems reasonable to me, and I haven't been able to think of a better one.</p>\n<p>Using <code>nest</code>, we can rewrite <code>caesarCipher</code> to be even shorter:</p>\n<pre><code>caesarCipher = lift $ nest upperAsOrd caesarShift\n</code></pre>\n<p>We also used <code>$</code> to avoid having to wrap parentheses around the <code>nest</code>.</p>\n<p><code>gravitizeMat</code> doesn't change, except for namechanges, but it is more readable.</p>\n<p>Before:</p>\n<pre><code>data Dir = DU | DD | DL | DR deriving (Eq, Ord, Enum, Show, Bounded)\ngravitizeMat :: Dir -> [[Int]] -> [[Int]]\ngravitizeMat dir = borrow invertible (map compactLeft)\n where mirrorI = selfInv (map reverse)\n diagonalI = selfInv transpose\n invertible = case dir of\n DL -> rempty\n DR -> mirrorI\n DU -> diagonalI\n DD -> diagonalI `rappend` mirrorI\n</code></pre>\n<p>After:</p>\n<pre><code>data Dir = UP | DOWN | LEFT | RIGHT deriving (Eq, Ord, Enum, Show, Bounded)\ngravitizeMat :: Dir -> [[Int]] -> [[Int]]\ngravitizeMat dir = within transform (map compactLeft)\n where mirror = involution (map reverse)\n diagonal = involution transpose\n transform = case dir of\n LEFT -> idT\n RIGHT -> mirror\n UP -> diagonal\n DOWN -> diagonal >>> mirror\n</code></pre>\n<p><code>exampleCaesar</code> doesn't change much, but this part looks nicer.</p>\n<p>Before:</p>\n<pre><code> encrypted' = borrow (flipInv caesarCipher\n `rappend` ouAsList) (++ "JUMPSOVERTHELAZYDOG") encrypted\n</code></pre>\n<p>After:</p>\n<pre><code> encrypted' = within (backwards caesarCipher >>> ouAsList)\n (++ "JUMPSOVERTHELAZYDOG") encrypted\n</code></pre>\n<p>Here I think the suggestion for <code>backwards</code> really shines, since the forward direction of <code>caesarCipher</code> is encryption and the reverse direction is decryption, but here, we're trying to mess with the plaintext of an encryptedtext, which is using it backwards.</p>\n<p><strong>Overall:</strong></p>\n<p>It was nice code. There were several names that could be made more suggestive, and a couple of places where complex expressions could be simplified, but overall, it was pleasant to read, and an interesting idea as well.</p>\n<p><strong>Complete Modified Code:</strong></p>\n<pre><code>{-# LANGUAGE DeriveFunctor #-}\nimport Data.Char\nimport Data.Function\nimport Data.List\n\ndata Transform a b = Transform\n { fwd :: a -> b\n , rev :: b -> a\n }\n\ninvolution :: (a -> a) -> Transform a a\ninvolution f = Transform f f\n\nidT :: Transform a a\nidT = involution id\n\n(>>>) :: Transform a b -> Transform b c -> Transform a c\n(Transform f1 g1) >>> (Transform f2 g2) =\n Transform (f2 . f1) (g1 . g2)\n\n(<<<) :: Transform b c -> Transform a b -> Transform a c\nf <<< g = g >>> f\n\nbackwards :: Transform a b -> Transform b a\nbackwards (Transform f g) = Transform g f\n\nwithin :: Transform a b -> (b -> b) -> a -> a\nwithin (Transform f f') g = f' . g . f\n\nnest :: Transform a b -> Transform b b -> Transform a a\nnest ab bb = backwards ab <<< bb <<< ab\n\nlift :: (Functor f) => Transform a b -> Transform (f a) (f b)\nlift (Transform f g) = Transform (fmap f) (fmap g)\n\n-- examples\n-- constructor should be invisible from outside\nnewtype OnlyUpper a = OnlyUpper\n { getOU :: [a]\n } deriving (Eq, Ord, Show, Functor)\n\nouAsList :: Transform (OnlyUpper a) [a]\nouAsList = Transform getOU OnlyUpper\n\nonlyUpper :: String -> OnlyUpper Char\nonlyUpper = OnlyUpper . filter isAsciiUpper\n\nupperAsOrd :: Transform Char Int\nupperAsOrd = Transform ord' chr'\n where\n ord' x = ord x - ord 'A'\n chr' x = chr (x + ord 'A')\n\nmodShift :: Int -> Int -> Transform Int Int\nmodShift base offset = Transform f g\n where\n f x = (x + offset) `mod` base\n g y = (y - offset) `mod` base\n\ncaesarShift :: Transform Int Int\ncaesarShift = modShift 26 4\n\ncaesarCipher :: Transform (OnlyUpper Char) (OnlyUpper Char)\ncaesarCipher = lift $ nest upperAsOrd caesarShift\n\nexampleCaesar :: IO ()\nexampleCaesar = do\n let encF = fwd caesarCipher\n decF = rev caesarCipher\n encrypted = encF (onlyUpper "THEQUICKBROWNFOX")\n decrypted = decF encrypted\n encrypted' = within (backwards caesarCipher >>> ouAsList)\n (++ "JUMPSOVERTHELAZYDOG") encrypted\n decrypted' = decF encrypted'\n\n print encrypted\n -- OnlyUpper {getOU = "XLIUYMGOFVSARJSB"}\n print decrypted\n -- OnlyUpper {getOU = "THEQUICKBROWNFOX"}\n\n print encrypted'\n -- OnlyUpper {getOU = "XLIUYMGOFVSARJSBNYQTWSZIVXLIPEDCHSK"}\n print decrypted'\n -- OnlyUpper {getOU = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"}\n\n\n-- gravitize\ncompactLeft :: [Int] -> [Int]\ncompactLeft xs = take (length xs) $ nonZeros ++ repeat 0\n where nonZeros = filter (/= 0) xs\n\ndata Dir = UP | DOWN | LEFT | RIGHT deriving (Eq, Ord, Enum, Show, Bounded)\n\ngravitizeMat :: Dir -> [[Int]] -> [[Int]]\ngravitizeMat dir = within transform (map compactLeft)\n where mirror = involution (map reverse)\n diagonal = involution transpose\n transform = case dir of\n LEFT -> idT\n RIGHT -> mirror\n UP -> diagonal\n DOWN -> diagonal >>> mirror\n\nprint2DMat :: (Show a) => [[a]] -> IO ()\nprint2DMat mat = do\n putStrLn "Matrix: ["\n mapM_ print mat\n putStrLn "]"\n\nexampleMatGravitize :: IO ()\nexampleMatGravitize = do\n let mat = [ [1,0,2,0]\n , [0,3,4,0]\n , [0,0,0,5]\n ]\n print2DMat mat\n\n let showExample d = do\n putStrLn $ "Direction: " ++ show d\n print2DMat $ gravitizeMat d mat\n\n mapM_ showExample [minBound .. maxBound]\n\nmain :: IO ()\nmain = do\n exampleCaesar\n exampleMatGravitize\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-18T08:45:13.343",
"Id": "67094",
"ParentId": "44550",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T07:11:05.360",
"Id": "44550",
"Score": "46",
"Tags": [
"haskell",
"matrix"
],
"Title": "Capture the notion of invertible functions"
} | 44550 |
<p>Here is my Code. But I feel that my code isn't really that much object oriented.</p>
<p>There is a small piece of "styling" in it as well, the "message error" thing at the end. </p>
<p>Should that be in my class or should it go somewhere else?</p>
<pre><code><?php
require 'contact.class.php';
?>
<form action="" method="post">
<?php
if (isset($_POST["submit"])) {
$sendMail = new gw2Mail();
$sendMail->senderName = $_POST['senderName'];
$sendMail->senderEmail = $_POST['senderEmail'];
$sendMail->recipient = $_POST['recipient'];
$sendMail->copy = $_POST['copy'];
$sendMail->subject = $_POST['subject'];
$sendMail->message = $_POST['message'];
$sendMail->sendMail();
}
?>
<table class='ipb_table ipsMemberList'>
<tr class='header' colspan='4'>
<th scope='col' colspan='5'>Send E-mail</th>
</tr>
<tr class='row1'>
<td style='width: 50%'><strong>From:</strong><br />Enter the sender's name in this field.</td>
<td><input type="text" class="input_text" name="senderName" id="senderName" value="<?php if (isset($_POST['senderName'])) { echo $_POST['senderName']; } ?>" size="50" maxlength="125" /></td>
</tr>
<tr class='row2'>
<td style='width: 50%'><strong>From E-mail:</strong><br />Enter the sender's e-mail address in this field.</td>
<td><input type="text" class="input_text" name="senderEmail" id="senderEmail" value="<?php if (isset($_POST['senderEmail'])) { echo $_POST['senderEmail']; } ?>" size="50" maxlength="125" /></td>
</tr>
<tr class='row1'>
<td style='width: 50%'><strong>Recipient:</strong><br />Enter the recipient's e-mail address in this field.</td>
<td><input type="text" class="input_text" name="recipient" id="recipient" value="<?php if (isset($_POST['recipient'])) { echo $_POST['recipient']; } ?>" size="50" maxlength="125" /></td>
</tr>
<tr class='row2'>
<td style='width: 50%'><strong>Carbon Copy:</strong><br />Send a copy to someone else? Enter another e-mail address here. Leave blank for no copy.</td>
<td><input type="text" class="input_text" name="copy" id="copy" value="<?php if (isset($_POST['copy'])) { echo $_POST['copy']; } ?>" size="50" maxlength="125" /></td>
</tr>
<tr class='row1'>
<td style='width: 50%'><strong>Subject:</strong><br />Enter a subject in this field.</td>
<td><input type="text" class="input_text" name="subject" id="subject" value="<?php if (isset($_POST['subject'])) { echo $_POST['subject']; } ?>" size="50" maxlength="50" /></td>
</tr>
<tr class='row2'>
<td colspan='2' style='width: 100%'><textarea style="height: 250px; width: 99%;" name="message" id="message" cols="30" rows="14" virtual wrap="on"><?php if (isset($_POST['message'])) { echo $_POST['message']; } ?></textarea></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit" tabindex="50" class="input_submit" accesskey="s" />
</form>
</code></pre>
<p>And this is the <code>contact.class.php</code>:</p>
<pre><code><?php
class gw2Mail {
var $senderName;
var $senderEmail;
var $recipient;
var $copy;
var $subject;
var $message;
var $bcc;
public function sendMail()
{
if ($this->senderName != "") {
$this->senderName = filter_var($this->senderName, FILTER_SANITIZE_STRING);
if ($this->senderName == "") {
$errors .= '- Please enter a valid name!';
}
} else {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->senderEmail != "") {
$this->senderEmail = filter_var($this->senderEmail, FILTER_SANITIZE_STRING);
if ($this->senderEmail == "") {
$errors .= '- Please enter a valid Email!';
}
} else {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->recipient != "") {
$this->recipient = filter_var($this->recipient, FILTER_SANITIZE_STRING);
if ($this->recipient == "") {
$errors .= '- Please enter a valid recipient email!';
}
} else {
$errors .= '- You forgot to enter a recipient email!<br />';
}
if ($this->subject != "") {
$this->subject = filter_var($this->subject, FILTER_SANITIZE_STRING);
if ($this->subject == "") {
$errors .= '- Please enter a valid subject!';
}
} else {
$errors .= '- You forgot to enter a subject!<br />';
}
if ($this->message != "") {
$this->message = filter_var($this->message, FILTER_SANITIZE_STRING);
if ($this->message == "") {
$errors .= '- Please enter a valid message!';
}
} else {
$errors .= '- You forgot to enter a message!<br />';
}
if (!$errors) {
$this->bcc="";
$headers = "From: $this->senderName <$this->senderEmail>";
$headers .= "\r\nCc: $this->copy";
$headers .= "\r\nBcc: $this->bcc\r\n\r\n";
$send_contact=mail("$this->recipient","$this->subject","$this->message","$headers");
} else {
echo '<p class=\'message error\'>';
echo '<font color="#FFFFFF">' . $errors . '</font>';
echo '</p><br />';
}
}
}
?>
</code></pre>
| [] | [
{
"body": "<p>Here are some observations noticed:</p>\n\n<p>For something to be OOP it needs to be somewhat reusable. As always use SOLID principles to achieve this.</p>\n\n<p>Because you are using styling it broke some of the rules. Consider returning outputs such as errors and such to be pure text without styling and let the return handle it. Reason: what happens if you want to log the fail message and shoot it out internally or to a log file.</p>\n\n<p>Your sendmail is a jack of all trade: it does the header, store the emails, AND checks for errors - this is procedural (start, middle end) - consider separating it into different functions of class (your original one and then have a separate class to do validations which you send as arguments).</p>\n\n<p>Consider using a constructor. You initialize the object with settings and then reuse the function. </p>\n\n<p>Another point to add: attributes (or variables from a class that pertains to the class) should never be never accessible to the \"main\" or elsewhere but to the class itself. Use accessor functions like get/set or magic functions <code>_get</code> <code>_set</code> instead. Classes are suppose to be encapsulated so that outside code cannot effected without going through a checker. I'm aware that its easier to just access it directly but you defeat the purpose of OOP in that sense.</p>\n\n<p>Lastly, too many if/else renders the code too tight which is why I suggested the validation class - let that be the class to check on the arguments rather than the mailer itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T13:13:51.183",
"Id": "44568",
"ParentId": "44551",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>The <a href=\"http://hu1.php.net/manual/en/function.mail.php\" rel=\"nofollow noreferrer\">result</a> is unused here:</p>\n\n<blockquote>\n<pre><code>$send_contact=mail(\"$this->recipient\",\"$this->subject\",\"$this->message\",\"$headers\");\n</code></pre>\n</blockquote>\n\n<p><code>mail</code> returns <code>TRUE</code> if the mail was successfully accepted for delivery and <code>FALSE</code> otherwise. You could show that to the user.</p></li>\n<li><blockquote>\n<pre><code>$sendMail->senderName = $_POST['senderName'];\n$sendMail->senderEmail = $_POST['senderEmail'];\n$sendMail->recipient = $_POST['recipient'];\n$sendMail->copy = $_POST['copy'];\n$sendMail->subject = $_POST['subject'];\n$sendMail->message = $_POST['message'];\n</code></pre>\n</blockquote>\n\n<p>I've found this kind of indentation hard to maintain. If you have a new variable with a longer name you have to modify several other lines too to keep it nice. It could also cause unnecessary patch/merge conflicts.</p></li>\n<li><blockquote>\n<pre><code>$errors .= '- Please enter a valid name!';\n</code></pre>\n</blockquote>\n\n<p>How does a valid name look like? Help users with detailed error messages.</p></li>\n<li><blockquote>\n<pre><code>$errors .= '- You forgot to enter an email!<br />';\n</code></pre>\n</blockquote>\n\n<p>Error messages shouldn't blame the user (don't say what he did is wrong), give a suggestion about what they should do. (See: <a href=\"https://ux.stackexchange.com/q/48256/14623\">Should we avoid negative words when writing error messages?</a>, <a href=\"https://ux.stackexchange.com/q/8112/14623\">What will be the Best notifications and error messages?</a>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:35:10.040",
"Id": "77348",
"Score": "0",
"body": "I think we also miss one more thing about oop - that his attributes are set to public when it should be private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:45:51.640",
"Id": "77350",
"Score": "0",
"body": "@azngunit81: Yes, I guess you're right, feel free to edit your answer. I'm not too familar with OOP in PHP so it was just a few notes about the code. (According to the [help center](http://codereview.stackexchange.com/help/on-topic), reviewers may comment on any part of the code.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:48:51.783",
"Id": "77352",
"Score": "0",
"body": "OOP is general subject let it be C++(where i learned it from) to java and php (there is even OOP in javascript imagine that)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:20:49.337",
"Id": "44576",
"ParentId": "44551",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44568",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-17T07:56:29.893",
"Id": "44551",
"Score": "7",
"Tags": [
"php",
"object-oriented"
],
"Title": "OOP simple contact form"
} | 44551 |
<p>I needed to write a small program to convert floats from any base to any other base. The thing is, it got big. I know there are other ways to implement the conversions (such as doing subtractions instead of divisions), but isn't there a more simple way to do the whole process? I feel like I'm missing something. Any optimization tips are welcome as well.</p>
<pre><code>import string
symbols = string.digits + string.uppercase
def _int_from_base(number, original_base):
return int(number, original_base)
def _int_to_base(number, new_base):
# Uses "the division method"
sign = -1 if number < 0 else 1
number *= sign
ans = ''
while number:
ans += symbols[number % new_base]
number //= new_base
if sign == -1:
ans += '-'
return ans[::-1]
def _fractional_from_base(number, original_base):
# The value of a symbol at position i after the decimal point is, by
# definition, the value of that symbol * b^-i
ans = 0
for i in xrange(1, len(number)+1):
ans += symbols.index(number[i-1]) * original_base**-i
return ans
def _fractional_to_base(number, new_base, precision=5):
# I don't know what this method is called
ans = ''
for i in xrange(precision):
tmp = number * new_base
itmp = int(tmp)
ans += str(symbols[itmp])
number = tmp - itmp
return ans
def convert(number, original_base, new_base, precision=None):
"""Converts any number from any base to any other base (2 <= base <= 36).
number should be a string representing a float in any base, e.g. '1.23'.
original_base, new_base should be integers representing the desired bases.
precision should be an integer representing how many digits after the
decimal point will be calculated on the conversion. Default is the same
number as the number of digits after the decimal point on number.
"""
try:
integer_part, fractional_part = number.split('.')
precision = len(fractional_part) if precision is None else precision
integer_part = _int_to_base(
_int_from_base(integer_part, original_base),
new_base
)
fractional_part = _fractional_to_base(
_fractional_from_base(fractional_part, original_base),
new_base,
precision
)
return integer_part+'.'+fractional_part
except ValueError: # number was a str representing an int not a float
return _int_to_base(_int_from_base(number, original_base), new_base)
</code></pre>
<p>I didn't test it thoroughly but it seems to work. A few test cases:</p>
<pre><code>>>> a = convert('632.6442', 10, 2);a # Loss of info. is expected
'1001111000.1010'
>>> convert(a, 2, 10)
'632.6250'
>>> b = convert('222.0', 3, 16);b
'1A.0'
>>> convert(b, 16, 3)
'222.0'
</code></pre>
| [] | [
{
"body": "<p>It is not necessary to deal separately with the integral and fractional parts.</p>\n\n<ul>\n<li>When converting from string, remove the point, convert as integer and scale according to the position where the point was.</li>\n<li>When converting to string, scale to integer, convert and insert point in the right place.</li>\n</ul>\n\n<p>Here's how you can implement <code>convert</code> with <code>_int_to_base</code> as the only helper function:</p>\n\n<pre><code>def convert(number, original_base, new_base, precision=None):\n #from original_base\n integral, point, fractional = number.strip().partition('.')\n num = int(integral + fractional, original_base) * original_base ** -len(fractional)\n\n #to new_base\n precision = len(fractional) if precision is None else precision\n s = _int_to_base(int(round(num / new_base ** -precision)), new_base)\n if precision:\n return s[:-precision] + '.' + s[-precision:]\n else:\n return s\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T11:46:20.103",
"Id": "44562",
"ParentId": "44553",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44562",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T08:57:42.110",
"Id": "44553",
"Score": "4",
"Tags": [
"python",
"optimization",
"converting"
],
"Title": "Converting float from arbitrary base to arbitrary base"
} | 44553 |
<p><a href="https://codereview.stackexchange.com/questions/44361/form-controls-single-event-handler-for-multiple-controls-without-sacrifices">This question</a> I asked previously mentions a function named <code>BuildControlCollection</code>, which I didn't go into the details of since it wasn't relevant. However, because the implementation contains some funky code I'm not 100% on (it completely works, I'm just unsure if it's the best way to do it), I decided to put this up for review too.</p>
<pre><code>Public Sub BuildControlCollection(ByRef ipForm As Form,
ByRef mpCollection As Collection,
ByVal ipControlType As ControlTypes)
</code></pre>
<p>The function takes the form that we're building a control collection from, an unset collection object (which will be created and filled), and an enum value to indicate the type(s) of controls to fill the collection with.</p>
<pre><code>Enum ControlTypes
eTextBox = &H1
eComboBox = &H2
eLabel = &H4
eButton = &H8
eFrame = &H10
eRadioButton = &H20
eListBox = &H40
eLine = &H80
eRectangle = &H100
eCheckbox = &H200
eChart = &H400
eAll = &H800
End Enum
Public Sub BuildControlCollection(ByRef ipForm As Form, _
ByRef mpCollection As Collection, _
ByVal ipControlType As ControlTypes)
If Not mpCollection Is Nothing Then
Err.Raise 5000, "Collection has previously been set. This operation would delete the collection."
End If
Set mpCollection = New Collection
Dim lControl As Control
For Each lControl In ipForm.Controls
If ipControlType And eAll Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eButton) And TypeName(lControl) = "CommandButton" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eChart) And TypeName(lControl) = "ObjectFrame" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eCheckbox) And TypeName(lControl) = "CheckBox" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eComboBox) And TypeName(lControl) = "ComboBox" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eFrame) And TypeName(lControl) = "Frame" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eLabel) And TypeName(lControl) = "Label" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eLine) And TypeName(lControl) = "Line" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eListBox) And TypeName(lControl) = "ListBox" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eRadioButton) And TypeName(lControl) = "RadioButton" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eRectangle) And TypeName(lControl) = "Rectangle" Then
mpCollection.Add lControl
ElseIf (ipControlType And ControlTypes.eTextBox) And TypeName(lControl) = "TextBox" Then
mpCollection.Add lControl
End If
Next lControl
End Sub
</code></pre>
<p>The thinking behind the last argument of <code>BuildControlCollection</code> is to allow multiple options to be passed (eg <code>eTextBox Or eButton</code>) - I've seen this used in the built-in functions such as <code>MsgBox</code> - the second argument (somewhat inaccurately named <code>Buttons</code>) of which allows you to specify for eg <code>vbOKOnly Or vbExclamation</code> to get a messagebox with both an OK button and a warning triangle. I don't know what this is called, so I haven't been able to Google a real implementation, so I've had to make my best guess at it.</p>
<p>I understand that it works by comparing bits - for eg, <code>vbOKOnly</code> may be <code>0000 0001</code>, whilst <code>vbExclamation</code> may be <code>0001 0000</code>, so passing <code>vbOkOnly Or vbExclamation</code> (<code>0001 0001</code>) matches on both bits.</p>
<p>Whilst my implementation above definitely <em>works</em>, that enormous <code>If/ElseIf</code> smells funny. If anyone can tell me what the bit flagging thing used in <code>MsgBox</code> is called, that would be really useful too.</p>
| [] | [
{
"body": "<blockquote>\n <p><em>I don't know what this is called, so I haven't been able to Google a real implementation, so I've had to make my best guess at it. [...] If anyone can tell me what the bit <strong>flagging</strong> thing used in <code>MsgBox</code> is called, that would be really useful too.</em></p>\n</blockquote>\n\n<p>They're called <em>Flag enums</em> in .NET (<a href=\"https://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c\">see this SO question</a>), and <a href=\"https://stackoverflow.com/questions/4627492/flags-in-vb6-does-not-return-a-correct-value\">apparently the naming is also appropriate for VB6 enums</a>.</p>\n\n<hr>\n\n<p>That <code>If</code> block definitely smells, because all branches result in <code>lControl</code> being added to <code>mpCollection</code>. Hence, it's not really an <code>If...Else If</code> logic you need here, rather something like:</p>\n\n<pre><code>If CanAddThisControl(ipControlType, lControl) Then mpCollection.Add lControl\n</code></pre>\n\n<p>This effectively eliminates/replaces the entire <code>If</code> block, but leaves you with a <code>CanAddThisControl</code> method to implement. Let's see...</p>\n\n<pre><code>Private Function CanAddThisControl(ipControlType As ControlTypes, lControl As Control) As Boolean\n\n 'return true if the enum value matches the control's type\n\nEnd Function\n</code></pre>\n\n<p>This is where VB6/VBA's lack of structures really hurts. What you need is really some kind of <code>KeyValuePair</code> that associates an enum value with a control type. What if we created a class to do just that?</p>\n\n<pre><code>Private Type tKeyValuePair\n key As Variant\n value As Variant\nEnd Type\n\nPrivate this As tKeyValuePair\nOption Explicit\n\nPublic Property Get key() As Variant\n If IsObject(this.key) Then\n Set key = this.key\n Else\n key = this.key\n End If\nEnd Property\n\nPublic Property Let key(k As Variant)\n If IsEmpty(k) Then Err.Raise 5\n this.key = k\nEnd Property\n\nPublic Property Set key(k As Variant)\n If IsEmpty(k) Then Err.Raise 5\n Set this.key = k\nEnd Property\n\nPublic Property Get value() As Variant\n If IsObject(this.value) Then\n Set value = this.value\n Else\n value = this.value\n End If\nEnd Property\n\nPublic Property Let value(v As Variant)\n this.value = v\nEnd Property\n\nPublic Property Set value(v As Variant)\n Set this.value = v\nEnd Property\n\nPublic Function ToString() As String\n ToString = TypeName(Me) & \"<\" & TypeName(this.key) & \",\" & TypeName(this.value) & \">\"\nEnd Function\n</code></pre>\n\n<p><sub>(damn VB6 case insensitivity!)</sub></p>\n\n<p>So now we have a way of associating enum values with a string:</p>\n\n<pre><code>Private Function CreateKeyValuePair(key As ControlTypes, value As String) As KeyValuePair\n Dim result As New KeyValuePair\n result.key = key\n result.value = value\n Set CreateKeyValuePair = result\nEnd Function\n\nPrivate Function GetControlTypesAsKeyValuePairs As Collection\n Dim result As New Collection\n result.Add CreateKeyValuePair(ControlTypes.eButton, \"Button\")\n result.Add CreateKeyValuePair(ControlTypes.eChart, \"ObjectFrame\")\n result.Add CreateKeyValuePair(ControlTypes.eCheckBox, \"CheckBox\")\n result.Add CreateKeyValuePair(ControlTypes.eComboBox, \"ComboBox\")\n result.Add CreateKeyValuePair(ControlTypes.eFrame, \"Frame\")\n result.Add CreateKeyValuePair(ControlTypes.eLabel, \"Label\")\n result.Add CreateKeyValuePair(ControlTypes.eLine, \"Line\")\n result.Add CreateKeyValuePair(ControlTypes.eListBox, \"ListBox\")\n result.Add CreateKeyValuePair(ControlTypes.eRadioButton, \"RadioButton\")\n result.Add CreateKeyValuePair(ControlTypes.eRectangle, \"Rectangle\")\n result.Add CreateKeyValuePair(ControlTypes.eTextBox, \"TextBox\")\n Set GetControlTypesAsKeyValuePairs = result\nEnd Function\n</code></pre>\n\n<p>The above code could be simplified to a one-liner if you implemented a <code>List</code> to wrap the poorly tooled <code>Collection</code> class; see <a href=\"https://codereview.stackexchange.com/questions/32618/listt-implementation-for-vb6-vba\">this CR post</a>:</p>\n\n<blockquote>\n<pre><code> Private Function GetControlTypesAsKeyValuePairs() As List\n Dim result As New List\n result.Add CreateKeyValuePair(ControlTypes.eButton, \"Button\"), _\n CreateKeyValuePair(ControlTypes.eChart, \"ObjectFrame\"), _\n CreateKeyValuePair(ControlTypes.eCheckBox, \"CheckBox\"), _\n CreateKeyValuePair(ControlTypes.eComboBox, \"ComboBox\"), _\n CreateKeyValuePair(ControlTypes.eFrame, \"Frame\"), _\n CreateKeyValuePair(ControlTypes.eLabel, \"Label\"), _\n CreateKeyValuePair(ControlTypes.eLine, \"Line\"), _\n CreateKeyValuePair(ControlTypes.eListBox, \"ListBox\"), _\n CreateKeyValuePair(ControlTypes.eRadioButton, \"RadioButton\"), _\n CreateKeyValuePair(ControlTypes.eRectangle, \"Rectangle\"), _\n CreateKeyValuePair(ControlTypes.eTextBox, \"TextBox\")\n Set GetControlTypesAsKeyValuePairs = result\n End Function\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Now that we have a way of associating each enum value with a specific string, we're equipped to implement <code>CanAddThisControl</code> - I'll assume you went with a <code>Collection</code>, but the code would be pretty much identical if you used the <code>List</code> class I've mentioned above (just swap <code>Collection</code> for <code>List</code>):</p>\n\n<pre><code>Private Function CanAddThisControl(ipControlType As ControlTypes, lControl As Control) As Boolean\n\n Dim enums As Collection\n Set enums = GetControlTypesAsKeyValuePairs\n\n Dim kvp As KeyValuePair\n For Each kvp In enums\n If (ipControlType And kvp.Key) And TypeName(lControl) = kvp.Value Then\n CanAddThisControl = True\n Exit For\n End If\n Next\n\nEnd Function\n</code></pre>\n\n<p>This <em>should</em> enable you to make the loop in <code>BuildControlCollection</code> as simple as this:</p>\n\n<pre><code>For Each lControl In ipForm.Controls\n\n If (ipControlType And eAll) Or CanAddThisControl(lControl) Then\n mpCollection.Add lControl\n End If\n\nNext\n</code></pre>\n\n<hr>\n\n<p>Now this is a little inefficient, because <code>CanAddThisControl</code> is rebuilding the <code>KeyValuePair</code> collection every time it's called. But it's a fair start I think.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:15:55.547",
"Id": "77362",
"Score": "1",
"body": "Beautiful, thanks. `(damn VB6 case insensitivity!)` Also this in *spades*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:34:34.393",
"Id": "77363",
"Score": "0",
"body": "@Kai my pleasure! BTW welcome to 150, you're officially counted as an \"avid user\" now. [*Are you running?*](http://meta.codereview.stackexchange.com/questions/1628/the-race-has-started-are-you-running)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T15:27:05.560",
"Id": "44581",
"ParentId": "44555",
"Score": "5"
}
},
{
"body": "<p>I know we're <em>supposed</em> to use Hungarian notation in VBA, but it's useless with the modern IDE. Get rid of it unless you're working in VBScript. The only reason I say to bother with Hungarian notation in VBScript is because everything is a variant in that flavor of the language. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-02T01:39:52.280",
"Id": "52232",
"ParentId": "44555",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T09:21:03.930",
"Id": "44555",
"Score": "8",
"Tags": [
"vba",
"ms-access"
],
"Title": "Generating a collection of controls"
} | 44555 |
<p>I have to create some APIs for a online game and I decided to learn to use namespaces correctly.</p>
<p>I used the factory pattern, then the <code>loadModule</code> method checks if in the Modules folder there is a class named $module and then it return the object.
The folders are synchronized with the namespaces.</p>
<p><strong>The main class <code>Metin2.class.php</code></strong>:</p>
<pre><code><?php
namespace Metin2;
use mysqli;
use \Metin2\Utilities as Utilities;
require_once("config.php");
require_once(UTILITIES_PATH . "Autoloader.class.php");
class Metin2
{
public $db;
public function __construct(mysqli $database)
{
spl_autoload_register("Metin2\\Utilities\\Autoloader::loadModel");
try {
if(!$database) throw new Exceptions\Metin2Exception("The database instance is not a valid instance");
$this->db = new Utilities\Database($database);
} catch (Exceptions\Metin2Exception $e) {
echo $e->errorMessage();
}
}
public function loadModule($module)
{
$m = "\\Metin2\\Modules\\" . $module;
return new $m;
}
}
</code></pre>
<p><strong>Autoloader class</strong>:</p>
<pre><code><?php
namespace Metin2\Utilities;
class Autoloader {
public static function loadModel($class){
$class = str_replace("\\","/",$class);
$class = explode("/",$class);
if($class[0] == "Metin2")unset($class[0]);
$class = implode("/",$class);
$path = ROOT_PATH.$class.".class.php";
if(file_exists($path)){
require_once($path);
}
}
}
</code></pre>
<p><strong>An example of a module</strong>:</p>
<pre><code><?php
namespace Metin2\Modules;
class Testdb {
public $db;
public function __construct(){
$this->db = \Metin2\Utilities\Database::getInstance();
print_r($this->db->getOne("account"));
}
}
</code></pre>
<p>Everything works well, but I want to know if there are any things I did wrong or if there are things I can do better.</p>
| [] | [
{
"body": "<p>My thoughts:</p>\n\n<ol>\n<li><p>Imho <code>Database</code> should not belong to <code>Utilities</code> namespace. Working with database is likely a core part of your application, \"Utilities\" suggest auxiliary tools to make your life easier. But maybe the class does something different than I expect</p></li>\n<li><p>Is there a reason to keep all your application in <code>Metin2</code> namespace but have separate <code>Exceptions</code> namespace with <code>Metin2Exception</code>? If it's for code completition, then a good IDE should only suggest classes inheriting from Exception in these contexts.</p></li>\n<li><p><code>Metin2::__constructor()</code>: can Utilities\\Database throw Metin2Exception? If not, then it's not really useful to throw exception only to catch it right away and echo</p></li>\n<li><p>It's worth considering using specialized Exception classes and keep Exception messages for details. That is because you can't catch Exception based on its message, but only class. Here you could have <code>ConnectionFailedException extends Metin2Exception</code>.</p></li>\n<li><p>Instead of echoing Exception message I would recommend making a function/class, that would enable you to redirect error messages to file, as it's not recommended to be printing out application messages for users to see. This way you'll also be able to log them.</p></li>\n<li><p>On a similar note you may take a look at <code>set_exception_handler</code>, that lets you assign a function/method to handle uncaught exceptions. And from that you can try either making your own or using a 3rd party exception handlers, which combined with <code>set_error_handler</code> that can be used for conversion of errors to exceptions can really improve your programming. Examples: <a href=\"https://github.com/nette/tracy\">https://github.com/nette/tracy</a> or ... maybe <a href=\"http://raveren.github.io/kint/\">http://raveren.github.io/kint/</a> (I'm sure there's another as nice as Tracy, but I can't remember its name).</p></li>\n<li><p>You can remove dependency of <code>Autoloader</code> on a global constant by adding a static property and using a setter to set its value</p></li>\n<li><p>When <code>Autoloader</code> finds out the target filepath does not exist, it does not react in any way ... maybe at least log it somehow, if not throw exception?</p></li>\n<li><p>What's the purpose of <code>Testdb</code>? I would discourage from using a service location especially when it comes to testing ... why not pass the <code>$db</code> as an argument?</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:17:17.237",
"Id": "77592",
"Score": "1",
"body": "1. I put Database class in the Utilities namespaces because the class make easier my life with its methods. 2. No, it isn't. I corrected this before 3. Yes, it does 4. Yes, you are right, thanks 5. In future i'm going to do as you wrote, i have done so because of testing .6 Wow very useful, i didn't know that. Thanks 7. I don't understand about what dependency are you talking abount 8. Yes, i corrected this stupid thing five minutes ago. 9. It was made only for check if the database and the autoloader works."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:46:45.310",
"Id": "44624",
"ParentId": "44565",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T13:11:01.847",
"Id": "44565",
"Score": "6",
"Tags": [
"php",
"object-oriented",
"namespaces"
],
"Title": "My first project using namespaces"
} | 44565 |
<p>I am trying to create a function that I want to use in my real data. Is there any way to optimize the following function? This is a function I created to filter the data. </p>
<pre><code>filter <- function(x, m, delt) {
series <- x
series_filtered <- rep(0,length(series))
delta_t <- delt # time step between data points (hours)
tau_crit <- 3 # critical period (hours)
theta_crit <- 2*pi*delta_t/tau_crit # critical frequency
M <- m # number of time steps before and after available in filtering window
h <- rep(0,(2*M+1)) # initialize the weights
# get the lanczos coefficients
for (n in (-1*M):M) {
h[M+n+1] <- ifelse(n == 0,theta_crit*delta_t/pi,
(sin(n*theta_crit*delta_t)/(pi*n)) * (sin(n*pi/M)/(n*pi/M)))
}
# need to adjust the weights so that they add up to 1
h_unbiased <- h/sum(h)
h <- h_unbiased
# step through each time for which we'd like to create a filtered value
for (t in (1+M):(length(series)-M)) {
for (n in (-1*M):M) {
# apply the cofficients to create the filtered series
series_filtered[t] = series_filtered[t] + series[t+n] * h[M+n+1]
}
}
# Filtered data
y2 <- series_filtered[(M+1):(length(series)-M)]
return(y2)
}
</code></pre>
<p>Any suggestions on removing <code>for</code> loop and replacing by <code>apply</code> or any other function is appreciated. </p>
<p>In the above function, I have one single <code>for</code> loop and one <code>double for</code> loop. </p>
<p><strong>Edit:</strong></p>
<p>A testing can be done by the following data:</p>
<pre><code>x <- 1:100
series <- sin(2*x)+sin(x/4) + sin(x/8) + rnorm(100)
jd2 <- filter(x=series,m=4, delt=(40/60))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:32:01.767",
"Id": "77337",
"Score": "1",
"body": "This isn't so much a question, as a code writing request. This is not trivial to interpret without any real information on the purpose or action of the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T12:41:01.650",
"Id": "77338",
"Score": "3",
"body": "It's a long-standing urban legend that `*apply` are faster than `for`. In general there's no speed gain, just clarity of code (maybe :-) ). However, anywhere you can vectorize rather than loop you'll save time, and anywhere you can pre-allocate (as you did with `series_filtered`) that'll help too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:54:59.390",
"Id": "85827",
"Score": "0",
"body": "@CarlWitthoft I primarily like the the apply family for their brevity of code. And I find them easier to read, but easyness is in the eye of the beholder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-16T21:06:30.643",
"Id": "94950",
"Score": "0",
"body": "have you looked into `rcpp`?"
}
] | [
{
"body": "<p>I have tried this, but I don't know, how much (and even if) faster it is. Anyway, you used a lot of redundant code (creating variables M, h_unbiased, delta_t etc.).</p>\n\n<pre><code>filter2 <- function(x, m, delt) {\n series <- x\n tau_crit <- 3 # critical period (hours)\n theta_crit <- 2*pi*delt/tau_crit # critical frequency\n # get the lanczos coefficients\n h <- sapply(-m:m, FUN=function(x)ifelse(x == 0,theta_crit*delta_t/pi, \n (sin(x*theta_crit*delt)/(pi*x)) * (sin(x*pi/m)/(x*pi/m))))\n # need to adjust the weights so that they add up to 1\n h <- h/sum(h)\n # step through each time for which we'd like to create a filtered value\n y2 <- sapply((1+m):(length(series)-m), function(t){\n sum(unlist(sapply(-m:m, FUN=function(x)(series[t+x]*h[m+x+1]))))\n })\n # return\n return(y2)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T17:20:28.410",
"Id": "77339",
"Score": "0",
"body": "+1 Thank you so much for your time and effort to try to update the function. Results are working fine and are consistent but it seems it is little slower than the code I wrote before."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T07:17:58.457",
"Id": "44567",
"ParentId": "44566",
"Score": "1"
}
},
{
"body": "<p>This works a little faster, taking advantage of vectorized code in a couple places.</p>\n\n<pre><code>filter3 <- function(x, m, delt) {\n xlen <- length(x)\n tau_crit <- 3 # critical period (hours)\n theta_crit <- 2*pi*delt/tau_crit # critical h\n n <- seq(-m, m)\n h <- (sin(n*theta_crit*delt)/(pi*n)) * (sin(n*pi/m)/(n*pi/m))\n h[n == 0] <- theta_crit * delt/pi\n h <- h/sum(h)\n sapply((1+m):(xlen-m), function(t) sum(series[t+n] * h[m+n+1]))\n}\n</code></pre>\n\n<p>(There were some variables defined but not used, and many defined for the sake of changing the variable name itself. Though not a huge savings with these input data, I opted to leave them out. If the input data is considerably larger, the memory footprint might have more of an effect.)</p>\n\n<p>When comparing performance of this with the original, it appears to operate in almost 20% of the time (I'm looking at the median for that stat):</p>\n\n<pre><code>require(microbenchmark)\nmicrobenchmark(f1=filter(x=series, m=4, delt=(40/60)), f3=filter3(x=series, m=4, delt=(40/60)), times=1000)\n## Unit: microseconds\n## expr min lq median uq max neval\n## f1 2121.381 2180.634 2227.229 2527.8990 17368.383 1000\n## f3 406.152 432.569 453.482 495.4905 2235.118 1000\n</code></pre>\n\n<p>HOWEVER, for some reason they are a <em>little</em> different:</p>\n\n<pre><code>f1 <- filter(x=series, m=4, delt=(40/60))\nf3 <- filter3(x=series, m=4, delt=(40/60))\nidentical(f1, f3)\n## [1] FALSE\nmax(f1-f3)\n## [1] 4.440892e-16\n</code></pre>\n\n<p>... but the difference is very small. (I tried it in both 32- and 64-bit mode with the same results.) Considering the lower magnitude your sample data creates is around <code>0.0268</code>, this <code>4.44e-16</code> seems a bit inconsequential.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-12T01:28:41.563",
"Id": "49489",
"ParentId": "44566",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:16:34.853",
"Id": "44566",
"Score": "0",
"Tags": [
"r"
],
"Title": "Optimizing the function in R by replacing for loop"
} | 44566 |
<p>I've created this router for my framework and wanted to get some feedback on if it's the most efficient way to search the routes.</p>
<p>The main router</p>
<pre><code>public static function route($modules = true){
$route = (isset($_GET['route']) && $_GET['route'] != '') ? trim($_GET['route'], '/') : '/';
$parts = explode('/', $route);
if($parts[0] == 'debug' && ENVIROMENT == 'development'){
array_shift($parts);
static::$debug = true;
}
unset($_GET['route']);
if($route != '/' && count($parts) != 0){
static::$routeParts = $parts;
if($parts[0] == 'modules' && $modules){
$path = null;
$fullpath = md5('/'.implode('/', $parts));
//exact match
$pathFound = key_exists($fullpath, static::$routingTable);
//if full path not found look for partial
if(!$pathFound){
$elements = count($parts);// - 2;//parts after the module name
$bits = $parts;
if($elements > 0){
//array_pop($bits); //remove the final element - wildcard
$paths = array();
for($i = 0; $i < $elements; $i++){
$searchPath = '/'.implode('/', $bits).'/*';
$paths[] = $searchPath;
foreach(static::$routingTable as $rt){
if($searchPath == $rt['path']){
$pathFound = true;
$path = $rt;
break;
}
}
if($pathFound)
break;
else
array_pop($bits);
}
/*if($pathFound !== true){
//match base module and send rest as params
$moduleSlug = $parts[1];
$fullpath = md5('/modules/'.$parts[1]);
$pathFound = key_exists($fullpath, static::$routingTable);
$path = static::$routingTable[$fullpath];
}*/
}
else{
$fullpath = md5('/'.implode('/', $parts).'/*');
$pathFound = key_exists($fullpath, static::$routingTable);
$path = static::$routingTable[$fullpath];
}
}
else
$path = static::$routingTable[$fullpath];
array_shift($parts);
array_shift($parts);
if($pathFound){
static::$view = 'view';
static::$args['dir'] = $path['callback']['config']['directory'];
static::$args['slug'] = $parts;
$_GET['params'] = $parts;
static::$args['module'] = true;
static::$args['fullwidth'] = (isset($path['callback']['config']['fullwidth']) ? $path['callback']['config']['fullwidth'] : false);
ModuleLoader::runModule($path);
}
else{
//not ideal
static::$view = '404';
static::$args['fullwidth'] = true;
}
}
else{
static::$view = $parts[0];
array_shift($parts);
array_shift($parts);
static::$args['slug'] = $parts;
$_GET['params'] = $parts;
}
}
else{
//home page module
static::$view = 'index';
static::$args['fullwidth'] = true;
}
static::$routed = true;
}
</code></pre>
<p>Some examples routes added are which will all be pre-pended with site directory + '/modules/' :</p>
<pre><code>/
/test
/test/
/test/*
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T13:30:31.757",
"Id": "44571",
"Score": "2",
"Tags": [
"mvc",
"php5"
],
"Title": "Modular dynamic based routing with wildcards"
} | 44571 |
<p>The program counts attributes of various (geo-)objects and prints them to different files. </p>
<p>One of the options compares two different datasets with each other. </p>
<pre><code>parser.add_option("-c", "--compare datasets", dest="compare",
help="If you want to campare two datasets (from different years for example) set the c-flag to 1. Run both datasets\
one after the other. After the second run you will find a file named COMPARE_* in the output folder. The default\
behaviour is no comaprison.")
</code></pre>
<p>I am concerned about the behavior of my current implementation. The basic idea is to pickle a list of file names when the -c flag is set to 1. When the program is run for the second time with the -c flag it will load all file names needed for the comparison from the pickle file.</p>
<pre><code>if options.compare == '1':
# check if there is a pickle file
p = glob.glob('%s/*.pikl' % data_output)
if len(p) > 1:
raise Exception('There are two pickle files. Comparison not possible.')
elif len(p) == 1:
pfiles_list = pickle.load(open(p[0],'rb'))
if len(pfiles_list) == len(files_to_compare):
for i,(f1,f2) in enumerate(zip(pfiles_list,files_to_compare)):
print 'comparing files...'
if i == 0:
csv_cmp_lazy(f1,f2, compare_file)
else:
csv_cmp_lazy(f1,f2, compare_file, append_file = True)
info_str = 'Deleting pickle file %s' % os.path.basename(p[0])
print info_str
logging.info(info_str)
os.remove(p[0])
else:
raise ValueError('len of files current and last run are not equal: Number of file current run/last run: %s/%s' % (len(files_to_compare),len(pfiles_list))
else:
pickle.dump(files_to_compare, open(pikl_file,'wb'))
</code></pre>
<p>This implementation relies on a few assumptions:</p>
<ul>
<li>that the pickle file won't be moved away from <code>data_output</code> </li>
<li>that <code>os.remove(p[0])</code> will be successful</li>
</ul>
<p>Not very secure, right? Besides, imagine the user finds an error in his data and wants to do the second run again: the comparison will fail because the pickle file won't be there anymore. This can be very annoying as the program may take longer than one hour to terminate (depending on input options and dataset).</p>
<p>Any suggestions on how to do this in a smarter way?</p>
| [] | [
{
"body": "<p>Simplify all the things! You and your users will benefit from simplicity.</p>\n\n<h2>Option parsing</h2>\n\n<p>If the <code>--compare</code> option is either <code>True</code> or <code>False</code>, make it a boolean flag with <code>False</code> as the default value. Your users won't have to remember if the <code>--compare</code> argument is 1, true or yes, they will simply write <code>--compare</code>.</p>\n\n<p>You should also consider moving from optparse to argparse: optparse is deprecated since Python 2.7 and Python 3.2 and could be removed in any future release.</p>\n\n<h2>About your assumptions</h2>\n\n<ul>\n<li>If the pickle file is moved away from <code>data_output</code>, then the users will simply see that the file is missing. You could catch the resulting exception to ask them to first run the program without comparison.</li>\n<li>If the removing fails, then something is really wrong anyway.</li>\n</ul>\n\n<p>I don't think resolving those specific issues is the way to go, and it should be easier for your users to provide this comparison feature differently.</p>\n\n<h2>Comparison logic</h2>\n\n<p>Your current solution is mostly a hack. It looks like you only asked yourself: what is the simplest way to implement this? The question should be different: what is the simplest way to <strong>use</strong> this?</p>\n\n<p>Say I want to compare 2010 and 2011. I first run your program with 2010, then with 2011 plus comparison. What if I actually made a typo and typed 2010 instead of 2009? What if one of the options for 2011 was wrong? I have to start all over again. Very frustrating since the processing is slow.</p>\n\n<p>I don't know your program well enough to be sure, but the simplest way could be to provide a --dump option, so that users would dump the first dataset (slow), dump the second dataset (slow), then compare the two (fast!).</p>\n\n<p>It would also be even clearer to provide two binaries, one for processing the datasets, and another one for comparison: this would reduce confusion.</p>\n\n<p>Users are now in control and understand what happens and how the comparison works. Fixing any issue does not require to run processing for the two datasets. User won't delete the dumped files, and if they did, that would be their fault since you exposed those files to them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T11:13:56.647",
"Id": "79144",
"Score": "0",
"body": "Thanks for taking the time to think along with this. Actually I think it is a good idea to split the data processing and the comparison into two different programs. That will make a lot of things easier, indeed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T10:47:23.553",
"Id": "45394",
"ParentId": "44575",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:05:50.493",
"Id": "44575",
"Score": "6",
"Tags": [
"python"
],
"Title": "Compare result files from two different runs the smart way?"
} | 44575 |
<p>Rock Paper Lizard Spock Monkey Banana</p>
<p>My <a href="https://codereview.stackexchange.com/questions/44177/rpsls-refactored-to-object-oriented">original post</a><br>
Based off of Malachi's <a href="https://codereview.stackexchange.com/questions/36482/rpsls-game-in-c">post</a></p>
<p>I've changed the way rules work in this version to allow ties to result in double loss or double win. While statistically picking monkey wins against the computer, my intention is to make this a multi-player game which would require more strategy than the completely flat RPS or RPSLS.</p>
<p>I'm looking for any criticism/advice/review on the following code. I think the Rules structure is pretty complex and daunting. </p>
<pre><code>Dictionary<Gesture, Tuple< // A dictionary of all the gestures
Dictionary<Gesture, string>, // A sub-dictionary of all of the gestures this one beats, and a string of why.
Dictionary<Gesture, string> // A sub-dictionary of all of the gestures this one loses to, and a string of why.
>>
</code></pre>
<p>I've considered moving it to a separate class. However, it does work perfectly fine as is, so I haven't.</p>
<p>Also you should note that the rules dictionary does contain a reason for why gestures lose, this isn't used in the current implementation, but I do plan to have it used when I have people playing in multi-player to be notified of "why they lost"... which is only slightly different from "why the other guy won".</p>
<p>Here is the full, runnable dump</p>
<pre><code>class Program
{
static void Main(string[] args)
{
var gameMenu = new string[] { "Play", "Clear Score", "Quit" };
var me = new Human();
var computer = new Computer();
var playAgain = true;
do
{
Utils.WriteLineColored("Options:", ConsoleColor.White);
Utils.PrintMenu(gameMenu.ToList());
switch (Utils.PromptForRangedInt(0, gameMenu.Length - 1, "Choose an Option: "))
{
case 0:
Console.Clear();
Game.Play(me, computer);
Console.WriteLine("Your scorecard: " + me.GetScoreCard() + Environment.NewLine);
break;
case 1:
Console.Clear();
me.ClearScore();
Utils.WriteLineColored("Your score has been cleared", ConsoleColor.Green);
break;
case 2:
Console.Clear();
playAgain = false;
Console.Write("Good bye, thanks for playing!\nPress any Key to contine...");
Console.ReadKey(true);
break;
}
} while (playAgain);
}
}
enum Gesture
{
Rock,
Paper,
Scissors,
Lizard,
Spock,
Monkey,
Banana
}
enum Performance
{
Lost,
Tied,
Won
}
abstract class Player
{
public uint Wins { get; private set; }
public uint Loses { get; private set; }
public uint Ties { get; private set; }
public abstract Gesture GetMove();
public string GetScoreCard()
{
return "[Wins: " + Wins + "] [Loses " + Loses + "] [Ties " + Ties + "]";
}
public void ClearScore()
{
Wins = Loses = Ties = 0;
}
public void GiveResult(Performance performance)
{
switch (performance)
{
case Performance.Lost: Loses++; break;
case Performance.Tied: Ties++; break;
case Performance.Won: Wins++; break;
}
}
}
class Human : Player
{
public override Gesture GetMove()
{
Utils.PrintMenu(Game.Gestures.Select(g => g.ToString()).ToList());
return Game.Gestures[Utils.PromptForRangedInt(0, Game.Gestures.Length - 1, "Please choose your Gesture: ")];
}
}
class Computer : Player
{
public override Gesture GetMove()
{
return (Gesture)Game.Gestures.GetValue(new Random().Next(Game.Gestures.Length));
}
}
static class Game
{
public static Gesture[] Gestures = (Gesture[])Enum.GetValues(typeof(Gesture));
private static Dictionary<Gesture, Tuple<Dictionary<Gesture, string>, Dictionary<Gesture, string>>> Rules = new Dictionary<Gesture, Tuple<Dictionary<Gesture, string>, Dictionary<Gesture, string>>>()
{
{Gesture.Rock, Tuple.Create(new Dictionary<Gesture, string>(){
{Gesture.Scissors,"Crushes"},
{Gesture.Lizard,"Crushes"},
{Gesture.Banana,"Smushes"}
}, new Dictionary<Gesture, string>(){
{Gesture.Paper,"Gets Covered By"},
{Gesture.Spock,"Gets Vaporized By"},
{Gesture.Monkey,"Gets Thrown By"},
})},
{Gesture.Paper, Tuple.Create(new Dictionary<Gesture, string>(){
{Gesture.Rock,"Covers"},
{Gesture.Spock,"Disproves"},
{Gesture.Banana,"Slowly Suffocates"}
}, new Dictionary<Gesture, string>(){
{Gesture.Scissors,"Gets Cut By"},
{Gesture.Lizard,"Gets Eaten By"},
{Gesture.Monkey,"Gets Shredded By"},
})},
{Gesture.Scissors, Tuple.Create(new Dictionary<Gesture, string>(){
{Gesture.Paper,"Cut"},
{Gesture.Lizard,"Decapitates"},
{Gesture.Banana,"Cuts"}
}, new Dictionary<Gesture, string>(){
{Gesture.Rock,"Gets Smashed By" },
{Gesture.Spock,"Gets Crushed By"},
{Gesture.Monkey,"Gets Broken By"},
})},
{Gesture.Lizard, Tuple.Create(new Dictionary<Gesture, string>(){
{Gesture.Paper,"Eats"},
{Gesture.Spock,"Poisons"},
{Gesture.Banana,"Eats"}
}, new Dictionary<Gesture, string>(){
{Gesture.Rock,"Gets Crushed By"},
{Gesture.Scissors,"Gets Decapitated By"},
{Gesture.Monkey,"Gets Eaten By"},
})},
{Gesture.Spock, Tuple.Create(new Dictionary<Gesture, string>(){
{Gesture.Rock,"Vaporizes"},
{Gesture.Scissors,"Smashes"},
{Gesture.Banana,"Studies"}
}, new Dictionary<Gesture, string>(){
{Gesture.Paper,"Gets Disproved By"},
{Gesture.Lizard,"Gets Poisoned By"},
{Gesture.Monkey,"Gets Boggled By" },
})},
{Gesture.Monkey, Tuple.Create(new Dictionary<Gesture, string>(){
{Gesture.Rock,"Throws"},
{Gesture.Paper,"Shreds"},
{Gesture.Scissors,"Breaks"},
{Gesture.Lizard,"Steps On"},
{Gesture.Spock,"Boggles"},
}, new Dictionary<Gesture, string>(){
{Gesture.Monkey,"Gets Beaten By"},
{Gesture.Banana,"Goes cRaZy From Eating The"}
})},
{Gesture.Banana, Tuple.Create(new Dictionary<Gesture, string>(){
{Gesture.Monkey,"Crazes"},
{Gesture.Banana,"Chills With"}
}, new Dictionary<Gesture, string>(){
{Gesture.Rock,"Gets Squished By"},
{Gesture.Paper,"Gets Slowly Suffocated By"},
{Gesture.Scissors,"Gets Cut By"},
{Gesture.Lizard,"Gets Eaten By"},
{Gesture.Spock,"Gets Beaten By"}
})}
};
public static void Play(Player player1, Player player2)
{
Gesture p1move = player1.GetMove();
Gesture p2move = player2.GetMove();
Console.Write("Player 1 Chose ");
Utils.WriteLineColored(p1move.ToString(), ConsoleColor.Green);
Console.Write("Player 2 Chose ");
Utils.WriteLineColored(p2move.ToString(), ConsoleColor.Green);
Performance p1perf = WhatHappensToMe(p1move, p2move);
Performance p2perf = WhatHappensToMe(p2move, p1move);
player1.GiveResult(p1perf);
player2.GiveResult(p2perf);
//Report to the console what has happened to player 1
if (p1perf == Performance.Tied)
Console.WriteLine("It was a tie!");
else
Console.WriteLine("Player 1 {0} Because, {1}.", p1perf, GetReason(p1move, p2move, p1perf));
}
private static Performance WhatHappensToMe(Gesture myMove, Gesture theirMove)
{
return
Rules[myMove].Item1.ContainsKey(theirMove) ? Performance.Won :
Rules[myMove].Item2.ContainsKey(theirMove) ? Performance.Lost :
Performance.Tied;
}
private static string GetReason(Gesture myMove, Gesture theirMove, Performance performance)
{
return myMove.ToString() + ' ' +
(performance == Performance.Won ? Rules[myMove].Item1 : Rules[myMove].Item2)[theirMove]
+ ' ' + theirMove.ToString();
}
}
static class Utils
{
public static int PromptForRangedInt(int min = int.MinValue, int max = int.MaxValue, string prompt = "Please enter an Integer: ")
{
int g;
do
{
Console.Write(prompt);
if (int.TryParse(Console.ReadLine(), out g))
{
if (g >= min && g <= max)
return g;
Console.WriteLine("You entered {0}, but the input must be in the range of ({1} - {2}. Please try again...", g, min, max);
}
else
Console.WriteLine("That is not a number. Please try again...");
} while (true);
}
public static void PrintMenu(List<string> values, int baseIndex = 0)
{
values.ForEach(value => Console.WriteLine("{0}: {1}", baseIndex++, value));
}
public static void WriteLineColored(string text, ConsoleColor color)
{
var curr = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ForegroundColor = curr;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:58:04.540",
"Id": "77353",
"Score": "5",
"body": "Who said Banana! Where? Where?"
}
] | [
{
"body": "<p>It might be simpler to define rules like this ...</p>\n\n<pre><code>List<Tuple<Gesture,Gesture,string,string>> Rules = new List<Tuple<Gesture,Gesture,string,string>> {\n Tuple.Create(Gesture.Rock,Gesture.Scissors,\"Crushes\",\"Get Crushed By\"),\n ... etc ...\n};\n</code></pre>\n\n<p>... because ...</p>\n\n<ul>\n<li>It's simpler (less \"daunting\")</li>\n<li>Easier to read (triplets of winning gesture, losing gesture, reason)</li>\n<li>Easier to e.g. load from a flat configuration/resource file.</li>\n<li>Less error-prone (you define everything twice, once for the winner and once for the loser; what you forget to define half the rule? where do you verify that you haven't forgotten?)</li>\n</ul>\n\n<p>You could convert such a structure into a dictionary of dictionaries at load-time, e.g. if you wanted the improved performance of a dictionary instead of scanning a list.</p>\n\n<hr>\n\n<p>The mapping between gameMenu options and integers isn't obvious unless you read the code; and the code is scattered (a gameMenu definition, a switch statement, Utils.PrintMenu, and Utils.PromptForRangedInt methods); perhaps instead have a UserInput class ...</p>\n\n<pre><code>static class UserInput\n{\n internal enum Choice { Play, Reset, Quit };\n static Choice PromptUserAndGetChoice() { etc. }\n}\n</code></pre>\n\n<p>... because then everything would be co-located in one class.</p>\n\n<hr>\n\n<p>I like to put <code>default: throw NotImplementedException();</code> at the end of switch statements.</p>\n\n<hr>\n\n<p>Instead of ...</p>\n\n<pre><code>return \"[Wins: \" + Wins + \"] [Loses \" + Loses + \"] [Ties \" + Ties + \"]\";\n</code></pre>\n\n<p>... perhaps ...</p>\n\n<pre><code>return string.Format(\"[Wins: {0}] [Loses {1}] [Ties {2}]\", Wins, Loses, Ties);\n</code></pre>\n\n<p>... because I find it easier to read the format of the latter output string.</p>\n\n<hr>\n\n<p>Instead of abstract Player with two subclasses, you could have a concrete player class which takes the abstraction as a delegate parameter passed into its constructor</p>\n\n<pre><code>Func<Gesture> GetMove;\nPlayer(Func<Gesture> getMove)\n{\n this.GetMove = getMove;\n}\n</code></pre>\n\n<p>It's worth having subclasses when there are two abstract methods, but when there's just one it's less code (only one class instead of three) to use a delegate.</p>\n\n<hr>\n\n<p>WhatHappensToMe is called twice and checks the rules twice. Instead, what happens to me is the complement of what happens to them; if you define the enum values as <code>-1</code>, <code>0</code>, and <code>1</code> then you could simply negate the value.</p>\n\n<hr>\n\n<p>GetReason checks the rules yet again. Instead, maybe looking-up the rule should return the result and the reason at the same time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:08:26.017",
"Id": "77368",
"Score": "0",
"body": "Your different Dictionary implementation would work, if Monkey and Banana weren't so weird. In standard RPSLS I would certainly go with that approach, but here Monkeys lose to each other, and Bananas win to each other instead of tie-ing. I see your point with the Player Abstraction, I'll think about that. And the reason WhatHappensToMe is called twice is because of the weird win-lose-tie cercumstances introduced by Monkey and Banana. GetReason looking up rules again I may indeed change if I implement a class structure for rules. Everything else I agree with :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:37:53.030",
"Id": "77375",
"Score": "1",
"body": "In that case I'd suggest adding a `bool?` or an `enum { WinAndLose, BothWin, BothLose }` to the list of tuples I suggested: to make that explicit: because it's difficult to verify/inspect the data you have. Also, on loading the list, verify that the same (unordered) pair of gestures isn't defined more than once in the list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:23:56.190",
"Id": "77417",
"Score": "0",
"body": "That is a valid point, and would replace what I have right now just fine. I may want to keep it this way in-case later I add other strange Gestures. You are correct, this current strucutre is difficult to verify"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:56:15.403",
"Id": "77448",
"Score": "1",
"body": "\"Hard to verify\" is high on my list of priorities to fix: because a main reason for doing a code review is \"verification\". I want to look at code (and data) and verify (by inspection) that it's correct. Alternatively I'll look to see whether code is self-verifying (e.g. your code could have a run-time check/assertion that most pairs are defined twice: once as a winner and again as a loser). Or (last resort) I'll look for an exhaustive list of unit test cases."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:39:34.273",
"Id": "44592",
"ParentId": "44577",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44592",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T14:44:20.157",
"Id": "44577",
"Score": "12",
"Tags": [
"c#",
"game",
".net",
"community-challenge",
"rock-paper-scissors"
],
"Title": "RPSLSMB OOP Version 2"
} | 44577 |
<p>So I noticed Chrome has quirky behaviour when it encounters <code>script</code> tags whose <code>src</code> is a base64 value. I decided to write a quick jQuery method that is supposed to work around it:</p>
<pre><code>jQuery.extend({
/**
* Takes a script decodes the base64 src, puts it into the body of the script tag,
* then puts it in whatever parent specified.
*
* @requires https://plugins.jquery.com/base64/
*
* @param {Object} script The script tag that should be manipulated
* @param {Object} parent The parent element to append the final script tag to.
*
* @return {Object} The script tag in question
*/
importBase64Script : function ( script, parent ) {
// Check for base64 library
if ( typeof $.base64 === 'undefined' )
throw 'No $.base64 found!';
// Sanitize our script var
// Normalize our script object
script = ( script instanceof jQuery ? script : $(script) );
// Check if it is a script tag
if ( script[0].tagName !== "SCRIPT" )
throw "Not a script tag";
// Set default parent value
parent = parent || $('head');
// Normalize our parent var
parent = ( parent instanceof jQuery ? parent : $(parent) );
// We're gonna extract the base64 value
var re = /data:[a-z]+\/[a-z]+;base64,([0-9a-zA-Z\=\+]+)/,
base64Content = script.prop('src').match(re)[1],
scriptContent = $.base64.decode( base64Content );
// Drop the decoded javascript into the contents of the script tag
script.html( scriptContent );
// Clear src value
script.prop('src','');
// Append it to the parent
parent.append(script);
return script;
}
});
</code></pre>
<p>I tested a few of the conditions on JsPerf to see which is better performance wise. Granted, I didn't do a full sweep on every browser.</p>
<p>Any suggestions that anybody could make?</p>
| [] | [
{
"body": "<p>Awesome,</p>\n\n<ul>\n<li>Well commented</li>\n<li>Nothing bad on JsHint.com</li>\n<li>Quiet and robust handling of parameters</li>\n<li>It does exactly what it says on the tin</li>\n</ul>\n\n<p>Unrelated to CR, but this is github worthy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:37:47.153",
"Id": "77442",
"Score": "0",
"body": "Thanks for the positive feedback! I'll wait a bit to see if anybody might spot some details that could improve the code but if not I'll mark your answer as correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:15:48.053",
"Id": "80804",
"Score": "0",
"body": "Added to https://github.com/martin-wiseweb/import-base64-script"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:25:39.947",
"Id": "44603",
"ParentId": "44583",
"Score": "2"
}
},
{
"body": "<p>Thanks for the post.</p>\n\n<p>Here, I refine this. If you have a string that may be a url or a base64 encoded script, it will be added as a normal script with src or as a script with the source decoded and embeded. I am using this within the context of nunjucks but it may prove useful elsewhere. jQuery not used.</p>\n\n<p>Note: <code><script src=\"{{my_script}}\"></script></code> does not seem to work with base64 encoded script URIs. I am using Chrome v67.0.3396.87</p>\n\n<pre><code><script>\n var addScript = function(data) {\n var m = data.match(/data:[a-z]+\\/[a-z]+;base64,([0-9a-zA-Z\\=\\+]+)/);\n if(m) document.write('<'+'SCRIPT>'+atob(m[1])+'<'+'/SCRIPT>');\n else document.write('<'+'SCRIPT src=\"'+data+'\"><\"+\"/SCRIPT>');\n }\n addScript(\"{{my_script}}\");\n</script>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-21T19:34:47.910",
"Id": "379553",
"Score": "3",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-21T19:19:05.037",
"Id": "197004",
"ParentId": "44583",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code>// We're gonna extract the base64 value\nvar re = /data:[a-z]+\\/[a-z]+;base64,([0-9a-zA-Z\\=\\+]+)/,\n</code></pre>\n</blockquote>\n<p>This regex is too limited. The "data" URL scheme is specified in <a href=\"https://www.rfc-editor.org/rfc/rfc2397\" rel=\"nofollow noreferrer\">RFC 2397</a>, which says:</p>\n<blockquote>\n<p>The URLs are of the form:</p>\n<pre><code>data:[<mediatype>][;base64],<data>\n</code></pre>\n<p>The <code><mediatype></code> is an Internet media type specification (<strong>with optional parameters</strong>.) The appearance of <code>;base64</code> means that the data is encoded as base64. <strong>Without <code>;base64</code>, the data (as a sequence of octets) is represented using ASCII encoding for octets inside the range of safe URL characters and using the standard <code>%xx</code> hex encoding of URLs</strong> for octets outside that range. <strong>If <code><mediatype></code> is omitted</strong>, it defaults to <code>text/plain;charset=US-ASCII</code>. As a shorthand, <code>text/plain</code> can be omitted but the charset parameter supplied.</p>\n</blockquote>\n<p>Furthermore, it says:</p>\n<blockquote>\n<pre><code> dataurl := "data:" [ mediatype ] [ ";base64" ] "," data\n mediatype := [ type "/" subtype ] *( ";" parameter )\n data := *urlchar\n parameter := attribute "=" value\n</code></pre>\n<p>where <code>urlchar</code> is imported from <a href=\"https://www.rfc-editor.org/rfc/rfc2396\" rel=\"nofollow noreferrer\">RFC2396</a>, and <code>type</code>, <code>subtype</code>, <code>attribute</code> and <code>value</code> are the corresponding tokens from <a href=\"https://www.rfc-editor.org/rfc/rfc2045\" rel=\"nofollow noreferrer\">RFC2045</a>, represented using <strong>URL escaped encoding of <a href=\"https://www.rfc-editor.org/rfc/rfc2396\" rel=\"nofollow noreferrer\">RFC2396</a> as necessary</strong>.</p>\n</blockquote>\n<p><a href=\"https://www.rfc-editor.org/rfc/rfc2045#section-5.1\" rel=\"nofollow noreferrer\">RFC 2045 Section 5.1</a> says:</p>\n<blockquote>\n<p>The type, subtype, and parameter names are <strong>not case sensitive</strong>.</p>\n</blockquote>\n<p>In summary,</p>\n<ul>\n<li>The mediatype is optional, is case-insensitive, may contain parameters, and may be URL-escaped.</li>\n<li>For completeness, you should probably also support percent-encoded data in addition to base64-encoded data.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-21T19:49:00.827",
"Id": "197006",
"ParentId": "44583",
"Score": "2"
}
},
{
"body": "<h1>Watch out!</h1>\n\n<p>jQuery is full of secrets. <code>html</code> method is not just a simple wrapper around <code>innerHTML</code> property.</p>\n\n<p>Possible fail condition:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var src = `if (\"<x/>\" !== \"<\" + \"x\" + \"/\" + \">\") {\n console.log(\"Math gone wrong.\");\n}`;\n\n$(\"<script>\").html(src).appendTo(document.head)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!-- latest jQuery -->\n<script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Let's see what exactly is happening here:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log($(\"<i>\").html(\"<x/>\")[0].innerHTML)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!-- latest jQuery -->\n<script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>jQuery <code>html</code> method replaces <code><x/></code> with <code><x></x></code>. I guess it is perfectly valid for some HTML, but it fails with our JavaScript input.</p>\n\n<h1>The π robbery</h1>\n\n<p>Let's try to exploit this with malicious input and steal some valuable data:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var src = `var username = \"Kevin <x\\\";alert(Math.PI);\\\"/> Mitnick\";`;\n\n$(\"<script>\").html(src).appendTo(document.head);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!-- latest jQuery -->\n<script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I suggest you to carefully check jQuery <a href=\"https://github.com/jquery/jquery/blob/662083ed7bfea6bad5f9cd4060dab77c1f32aacd/src/manipulation.js#L401\" rel=\"nofollow noreferrer\"><code>html</code> source code</a>.</p>\n\n<p>Also you may replace it with plain old <code>innerHTML</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-27T10:40:03.680",
"Id": "380372",
"Score": "0",
"body": "[Related issue](https://github.com/martin-wiseweb/import-base64-script/issues/1) at GitHub project."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-21T20:54:05.333",
"Id": "197010",
"ParentId": "44583",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44603",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T15:47:27.850",
"Id": "44583",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"dom"
],
"Title": "Fix base64 data URI scripts function"
} | 44583 |
<p>Part of my program is a variable-sized set of Star Systems randomly linked by Warp Points. I have an A* algorithm working rather well in the grid, but the random warp point links mean that even though the systems have X,Y coordinates for where they're located on a galactic map, a system at 2,3 isn't always linked directly to a system at 2,4 and so the shortest path may actually lead away from the target before it heads back towards it. I think this limitation eliminates A* since there's almost no way to get a good heuristic figured out.</p>
<p>What I've done instead is a recursive node search (I believe this specific pattern is a Depth-First Search), and while it gets the job done, it also evaluates every possible path in the entire network of systems and warp points, so I'm worried it will run very slowly on larger sets of systems. My test data is 11 systems with 1-4 warp points each, and it averages over 700 node recursions for any non-adjacent path.</p>
<p>My knowledge of search/pathfinding algorithms is limited, but surely there's a way to not search <em>every single node</em> without needing to calculate a heuristic, or at least is there a heuristic here I'm not seeing?</p>
<p>Here's my code so far:</p>
<pre><code>private int getNextSystem(StarSystem currentSystem, StarSystem targetSystem,
List<StarSystem> pathVisited)
{
// If we're in the target system, stop recursion and
// start counting backwards for comparison to other paths
if (currentSystem == targetSystem)
return 0;
// Arbitrary number higher than maximum count of StarSystems
int countOfJumps = 99;
StarSystem bestSystem = currentSystem;
foreach (StarSystem system in currentSystem.GetConnectedStarSystems()
.Where(f=>!pathVisited.Contains(f)))
{
// I re-create the path list for each node-path so
// that it doesn't modify the source list by reference
// and mess up other node-paths
List<StarSystem> newPath = new List<StarSystem>();
foreach (StarSystem s in pathVisited)
newPath.Add(s);
newPath.Add(system);
// recursive call until current == target
int jumps = getNextSystem(system, targetSystem, newPath);
// changes only if this is better than previously found
if (jumps < countOfJumps)
{
countOfJumps = jumps;
bestSystem = system;
}
}
// returns 100 if current path is a dead-end
return countOfJumps + 1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T23:56:20.867",
"Id": "77477",
"Score": "0",
"body": "A* requires you to be able to accurately estimate the lower bound of the distance that would be required to get from A to B. If you can calculate that, then teleports do not interfere with A* search. Unfortunately, accurately estimating lower bounds when teleports are involved is tricky."
}
] | [
{
"body": "<p>The efficiency of heuristic pathfinding algorithms comes from the fact that you are able to discard earlier (or that you work more directed).\nDiscarding any heuristic means the best you can get is a lucky hit (which is rather unlikely) or the Dijkstra algorithm, which is not that efficient (compared to some decent heuristic).</p>\n\n<p>So I think the way to go is a heuristic. As you mentioned the pure euclideon distance is not a good measure as it steers away from the warp holes.\nMy idea would be to build a coarser representation of the map (maybe nodes = clusters of systems ...) and for this new map you store the shortest distances between the clusters. On the finer level you store the nearest point in the cluster to each other cluster (lets call them cluster transfer points or CTP) and your heuristic uses the minimal cluster distance plus the distance to the CTP in the current cluster + the distance from the target clusters CTP to the target system. This hierarchical structure can be build up for many levels to handle big systems.</p>\n\n<p>The two important parts are:\n- Complex calculation stays local in the current detail level while the higher levels are used to give you a heuristic\n- don't forget to ensure that the heuristic is admissible (that could get a bit harder)</p>\n\n<p>I cannot evaluate your code very much as I am no C# expert but it makes sense to me as far as I can read it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:24:03.393",
"Id": "44587",
"ParentId": "44584",
"Score": "3"
}
},
{
"body": "<p>Instead of returning <code>countOfJumps + 1</code> for a dead end, you should return something like a <code>-1</code>, this way it will never change no matter how many <code>systems</code> you add to the code system, in other words it would be more maintainable.</p>\n\n<p>maybe that isn't the best way to do it.</p>\n\n<p>I am thinking that you should have a logical flow for if the first jump leads to a dead end or if any number of jumps leads to a dead end. </p>\n\n<hr>\n\n<p>you should probably wrap your for each inside of an if statement as well. something like:</p>\n\n<pre><code>if (currentSystem.GetConnectedStarSystems().Where(f=>!pathVisited.Contains(f))) {\n Return countOfJumps;\n} else if {\n foreach (StarSystem system in currentSystem.GetConnectedStarSystems()) {\n .....\n }\n}\n</code></pre>\n\n<p>I think that fits with what you have going on there, doing this might actually reduce redundant code, unfortunately I am not entirely sure what all is going on here, I don't have much experience with <code>A*</code> algorithms.</p>\n\n<p>I know that separating these two pieces of logic is logical, what you have looks like you tried to smoosh an if and a foreach together. I don't want to even setup a foreach if this system is the target system.</p>\n\n<p>you might also want to comment that in the code as well.</p>\n\n<hr>\n\n<p>It looks like you might be able to change something here:</p>\n\n<pre><code> foreach (StarSystem s in pathVisited)\n newPath.Add(s);\n newPath.Add(system); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:26:23.873",
"Id": "44588",
"ParentId": "44584",
"Score": "4"
}
},
{
"body": "<p>After typing up my problem, I realized I hadn't tried implementing a Breadth-First Search (BFS) algorithm for the same problem as my Depth-First Search (DFS). I did some additional research, and I think BFS code will result in quicker results on average<sup>1</sup>, since it terminates and returns as soon as it has an answer instead of continuing to evaluate all further possible solutions.</p>\n\n<p><sup>1</sup> - I'd love to know if there's mathematical logic to BFS vs DFS efficiency. I think it's related to the number of connections per node versus the number of nodes, but I'm not sure. If there's a logical way to determine when to switch between the two implementations, I'd love to hear about it.</p>\n\n<p>Here's the BFS code I came up with:</p>\n\n<pre><code>public StarSystem GetNextSystem(StarSystem startingSystem, StarSystem targetSystem)\n{\n // Players might call for path to current system\n if (startingSystem == targetSystem)\n return startingSystem;\n\n // Queue needs to store path-thus-far and current system\n Queue<Tuple<List<StarSystem>, StarSystem>> StarSystemQueue = \n new Queue<Tuple<List<StarSystem>, StarSystem>>();\n\n // Need to track visited systems to prevent infinite loops\n List<StarSystem> visitedSystems = new List<StarSystem>();\n // Starting system is already visited\n visitedSystems.Add(startingSystem);\n\n // For connected systems that we haven't already visited\n foreach (StarSystem system in startingSystem.GetConnectedStarSystems()\n .Where(f => !visitedSystems.Contains(f)))\n {\n List<StarSystem> pathList = new List<StarSystem>();\n pathList.Add(system);\n // Add to visited systems so it's not evaluated in the loop\n visitedSystems.Add(system);\n // Enqueue the path & system\n StarSystemQueue.Enqueue(\n new Tuple<List<StarSystem>, StarSystem>(pathList, system));\n }\n // Loop til there's an answer or all paths are exausted\n while(StarSystemQueue.Count>0)\n {\n // Grab current from the queue\n Tuple<List<StarSystem>,StarSystem> currentSystem = StarSystemQueue.Dequeue();\n\n // If current is the target, return the first system from the path\n if (currentSystem.Item2 == targetSystem)\n return currentSystem.Item1.First();\n\n // For connected systems that we haven't already visited\n foreach (StarSystem system in currentSystem.Item2.GetConnectedStarSystems()\n .Where(f => !visitedSystems.Contains(f)))\n {\n // rebuild path list to prevent changing other paths by reference\n List<StarSystem> pathList = new List<StarSystem>();\n foreach (var previous in currentSystem.Item1)\n pathList.Add(previous);\n pathList.Add(system); // add new system to path\n visitedSystems.Add(system); // add new system to visited\n // Enqueue the path & system\n StarSystemQueue.Enqueue(\n new Tuple<List<StarSystem>, StarSystem>(pathList, system));\n }\n }\n // No valid answer at this point, return starting system and handle in outer code\n return startingSystem;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:38:21.847",
"Id": "77376",
"Score": "3",
"body": "I think this is meant as a new question. Further reviews should be done that way, not as an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:45:32.063",
"Id": "77381",
"Score": "0",
"body": "@Jamal I think it's quite clear that this is not meant as a new question. This is a self-answer, which is perfectly fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:47:23.473",
"Id": "77383",
"Score": "1",
"body": "@SimonAndréForsberg: The third paragraph might've confused me, and it should be removed anyway as it's not relevant to the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T00:01:23.143",
"Id": "77478",
"Score": "0",
"body": "Since your DFS is about the slowest algorithm there is for pathfinding, I'm not surprised that your BFS was faster. That doesn't mean that BFS is faster than DFS. That means _your_ BFS was faster than _your_ DFS."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:36:21.117",
"Id": "44595",
"ParentId": "44584",
"Score": "6"
}
},
{
"body": "<h2>Complete and Incomplete Algorithms</h2>\n\n<p>Search algorithms can be classed into two categories: <em>complete</em> and <em>incomplete</em>. </p>\n\n<p>A <em>complete</em> algorithm will always succeed in finding what your searching for. And not surprisingly an <em>incomplete</em> algorithm may not always find your target node.</p>\n\n<p>For arbitrary connected graphs, without any a priori knowledge of the graph topology a <em>complete</em> algorithm may be forced to visit all nodes. But <strong>may</strong> find your sought for node before visiting all nodes. A* is a complete best-first method with a heuristic to try to avoid searching unlikely parts of the graph unless absolutely necessary.</p>\n\n<p>So unfortunately you can not guarantee that you will never visit all nodes whatever algorithm you choose. But you can reduce the likelihood of that happening.</p>\n\n<h2>Without pre-processing</h2>\n\n<p>If you cannot consider pre-processing your graph then you're stuck with a myriad of on-line algorithms such as depth-first, breadth-first, A* and greedy-best-first. Out of the bunch I'd bet on A* in most cases if the heuristic is even half good and the graphs are non-trivial.</p>\n\n<p>If you expect all routes to be short, a breadth-first algorithm with cycle detection and duplicate node removal may outperform A* with a poor heuristic. I wouldn't bet on it though, you need to evaluate.</p>\n\n<h2>With pre-processing</h2>\n\n<p>In your case I'd see if I could pre-process the graph, even if you need to repeatedly re-do the pre-processing when the graph changes as long as you do sufficiently many searches between pre-processing it would be worth it.</p>\n\n<p>You should look up <a href=\"http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm\" rel=\"nofollow\" title=\"Floyd-Warshall\">Floyd-Warshall</a> (or some derivative) and calculate the pairwise cost/distance/jumps between all nodes and use this table as a heuristic for your A*. This heuristic will not only be admissible, it will be exact and your A* search will complete in no-time.</p>\n\n<p>Unless you of course modify the algorithm to store all pairwise routes as they are detected in a matrix of vectors, then you have O(1) run time at the cost of memory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:59:48.067",
"Id": "77388",
"Score": "0",
"body": "Storing an adjacency matrix with O(n^2) entries can get too costly very soon!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:18:19.690",
"Id": "77392",
"Score": "0",
"body": "It's exactly n^2/2 entries (its symmetric), for 10k nodes its `sizeof(short)×1E(2×4)/2=1E8 ie: ~100MB` which is feasible on today's computers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:40:59.903",
"Id": "77402",
"Score": "0",
"body": "I was working on an answer myself when I noticed you had answered, I believe the Floyd-Warshall algorithm was what I was thinking about, but I couldn't exactly figure out at the moment how the \"backtracking\" worked to find the path. Feel free to take a look at my answer, and I will read up on wikipedia :) +1 to you anyways!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:37:44.527",
"Id": "77419",
"Score": "1",
"body": "Actually I just saw the path reconstruction section on wikipedia. The A* is not needed if you store 1 extra matrix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:37:22.810",
"Id": "77574",
"Score": "0",
"body": "This answers both parts of my question, and I think it is the best solution. Thank you! The BFS search was performing well enough with my target graph size (200-2000 nodes) so I've since moved on to other parts of the project, but I will certainly come back and implement a pre-processor for it at some point, and I think this will be an excellent design for it (running either of my searches at >4k nodes begins to take huge amounts of time, so if I want this to scale to huge graph sizes I'll have to have a better search)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:46:12.977",
"Id": "44597",
"ParentId": "44584",
"Score": "12"
}
},
{
"body": "<p>I'm not entirely sure about the efficiency of this, but there is a mathematical way of looking at this.</p>\n\n<p>Create a n x n matrix of your systems, for example</p>\n\n<pre><code> a b c d e\n -----------\na| 0 1 1 0 0\nb| 1 0 0 1 0\nc| 1 0 0 0 0\nd| 0 1 0 0 1\ne| 0 0 0 1 0\n</code></pre>\n\n<p>We will call this matrix <code>Paths</code>.</p>\n\n<p>This matrix is for a graph with the <strong>nodes</strong> a--e (your star systems). And the <strong>edges</strong> (paths) as follows: a->b, a->c, b->a, b->d, c->a, d->b, d->e, e->d.</p>\n\n<p>Now, let's say that we want to find the shortest path from a to e. We check <strong>row</strong> a and <strong>column</strong> e and we find that no, there is no direct path.</p>\n\n<p>To find the paths of length two, you can multiply the Matrix with itself. So, Paths * Paths results in:</p>\n\n<pre><code>2 0 0 1 0\n0 2 1 0 1\n0 1 1 0 0\n1 0 0 2 0\n0 1 0 0 1\n</code></pre>\n\n<p>Let's call this Matrix <code>PathsSize2</code></p>\n\n<p>This gives us all paths of length two. We see that the paths <strong>from</strong> node a is <code>2 0 0 1 0</code>. So that's two paths to itself and one way to <code>d</code>. But still no paths to b, c, or e. So we'll multiply <code>PathsSize2</code> with the previous matrix, <code>Paths</code>:</p>\n\n<pre><code>0 3 2 0 1\n3 0 0 3 0\n2 0 0 1 0\n0 3 1 0 2\n1 0 0 2 0\n</code></pre>\n\n<p>And so we see that we have a path from <code>a</code> to <code>e</code>! You should be able to find out <em>which</em> path that is from the matrices that you have calculated above. (I cannot remember myself exactly at the moment). I believe this method which I have partially described here is the Floyd-Warshall algorithm that Emily L. has also mentioned in her answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:03:28.543",
"Id": "77410",
"Score": "0",
"body": "I'm a woman... Why do people always assume I'm a man? :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:18:30.537",
"Id": "77414",
"Score": "0",
"body": "@EmilyL. Sorry, we're just not used to women on Code Review :) Fixed! We're glad to have you here!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:30:51.023",
"Id": "77418",
"Score": "0",
"body": "This is going to be very slow. One matrix multiplication is n^3 multiplications and n^2×(n-1) additions. If it's a long path you could end up doing close to n iterations, I.e: about 2n^4 instructions. For sparse graphs you can optimise the matrix multiplication by using sparse matrices. But still it is going to be slower than Floyd-Warshall for the same result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:14:48.077",
"Id": "77484",
"Score": "0",
"body": "you are just trying to impress us with big words now @EmilyL. JK LOL I don't know what you just said though. I mean I know math but it has been a long time since I have done matrix math"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:39:15.347",
"Id": "44600",
"ParentId": "44584",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44597",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T15:48:44.807",
"Id": "44584",
"Score": "9",
"Tags": [
"c#",
"recursion",
"search",
"pathfinding"
],
"Title": "Efficient pathfinding without heuristics?"
} | 44584 |
<p>Following along another code review (<a href="https://codereview.stackexchange.com/questions/44349/printing-out-json-data-from-twitter-as-a-csv">Printing out JSON data from Twitter as a CSV</a>) I would like to submit a slightly adapted code for review. </p>
<p>This code imports JSON data obtained from Twitter and prints out just the tweet author and if there are any users the author mentions in the tweet. User_mentions is a field that is provided in the JSON output. The difficult part I've encountered is that an author sometimes doesn't mention anyone, or mentions 5 other user. So I'm not sure of the best way to account for this, besides what I've cobbled together below. </p>
<p><strong>My ultimate goal:</strong>
Create an edgelist from this data to then put into a network visualization tool. I've been converting the output (example below) from this code using a UNIX command (also below) I wrote, but if anyone has a better way to do this within this code, please do let me know. </p>
<p><strong>Format after code:</strong></p>
<ul>
<li>author1,mention1,mention2,mention3 </li>
<li>author1,mention4</li>
<li>author2 author3,mention5 </li>
<li>author4,mention3,mention6</li>
</ul>
<p><strong>Ultimate format in CSV:</strong></p>
<ul>
<li>author1,mention1</li>
<li>author1,mention2</li>
<li>author1,mention3</li>
<li>author1,mention4</li>
<li>author3,mention5</li>
<li>author4,mention3</li>
<li>author4,mention6</li>
</ul>
<p><strong>Python Code:</strong></p>
<pre><code>import json
import sys
tweets=[]
# import tweets from JSON
for line in open(sys.argv[1]):
try:
tweets.append(json.loads(line))
except:
pass
# create a new variable for a single tweets
tweet=tweets[0]
# pull out various data from the tweets
tweet_author = [tweet['user']['screen_name'] for tweet in tweets]
tweet_mention1 = [(tweet['entities']['user_mentions'][0]['screen_name'] if len(tweet['entities']['user_mentions']) >= 1 else None) for tweet in tweets]
tweet_mention2 = [(tweet['entities']['user_mentions'][1]['screen_name'] if len(tweet['entities']['user_mentions']) >= 2 else None) for tweet in tweets]
tweet_mention3 = [(tweet['entities']['user_mentions'][2]['screen_name'] if len(tweet['entities']['user_mentions']) >= 3 else None) for tweet in tweets]
tweet_mention4 = [(tweet['entities']['user_mentions'][3]['screen_name'] if len(tweet['entities']['user_mentions']) >= 4 else None) for tweet in tweets]
tweet_mention5 = [(tweet['entities']['user_mentions'][4]['screen_name'] if len(tweet['entities']['user_mentions']) >= 5 else None) for tweet in tweets]
tweet_mention6 = [(tweet['entities']['user_mentions'][5]['screen_name'] if len(tweet['entities']['user_mentions']) >= 6 else None) for tweet in tweets]
tweet_mention7 = [(tweet['entities']['user_mentions'][6]['screen_name'] if len(tweet['entities']['user_mentions']) >= 7 else None) for tweet in tweets]
tweet_mention8 = [(tweet['entities']['user_mentions'][7]['screen_name'] if len(tweet['entities']['user_mentions']) >= 8 else None) for tweet in tweets]
tweet_mention9 = [(tweet['entities']['user_mentions'][8]['screen_name'] if len(tweet['entities']['user_mentions']) >= 9 else None) for tweet in tweets]
tweet_mention10 = [(tweet['entities']['user_mentions'][9]['screen_name'] if len(tweet['entities']['user_mentions']) >= 10 else None) for tweet in tweets]
#outputting to CSV
out = open(sys.argv[2], 'w')
rows = zip(tweet_author, tweet_mention1, tweet_mention2, tweet_mention3, tweet_mention4, tweet_mention5, tweet_mention6)
from csv import writer
csv = writer(out)
for row in rows:
values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
csv.writerow(values)
out.close()
</code></pre>
<p><strong>UNIX command:</strong>
Used to take the output of this code and format as an edgelist. If this part can be worked into the above code, it would be much appreciated!</p>
<pre><code>cat [file.txt] | sed 's/,/ /g' | awk '{print $1, $2 "##" $1, $3 "##" $1, $4 "##" $1, $5 "##" $1, $6 "##" $1, $7 "##" $1, $8 "##" $1, $9 "##" $1 $10}' | sed 's/##/\n/g' | sed 's/ /,/g'
</code></pre>
| [] | [
{
"body": "<p>I've found another answer on <a href=\"https://github.com/alexhanna\" rel=\"nofollow\">https://github.com/alexhanna</a> to this question that I've been able to adapt and enrich to somewhat meet my needs:</p>\n\n<pre><code>import json\nimport sys\nfrom csv import writer\nimport time\nfrom datetime import datetime\n\nstartTime = datetime.now()\n\nwith open(sys.argv[1]) as in_file, \\\n open(sys.argv[2], 'w') as out_file:\n print >> out_file\n csv = writer(out_file)\n tweet_count = 0\n\n for line in in_file:\n tweet_count += 1\n try:\n tweet = json.loads(line)\n except:\n pass\n\n if not (isinstance(tweet, dict)):\n pass\n elif 'delete' in tweet:\n pass\n elif 'user' not in tweet:\n pass\n else:\n if 'entities' in tweet and len(tweet['entities']['user_mentions']) > 0:\n user = tweet['user']\n user_mentions = tweet['entities']['user_mentions']\n\n for u2 in user_mentions:\n print \",\".join([\n user['screen_name'],\n u2['screen_name']\n ])\n\n#values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]\n#csv.writerow(values)\n\nprint \"File Imported:\", str(sys.argv[1])\nprint \"# Tweets Imported:\", tweet_count\nprint \"File Exported:\", str(sys.argv[2])\nprint \"Time Elapsed:\", (datetime.now()-startTime)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:55:07.243",
"Id": "44607",
"ParentId": "44585",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44607",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:00:05.487",
"Id": "44585",
"Score": "6",
"Tags": [
"python",
"json",
"twitter"
],
"Title": "JSON data from Twitter to Edgelist?"
} | 44585 |
<p>I was writing some geometry-related code again and had a closer look at my function supposed to compute the Euclidean distance between two points (N-dimensional points by the way, hence the <code>N</code> template parameter). Here is a simplified version:</p>
<pre><code>template<std::size_t N, typename T>
auto distance(const Point<N, T>& lhs, const Point<N, T>& rhs)
-> T
{
T res{};
for (std::size_t i = 0 ; i < N ; ++i)
{
auto tmp = std::abs(lhs[i] - rhs[i]);
res += tmp * tmp;
}
return std::sqrt(res);
}
</code></pre>
<p>So far, so good. However, one very common operation is to compare the distances. Generally speaking, when comparing the distances, the <code>sqrt</code> is optimized away and the sum of the squares is compared instead of the distance itself. Therefore, I tried to create some kind of expression template to represent the distance between two points, so that users will benefit from both the ease of use and the "get rid of <code>sqrt</code> optimization" when comparing distances. Basically, the call of <code>sqrt</code> is not done until the exact value of the distance is needed. Here is the class:</p>
<pre><code>template<typename T>
struct DistanceExpression
{
explicit constexpr DistanceExpression(T data):
_data(data)
{}
operator T() const
{
return std::sqrt(_data);
}
bool operator==(const DistanceExpression& other) const
{
return _data == other._data;
}
bool operator!=(const DistanceExpression& other) const
{
return !(*this == other);
}
private:
T _data;
};
</code></pre>
<p>My new <code>distance</code> function is implemented as such:</p>
<pre><code>template<std::size_t N, typename T>
auto distance(const Point<N, T>& lhs, const Point<N, T>& rhs)
-> DistanceExpression<T>
{
T res{};
for (std::size_t i = 0 ; i < N ; ++i)
{
auto tmp = std::abs(lhs[i] - rhs[i]);
res += tmp * tmp;
}
return DistanceExpression<T>{res};
}
</code></pre>
<p><a href="http://coliru.stacked-crooked.com/a/4633825d4f98e347">Here</a> is a minimal working code at Coliru. Is such a design reasonable or is it overkill to elegantly solve this problem?</p>
| [] | [
{
"body": "<p>My concern now is that you make multiple calls to get the actual distance.<br>\nEvery-time you do that then you incur the expense of the <code>sqrt()</code> operation.</p>\n\n<p>I suppose it depends on the exact use case of your application which happens more often. But if this is for general code that could be used a lot in either capacity. I would add another two fields to indicate if it was dirty or not and cache the result so you don't have to recompute the actual value each time.</p>\n\n<p>But that has the side affect of adding a conditional branch into the get which can also be expensive when looking at micro optimizations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T08:53:49.120",
"Id": "77522",
"Score": "0",
"body": "I have the same concern actually. It can probably be partly solved with documentation, but it's not entirely satisfying. I get your point for the cache, but I don't get what you mean by \"dirty\" though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:25:59.097",
"Id": "77595",
"Score": "1",
"body": "I mean a `bool` called `dirty` and a `T` called `cache`. The `dirty` member just to indicate that the `cache` value needs re-calculating."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:31:59.337",
"Id": "77598",
"Score": "0",
"body": "Oh, ok. I thought you were talking about something more complicated. My bad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:45:29.987",
"Id": "44605",
"ParentId": "44589",
"Score": "8"
}
},
{
"body": "<p>I agree that more context is necessary to know whether this is the right approach. When I've worked with ray tracing, you more often needed to know the closest item, or that a distance was above or below some threshold, but did not need to know what the actual distance was. In those contexts, at the time, I worked with raw numbers that were explicitly the square of the distance, returned from a function called <code>distance2</code>; I think I prefer that approach.</p>\n\n<p>It looks like you're trying to hide the squares and square roots. Abstractions like that can be very useful, but come at a cost. Without the abstraction, the programmer has to track the complexity, and this means fewer other things will fit in the programmer's head at the same time. When hiding this optimization, however, you either have to make another time vs. space trade-off (for instance, you initially save time by delaying or avoiding the sqrt call, but then have to choose whether to cache the results; caching saves time but costs space). Essentially the class is trying to guess what the programmer needs, and this often goes badly.</p>\n\n<p>If memory use is a concern, you can mitigate the extra space requirements of a cache by adding complexity. Relying on the fact that no distances are negative; using a negative distance can mark whether it is the distance or its square. But despite saving the extra storage, that complexity shows up in all operators.</p>\n\n<p>How far should this abstraction go? Should you have specified comparison operators such as <code>operator<</code>? If so, should you specify them both for two <code>DistanceExpression<T></code> values as well as for a <code>T</code> and a <code>DistanceExpression<T></code> value? This could be useful if you want to write <code>if (distance(p, q) < 10)</code> without requiring the sqrt call. But again <code>if (distance2(p, q) < 100)</code> is also quite clear.</p>\n\n<p>Reviewing beyond your explicit question, good call on marking <code>DistanceExpression<T></code>'s constructor <code>explicit</code>, although was surprised that you initialized its <code>_data</code> member using parenthesis <code>()</code> instead of curly braces <code>{}</code>. Old habits die hard! I also prefer avoiding the leading underscore on member names, but it appears that only when the next letter is capital is it categorically reserved. Beware thin ice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:46:51.343",
"Id": "77769",
"Score": "0",
"body": "Concerning the relational operators, I intended to add them, but only provided `operator==` and `operator!=` in order to show the design without boilerplate here. I agree that the \"guess what the programmer want to do\" is a bet, but some documentation can help. My class `Point` doesn't provide `operator*`; there is a dedicated `Vector` class to represent vectors. And I agree that I still have trouble chaging my habits for `()` vs `{}`. Also, I know when a name is reserved in C++ and when it isn't, don't worry. Overall, thanks for the review :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T02:20:58.907",
"Id": "44721",
"ParentId": "44589",
"Score": "8"
}
},
{
"body": "<p>I find all this an overkill. Agreeing in general with <a href=\"https://codereview.stackexchange.com/a/44721/39083\">Michael Urman</a>, the programmer/user should be aware of such choices. I can clearly see at least two different functions here:</p>\n\n<pre><code>template<std::size_t N, typename T>\nT squared_distance(const Point<N, T>& lhs, const Point<N, T>& rhs)\n{\n T res{};\n for (std::size_t i = 0 ; i < N ; ++i)\n {\n auto tmp = lhs[i] - rhs[i];\n res += tmp * tmp;\n }\n return res;\n}\n\ntemplate<std::size_t N, typename T>\nT distance(const Point<N, T>& lhs, const Point<N, T>& rhs)\n{\n return std::sqrt(squared_distance(lhs, rhs));\n}\n</code></pre>\n\n<p>There are so many more useful cases for introducing expression templates, so why an extra burden for the compiler just for this?</p>\n\n<p>For instance, given <code>Point</code>'s <code>x</code>, <code>y</code>, vector subtraction</p>\n\n<pre><code>z = x - y\n</code></pre>\n\n<p>could be an expression template, so that <code>z[i] == x[i] - y[i]</code> for each <code>i</code>. Squaring each element would be another expression template, so that</p>\n\n<pre><code>z = square(x - y)\n</code></pre>\n\n<p>would have <code>z[i] == w * w</code> for each <code>i</code>, where <code>w = (x - y)[i]</code>. Then,</p>\n\n<pre><code>squared_norm(x - y)\n</code></pre>\n\n<p>would compute the actual reduction as</p>\n\n<pre><code>template<typename X>\nT sum(const X& x) { return std::accumulate(x.begin(), x.end(), X{}); }\n\ntemplate<typename X>\nT squared_norm(const X& x) { return sum(square(x)); }\n</code></pre>\n\n<p>assuming <code>Point</code> or a more general expression template are equipped with <code>begin()</code>, <code>end()</code> (which they should). Note I am not using <code>std::inner_product</code> to avoid the extra cost when <code>x</code> is a (lazy) expression template. Then, <code>squared_distance</code> would be trivial</p>\n\n<pre><code>template<typename X, typename Y>\nT squared_distance(const X& x, const Y& y) { return squared_norm(x - y); }\n</code></pre>\n\n<p>or not needed at all, while <code>distance</code> generalized as</p>\n\n<pre><code>template<typename X, typename Y>\nT distance(const X& x, const Y& y) { return std::sqrt(squared_distance(x, y)); }\n</code></pre>\n\n<p>There's more to be generalized by considering rvalue references and forwading as appropriate, but I wanted to keep this clean.</p>\n\n<p>The user should explicitly use squared Euclidean norms and distances when needed. For instance, consider this <a href=\"http://www.robots.ox.ac.uk/~vilem/cvpr2012.pdf\" rel=\"nofollow noreferrer\">scientific article</a> on nearest-neighbor search:</p>\n\n<blockquote>\n <p>In (1), the distance measures d1 and d2 in R are induced\n by d, so that for all a, b : d(a, b) = d1(a1, b1) + d2(a2, b2). The simplest and most important case is setting d, d1, and d2 to be squared Euclidean distances in respective spaces.</p>\n</blockquote>\n\n<p>In other words, we are making use of the separability of the squared Euclidean distance in product spaces. The entire algorithm is based on this choice, and your design would not help in this case.</p>\n\n<p>PS. Why would you need <code>std::abs()</code> at all? And why not just <code>std::array<T, N></code> instead of <code>Point<N, T></code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:01:35.487",
"Id": "78063",
"Score": "0",
"body": "First for the P.S. : `std::abs` is totally useless, you're right. `Point<N, T>` is supports more operations than you can see (I used a minimal implementation for this question) and I wouldn't want to compute the `distance` between two `std::array`s. BTW, my actual `Point<N, T>` implementation uses an `std::array<T, N>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:08:07.283",
"Id": "78069",
"Score": "0",
"body": "And the point scientific article quote is simply great. Thanks. I have nothing to add :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:09:52.587",
"Id": "44844",
"ParentId": "44589",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44844",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:28:23.960",
"Id": "44589",
"Score": "13",
"Tags": [
"c++",
"c++11",
"mathematics",
"template"
],
"Title": "Expression template to compute the Euclidean distance"
} | 44589 |
<p>I've taken a look at the SPL Listener/Observer model but found that it doesn't work when using static methods. So I wrote my own but it's very simply. Can anyone suggest ways to make it more like the Model standards and if there is anything obvious that I've missed?</p>
<pre><code><?php
namespace modular\core;
class Listeners{
private static $listeners = array();
private static $triggered = array();
private static $broadcasts = array();
public static function attach($event, $key, $callback){
$config = \modular\core\ModuleLoader::getModuleConfig($key);
$config['instance'] = get_class($callback[0]);
$callback['config'] = $config;
static::$listeners[$event][md5($event.$key)] = array('module' => $key, 'callback' => $callback);
}
public static function detach($event, $key, $callback){
unset(static::$listeners[$event][md5($event.$key)]);
}
public static function listeners($event = ''){
return ($event == '') ? static::$listeners : static::$listeners[$event];
}
public static function listenersRegistered(){
return static::$listeners;
}
public static function listenersTriggered(){
return static::$triggered;
}
public static function getBroadcasts(){
return static::$broadcasts;
}
public static function broadcast($event){
$rendered = \modular\core\Renderer::rendered();
$caller = debug_backtrace();//true, 1 - check version and implement this
array_shift($caller);
static::$broadcasts[$event][] = $caller;
if(isset(static::$listeners[$event])){
if(!$rendered)
ob_start();
foreach(static::$listeners[$event] as $listener){
$myEvent = (\modular\core\Router::routed() ? ($listener['module'] == \modular\core\ModuleLoader::getActiveModule()) : true);
if($myEvent){
static::$triggered[$event] = $listener;
$test = \modular\core\ModuleLoader::runModule($listener);
}
}
if(!$rendered)
ob_end_clean();
}
}
}
?>
</code></pre>
<p>The code to add a listener: </p>
<pre><code>public static function addListener($event, $callback){
$modules = \modular\core\ModuleLoader::getModules();
if(($key = array_search($callback[0], $modules)) !== false){
\modular\core\Listeners::attach($event, $key, $callback);
}
else{
//problem - object not found...
}
}
_::addListener('pre-render', array(&$this, 'init'));
</code></pre>
<p>Callback is a callback function set as an array to specify the instance </p>
<p>The MD5 is used to combine both the <code>$event</code> and <code>$key</code> as a <code>$key</code> (module) can register to multiple events and vice-versa.</p>
<p>Broadcast is purely checking if any output has already occurred, if not then block all output if so then allow output whilst it calls the module callback method.</p>
<p>Because it's a framework static methods are used as my preferred method to access a class from multiple classes without having to worry about creating variables of instances that I either have to remember globally or re-instantiating the class constantly.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:19:42.140",
"Id": "77393",
"Score": "1",
"body": "Question (maybe its just me but i want to help you out): are you asking to turn your static class into a more traditional OOP class since you are using too many static classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:24:56.107",
"Id": "77395",
"Score": "0",
"body": "@azngunit81 given that the *Observer Pattern* and *design patterns* in general are something that makes *elements of reusable **object-oriented** software*, I think an answer that approaches the OP's code from an OOP perspective would be very much valuable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:40:32.617",
"Id": "77400",
"Score": "0",
"body": "@Mat'sMug right which is why before I started to chop his code up and render it as OOP I just wanted to know if thats what he wanted because in his edit he likes static methods but what he describes can be remedy by using a SOLID approach and have the D part handle with a IoC so that he doesn't need to worry about redefining classes so much"
}
] | [
{
"body": "<p>I see several problems here:</p>\n\n<ul>\n<li><p>It's hard to understand your code because you have not documented any of the methods and their arguments. I have trouble understanding what's the purpose of <code>$event</code>, <code>$key</code> and <code>$callback</code> arguments. First off I though that <code>$callback</code> must be a the callback function, but from code it looks like it's an array of some sort. What should it contain?</p></li>\n<li><p>I don't understand why the <code>md5()</code> function is used. Why don't you just index by <code>$key</code>?</p></li>\n<li><p>The broadcast() seems to be doing some rendering and output buffering. Looks like too many responsibilities for a Listeners class that should be dealing only with event delegation.</p></li>\n<li><p>There are static references to several classes like <code>\\modular\\core\\ModuleLoader</code>. Which means your Listeners class is very tightly coupled with these. It also doesn't help my understanding of your code, as I don't have access to these classes.</p></li>\n<li><p>The fact that you have a need for a static Listeners class feels like a design smell. Too many static methods usually means you aren't really doing proper object-oriented programming, but rather just using classes as containers for your functions. Instead you should consider implementing it as a simple class with normal methods and just instantiating it as a globally available singleton.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:53:51.593",
"Id": "77386",
"Score": "0",
"body": "Have edited to clarify, let me know if it helps"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T17:37:55.350",
"Id": "44596",
"ParentId": "44591",
"Score": "6"
}
},
{
"body": "<blockquote>\n <p><em>Because it's a framework static methods are used as my preferred method to access a class from multiple classes without having to worry about creating variables of instances that I either have to remember globally or re-instantiating the class constantly.</em></p>\n</blockquote>\n\n<p>I don't do <a href=\"/questions/tagged/php\" class=\"post-tag\" title=\"show questions tagged 'php'\" rel=\"tag\">php</a>, but I'll give this one a try.</p>\n\n<p><em>Being a framework</em> shouldn't be a reason to prefer <code>static</code> methods everywhere.</p>\n\n<p>The <em>Observer Pattern</em> can be depicted as follows:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Lj7Ir.png\" alt=\"Observer pattern\"></p>\n\n<blockquote>\n <p><em>I've taken a look at the SPL Listener/Observer model but found that it doesn't work when using static methods.</em></p>\n</blockquote>\n\n<p>There's a reason for that. If I read the code correctly, then when you have a class called <code>SubjectA</code>, and register 3 observers statically, <em>every single instance</em> of <code>SubjectA</code> will have the 3 observers registered; this is unlikely to be the intended behavior (not to mention threading issues), and it's only happening because of the <code>static</code> stuff.<sup>1</sup></p>\n\n<p>It looks like your <code>Listeners</code> class is intended to be used in <em>object composition</em>, like, you'll create a <code>Car</code> class that <em>has a</em> <code>Listeners</code> instance, and you'll register listeners for an <code>Explode</code> event. Then you might have a <code>Dog</code> class that <em>has a</em>[nother] <code>Listeners</code> instance, and you'll register listeners for a <code>Bark</code> event. If I assessed the situation correctly, that will give you a barking <code>Car</code> and an exploding <code>Dog</code>, on top of the expected events.</p>\n\n<p><sub><sup>1</sup> that is, if <code>static</code> in <a href=\"/questions/tagged/php\" class=\"post-tag\" title=\"show questions tagged 'php'\" rel=\"tag\">php</a> has the same meaning as <code>static</code> in <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a>, which I'm assuming here.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:39:17.107",
"Id": "77420",
"Score": "1",
"body": "I'm always surprise when my car barks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:27:00.477",
"Id": "44604",
"ParentId": "44591",
"Score": "8"
}
},
{
"body": "<p><code>$broadcasts</code> are just for debugging purposes, right?</p>\n\n<p>My thoughts:</p>\n\n<ul>\n<li><p>The name <code>Listeners</code> sounds to me like it's an enhanced homogenous collection. Considering a core part is broadcasting I would suggest renaming. I believe Doctrine2 uses name <code>EventManager</code>, so maybe something along those lines</p></li>\n<li><p>As suggested I would consider moving away from static-ness. You can arguably keep your static method <code>::addListener()</code> and have an instance of Listeners as a static property if you really do want to keep the static access.</p>\n\n<p>But in a well-designed application (where classes have reasonable number of dependencies) handling instances shouldn't be an issue. The class will be more flexible and easier to test (for that matter I wouldn't even recommend the class itself as singleton, having just one instance can be handled as noted above).</p>\n\n<p>Take a look at <em>Misko Hevery's Guide: Writing Testable Code</em> (while individual points are arguable the overall approach is something worth at least considering).</p></li>\n<li><p>As also suggested <code>::broadcast()</code> probably does more than it should, but I don't have enough understanding of your application to make a suggestion.</p></li>\n<li><p>I would rename <code>::listeners()</code> to <code>::getListeners()</code>, for clarify and for consistency with <code>::getBroadcasts()</code>. Same for other <code>::listeners##()</code> methods. Somewhat nitpicky would be to suggest usage of <code>null</code> over an empty string to mark an empty value</p></li>\n<li><p>Don't know if it's only for clarity here, but you keep referencing classes from the same namespace as <code>Listeners</code> using their fully qualified name. You can remove all those <code>\\module\\core\\</code> as it's all in the same namespace. You may also search for <strong>use</strong> keyword, may come in handy one day.</p></li>\n<li><p>You do not have to re-instantiate instances! If you want more parts of application (say classes) to have access to a certain instance you pass the instance to them in some way (like constructor or setter injection) and assign it to a property. (don't worry about passing-by-value as in case of instances PHP actually just passes an object ID, so it is pretty much a reference).</p></li>\n<li><p>MD5 is not needed, PHP indexes are already being hashed. Some nice articles: </p>\n\n<ul>\n<li><p><a href=\"http://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html\" rel=\"nofollow\">Understanding PHP's internal array implementation</a></p></li>\n<li><p><a href=\"http://www.phpinternalsbook.com/hashtables/hash_algorithm.html\" rel=\"nofollow\">Hash algorithm and collisions</a></p></li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T06:42:06.507",
"Id": "387575",
"Score": "0",
"body": "The convention for PHP namespaces is the same for classes: they should be in PascalCase, i.e. `namespace Modular\\Core;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-09T15:37:51.273",
"Id": "387663",
"Score": "0",
"body": "@CJDennis I don't see how this relates to my answer, would probably be better to post it under the question or as an answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:06:30.530",
"Id": "44621",
"ParentId": "44591",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:30:56.420",
"Id": "44591",
"Score": "10",
"Tags": [
"php",
"design-patterns",
"mvc",
"php5"
],
"Title": "Listener/Observer Model in PHP"
} | 44591 |
<p>I'm implementing an algorithm that traverses a graph of nodes (after a given input) and outputs 3 things:</p>
<ol>
<li>Number of Strongly connected components </li>
<li>Size of the largest strongly connected component</li>
<li><p>(And here I think is the step that slows down my algorithm) The number of SCC's that are ONLY connected between them.</p>
<p>This means that, for every node in that SCC, none of them has a path to other nodes outside the SCC. Only other nodes outside of the SCC connect to them. Like they are isolated inside the SCC.</p>
<p>If this isn't clear, please tell me so I can rephrase.</p></li>
</ol>
<p>Here's the code and how to use it:</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Tarjan {
int time;
static int N;
static int P;
List<Integer>[] graph;
int[] lowlink;
boolean[] used;
List<Integer> stack;
List<List<Integer>> components;
int maxSize = 0;
private int getMaxSize() {
return maxSize;
}
public List<List<Integer>> scc(List<Integer>[] graph) {
int n = graph.length;
this.graph = graph;
lowlink = new int[n];
used = new boolean[n];
stack = new ArrayList<Integer>();
components = new ArrayList<List<Integer>>();
for (int u = 0; u < n; u++)
if (!used[u])
dfs(u);
return components;
}
void dfs(int u) {
lowlink[u] = time++;
used[u] = true;
stack.add(u);
boolean isComponentRoot = true;
for (int v : graph[u]) {
if (!used[v])
dfs(v);
if (lowlink[u] > lowlink[v]) {
lowlink[u] = lowlink[v];
isComponentRoot = false;
}
}
if (isComponentRoot) {
List<Integer> component = new ArrayList<Integer>();
while (true) {
int k = stack.remove(stack.size() - 1);
component.add(k);
lowlink[k] = Integer.MAX_VALUE;
if (k == u)
break;
}
int size = component.size();
if (size > this.maxSize)
maxSize = size;
components.add(component);
}
}
public static void main(String[] args) {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
String s = read.readLine();
String[] parts = s.split(" ");
String part1 = parts[0];
String part2 = parts[1];
N = Integer.parseInt(part1);
P = Integer.parseInt(part2);
} catch (IOException e) {
e.printStackTrace();
}
int counter = 0;
@SuppressWarnings("unchecked")
List<Integer>[] g = new List[N];
for (int i = 0; i < g.length; i++) {
g[i] = new ArrayList<Integer>();
}
while (counter < P) {
String s;
try {
s = read.readLine();
String[] parts = s.split(" ");
String part1 = parts[0];
String part2 = parts[1];
int x = Integer.parseInt(part1);
int y = Integer.parseInt(part2);
g[x - 1].add(y - 1);
} catch (IOException e) {
e.printStackTrace();
}
counter++;
}
Tarjan t = new Tarjan();
List<List<Integer>> components = t.scc(g);
System.out.println(components.size());
/* Check note 1 below that explains this part of the algorithm */
int isolatedScc = 0;
int contains = 1;
for (List<Integer> sccList : components) {
int i;
contains = 1;
for (i = 0; i < g.length; i++) {
if (sccList.contains(i))
continue;
else {
for (Integer nodeInScc : sccList) {
List<Integer> nodesConnectedToTheNodesInSCC = g[nodeInScc];
if (nodesConnectedToTheNodesInSCC.contains(i)) {
contains = 0;
break;
}
}
}
}
if (contains == 1)
isolatedScc++;
}
System.out.println(t.getMaxSize());
System.out.println(isolatedScc);
}
}
</code></pre>
<p>To test the program, simply run it. It will wait for your input. The first two number you input will define the number of nodes and the number of connection. The rest of the lines define the connections between nodes.</p>
<pre><code>5 4
1 2
1 3
2 3
4 1
</code></pre>
<p>In this example we have: number of nodes: 5. Number of connections between nodes: 4 The rest of the lines are the 4 connections between the 5 nodes.</p>
<p><strong>Note 1:</strong></p>
<p>This is the part of the algorithm that I think slows it down a lot. Basically what I'm doing here is, for every node in the SCCS, check any node that isn't inside that SCC and check any of them has a connection to any node outside of the SCC (that is, a path between that node to the node outside of the SCC). If so, then break. If it reaches the end of the loop, than that situation doesn't happen. So increase a counter</p>
<p>Is there any possible way I can speed up this thing? I compiled it with jdk1.6.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:40:39.493",
"Id": "77401",
"Score": "0",
"body": "Your sentences `This means that, for every node in that SCC, none of them has a path to other nodes outside the SCC. Only other nodes outside of the SCC connect to them.` seem to contradict each other. Please clarify this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:15:01.590",
"Id": "77413",
"Score": "0",
"body": "Uh, im not native english so i have a had a hard time explaining that xD. What i want to mean is, an SCC where the nodes ONLY connect to the inside that SCC. Its like they are isolated. Other nodes (outside of that SCC) can reach them, but the nodes of that SCC can ONLY reach eachother (like in cycle)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:01:33.517",
"Id": "77427",
"Score": "0",
"body": "I don't understand the third point, either. And when you say \"connection\", I assume you mean \"edge\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:26:57.573",
"Id": "77437",
"Score": "0",
"body": "@riotvan: It will be hard to discuss if even the basic understanding is missing. But still you could try drawing images that explain what you mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:16:49.310",
"Id": "77456",
"Score": "0",
"body": "http://i.imgur.com/fYZCCPM.png This is what i want to do. The nodes in the SCC on red, have edges only to them selfs, not to any node outside the SCC. This is want i want to calculate. The number of groups where this happens"
}
] | [
{
"body": "<h2>Generics</h2>\n\n<p>Java Generics will not accept the declaration: <code>List<Integer>[]</code> You cannot have an array of a generically typed component. There are ways to make it neater, but, you should be using <code>List<List<Integer>></code> in a general case.</p>\n\n<h2>Variable names</h2>\n\n<p>Variables like <code>n</code>, <code>t</code>, <code>N</code>, <code>P</code>, <code>u</code>, etc. are not helpful. They make the code hard to read and understand. Use descriptive variable names. It helps. A lot!</p>\n\n<h2>Variable Scope</h2>\n\n<p>Static non-final variables are almost always a sign of bad ObjectOriented design:</p>\n\n<blockquote>\n<pre><code>static int N;\nstatic int P;\n</code></pre>\n</blockquote>\n\n<p>These should be final instance variables on your class, or something, but setting them in the main method and using them in an instance method is backward. It also means you can only have one (working) instance of your graph.</p>\n\n<h2>Object Structure</h2>\n\n<p>Your class is not a class.... it is a procedural mashup. You have a procedural system for setting up your graph (which is contained in two Lists), and then you create a TarJan instance for no particular reason other than that the methods are not static.... You then delegate some work to the TarJan instance, pull the results back in to the main method, and then procedurally complete the process.</p>\n\n<p>This is a poor design.</p>\n\n<p>The graph should be self-contained in a single instance object, and its data structure should all be internal.</p>\n\n<p>Java Functions should also have a single-responsibility defined in the function: do one thing, and one thing well.</p>\n\n<p>Your main method should look more like:</p>\n\n<pre><code>public void main (String[] args) {\n Graph graph = buildGraphFromStdIn();\n System.out.println(\"Component Count: \" + graph.getComponentCount());\n System.out.println(\"Largest SCC Size: \" + graph.getLargestComponentSize());\n ....\n}\n</code></pre>\n\n<h2>Performance</h2>\n\n<p>Performance should normally come after functionality. At the moment, your code needs a fix-up with respect to conventions and style. As you go through the code mobing things in to neat compartments, you will likely find the performance improves simply because you structure things better, and notice where things go wrong.</p>\n\n<p>At the moment, it is pretty hard to see what is happening, so I am not particularly inclined to dig though it and guess what's going wrong (performance wise).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:13:34.830",
"Id": "77455",
"Score": "0",
"body": "Yeah i know about that, but for this assignment, i just have to submit a simple code like this. The design or the architecture wont be evaluated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:14:03.247",
"Id": "77590",
"Score": "0",
"body": "@riotvan Just because the architecture won't be evaluated doesn't mean you have to write badly structured code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:51:21.317",
"Id": "44616",
"ParentId": "44599",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T18:35:22.867",
"Id": "44599",
"Score": "5",
"Tags": [
"java",
"algorithm",
"performance"
],
"Title": "Speeding up this Tarjan's algorithm"
} | 44599 |
<p>Here is a fast recursive Fibonacci-like <code>for</code> loop. How can it be more readable, and is it possible remove <code>TArg</code>s? </p>
<pre><code>public static class Fibonacci
{
public static BigInteger Calculate(BigInteger number)
{
var fibo = AnonRecursiveFiboFunc<BigInteger>(
func => (step, fibo1, fibo2) => step == number
? fibo2
: func(++step, fibo1 + fibo2, fibo1));
return fibo(0, 1, 0);
}
delegate Func<TArg1, TArg2, TArg3, TArg4>
Recursive<TArg1, TArg2, TArg3, TArg4>(
Recursive<TArg1, TArg2, TArg3, TArg4> r);
private static Func<TArg, TArg, TArg, TArg>
AnonRecursiveFiboFunc<TArg>(Func<Func<TArg, TArg, TArg, TArg>,
Func<TArg, TArg, TArg, TArg>> function)
{
Recursive<TArg, TArg, TArg, TArg> recursive =
rec => (step, fibo1, fibo2) =>
function(rec(rec))(step, fibo1, fibo2);
return recursive(recursive);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:41:22.003",
"Id": "77422",
"Score": "0",
"body": "I'm not sure I understand why you are using a delegate instead of using an actual function. It seems to me like this is taking the scenic route instead of the interstate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:03:31.830",
"Id": "77428",
"Score": "0",
"body": "i use delegate because i want try it with delegates :) but i dont like multiple TArg's. \nAnd i know this is not the best way. I test what can i do with delegates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:40:10.723",
"Id": "77471",
"Score": "1",
"body": "I always get confused by this kind of recursion. Is this supposed to be [the Y combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator)?"
}
] | [
{
"body": "<ol>\n<li><p>I like to say <code>T1</code> <code>T2</code> instead of <code>TArg1</code>, it just makes it more clear to me what is going on. Your code would look more like this.</p>\n\n<pre><code>delegate Func<T1, T2, T3, T4> Recursive<T1, T2, T3, T4>( Recursive<T1, T2, T3, T4> r);\n\nprivate static Func<T, T, T, T> AnonRecursiveFiboFunc<T>(Func<Func<T, T, T, T>, Func<T, T, T, T>> function)\n{\n Recursive<T, T, T, T> recursive = rec => (step, fibo1, fibo2) => function(rec(rec))(step, fibo1, fibo2);\n return recursive(recursive);\n}\n</code></pre></li>\n</ol>\n\n<p>Other than that... this code seems pretty solid, except for the crazy lack of immediate readability :D and like mentioned in the comments the fact that you are using delegates at all here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:01:11.997",
"Id": "44617",
"ParentId": "44602",
"Score": "5"
}
},
{
"body": "<p>The opposite of BenVlodgi's answer: i.e. <code>AnonRecursiveFiboFunc<TArg></code> has only one template parameter, therefore all the template arguments passed to <code>Recursive<TArg, TArg, TArg, TArg> recursive</code> are the same, therefore there only needs to be one of them.</p>\n\n<p>You can rewrite the code as:</p>\n\n<pre><code> delegate Func<T, T, T, T> Recursive<T>(Recursive<T> r);\n\n private static Func<TArg, TArg, TArg, TArg>\n AnonRecursiveFiboFunc<TArg>(Func<Func<TArg, TArg, TArg, TArg>,\n Func<TArg, TArg, TArg, TArg>> function)\n {\n Recursive<TArg> recursive =\n rec => (step, fibo1, fibo2) =>\n function(rec(rec))(step, fibo1, fibo2);\n return recursive(recursive);\n }\n</code></pre>\n\n<p>Given that all the arguments passed to Func are the same, you can reduce it further by defining your own delegate (which I named Function3) as follows:</p>\n\n<pre><code> delegate T Function3<T>(T arg1, T arg2, T arg3);\n\n delegate Function3<T> Recursive<T>(Recursive<T> r);\n\n private static Function3<TArg>\n AnonRecursiveFiboFunc<TArg>(Func<Function3<TArg>,\n Function3<TArg>> function)\n {\n Recursive<TArg> recursive =\n rec => (step, fibo1, fibo2) =>\n function(rec(rec))(step, fibo1, fibo2);\n return recursive(recursive);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:59:02.423",
"Id": "77497",
"Score": "1",
"body": "I almost suggested this, but because he was using BigInteger for one type and not for the others, I didn't. Although I guess 3 of them could have indeed been collapsed.... unless I read it wrong o_O"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T07:31:12.170",
"Id": "77515",
"Score": "0",
"body": "Ok i see it now :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T11:34:01.503",
"Id": "77541",
"Score": "0",
"body": "@BenVlodgi He wasn't using BigInteger for one type and not for the others: BigInteger is the only type because there is only one type, i.e. the type that's passed to the `AnonRecursiveFiboFunc<TArg>` method, which only has one template parameter. I downvoted your answer because your suggestion made that even less clear, not \"more clear\" as you said."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T11:43:34.480",
"Id": "77543",
"Score": "0",
"body": "@ChrisW The only thing I suggested was that he rename his T arguments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:03:35.807",
"Id": "77550",
"Score": "1",
"body": "I already liked @ChrisW's answer. It's good option with yours."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:15:02.117",
"Id": "44622",
"ParentId": "44602",
"Score": "5"
}
},
{
"body": "<p>I know you said you liked using delegates, and you wanted to see what you could do with them. But I think its good to recognize when you don't need to make your own.</p>\n\n<p>Here is a simpler refactored version of your code. It does not use your <code>A non recursive function</code> delegate. Also, technically what you were doing before was recursion still. </p>\n\n<pre><code>public static BigInteger Calculate(BigInteger number)\n{\n Func<BigInteger, BigInteger, BigInteger, BigInteger> fibo = null;\n fibo = ((step, fibo1, fibo2) => (step == number) ? fibo2 : fibo(++step, fibo1 + fibo2, fibo1));\n return fibo(0, 1, 0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:38:35.833",
"Id": "77777",
"Score": "0",
"body": "i use another method because i dont like `= null;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:58:47.573",
"Id": "77792",
"Score": "0",
"body": "@VictorTomaili I didn't like it either... but that is a bit over-kill :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T23:16:04.470",
"Id": "446042",
"Score": "0",
"body": "`Func<> fibo = null;` is required to provide an instantiation, prior to the definition; somewhat like a forward reference."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:36:01.347",
"Id": "44668",
"ParentId": "44602",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:19:49.803",
"Id": "44602",
"Score": "10",
"Tags": [
"c#",
"recursion",
"generics",
"fibonacci-sequence"
],
"Title": "Recursive Fibonacci with Generic delegates"
} | 44602 |
<p>I have written an age calculator that takes a <code>birthDate</code> as input.</p>
<p>I'd like a general review of this. I'm especially concerned about the <code>message</code> variable and the lines after the <code>try/catch</code> statement.</p>
<pre><code>namespace Age
{
class Program
{
static void Main(string[] args)
{
while (true)
{
try
{
Console.Write("Enter your birtdate: ");
DateTime birthDate = DateTime.Parse(Console.ReadLine());
int Days = (DateTime.Now.Year * 365 + DateTime.Now.DayOfYear) - (birthDate.Year * 365 + birthDate.DayOfYear);
int Years = Days / 365;
string message = (Days >= 365) ? "Your age: " + Years + " years" : "Your age: " + Days + " days";
Console.WriteLine(message);
}
catch
{
Console.WriteLine("You have entered an invalid date.\n");
}
Console.WriteLine("Exit? (y/n)");
string userValue = Console.ReadLine();
if (userValue == "y")
{
Environment.Exit(0);
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:52:56.253",
"Id": "77424",
"Score": "0",
"body": "Is there something specific that you would like a feedback about your code or you just want a general review ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:56:19.670",
"Id": "77426",
"Score": "1",
"body": "Should this be tagged [tag:homework]? Leap-years contain 366 days."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:05:25.707",
"Id": "77429",
"Score": "0",
"body": "I just wanted a general review. Still, I'm a little uncertain about the \"string message\"-variable and the lines after the try-catch statement. I've never really terminated an application like this before.\n\nThis is not homework, just me programming on hobby basis."
}
] | [
{
"body": "<blockquote>\n<pre><code>Console.Write(\"Enter your birtdate: \");\nDateTime birthDate = DateTime.Parse(Console.ReadLine());\n</code></pre>\n</blockquote>\n\n<p>Your <code>catch</code> block looks like it's assuming a <code>ParseException</code> that would be thrown by the above <code>DateTime.Parse</code> call. Thus, it would be better to be explicit about it:</p>\n\n<pre><code>catch(ParseException)\n{\n Console.WriteLine(\"You have entered an invalid date.\\n\");\n}\n</code></pre>\n\n<p>This way, if <em>another exception type</em> is thrown somewhere else in the loop, you will not be displaying a misleading message.</p>\n\n<p>Now, how about using <a href=\"http://msdn.microsoft.com/en-us/library/w2sa9yss%28v=vs.110%29.aspx\">DateTime.ParseExact</a>, and specify what would be the expected date format?</p>\n\n<pre><code>Console.Write(\"Enter your birtdate (yyyy-MM-dd): \");\nDateTime birthDate = DateTime.ParseExact(Console.ReadLine(), \"yyyy-MM-dd\", CultureInfo.InvariantCulture);\n</code></pre>\n\n<p>That's all great, too many things are happening in a single line of code here:</p>\n\n<ul>\n<li><code>Controle.ReadLine()</code> is getting the console input</li>\n<li><code>DateTime.Parse</code> | <code>DateTime.ParseExact</code> is parsing the console input</li>\n</ul>\n\n<p>You should break this down into 2 separate instructions:</p>\n\n<pre><code>Console.Write(\"Enter your birtdate (yyyy-MM-dd): \");\nvar input = Console.ReadLine();\nvar birthDate = DateTime.ParseExact(input, \"yyyy-MM-dd\", CultureInfo.InvariantCulture);\n</code></pre>\n\n<p>Note that I'm using <code>var</code> for brevety here, <code>input</code> is a <code>string</code> and <code>birthDate</code> is a <code>DateTime</code>.</p>\n\n<p>The next step would be to <em>extract a method</em> out of these few lines - have a method called <code>GetBirthDate</code> that returns a <code>DateTime</code>, or throws a <code>ParseException</code> that your <code>catch</code> block can handle.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:09:18.677",
"Id": "44609",
"ParentId": "44606",
"Score": "17"
}
},
{
"body": "<ol>\n<li><p>You should give the user some format to follow when entering their birthday</p>\n\n<pre><code>Console.Write(\"Enter your birthdate (MM/DD/YYYY): \");\n</code></pre></li>\n<li><p>You should give the user a way to close the program. While this isn't incredibly necessary for simple learning programs, it is a good habit to get into.</p></li>\n<li><p>You should avoid throwing exceptions, they break up your program's flow. Certainly use them where necessary, but this is not one of those places. Exceptions should be used in situations when your function doesn't have the ability to handle a situation/error.</p>\n\n<p>In the following snippet, I've declared the DateTime object, and a Boolean which will tell us if the string entered by the user was able to be parsed. Notice how I am calling the TryParse Method. The TryParse method takes in a string, and an <code>out</code> <code>DateTime</code> <code>object</code>. This is important, the out keyword is a bit more advanced than you have come accross. It is a keyword which implements functionality programmers were used to in C using pointers. Suffice to say that this function will set whatever object you pass in, to be the parsed value. </p>\n\n<pre><code>DateTime birthDate;\nbool succeeded = DateTime.TryParse(Console.ReadLine(), out birthDate);\n</code></pre>\n\n<p>Because the TryParse method returns a bool you can just use this in an if statement which is conditional on the TryParse returning true.</p>\n\n<pre><code>if(DateTime.TryParse(Console.ReadLine(), out birthDate))\n{\n // more stuff\n}\nelse\n Console.WriteLine(\"You have entered an invalid date.\");\n</code></pre></li>\n<li><p>I noticed you used <code>\\n</code> in your program. While I will say that I am guilty of using this all the time, you should actually use <code>Environment.NewLine</code>. The reason is because of in-consistency of newline/carriage returning in different programs. <code>Environment.NewLine</code> always uses the proper line ending. </p>\n\n<pre><code>Console.WriteLine(\"You have entered an invalid date.\" + Environment.NewLine);\n</code></pre></li>\n<li><p>You can use + or - operators on DateTime objects which results in a TimeSpan object</p>\n\n<pre><code>TimeSpan age = DateTime.Now - birthDate;\n</code></pre>\n\n<p>TimeSpan objects have properties like Days, Hours. the calculation done, does take into consideration leap years.</p></li>\n<li><p>Printing to the console can be made easier by sending parameters to be inserted into your string.</p>\n\n<pre><code>Console.WriteLine(\"Your age: {0} years and {1} days\", (int)(age.Days/365.25), age.Days % 365.25);\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p>Over all, your program could look like this. Note: I didn't programatically address the issue of the user escaping your program, I noticed you updated your OP with that.</p>\n\n<pre><code>while (true)\n{\n Console.Write(\"Enter your birtdate (MM/DD/YYYY): \");\n DateTime birthDate;\n if (DateTime.TryParse(Console.ReadLine(), out birthDate))\n {\n TimeSpan age = DateTime.Now - birthDate;\n Console.WriteLine(\"Your age: {0} years and {1} days\", (int)(age.Days/365.25), age.Days % 365.25);\n }\n else\n Console.WriteLine(\"You have entered an invalid date.\" + Environment.NewLine);\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong>: This is of-course personal taste, but I dislike (what I consider to be unnessary brackets taking up newlines).</p>\n\n<pre><code>else\n{\n Console.WriteLine(\"You have entered an invalid date.\" + Environment.NewLine);\n}\n</code></pre>\n\n<p>Some people prefer that, I just am not, and that is up to every coder to decide. If I was to put brackets arround that, I would probably do it this way</p>\n\n<pre><code>else\n { Console.WriteLine(\"You have entered an invalid date.\" + Environment.NewLine); }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:47:15.497",
"Id": "77472",
"Score": "0",
"body": "I think that even better than `NewLine` would be to use a separate second `Console.WriteLine()` for the second newline."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:50:36.700",
"Id": "77473",
"Score": "1",
"body": "Also, I don't think using 365.25 makes sense here. For example, `700 % 365.25` is `334.75`, I don't think that's what you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:48:28.747",
"Id": "77637",
"Score": "0",
"body": "3. Your if-else statement looks really weird to me since the `if` part is using bracket and the `else` one don't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:52:28.783",
"Id": "77639",
"Score": "0",
"body": "@svick I almost suggested that, but I wanted him to be aware of Environment.Newline. Also, the 365.25 was just to account for leapyear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:53:58.390",
"Id": "77641",
"Score": "1",
"body": "@Marc-Andre its up to you to bracket how you feel, while they don't match, I think single lines look ugly when surrounded by brackets. If you wanted to you could even put brackets at the beginning and ending of the line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T17:00:33.950",
"Id": "77644",
"Score": "0",
"body": "@BenVlodgi `I think single lines look ugly when surrounded by brackets.` well I won't bother you with that again since I strongly disagree with that, since it's a personal taste!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T17:05:28.847",
"Id": "77645",
"Score": "0",
"body": "@Marc-Andre yes it is just a coder choice, I did add an edit showing what I meant by my earlier statement."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:25:38.827",
"Id": "44612",
"ParentId": "44606",
"Score": "17"
}
},
{
"body": "<p>To calculate the date difference properly, you need to take leap years into account. And you need to use the proper rules for deciding when is a leap year. Fortunately, the .Net libraries already know all that.</p>\n\n<p>So, how to do it? Find out the person's last birthday and then calculate the year difference since the birth date and then the day difference until today. In code:</p>\n\n<pre><code>public static Tuple<int, int> GetDifferenceInYearsAndDays(DateTime birth, DateTime today)\n{\n if (birth > today)\n throw new InvalidOperationException();\n\n var thisYearBirthday = new DateTime(today.Year, birth.Month, birth.Day);\n var lastBirthday =\n thisYearBirthday <= today ? thisYearBirthday : thisYearBirthday.AddYears(-1);\n\n int years = lastBirthday.Year - birth.Year;\n int days = (today - lastBirthday).Days;\n\n return Tuple.Create(years, days);\n}\n</code></pre>\n\n<p>This might be more complicated than your code, but it's correct, and I also think that it's more readable.</p>\n\n<p>The code is in a separate method, to follow <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\">separation of concerns</a>.</p>\n\n<hr>\n\n<p>One more thing: whenever you use <code>DateTime.Now</code> (or <code>DateTime.Today</code>), you should access that property only once and store that value in a variable, or something. Otherwise, your code might have a really weird bug while everyone else is celebrating New Year.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T11:52:29.657",
"Id": "77547",
"Score": "0",
"body": "I just realized that this won't work if the birth date is on 29 February. Not sure how to fix that, while still keeping the code relatively simple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T12:36:17.990",
"Id": "78273",
"Score": "1",
"body": "Assuming that in a leap year the birthday is on 28 February: `thisYearBirthday = new DateTime(today.Year, birth.Month, birth.Day > DateTime.DaysInMonth(today.year, birth.Month) ? DateTime.DaysInMonth(today.year, birth.Month) : birth.Day)`. But introducing a variable for DaysInMonth would be better. Maybe this would make the code not so simple anymore"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T23:28:35.673",
"Id": "44627",
"ParentId": "44606",
"Score": "11"
}
},
{
"body": "<p>I was going to edit my other answer, but instead I'm going to take a different approach - I mean, I'll push it to the extreme ;)</p>\n<hr />\n<blockquote>\n<h1>Warning</h1>\n<p><em>I'll push it to the extreme</em> is to be taken literally. This solution doesn't aim at solving the <em>simple age calculator</em> problem, rather at showing how one would architect a SOLID application - <em>if the goal is just to calculate the difference between two dates, this is absolute overkill</em>. If the goal is to learn how to write good OOP using a trivial/simple problem as an excuse...</p>\n<p><strong>Buckle up, you're in for a ride.</strong></p>\n</blockquote>\n<hr />\n<h3>static void Main(string[] args)</h3>\n<p>As you know by now, this is your application's <em>entry point</em>. When this <code>static</code> method returns, the program ends. To terminate your program, simply use <code>return;</code> in this method, or structure your program flow so that <em>normal exit</em> simply causes the main thread (imagine a cursor running each instruction sequentially - or <em>step through</em> your code in the debugger) to reach the bottom of the <code>Main</code> method.</p>\n<p>This method being <code>static</code>, if you're going to call anything outside of it, it's going to have to be <code>static</code> as well. If you're writing <em>procedural</em> code, it doesn't matter.</p>\n<p>If you want <em>object-oriented</em> code, the <code>Main</code> method will probably have a very high <em>level of abstraction</em>, and will read like pseudo-code, if not like plain English.</p>\n<p>The method revolves around the idea that it's a program's birth, life, and death.</p>\n<p><em>Dependency Injection</em> (DI) disciples (guilty!) call this entry point, the <em>composition root</em>. This is where you <em>instantiate</em> the application (and its <em>dependencies</em>), and run it.</p>\n<p>Simplified to the extreme:</p>\n<pre><code>static void Main(string[] args)\n{\n var app = new MyApplication();\n app.Run();\n}\n</code></pre>\n<p>What's in the <code>Run()</code> method?</p>\n<pre><code>public class MyApplication\n{\n public MyApplication()\n {\n // initialisation here\n }\n\n public void Run()\n {\n // app logic here\n }\n}\n</code></pre>\n<p>Notice that the <code>Run</code> method is <em>not</em> <code>static</code>. It exists only as a <em>member</em> of the <em>interface</em> of an <em>object</em> defined by this <code>MyApplication</code> class - in other words, you need an <em>instance</em> of <code>MyApplication</code> to call this method.</p>\n<p>In this case the <em>application logic</em> part will feature our main loop, from which we will exit based on a condition.</p>\n<pre><code>public void Run()\n{\n var keepRunning = true;\n\n while(keepRunning)\n {\n // application logic\n keepRunning = false; // exit\n }\n}\n</code></pre>\n<p>At this point, we've reached a <em>point of no return</em>. Anything else we code in the <code>Run</code> method will impact maintainability, testability, and readability. Better keep it to a minimum.</p>\n<hr />\n<p>The key resides in <em>delegating the work</em>. The <code>MyApplication</code> class cannot do its work alone without using the <code>new</code> keyword, which would <em>increase coupling</em>, and without doing the work all by itself, which would <em>decrease cohesion</em>. Since we want <em>low coupling</em> and <em>high cohesion</em>, we'll start by avoiding the use of <code>static</code> methods and of the <code>new</code> keyword.</p>\n<blockquote>\n<p><strong>Why?</strong></p>\n<p><em>Good code is testable code</em>. You'll want to be able to write tests for the code you write - whether you write these tests or not, writing <em>testable</em> code will tend to produce code that is more <em>cohesive</em> and less <em>coupled</em>.</p>\n<p><sub><strong>See also:</strong> <a href=\"https://stackoverflow.com/a/3085419/1188513\">https://stackoverflow.com/a/3085419/1188513</a></sub></p>\n</blockquote>\n<h3>IUserInteraction</h3>\n<p>We know we want to use the console to interact with the user, but in order to test our application logic, we'll want to be able to substitute the user's input for whatever our tests need.</p>\n<pre><code>public interface IUserInputProvider\n{\n string GetUserInput(string prompt);\n T GetUserInput<T>(string prompt, IUserInputValidator<T> validator);\n}\n</code></pre>\n<p>With that - and that only, we already have enough to go back to the <code>MyApplication</code> class:</p>\n<pre><code>public class MyApplication\n{\n private readonly IUserInputProvider _inputProvider;\n\n public MyApplication(IUserInputProvider inputProvider)\n {\n _inputProvider = inputProvider;\n }\n\n public void Run()\n {\n var keepRunning = true;\n\n while(keepRunning)\n {\n var prompt = "Enter your birth date:";\n var input = _inputProvider.GetUserInput(prompt); // no validation for now\n // ...\n\n keepRunning = false; // exit\n }\n }\n}\n</code></pre>\n<p>I'll get back to the <code>IUserInputValidator<T></code> later.</p>\n<blockquote>\n<p><strong>Mocking</strong></p>\n<p><code>GetUserInput</code> is a method that returns a <code>string</code>. Nothing more, nothing less. We <em>know</em> that we want to call <code>Console.ReadLine()</code>, but that's an <em>implementation detail</em> that the <code>MyApplication</code> class does not need to know about.</p>\n<p>If we were to write a test to see if the <code>Run</code> method effectively exits when the user enters "y", we would not bring up a console and wait for someone to enter "y" - instead we would set up a <em>mock</em> - a "fake" implementation of the <code>IUserInputProvider</code> interface that returns "y" when we ask it to <code>GetUserInput</code>.</p>\n</blockquote>\n<p><strong>Implementation</strong></p>\n<p>The concrete implementation we're going to be using will use the console. Nothing prevents making another concrete implementation that pops up a dialog window instead - as long as we use a <code>prompt</code> and return a <code>string</code>, anything can work. This means the implementation(s) can be modified in every possible way, the only assumption the <code>MyApplication</code> class makes is that there's a <code>GetUserInput</code> method that takes a <code>string prompt</code> and returns a <code>string</code>.</p>\n<p>This could be an implementation:</p>\n<pre><code>public class ConsoleUserInputProvider : IUserInputProvider\n{\n public string GetUserInput(string prompt)\n {\n Console.WriteLine(prompt);\n return Console.ReadLine();\n }\n\n public T GetUserInput<T>(string prompt, IUserInputValidator<T> validator)\n {\n string input;\n T result;\n\n var isValidInput = false;\n while(!isValidInput)\n {\n input = GetUserInput(prompt);\n isValidInput = validator.Validate(input, out result);\n }\n\n return result;\n }\n}\n</code></pre>\n<p>Where <code>IUserInputValidator</code> is yet another abstraction that exposes a <code>bool Validate(string input)</code> method.</p>\n<p>Let's make it a generic interface:</p>\n<pre><code>public interface IUserInputValidator<T>\n{\n bool Validate(string input, out T result);\n}\n</code></pre>\n<p>One could implement it like this:</p>\n<pre><code>public class BirthDateValidator : IUserInputValidator<DateTime>\n{\n public bool Validate(string input, out DateTime result)\n {\n return DateTime.TryParse(input, out result);\n }\n}\n</code></pre>\n<p>Or like this:</p>\n<pre><code>public enum YesNoResult\n{\n Unknown,\n Yes,\n No\n}\n\npublic class YesNoValidator : IUserInputValidator<YesNoResult>\n{\n private readonly IDictionary<string, YesNoResult> _values;\n\n public YesNoValidator(IDictionary<string, YesNoResult> values)\n {\n _values = values;\n }\n\n public bool Validate(string input, out YesNoResult result)\n {\n if (string.IsNullOrEmpty(input))\n {\n throw new ArgumentException("input", "input string is empty.");\n }\n\n var lowerCase = input.Substring(0, 1).ToLower();\n \n var isValue = values.TryGetValue(lowerCase, out result);\n if (!isValue)\n {\n result = YesNoResult.Unknown;\n }\n \n return (result != YesNoResult.Unknown);\n }\n}\n</code></pre>\n<hr />\n<p>As you can see, this approach produces very focused and specialized code - code that does one thing, so well, that it can't possibly even <em>need</em> to change. And yet it remains extensible - you could <em>decorate</em> any <code>Validator</code> implementation with, say, a <code>ValidationLoggerDecorator</code> that can log all failed validations:</p>\n<pre><code>public class ValidationLoggerDecorator<T> : IUserInputValidator<T>\n{\n private readonly IUserInputValidator<T> _validator;\n private readonly ILogger _logger;\n\n public ValidationLoggerDecorator(IUserInputValidator<T> validator, ILogger logger)\n {\n _validator = validator;\n _logger = logger;\n }\n\n public bool Validate(string input, out T result)\n {\n var isValid = _validator.Validate(input, out result);\n\n if (!isValid)\n {\n _logger.Info(string.Format("Validation failed for input '{0}'.", input));\n }\n\n return isValid;\n }\n}\n</code></pre>\n<p>Let's step back and take a look at what we've got here:</p>\n<ul>\n<li><p>The code remains focused on a <em>single responsibility</em> - following the <em>Single Responsibility Principle</em>.</p>\n</li>\n<li><p>The extensibility depicted with the decorator example, is a side-effect of the <em>Open/Closed</em> principle: a class is closed for modification, open for extension.</p>\n</li>\n<li><p>The fact that the <code>MyApplication</code> class can work with any implementation of the <code>IUserInputProvider</code> interface, regardless of what dependencies that implementation might have, is a side-effect of the <em>Liskov Substitution Principle</em>.</p>\n</li>\n<li><p>Following the <em>Interface Segregation Principle</em> makes our interfaces be very focused as well, <em>ideally</em> exposing only a single member. This point greatly influences <em>cohesion</em>.</p>\n</li>\n<li><p>The fact that all <em>implementations</em> ("concrete" classes) <em>depend on abstractions</em>, and that these <em>dependencies</em> are <em>injected</em> into their constructor, is following the Dependency Inversion Principle*.</p>\n</li>\n</ul>\n<p>Together, these 5 points spell <a href=\"http://en.wikipedia.org/wiki/Solid_(object-oriented_design)\" rel=\"noreferrer\">SOLID</a>.</p>\n<hr />\n<p>The <code>IUserInputValidator</code> we're passing to the <code>GetUserInput()</code> method, must come from somewhere. But if we create a <code>new BirthDateValidator()</code> our class will be <em>tightly coupled</em> with that specific implementation, and it will become very hard to test the <code>GetUserInput()</code> method and control validation from the outside.</p>\n<p>The <code>MyApplication</code> class can receive the validators it needs in its constructor, and we can extract some of the logic from the <code>Run</code> method, into their own private methods:</p>\n<pre><code>public class MyApplication\n{\n private readonly IUserInputProvider _inputProvider;\n private readonly IUserInputValidator<DateTime> _dateValidator;\n private readonly IUserInputValidator<YesNoResult> _confirmationValidator;\n\n public MyApplication(IUserInputProvider inputProvider, \n IUserInputValidator<DateTime> dateValidator, \n IUserInputValidator<YesNoResult> confirmationValidator)\n {\n _inputProvider = inputProvider;\n _dateValidator = dateValidator;\n _confirmationValidator = confirmationValidator;\n }\n\n public void Run()\n {\n var keepRunning = true;\n\n while(keepRunning)\n {\n var date = GetBirthDate();\n // ...\n\n keepRunning = !GetExitConfirmation();\n }\n }\n\n private DateTime GetBirthDate()\n {\n var prompt = "Enter your birth date:";\n var input = _inputProvider.GetUserInput(prompt, _dateValidator);\n \n return DateTime.Parse(input);\n }\n\n private bool GetExitConfirmation()\n {\n var prompt = "Exit (Y|N)?";\n var input = _inputProvider.GetUserInput(confirmPrompt, _confirmationValidator);\n\n return input == YesNoResult.Yes;\n }\n}\n</code></pre>\n<p>Notice how the constructor could easily get bloated with possibly as many validators as there are things we want to get from the user. 3 constructor parameters is probably ok. More than that though, and I would be tempted to extract the validators into their own object, so as to keep the message clear: the <code>MyApplication</code> class <em>needs</em> validators - it doesn't <em>do</em> validation.</p>\n<p>Let's extract them anyway to see what we get:</p>\n<pre><code>public class UserInputValidation\n{\n private readonly IUserInputValidator<DateTime> _dateValidator;\n private readonly IUserInputValidator<YesNoResult> _confirmationValidator;\n\n public UserInputValidation(IUserInputValidator<DateTime> dateValidator, \n IUserInputValidator<YesNoResult> confirmationValidator)\n {\n _dateValidator = dateValidator;\n _confirmationValidator = confirmationValidator\n }\n\n public IUserInputValidator<DateTime> DateValidator { get { return _dateValidator; } }\n public IUserInputValidator<YesNoResult> ConfirmationValidator { get { return _confirmationValidator; } }\n}\n</code></pre>\n<hr />\n<p>Because the actual calculation algorithm would, by itself, be a <em>reason to change</em>, it's best to encapsulate it in its own class.</p>\n<p><a href=\"https://codereview.stackexchange.com/a/44627/23788\">@svick's answer</a> could be an implementation of some <code>IAgeCalculator</code> interface.</p>\n<p>The <code>MyApplication</code> class now looks like this:</p>\n<pre><code>public class MyApplication\n{\n private readonly IUserInputProvider _inputProvider;\n private readonly IAgeCalculator _calculator;\n private readonly UserInputValidation _validation;\n\n public MyApplication(IUserInputProvider inputProvider,\n IAgeCalculator calculator, \n UserInputValidation validation)\n {\n _inputProvider = inputProvider;\n _calculator = calculator;\n _validation = validation;\n }\n\n public void Run()\n {\n var keepRunning = true;\n\n while(keepRunning)\n {\n var date = GetBirthDate();\n DisplayAge(date);\n\n keepRunning = !GetExitConfirmation();\n }\n }\n\n private DateTime GetBirthDate()\n {\n var prompt = "Enter your birth date:"; \n var input = _inputProvider.GetUserInput(prompt, _validation.DateValidator);\n \n return DateTime.Parse(input);\n }\n\n private void DisplayAge(DateTime date)\n {\n var result = _calculator.GetDifferenceInYearsAndDays(date, DateTime.Today);\n var message = string.Format("Your age: {0} years and {1} days", result.Item1, result.Item2);\n _inputProvider.ShowMessage(message);\n }\n\n private bool GetExitConfirmation()\n {\n var prompt = "Exit (Y|N)?"; \n var input = _inputProvider.GetUserInput(confirmPrompt, _validation.ConfirmationValidator);\n\n return input == YesNoResult.Yes;\n }\n}\n</code></pre>\n<hr />\n<p>The above assumes a <code>ShowMessage</code> method was added to the <code>IUserInputProvider</code> interface; this method is implemented like this:</p>\n<pre><code>public void ShowMessage(string message)\n{\n Console.WriteLine(message);\n}\n</code></pre>\n<hr />\n<p>Now, the <code>Main</code> method can serve its purpose: <em>compose</em> the application!</p>\n<pre><code>static void Main(string[] args)\n{\n var input = new ConsoleInputProvider();\n var calculator = new AgeCalculator();\n var logger = LogManager.GetLogger("logger"); // gets a NLog logger\n var dateValidator = new ValidationLoggerDecorator(new BirthDateValidator(), logger);\n var yesNoValues = new Dictionary<string, YesNoResult>\n {\n { "y", YesNoResult.Yes },\n { "n", YesNoResult.No }\n };\n var confirmationValidator = new YesNoValidator(values);\n var validation = new UserInputValidation(dateValidator, confirmationValidator);\n\n var app = new MyApplication(input, calculator, validation);\n app.Run();\n}\n</code></pre>\n<p>As you can see, <em>inversion of control</em> makes it easy to change our minds and swap the <code>dateValidator</code> for a simple <code>BirthDateValidator</code>, or to write a unit test that will only test how date validation operates, or only how age gets calculated, independently of everything else, without requiring user intervention, and with every dependency under full control.</p>\n<p>Of course the <em>composition root</em> for this trivial application is instantiating the objects manually (a.k.a. <em>poor man's DI</em>), and it's quite manageable. For a bigger application, you could leave this daunting task to your favorite IoC container, leaving your <code>Main</code> method looking something like this (here using Ninject):</p>\n<pre><code>static void Main(string[] args)\n{\n var kernel = new StandardKernel(new MyApplicationNinjectModule());\n var app = kernel.Get<MyApplication>();\n app.Run();\n}\n</code></pre>\n<p>The entire application's dependency graph gets resolved in a single method call - Ninject isn't the fastest at that, but its nice syntax and great extensibility make it a solid candidate to consider. If you don't know what a <code>StandardKernel</code> does, the above code might seem <em>automagical</em> if I tell you that it does the exact same thing as the previous snippet.</p>\n<p>And that's long enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T09:22:41.817",
"Id": "77525",
"Score": "0",
"body": "You call both `DateTime.TryParse(input)` and `DateTime.Parse(input)`. You also have `input.ToLower() == \"y\"` in `YesNoValidator` and `input.ToUpper() == \"Y\"` This is not dry. You really need something like F# `Option` or use `null` as return value or something similar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:34:26.023",
"Id": "77571",
"Score": "1",
"body": "Doesn't \"ideally exposing only a single member\" imply that everything can be declared as a delegate instead of as an interface? For example, instead of `IUserInputProvider inputProvider`, `Func<string,string> GetUserInput` (input parameter is the prompt and return value is the user input)? And instead of `IUserInputValidator confirmationValidator`, `Func<string,bool> Validate`? With interfaces, you need to declare the interface, declare the method in the interface, declare a separate class which implements the interfaces, construct an instance of the class, ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:35:01.050",
"Id": "77572",
"Score": "0",
"body": "@abuzittingillifirca I thought of turning `Validate()` into `Validate<TValue>()` and adding an `out TValue value` parameter, but I didn't, because I wanted the post to focus on SOLID - getting into `out` parameters and generics was going to be way overboard... already is ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:36:07.357",
"Id": "77573",
"Score": "1",
"body": "... with delegates you just declare the delegate type, or use one of the `Func<>` overloads to declare the delegate type; and the method which implements the delegate can be anything, even just a static method of the Main or Application or Test class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:42:27.113",
"Id": "77576",
"Score": "1",
"body": "Maybe teaching/implementing this using interfaces instead of delegates is a hang-over from Java?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:48:54.003",
"Id": "77580",
"Score": "3",
"body": "@ChrisW lol, this is overkill in many, many ways; indeed, delegates would be simpler - the idea was to use the OP's code/project as a \"small app\" to show how one would use these techniques to make a \"bigger app\" (as explained in [*Is decoupling necessary for very small applications?*](http://codereview.stackexchange.com/questions/42023/is-decoupling-necessary-for-very-small-applications/42094#42094)). OTOH I do have a tendency to underexploit delegates and overuse interfaces, you have a point :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:17:38.237",
"Id": "77593",
"Score": "1",
"body": "I'd be inclined to use an interface (or class) instead of a delegate (or method) iff there are two related/codependent method rather than just one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T12:27:31.027",
"Id": "78264",
"Score": "0",
"body": "Your `keepRunning = GetExitConfirmation();` seems to be incorrect. `GetExitConfirmation` returns `true` if the user wants to exit, not if the user wants to keep running the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T13:10:05.933",
"Id": "78291",
"Score": "0",
"body": "@comecme fixed, thanks! Ironically, a simple unit test would have caught that bug in a splitsecond :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-23T15:21:18.210",
"Id": "123446",
"Score": "0",
"body": "This might be the longest answer I've ever seen on CR"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T05:08:37.377",
"Id": "44643",
"ParentId": "44606",
"Score": "18"
}
}
] | {
"AcceptedAnswerId": "44612",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T19:47:05.550",
"Id": "44606",
"Score": "24",
"Tags": [
"c#",
"beginner",
"datetime"
],
"Title": "Simple Age Calculator"
} | 44606 |
<p>I am creating a TicTacToe game for my college project, and when I finished the code for computer AI, I ended up with a big chunk of code.</p>
<p>It allows the computer to make the winning move, stopping the player from winning and making a random move if the computer can't make any winning move or stop the player from winning. The code I have contains a series of <code>if</code> and <code>else if</code> statements.</p>
<p>I was wondering if it would be possible to reduce this amount of code in any way. I have tried putting one of the <code>if</code> statements in a method and then calling the method several times, but this does not work because the <code>else</code> statement does not run.</p>
<pre><code>public void AI(){
count++;
if(buttons[1].getText().equals("O") && buttons[2].getText().equals("O") && buttons[3].getText().equals("")){
buttons[3].setText("O");
buttons[3].setEnabled(false);
} else if(buttons[4].getText().equals("O") && buttons[5].getText().equals("O") && buttons[6].getText().equals("")){
buttons[6].setText("O");
buttons[6].setEnabled(false);
} else if(buttons[7].getText().equals("O") && buttons[8].getText().equals("O") && buttons[9].getText().equals("")){
buttons[9].setText("O");
buttons[9].setEnabled(false);
}
else if(buttons[2].getText().equals("O") && buttons[3].getText().equals("O") && buttons[1].getText().equals("")){
buttons[1].setText("O");
buttons[1].setEnabled(false);
} else if(buttons[5].getText().equals("O") && buttons[6].getText().equals("O") && buttons[4].getText().equals("")){
buttons[4].setText("O");
buttons[4].setEnabled(false);
} else if(buttons[8].getText().equals("O") && buttons[9].getText().equals("O") && buttons[7].getText().equals("")){
buttons[7].setText("O");
buttons[7].setEnabled(false);
}
else if(buttons[1].getText().equals("O") && buttons[3].getText().equals("O") && buttons[2].getText().equals("")){
buttons[2].setText("O");
buttons[2].setEnabled(false);
} else if(buttons[4].getText().equals("O") && buttons[6].getText().equals("O") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
} else if(buttons[7].getText().equals("O") && buttons[9].getText().equals("O") && buttons[8].getText().equals("")){
buttons[8].setText("O");
buttons[8].setEnabled(false);
}
else if(buttons[1].getText().equals("O") && buttons[4].getText().equals("O") && buttons[7].getText().equals("")){
buttons[7].setText("O");
buttons[7].setEnabled(false);
} else if(buttons[2].getText().equals("O") && buttons[5].getText().equals("O") && buttons[8].getText().equals("")){
buttons[4].setText("O");
buttons[4].setEnabled(false);
} else if(buttons[3].getText().equals("O") && buttons[6].getText().equals("O") && buttons[9].getText().equals("")){
buttons[9].setText("O");
buttons[9].setEnabled(false);
}
else if(buttons[4].getText().equals("O") && buttons[7].getText().equals("O") && buttons[1].getText().equals("")){
buttons[1].setText("O");
buttons[1].setEnabled(false);
} else if(buttons[5].getText().equals("O") && buttons[8].getText().equals("O") && buttons[2].getText().equals("")){
buttons[2].setText("O");
buttons[2].setEnabled(false);
} else if(buttons[6].getText().equals("O") && buttons[9].getText().equals("O") && buttons[3].getText().equals("")){
buttons[3].setText("O");
buttons[3].setEnabled(false);
}
else if(buttons[1].getText().equals("O") && buttons[7].getText().equals("O") && buttons[4].getText().equals("")){
buttons[4].setText("O");
buttons[4].setEnabled(false);
} else if(buttons[2].getText().equals("O") && buttons[8].getText().equals("O") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
} else if(buttons[3].getText().equals("O") && buttons[9].getText().equals("O") && buttons[6].getText().equals("")){
buttons[6].setText("O");
buttons[6].setEnabled(false);
}
else if(buttons[1].getText().equals("O") && buttons[5].getText().equals("O") && buttons[9].getText().equals("")){
buttons[9].setText("O");
buttons[9].setEnabled(false);
} else if(buttons[5].getText().equals("O") && buttons[9].getText().equals("O") && buttons[1].getText().equals("")){
buttons[1].setText("O");
buttons[1].setEnabled(false);
} else if(buttons[1].getText().equals("O") && buttons[9].getText().equals("O") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
}
else if(buttons[3].getText().equals("O") && buttons[5].getText().equals("O") && buttons[7].getText().equals("")){
buttons[7].setText("O");
buttons[7].setEnabled(false);
} else if(buttons[7].getText().equals("O") && buttons[5].getText().equals("O") && buttons[3].getText().equals("")){
buttons[3].setText("O");
buttons[3].setEnabled(false);
} else if(buttons[7].getText().equals("O") && buttons[3].getText().equals("O") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
}
else if(buttons[1].getText().equals("X") && buttons[2].getText().equals("X") && buttons[3].getText().equals("")){
buttons[3].setText("O");
buttons[3].setEnabled(false);
} else if(buttons[4].getText().equals("X") && buttons[5].getText().equals("X") && buttons[6].getText().equals("")){
buttons[6].setText("O");
buttons[6].setEnabled(false);
} else if(buttons[7].getText().equals("X") && buttons[8].getText().equals("X") && buttons[9].getText().equals("")){
buttons[9].setText("O");
buttons[9].setEnabled(false);
}
else if(buttons[2].getText().equals("X") && buttons[3].getText().equals("X") && buttons[1].getText().equals("")){
buttons[1].setText("O");
buttons[1].setEnabled(false);
} else if(buttons[5].getText().equals("X") && buttons[6].getText().equals("X") && buttons[4].getText().equals("")){
buttons[4].setText("O");
buttons[4].setEnabled(false);
} else if(buttons[8].getText().equals("X") && buttons[9].getText().equals("X") && buttons[7].getText().equals("")){
buttons[7].setText("O");
buttons[7].setEnabled(false);
}
else if(buttons[1].getText().equals("X") && buttons[3].getText().equals("X") && buttons[2].getText().equals("")){
buttons[2].setText("O");
buttons[2].setEnabled(false);
} else if(buttons[4].getText().equals("X") && buttons[6].getText().equals("X") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
} else if(buttons[7].getText().equals("X") && buttons[9].getText().equals("X") && buttons[8].getText().equals("")){
buttons[8].setText("O");
buttons[8].setEnabled(false);
}
else if(buttons[1].getText().equals("X") && buttons[4].getText().equals("X") && buttons[7].getText().equals("")){
buttons[7].setText("O");
buttons[7].setEnabled(false);
} else if(buttons[2].getText().equals("X") && buttons[5].getText().equals("X") && buttons[8].getText().equals("")){
buttons[8].setText("O");
buttons[8].setEnabled(false);
} else if(buttons[3].getText().equals("X") && buttons[6].getText().equals("X") && buttons[9].getText().equals("")){
buttons[9].setText("O");
buttons[9].setEnabled(false);
}
else if(buttons[4].getText().equals("X") && buttons[7].getText().equals("X") && buttons[1].getText().equals("")){
buttons[1].setText("O");
buttons[1].setEnabled(false);
} else if(buttons[5].getText().equals("X") && buttons[8].getText().equals("X") && buttons[2].getText().equals("")){
buttons[2].setText("O");
buttons[2].setEnabled(false);
} else if(buttons[6].getText().equals("X") && buttons[9].getText().equals("X") && buttons[3].getText().equals("")){
buttons[3].setText("O");
buttons[3].setEnabled(false);
}
else if(buttons[1].getText().equals("X") && buttons[7].getText().equals("X") && buttons[4].getText().equals("")){
buttons[4].setText("O");
buttons[4].setEnabled(false);
} else if(buttons[2].getText().equals("X") && buttons[8].getText().equals("X") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
} else if(buttons[3].getText().equals("X") && buttons[9].getText().equals("X") && buttons[6].getText().equals("")){
buttons[6].setText("O");
buttons[6].setEnabled(false);
}
else if(buttons[1].getText().equals("X") && buttons[5].getText().equals("X") && buttons[9].getText().equals("")){
buttons[9].setText("O");
buttons[9].setEnabled(false);
} else if(buttons[5].getText().equals("X") && buttons[9].getText().equals("X") && buttons[1].getText().equals("")){
buttons[1].setText("O");
buttons[1].setEnabled(false);
} else if(buttons[1].getText().equals("X") && buttons[9].getText().equals("X") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
}
else if(buttons[3].getText().equals("X") && buttons[5].getText().equals("X") && buttons[7].getText().equals("")){
buttons[7].setText("O");
buttons[7].setEnabled(false);
} else if(buttons[7].getText().equals("X") && buttons[5].getText().equals("X") && buttons[3].getText().equals("")){
buttons[3].setText("O");
buttons[3].setEnabled(false);
} else if(buttons[7].getText().equals("X") && buttons[3].getText().equals("X") && buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
}
else if(buttons[1].getText().equals("X") && buttons[5].getText().equals("O") && buttons[9].getText().equals("X")) {
buttons[6].setText("O");
buttons[6].setEnabled(false);
}
else if(buttons[3].getText().equals("X") && buttons[5].getText().equals("O") && buttons[7].getText().equals("X")) {
buttons[4].setText("O");
buttons[4].setEnabled(false);
}
else if(buttons[5].getText().equals("")){
buttons[5].setText("O");
buttons[5].setEnabled(false);
}
else if(buttons[1].getText().equals("")){
buttons[1].setText("O");
buttons[1].setEnabled(false);
}
else {
if(count >= 9)
checkWin();
else
RandomMove();
}
checkWin();
}
</code></pre>
<p><strong>Edited:</strong> The <code>if</code> statements I have check for all the different possibilities that computer can make a winning move or stop the player from winning. </p>
<p>edited 3:</p>
<pre><code>for(int i=0; i<=3; i++){
if (buttons[i*3].getText().equals("X") && buttons[i*3+1].getText().equals("X") && buttons[i*3+2].getText().equals(""))
buttons[i*3+2].setText("O");
win = true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:17:06.553",
"Id": "77430",
"Score": "0",
"body": "Sometimes it's possible to use a dictionary in place of a series of if statements. Have you considered this approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:17:43.837",
"Id": "77431",
"Score": "0",
"body": "Hi, sorry i am quite new to java and have never heard of dictionary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:17:57.157",
"Id": "77432",
"Score": "5",
"body": "At a glance, your AI logic seems very *tightly coupled* with your UI /user interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:19:45.797",
"Id": "77433",
"Score": "0",
"body": "does UI stand for user interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:20:06.070",
"Id": "77434",
"Score": "1",
"body": "@Seeker: a dictionary, or hash table, is a data structure that maps a distinct key to a value. Dictionaries often can help simplify the representation of your problem, and are a great tools for many applications. In Java, I think you need to implement `Map` (the equivalent to the data structure I'm describing)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:21:21.803",
"Id": "77435",
"Score": "0",
"body": "@gfdanis would it be possible to give me an example of how I can use dictionary, please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:22:23.320",
"Id": "77436",
"Score": "0",
"body": "@Seeker: http://stackoverflow.com/questions/13543457/how-do-you-create-a-dictionary-using-java"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:35:22.780",
"Id": "77441",
"Score": "1",
"body": "@gjdanis I am not sure how or in what way exactly a Map would help here? How do you suggest the OP should use it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:44:36.767",
"Id": "77444",
"Score": "0",
"body": "@SimonAndréForsberg Could you not map a \"case\" to an \"action\"? Might this make the statements for checking a situation on the board more concise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:58:50.097",
"Id": "77449",
"Score": "0",
"body": "@gjdanis You'd still have the problem of creating all the possible cases. I think the problem needs to be generalized."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:02:42.957",
"Id": "77451",
"Score": "0",
"body": "@SimonAndréForsberg Yes, just a technique that I've used in the past that may or may not be fruitful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T00:17:44.300",
"Id": "77479",
"Score": "5",
"body": "Just, you know, leaving this here... http://xkcd.com/832/"
}
] | [
{
"body": "<p>When confronted with a problem like this it helps to implement the <a href=\"http://en.wikipedia.org/wiki/Chain_of_responsibility_pattern\">chain-of-responsibility pattern</a>. In this case, you have a hierarchy of sorts, with a winning move, defensive move, and a random move.</p>\n\n<p>You should create an interface along the lines of:</p>\n\n<pre><code>public interface TicTacToeStrategy {\n public boolean apply(Button[] buttons);\n}\n</code></pre>\n\n<p>Then, you should have a number of implementations of this strategy....</p>\n\n<p>Something like:</p>\n\n<pre><code>public ForTheWinStrategy implements TicTacToeStrategy {\n public boolean apply(Button[] buttons) {\n if (.... there is a winning move) {\n apply the winning move\n return true;\n }\n return false;\n }\n}\n</code></pre>\n\n<p>Then you can have the <code>DefensiveStrategy</code>, and the <code>RandomStrategy</code>.</p>\n\n<pre><code> private static final TicTacToeStrategy[] STRATEGIES = {\n new ForTheWinStrategy(),\n new DefensiveStrategy(),\n new RandomStrategy()\n };\n</code></pre>\n\n<p>Your main code can then become:</p>\n\n<pre><code>for(TicTacToeStrategy strategy : STRATEGIES) {\n if (strategy.apply(buttons)) {\n break;\n }\n}\n</code></pre>\n\n<p>As for all the if statements.... you need to rationalize them somehow.</p>\n\n<p>Extracting them to a function would be good, or setting up a number of three-in-a-row sets....</p>\n\n<pre><code>private static final int[][] THREEINAROW = {\n {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9},\n {1, 4, 7},\n {2, 5, 8},\n {3, 5, 9},\n {1, 5, 9},\n {3, 5, 7}\n}\n</code></pre>\n\n<p>With the above setup, you can relatively easily say:</p>\n\n<pre><code>for (int[] tiaw : THREEINAROW) {\n if (2 are us, and one is empty) {\n we have a winner!\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:32:30.597",
"Id": "77439",
"Score": "0",
"body": "Hi, i just had a good read through on your example but i am unclear as to where new DefensiveStrategy() and new RandomStrategy() are being called from."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:33:30.020",
"Id": "77440",
"Score": "0",
"body": "@Seeker They are being declared as instances in the STRATEGIES array, and then they are being called inside the main loop `if (strategy.apply(buttons)) {....}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:02:32.247",
"Id": "77450",
"Score": "0",
"body": "I was just over your code and i am finding it little confusing to understand how the last for loop works, for (int[] tiaw : THREEINAROW) {. if i am not mistaken, it loops through the pre-defined Threeinarow array and check if any two buttons have the same value and if it does, then make the winning move but how would you pass the buttons in the if statement?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:22:04.290",
"Id": "44611",
"ParentId": "44608",
"Score": "13"
}
},
{
"body": "<p>Yes, you really need to use loops and generalize this!</p>\n\n<p>In order for you to learn the most, I won't give any exact code but I will tell you a bit about what you need to do</p>\n\n<ul>\n<li><p>Your array seems to be index 1-9 based, I would recommend using index 0 to 8 instead. Array index always start at zero, it just seem like you're just not using it. Instead, use it.</p></li>\n<li><p>Use for-loops to iterate through <strong>rows</strong>, <strong>columns</strong> and the <strong>diagonals</strong> of your game board. 3 rows, 3 columns, and 2 diagonals. <code>for (int x = 0; x < 3; x++)</code> is a simple way of looping through all x's (columns).</p></li>\n<li><p>Hint: The row and column of a button can be calculated by using either <code>index / 3</code> or <code>index % 3</code> (<code>%</code> is the 'modulo'-operator). This is a reason for why you should use zero-index based arrays. It makes it so much easier to do this calculation.</p></li>\n<li><p>You might want to use an <code>enum</code> for <code>UNPLAYED</code>, <code>X</code> and <code>O</code>. Using an appropriate <code>enum</code> can really help clean up your code massively.</p>\n\n<p>public enum PlayedBy {\n UNPLAYED, X, O;\n}</p></li>\n<li><p><strong>Decoupling</strong>. This is a bit more advanced and nothing you should be focusing on <em>primarily</em>. But in the future, it will help you greatly. Right now your AI knows everything about your <em>view</em> (view = the objects that the user sees). What if you wanted to make two AIs play against each other and only output to the console? What if you wanted to make an Android app of this? What if you wanted to make a Web application with GWT? (In the future you might want this!) You should look into the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\">MVC pattern</a> and/or <strong>use interfaces!</strong> to decouple your code.</p></li>\n</ul>\n\n<p>You repeat this part very often</p>\n\n<pre><code>buttons[x].setText(\"O\");\nbuttons[x].setEnabled(false);\n</code></pre>\n\n<p>That is something that should be put into a method:</p>\n\n<pre><code>void setButtonPlayer(JButton position, String player) {\n position.setText(player);\n position.setEnabled(false);\n}\n</code></pre>\n\n<p>Now you only have to use <code>setButtonPlayer(buttons[4], \"O\");</code> to make a move on button 4. If you use an enum, you could use <code>setButtonPlayer(JButton button, PlayedBy player)</code>.</p>\n\n<p>Once you have cleaned this up a bit, I recommend you post a follow-up question, as there is likely more things that can be cleaned up then.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:43:53.293",
"Id": "77443",
"Score": "0",
"body": "hi, I am unsure how I can use a for loop to check all the different possibilities of the computer making the winning move. I have attempted something but i am not sure if this is correct. I have updated my post, please let me know if i am going in the correct path. thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:04:15.420",
"Id": "77453",
"Score": "0",
"body": "@Seeker Almost on the correct path. Only loop through 0 to 2, and get the index of the first button to check by `i * 3`. Alternatively, use a two-dimensional array `JButton[][] buttons = new JButton[3][3];` Two-dimensional arrays might be difficult to get started with, but in the long run they will help you. But if you'd like, just stick to a one-dimensional array as you have now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:06:03.460",
"Id": "77454",
"Score": "0",
"body": "This question might sound a bit stupid, but why are we doing i * 3. sorry if this is silly question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:17:48.503",
"Id": "77457",
"Score": "0",
"body": "@Seeker Not at all. Very good question. Think about which indexes you want to check, as I understand it you'd want (0 1 2), (3 4 5), (6 7 8). That is, (i*3, i*3 + 1, i*3 + 2)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:22:00.760",
"Id": "77458",
"Score": "0",
"body": "Now i understand why we need to * 3 but how would putting this in a for loop checking for all the different possibilities of the computer making the winning move and stopping the player from winning, there are about 24 different ways that computer can win or stop the player from winning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:24:13.673",
"Id": "77459",
"Score": "0",
"body": "I have edited my post, showing how I think the for loop is written, am i correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:32:25.267",
"Id": "77461",
"Score": "0",
"body": "@Seeker You should use `< 3` and not `<= 3`. But that's correct, yes. There's also a way to simplify the inner part, but that would require an inner loop (which is good to learn how to use!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:32:43.740",
"Id": "77462",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13666/discussion-between-simon-andre-forsberg-and-seeker)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:52:40.937",
"Id": "77474",
"Score": "0",
"body": "What are the 3 diagonals of a tic tac toe board again?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T08:12:17.707",
"Id": "77518",
"Score": "1",
"body": "@Mat'sMug Yeah yeah yeah ;)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:30:20.163",
"Id": "44613",
"ParentId": "44608",
"Score": "15"
}
},
{
"body": "<p>You basically hard-coded everything. It is not recommended to hard-code everything for AI. What if you were writing something a bit more complex? Then you might get a case where your AI completely fails. This is why I believe you should develop your own algorithm or implement someone else's.</p>\n\n<p>For your problem, I suggest you implementing minimax algorithm which is basically recursively checking all possible options to finish the game. Here's the pseudocode:</p>\n\n<pre><code>function minimax(node, depth, maximizingPlayer)\n if depth = 0 or node is a terminal node\n return the heuristic value of node\n if maximizingPlayer\n bestValue := -∞\n for each child of node\n val := minimax(child, depth - 1, FALSE))\n bestValue := max(bestValue, val);\n return bestValue\n else\n bestValue := +∞\n for each child of node\n val := minimax(child, depth - 1, TRUE))\n bestValue := min(bestValue, val);\n return bestValue\n\n(* Initial call for maximizing player *)\nminimax(origin, depth, TRUE)\n</code></pre>\n\n<p>source: <a href=\"http://en.wikipedia.org/wiki/Minimax\">http://en.wikipedia.org/wiki/Minimax</a></p>\n\n<p>Also another source that implements minimax for tic tac toe:\n<a href=\"http://www.codeproject.com/Articles/43622/Solve-Tic-Tac-Toe-with-the-MiniMax-algorithm\">http://www.codeproject.com/Articles/43622/Solve-Tic-Tac-Toe-with-the-MiniMax-algorithm</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:51:33.607",
"Id": "77495",
"Score": "5",
"body": "I'm not aware of any definition of AI that excludes hard-coding all the options."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T08:44:28.777",
"Id": "77521",
"Score": "0",
"body": "Anyone care to explain why did I get minuses?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:58:12.700",
"Id": "77539",
"Score": "2",
"body": "\"What if you were writing something a bit more complex? \" - if the problem we're different, then yes, you'd need different code. For *this* problem, *this* approach works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T11:47:35.437",
"Id": "77544",
"Score": "5",
"body": "@AakashM The purpose of Code review is to review the code. This is not stackoverflow. Therefore I don't see any reason why not to recommend completely different approach, as it is more elegant and understandable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:50:19.547",
"Id": "77638",
"Score": "0",
"body": "FWIW, minimax was the first thing I thought of when I read the question title and was surprised to find a string of `if-else-if` statements. They are fine as a start, of course, and minimax may be too advanced at the OP's stage in learning, but this answer hardly deserves a downvote!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:21:34.423",
"Id": "44637",
"ParentId": "44608",
"Score": "7"
}
},
{
"body": "<p>The problem you have is that you are checking for each specific situation, rather than abstracting for the type of situation. This makes the code you are writing much harder to read, write, debug and maintain.</p>\n\n<p>So for example you have :</p>\n\n<pre><code>else if(buttons[1].getText().equals(\"X\") && buttons[4].getText().equals(\"X\") && buttons[7].getText().equals(\"\")){\n buttons[7].setText(\"O\");\n buttons[7].setEnabled(false);}\n</code></pre>\n\n<p>The first level of abstraction you could use would be to define a method to uncover what is in the square, this would make the code more readable:</p>\n\n<pre><code>private boolean containsX(int square){\n return buttons[square].getText().equals(\"X\");}\n</code></pre>\n\n<p>This (and similar methods) makes the code more readable:</p>\n\n<pre><code>else if(containsX(1) && containsX(4) && isEmpty(7){\n placeMove(\"O\", 7);} \n</code></pre>\n\n<p>Now you have abstracted the code into methods you can read, however the 'logic' is still specified one piece at a time, and you can abstract that too. Other people have suggested different ways of doing it on this page, but the ideas are always the same, you need to express in general terms what each specific line is trying to do. so instead of the line above, you might have:</p>\n\n<pre><code>else if (canWinInFirstColumn)\n { playMoveInFirstColumn() }\n</code></pre>\n\n<p>however as soon as you start to write these, you realise that they are the same for each column, and the code for canWinInFirstColumn could simply be remade as canWinInColumnNumber(int colNumber) and would work for every column.</p>\n\n<p>Then you realise that the code for columns and rows is similar, and you only really need to worry about the diagonals, so you make methods for each of those and then have a method that calls them all;</p>\n\n<pre><code>private boolean canWin(){\n for (int i=0;i<3;i++){\n if (canWinInRow(i)){\n playMoveInRow(i);\n return true;\n }\n if (canWinInColumn(i)){\n playMoveInColumn(i);\n return true;\n }\n }\n if (canWinInFirstDiagonal){\n playMoveInFirstDiagonal();\n return true;\n }\n if (canWinInSecondDiagonal){\n playMoveInSecondDiagonal();\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Obviously you can keep on going and abstract much of the code into methods that contain the logic, and experienced programmers will skip many of these steps and end up with a single method that calls a few functions. There are other 'tricks' to making the code neater, for example noticing that the board is symmetrical or using maths to work out if there is a row or column with two of your pieces and an empty space, or two of their pieces and an empty space.</p>\n\n<p>Finally you have a 'view' of the board (that is buttons with the letter X is buttons with the letter X or O) assigned to them, but that is also doubling as your 'model', that is you are using it to work out what is where. It is very common to separate the two, so you would have a simple array (e.g. integers) that contains what is in each square (0=empty, 1=X, 2=O) and then your logic can be much neater (no need for .getText().equals('X') everywhere, just ==1) and you just have a single method that reads in all the 0s, 1s and 2s from the model and sets the values of the appropriate squares to X or O as appropriate whenever something changes. This means that the code that is 'intensive' is using an efficient data structure, and the code that is simply rendering the outcome (the buttons with text on them) is only being updated when it needs to be.</p>\n\n<p>Hope this helps :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:12:59.360",
"Id": "44670",
"ParentId": "44608",
"Score": "5"
}
},
{
"body": "<p>I recently wrote a program to do something like this, and my implementation came down basically to this:</p>\n\n<ul>\n<li>To store the marks, I had an <code>enum Mark { NOBODY, X, O }</code> </li>\n<li>To store a move in the game, I had a <code>Move</code> class that tracked a mark and a location on a board</li>\n<li>To store the game state, I had a <code>Board</code> class. My implementation made the board object immutable, and one could only derive other board objects via its <code>put(Move m)</code> method. It also supplied methods for querying the values held in its cells.</li>\n<li>Players were represented by the <code>Player</code> interface. For the real player, I had a MCV thing, while my implementation of <code>ComputerPlayer</code> delegated to some <code>Strategy</code> objects. (The <code>Player</code> interface also had a method to report the end state of the game, to facilitate self-learning AI). On the player's turn, the game model called the player's <code>getMove(Board b)</code> method to obtain a <code>Move</code> object representing their response to that particular state.</li>\n<li>However, all the information about the actual rules of the game, with regards to valid moves, winning, and the like, was contained in a separate class, <code>Rules</code>. One could get an <code>Iterable</code> containing all rows, columns, and diagonals of a board with one method, query the winner of a particular board state with another method, check if a <code>Move</code> object could legally be added to a <code>Board</code> with yet another method, or get a list of all moves they could legally make. My implementation of an AI used these exclusively for deciding where to place its move, making them fairly independent of the particular rules, and so they would still work if I changed those rules.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:11:45.663",
"Id": "44680",
"ParentId": "44608",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:07:45.207",
"Id": "44608",
"Score": "22",
"Tags": [
"java",
"game",
"tic-tac-toe",
"ai"
],
"Title": "Tic Tac Toe computer AI"
} | 44608 |
<p>I'm looking to improve my code to make it more efficient, such as shortening it but continuing to gain the same output, or to add some more complex functions into the code.</p>
<pre><code>restart ='Y'
while restart not in ('N', 'n', 'NO', 'no'):
print ("Making A Cup Of Tea")
num_orders = int(input("How many for Tea? "))
print ("there are", num_orders, "People for tea")
orders = []
for i in range(num_orders):
b = input ("Person %i, Would you like Sugar? YES/NO " % (i + 1))
sugar = None
if b in ("YES", "Y", "y", "yes"):
sugar = input("How many sugars? ")
else:
print ("Okay No sugar")
milk = input("How Much Milk Would You Like? SMALL/MEDIUM/LARGE ")
print ("Order is being processed, next order:\n")
orders.append({'sugar': sugar, 'milk': milk })
print('The orders has been processed with these data:')
for i in range(num_orders):
order = orders[i]
print (' - Person', i + 1, 'wants tea', ('with %i' % int(order['sugar']) if
order['sugar'] else 'without'), 'sugar and ', order['milk'], 'milk')
print('')
restart = input('Would you like to Re-Order? Y/N')
if restart in ('n', 'N'):
print('')
print ('Okay, Thank You, Enjoy Your Tea')
</code></pre>
| [] | [
{
"body": "<p>It's not always about shortening code, but in most cases about having your code easy to maintain. For example, if this code is to go in production, I would change it as follows:</p>\n\n<pre><code>\"\"\"A script for ordering a tea party.\"\"\"\n\nYES = ('y', 'yes')\nMILK_SIZES = ('small', 'medium', 'large')\n\nwhile True:\n print(\"Making a cup of tea.\")\n num_orders = ask_number_of_orders()\n orders = []\n for person_num in range(num_orders):\n print(\"Person %d, would you like:\" % person_num + 1)\n sugar = ask_for_sugar()\n milk = ask_for_milk()\n orders.append((sugar, milk))\n print(\"Your order is being processed.\", end=\"\")\n if person_num + 1 < num_orders:\n print(\" Next order:\")\n print(\"The orders have been processed with the following data:\")\n for person_num, (sugar, milk) in enumerate(orders):\n order_status = construct_order_status(person_num + 1, sugar, milk)\n print(order_status)\n print(\"\")\n restart = input(\"Would you like to re-order? Y/N.\")\n if restart.lower() not in YES:\n print(\"\")\n print(\"Ok, thank you, enjoy your day!\")\n break\n\n\ndef ask_for_number_of_orders():\n \"\"\"Get number of orders from the user.\"\"\"\n while True:\n try:\n num_orders = int(input(\"How many for tea?\"))\n if num_order < 1:\n raise ValueError\n print(\"There are %d people for tea.\" % num_orders)\n return num_orders\n except ValueError:\n print(\"Please enter non-negative integer, let's try again.\")\n\n\ndef ask_for_sugar():\n \"\"\"Prompt user for sugar, if yes - how much.\n\n Returns number of sugar cubes (int) or None.\n \"\"\"\n while True:\n sugar = input(\"Would you like sugar? Y/N.\")\n if sugar.lower() not in YES:\n print(\"Okay, no sugar.\")\n return\n while True:\n try:\n sugar = int(input(\"How many sugars?\"))\n if sugar < 1:\n raise ValueError\n return sugar\n except ValueError:\n print(\"Please enter non-negative integer, let's try again.\")\n\n\ndef ask_for_milk():\n \"\"\"Prompts user for the amount of milk.\"\"\"\n while True:\n milk = input(\"How much milk would you like? Small/medium/large.\")\n if milk.lower() in MILK_SIZES:\n return milk.lower()\n else:\n print(\"Sorry, did not catch that. Small, medium, or large?\")\n\n\ndef construct_order_status(person_num, sugar, milk):\n \"\"\"Constructs order status string.\n\n Args:\n person_num: Number of the person.\n sugar: Number of sugar cubes or None.\n milk: Size of the milk: small, medium, or large.\n\n Returns a string representing order status.\n \"\"\"\n order_status = \" - Person %d wants tea \" % person_num\n if sugar is None:\n order_status += \"without sugar\"\n else:\n order_status += \"with %d pieces of sugar\" % sugar\n order_status += \" and %s milk.\" % milk\n return order_status\n</code></pre>\n\n<p>I added few user input validators and separated key points of the program into methods. This did not make it shorter, but it did make it more maintainable and easier to change (which is inevitable in a real life software cycle).</p>\n\n<p>I would also add tests, and <code>__main__</code>, but this is going out of the scope of the question. This is, again, just one way to look at the problem: from the real life software development cycle perspective.</p>\n\n<p>EDIT: The only style correction - which is tiny - is to not put space in <code>print (</code>. In <code>python3</code> it's a function, and according to PEP8 no leading spaces are permitted before the parentheses: <a href=\"http://legacy.python.org/dev/peps/pep-0008/#id18\">http://legacy.python.org/dev/peps/pep-0008/#id18</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:10:16.133",
"Id": "44636",
"ParentId": "44614",
"Score": "12"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>while restart not in ('N', 'n', 'NO', 'no')</code>. In Python is more idiomatic to write <code>while True</code> and <code>break</code> inside the loop. It's not pretty but avoids weird pre-initializations.</p></li>\n<li><p><code>print (\"Making A Cup Of Tea\")</code>. No spaces between function name and parenthesis.</p></li>\n<li><p><code>('N', 'n', 'NO', 'no')</code>. Use lists for homogeneous values (i.e. same type) and tuples otherwise.</p></li>\n<li><p><code>print (\"there are\", num_orders, \"People for tea\")</code>. Use <code>string.format</code> instead.</p></li>\n<li><p><code>sugar = None</code>. It's more clear if you write that in an <code>else</code> branch.</p></li>\n<li><p><code>print (' - Person', i + 1</code>. This line is too long, it's hard to see its components. Break it down.</p></li>\n<li><p>Some bottom-up abstraction is required, use auxiliar functions.</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def ask(message, options):\n while True:\n response = input(\"{0} [{1}]: \".format(message, \"/\".join(options)))\n possible_options = set(option for idx in range(1, len(response)+1)\n for option in options if response[:idx] == option[:idx])\n if len(possible_options) == 1:\n return list(possible_options)[0]\n else:\n print(\"Unknown option: {0}, try again\".format(response))\n\ndef ask_yes_no(message):\n return (ask(message, [\"yes\", \"no\"]) == \"yes\")\n\ndef get_order(person):\n sugar_question = \"Person {0}, Would you like Sugar?\".format(person)\n if ask_yes_no(sugar_question):\n sugar = int(input(\"How many sugars? \"))\n else:\n print(\"Okay, No sugar\")\n sugar = None\n\n milk = ask(\"How Much Milk Would You Like?\", [\"small\", \"medium\", \"large\"])\n print(\"Order is being processed, next order:\\n\")\n return {\"person\": person, \"sugar\": sugar, \"milk\": milk}\n\ndef process_orders():\n while 1:\n print(\"Making A Cup Of Tea\")\n num_orders = int(input(\"How many for Tea? \"))\n print(\"There are {0} people for tea\".format(num_orders))\n\n orders = [get_order(person) for person in range(1, num_orders+1)]\n print('The orders has been processed with these data:')\n for order in orders:\n print(\" \".join([\n ' - Person {0} wants tea'.format(order[\"person\"]),\n ('with {0}'.format(order['sugar']) if order['sugar'] else 'without'), \n \"sugar and {0} milk\".format(order[\"milk\"]),\n ])\n\n if not ask_yes_no('Would you like to re-order?'):\n print(\"\\nOkay, Thank You, Enjoy Your Tea\")\n break\n\nprocess_orders()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T05:11:04.663",
"Id": "78014",
"Score": "0",
"body": "i read @Roslan answer , i was wondering why not do a conidtion checking instead of `while True:` , then i scroll down and saw your answer . thank you for the explanation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T09:13:00.437",
"Id": "89171",
"Score": "0",
"body": "Your `\" \".join` in the `print` looks unneeded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-01T08:11:43.687",
"Id": "313149",
"Score": "0",
"body": "Doesn't the tuple you're making contain just \"homogeneous values\"? I think a simpler explanation about why you should use tuples are: for the immutability (irrelevant here), and for the [peephole optimisation](https://sopython.com/wiki/Peephole_optimisations_for_tuple,_list,_set)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-01T09:42:31.450",
"Id": "313162",
"Score": "0",
"body": "@Peilonrayz: Where do I use tuples? `('N', 'n', 'NO', 'no')` is the OP's code. More than mutable/immutable I prefer the distinction from the FP world (which is also the math distinction of lists/tuples)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T18:55:15.523",
"Id": "44688",
"ParentId": "44614",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "44688",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:37:20.420",
"Id": "44614",
"Score": "14",
"Tags": [
"python",
"python-3.x",
"console"
],
"Title": "Drink order program"
} | 44614 |
<p>My code below is for a sort of onscreen keyboard. I was just wondering if it could be written shorter with a lot of <code>if</code>s and <code>else</code>s. </p>
<pre><code>function input(key) {
fieldName = currentSide+'_scratchfield';
field = document.getElementById(fieldName);
del = "DELETE";
if(key == 'sp') key = ' ';
if(key == 'minus') {
if(field.value == del) {
return false;
} else if(field.value.charAt(0) == "-") {
field.value = field.value.substr(1, field.value.length);
return false;
} else {
field.value = "-"+field.value;
return false;
}
}
if(key == 'clr') {
if(field.value == "" || field.value == null) {
return false;
} else if (field.value == del) {
field.value = "";
return false;
} else {
field.value = field.value.substring(0, field.value.length-1);
return false;
}
}
if(key == 'del') {
if(field.value == "" || field.value == null) {
key = del;
} else if(field.value == del) {
field.value = "";
return false;
} else {
field.value = "";
key = del;
}
}
key = key.toUpperCase();
if(field.value == del) { field.value = ""; }
field.value += key;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:21:09.583",
"Id": "77531",
"Score": "1",
"body": "I'm not sure I understand the logic: If a user inputs the `\"del\"` key, the field's value is set to the string \"DELETE\", meaning that the _next_ input will set the field's value to \"\" instead of its usual effect - _except_ if the next key is `\"sp\"`, which will just set the field to \" \". I'm confused as to what the purpose of this is."
}
] | [
{
"body": "<p>I am not sure about getting it shorter, but it could be improved.</p>\n\n<ul>\n<li>Indentation is a bit of a problem, check out <a href=\"http://jsbeautifier.org/\">http://jsbeautifier.org/</a> and paste your code to see what I mean</li>\n<li>Use <code>var</code> to declare your variables!</li>\n<li>If you <code>return</code> in an <code>if</code> block, then you don't need an <code>else if</code> block, just <code>if</code> will do</li>\n<li>Your code needs more comment, <code>if(key == 'sp')</code> <- what does <code>sp</code> mean ??</li>\n<li>I wish we had more code so that we could give a more insightful review</li>\n<li>You can replace <code>if(field.value == \"\" || field.value == null) {</code> with <code>if(!field.value)</code></li>\n<li>You can skip the curly braces of an <code>if</code>, but you should not skip the newlines.</li>\n</ul>\n\n<p>All in all, that makes something like this:</p>\n\n<pre><code>function input(key) {\n var fieldName = currentSide + '_scratchfield',\n field = document.getElementById(fieldName),\n del = \"DELETE\";\n if(key == 'sp')\n key = ' ';\n if(key == 'minus'){\n if(field.value == del)\n return false;\n if(field.value.charAt(0) == \"-\") {\n field.value = field.value.substr(1, field.value.length);\n return false;\n }\n field.value = \"-\"+field.value;\n return false;\n }\n if(key == 'clr'){\n if(!field.value)\n return false;\n if (field.value == del){\n field.value = \"\";\n return false;\n }\n field.value = field.value.substring(0, field.value.length-1);\n return false;\n }\n if(key == 'del'){\n if(!field.value)\n key = del;\n if(field.value == del) {\n field.value = \"\";\n return false;\n }\n field.value = \"\";\n key = del;\n }\n key = key.toUpperCase();\n if(field.value == del)\n field.value = \"\";\n field.value += key;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T08:09:56.187",
"Id": "77517",
"Score": "0",
"body": "Thankyou! Sp stands for . I was more wondering if it could be written with less if/else statements! Thanks so far though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:53:35.413",
"Id": "44633",
"ParentId": "44619",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:49:43.177",
"Id": "44619",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Onscreen keyboard"
} | 44619 |
<p>I am just coding some classic brute force password cracking program, just to improve myself.</p>
<p>I've explained how my program works at the start of the code. Check some of those screenshots to understand easier.</p>
<p>My program works really well but it's a bit dirty and it can be faster if I solve these two problems:</p>
<ol>
<li><p>The main code is not that long. It looks so long and dirty because I copied a code block 8 times in a switch case statement. For example, case 1 loops with one character length passwords. <code>case 2</code> = two characters, <code>case 8</code> = 8 characters length password. The one and only difference between those cases is the "for loop" count. <code>case 1</code> has 1 <code>for</code> loop, <code>case 8</code> has 8 nested for loops. I want to make my code prettier, so how can I get rid of this copy/pasted code and make it 1/8 size of current size? CTRL + MOUSE WHEEL DOWN, zoom-out and see the copy pasted parts.</p></li>
<li><p>It tries 1 digit first, then 2 digits, then 3 digits and so on. So it should wait for 1, 2, 3 to get the 4 digit ones. And it makes the program lose so much time at higher digits. My CPU is i7 3770k got 6 cores and the program runs only with one. I guess it's because it says 13% CPU usage. I want to make it higher, like 6 cores on the same task, or each core will take care of one part. The first core will start looping only the 8 character length ones, and second core will do the same with 7 character length ones... and when one of them finds the answer, the program will end. Can we really do it?</p></li>
</ol>
<p><a href="http://pastebin.com/ZT373674/">Here is the code</a></p>
<pre><code>#include <iostream>
#include <ctime>
using namespace std;
string crackPassword(string pass);
long long int attempt;
clock_t start_t, end_t;
int main(){
string password;
cout << "Enter the password to crack : ";
cin >> password;
cout << endl << endl << endl << ">\n>> CRACKED THE PASSWORD! >>\n>" << endl << endl <<"The password : " << crackPassword(password) << endl;
cout << "The number of attempts : " << attempt << endl;
cout << "The time duration passed : " << (double)(end_t - start_t)/1000 << " seconds" << endl << endl;
return 0;
}
string crackPassword(string pass){
int digit[7],alphabetSet=1,passwordLength=1;
start_t = clock();
string test,alphabet = "1337 also daktari is pro";
while(1){
switch(passwordLength){
case 1:
while(alphabetSet<4){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
}
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
case 2:
alphabetSet=1;
while(alphabetSet<6){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
case 4 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyz) - 36 Characters, please wait"; break;
case 5 : alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
for(digit[1]=0;digit[1]<alphabet.length();digit[1]++)
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
case 3:
alphabetSet=1;
while(alphabetSet<8){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
case 4 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyz) - 36 Characters, please wait"; break;
case 5 : alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing uppercase characters and numbers(0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 36 Characters, please wait"; break;
case 6 : alphabet = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 52 Characters, please wait"; break;
case 7 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 62 Characters, please wait"; break;
}
for(digit[2]=0;digit[2]<alphabet.length();digit[2]++)
for(digit[1]=0;digit[1]<alphabet.length();digit[1]++)
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
case 4:
alphabetSet=1;
while(alphabetSet<8){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
case 4 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyz) - 36 Characters, please wait"; break;
case 5 : alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing uppercase characters and numbers(0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 36 Characters, please wait"; break;
case 6 : alphabet = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 52 Characters, please wait"; break;
case 7 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 62 Characters, please wait"; break;
}
for(digit[3]=0;digit[3]<alphabet.length();digit[3]++)
for(digit[2]=0;digit[2]<alphabet.length();digit[2]++)
for(digit[1]=0;digit[1]<alphabet.length();digit[1]++)
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
case 5:
alphabetSet=1;
while(alphabetSet<8){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
case 4 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyz) - 36 Characters, please wait"; break;
case 5 : alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing uppercase characters and numbers(0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 36 Characters, please wait"; break;
case 6 : alphabet = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 52 Characters, please wait"; break;
case 7 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 62 Characters, please wait"; break;
}
for(digit[4]=0;digit[4]<alphabet.length();digit[4]++)
for(digit[3]=0;digit[3]<alphabet.length();digit[3]++)
for(digit[2]=0;digit[2]<alphabet.length();digit[2]++)
for(digit[1]=0;digit[1]<alphabet.length();digit[1]++)
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
case 6:
alphabetSet=1;
while(alphabetSet<8){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
case 4 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyz) - 36 Characters, please wait"; break;
case 5 : alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing uppercase characters and numbers(0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 36 Characters, please wait"; break;
case 6 : alphabet = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 52 Characters, please wait"; break;
case 7 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 62 Characters, please wait"; break;
}
for(digit[5]=0;digit[5]<alphabet.length();digit[5]++)
for(digit[4]=0;digit[4]<alphabet.length();digit[4]++)
for(digit[3]=0;digit[3]<alphabet.length();digit[3]++)
for(digit[2]=0;digit[2]<alphabet.length();digit[2]++)
for(digit[1]=0;digit[1]<alphabet.length();digit[1]++)
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
case 7:
alphabetSet=1;
while(alphabetSet<8){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
case 4 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyz) - 36 Characters, please wait"; break;
case 5 : alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing uppercase characters and numbers(0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 36 Characters, please wait"; break;
case 6 : alphabet = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 52 Characters, please wait"; break;
case 7 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 62 Characters, please wait"; break;
}
for(digit[6]=0;digit[6]<alphabet.length();digit[6]++)
for(digit[5]=0;digit[5]<alphabet.length();digit[5]++)
for(digit[4]=0;digit[4]<alphabet.length();digit[4]++)
for(digit[3]=0;digit[3]<alphabet.length();digit[3]++)
for(digit[2]=0;digit[2]<alphabet.length();digit[2]++)
for(digit[1]=0;digit[1]<alphabet.length();digit[1]++)
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
case 8:
alphabetSet=1;
while(alphabetSet<8){
switch(alphabetSet){
case 1 : alphabet = "-0123456789";
cout << endl << endl <<"Testing only digits(0123456789) - 10 Characters, please wait"; break;
case 2 : alphabet = "-abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only lowercase characters(abcdefghijklmnopqrstuvwxyz) - 26 Characters, please wait"; break;
case 3 : alphabet = "-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing only uppercase characters(ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 26 Characters, please wait"; break;
case 4 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyz) - 36 Characters, please wait"; break;
case 5 : alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing uppercase characters and numbers(0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ) - 36 Characters, please wait"; break;
case 6 : alphabet = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 52 Characters, please wait"; break;
case 7 : alphabet = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << endl << "Couldn't find the password, increasing the searching level."<< endl << endl << "Testing lowercase, uppercase characters and numbers(0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ) - 62 Characters, please wait"; break;
}
for(digit[7]=0;digit[7]<alphabet.length();digit[7]++)
for(digit[6]=0;digit[6]<alphabet.length();digit[6]++)
for(digit[5]=0;digit[5]<alphabet.length();digit[5]++)
for(digit[4]=0;digit[4]<alphabet.length();digit[4]++)
for(digit[3]=0;digit[3]<alphabet.length();digit[3]++)
for(digit[2]=0;digit[2]<alphabet.length();digit[2]++)
for(digit[1]=0;digit[1]<alphabet.length();digit[1]++)
for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){
attempt++;
if(attempt%2500000==0) cout << ".";
test=alphabet[digit[0]];
for(int i=1;i<passwordLength;i++)
if(alphabet[digit[i]]!='-')test+=alphabet[digit[i]];
if(pass.compare(test)==0){end_t = clock(); return test;}
}
alphabetSet++;
}
break;
}
cout << endl << endl << endl << endl << "*" << endl;
cout << "*** Password length is not " << passwordLength << ". Increasing password length! ***";
cout << endl << "*" << endl << endl;
passwordLength++;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T03:17:44.317",
"Id": "77498",
"Score": "0",
"body": "\"I want to make it higher like 6 cores ... Can we really do it?\" Yes that can be done. To do it, I think you need to use \"multithreading\". Support for multithreading is built-in to C++11 ([see for example here](http://www.cplusplus.com/reference/thread/thread/))."
}
] | [
{
"body": "<ul>\n<li><p>Prefer not to get into the habit of using <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a>.</p></li>\n<li><p>Make sure to include <code><string></code>.</p></li>\n<li><p>For the <code><ctime></code> library, you should use <code>std::clock_t</code> instead of <code>clock_t</code>.</p></li>\n<li><p>Prefer to avoid global variables:</p>\n\n<pre><code>long long int attempt;\nclock_t start_t, end_t;\n</code></pre>\n\n<p>As these variables can be modified anywhere in the program, you could introduce bugs, which will also hurt maintainability and testability.</p>\n\n<p>You should have <code>attempt</code> initialized to 0 (it's being incremented) in <code>main()</code> and pass it to <code>crackPassword()</code> by reference. In this way, you'll know that only these two functions can recognize <code>attempt</code> (if you ever add additional functions).</p>\n\n<p><code>start_t</code> and <code>end_t</code> just need to be in <code>main()</code>. I'd also recommend renaming them (especially remove the <code>_t</code>), otherwise it may look like they're part of the library.</p></li>\n<li><p>There's no need to use <code>std::endl</code> so many times, which <em>also</em> flushes the buffer, needlessly slowing down the code. Just use <code>\"\\n\"</code>, which only gives a newline. It'll also make the code a bit shorter, especially in places where it can be put into an existing hard-coded output line.</p>\n\n<p>This, for instance:</p>\n\n<pre><code>cout << endl << endl << endl << \">\\n>> CRACKED THE PASSWORD! >>\\n>\" << endl << endl <<\"The password : \" << crackPassword(password) << endl;\n</code></pre>\n\n<p>would turn into this:</p>\n\n<pre><code>cout << \"\\n\\n\\n>\\n>> CRACKED THE PASSWORD! >>\\n>\\n\\n The password : \" << crackPassword(password) << \"\\n\";\n</code></pre>\n\n<p>You could also split this into separate lines for clarity, and to keep the lines shorter:</p>\n\n<pre><code>cout << \"\\n\\n\\n>\\n>> CRACKED THE PASSWORD! >>\\n>\\n\\n;\ncout << \"The password : \" << crackPassword(password) << \"\\n\";\n</code></pre></li>\n<li><p>You don't specifically need a C-style cast here:</p>\n\n<pre><code>(double)(end_t - start_t)/1000\n</code></pre>\n\n<p>Cast the C++ way, with <code>static_cast<></code>:</p>\n\n<pre><code>static_cast<double>(end_t - start_t)/1000\n</code></pre>\n\n<p>Also, in case you'll need to use this in other places, consider having it as a variable. You should also use the <code>CLOCKS_PER_SEC</code> macro, which is part of the library.</p>\n\n<pre><code>double timeDuration = static_cast<double>(end_t - start_t) / CLOCKS_PER_SEC;\n</code></pre></li>\n<li><p>In <code>crackPassword()</code>, <code>pass</code> should be passed by <code>const&</code> instead of by value as it's not being modified inside the function. This will also save an unnecessary copy.</p>\n\n<pre><code>string crackPassword(string const& pass){\n</code></pre></li>\n<li><p>Prefer to have one variable declaration/initialization per line:</p>\n\n<pre><code>int digit[7];\nint alphabetSet=1;\nint passwordLength=1;\n</code></pre>\n\n<p>This will allow each variable to be more visible. It will also be possible to add a comment for separate variables if needed.</p></li>\n<li><p>A line like this:</p>\n\n<pre><code>for(digit[0]=1;digit[0]<alphabet.length();digit[0]++){\n</code></pre>\n\n<p>should use appropriate whitespace for readability:</p>\n\n<pre><code>for (digit[0] = 1; digit[0] < alphabet.length(); digit[0]++) {\n</code></pre>\n\n<p>Generally, keep whitespace between operators, and in the case of <code>for</code> loop statements, separate each part as well.</p>\n\n<p>If this is being avoided because the line is too long, then it should be effectively shortened in some other way. All of that will help with readability.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T06:30:44.443",
"Id": "77511",
"Score": "0",
"body": "Can you explain me why \"using namespace std\" is bad? Thank you by the way, these information are useful for me!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T06:36:57.890",
"Id": "77513",
"Score": "2",
"body": "@daktari: It's generally discouraged as it exposes the STL code (which is contained in the `std` namespace) to the global namespace. For instance, if you were to create your own `string` class and use some of the same names, then with `using namespace std`, name-clashing will occur. This will create ambiguities and could prevent compilation. For small applications, or if you put this in a local scope (such as a function), then it's not a big deal. But if it's put in global, then it's exposed to the entire program."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:17:51.877",
"Id": "44630",
"ParentId": "44620",
"Score": "16"
}
},
{
"body": "<blockquote>\n <p>The one and only difference between those cases is the \"for loop\" count, case 1 got 1 for loop, case 8 got 8 nested for loops. I want to make my code prettier, so how can I get rid of this copy&paste code and make it 1/8 size of current size.</p>\n</blockquote>\n\n<p>Iterating through passwords is like counting numbers:</p>\n\n<ul>\n<li>Start with the first digit \"0\"</li>\n<li>Increment until you get to the last digit \"9\"</li>\n<li>Next increment, increment the next digit and reset this digit \"10\"</li>\n<li>Increment the first digit again: \"11\", \"12\", etc.</li>\n<li>Increment the next digit when you have to: \"20\"</li>\n<li>If you can't increment the next digit then increment the one after that: \"99\" \"100\"</li>\n</ul>\n\n<p>So something like (untested code ahead):</p>\n\n<pre><code>// try up to 8 digit password\nchar password[9];\n// password is null terminated\npassword[8] = 0;\n// password is initially zero-filled\nmemset(password,0,8);\n// start at last character and make it bigger by building to the left\nchar* pass = &password[7];\n\nfor (;;)\n{\n for(int i = 0; i < alphabet.length; ++i)\n {\n password[7] = alphabet[i];\n // test for password match here\n if (test.compare(pass))\n return string(pass); // found!\n }\n // increment one or more chars to the left\n // and maybe decrement pass to make it bigger\n // before we run the above for loop again on the right-most char\n for (int j = 6; j >= 0; --j)\n {\n if (password[j] == 0)\n {\n // first time we've overflowed this high\n --pass;\n password[j] = alphabet[0];\n break;\n }\n // increment the existing character\n string::size_t found = alphabet.find(password[j]);\n ++found;\n if (found < alphabet.length)\n {\n password[j] = alphabet[found];\n break;\n }\n // else need to overflow to the next higher\n password[j] = alphabet[0];\n if (j == 0)\n {\n // can't go higher, return failure\n return string(\"\");\n }\n continue; // i.e. try again with --j \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T06:35:41.340",
"Id": "77512",
"Score": "0",
"body": "I'll test it, it looks really fine but what about using \"Recursion\" for \"nested for loops\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:32:48.530",
"Id": "77633",
"Score": "0",
"body": "Recursion seems to me another possible, valid way to implement it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:46:42.610",
"Id": "77636",
"Score": "0",
"body": "I could not convert my nested loop to some recursion function, it is too complicated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:45:36.667",
"Id": "44639",
"ParentId": "44620",
"Score": "6"
}
},
{
"body": "<p>@ChrisW raises a good point, but doesn't take the concept as far as I would.</p>\n\n<p>He's absolutely correct that what you're doing it basically just counting. What he doesn't point out is that it can (and probably should) be <em>implemented</em> as actual counting.</p>\n\n<p>For example, to test all passwords up to 8 characters long, using only digits for the alphabet, we end up simply counting from 0 to 99999999. We convert each of those from a number to a string, then test the resulting string.</p>\n\n<p>I would, however, advise <em>against</em> the strategy you suggested of testing 1 digit numbers in one thread, 2 digit numbers in a second thread, and so on. The problem is fairly simple: each digit you add multiplies the number of combinations by 10. Your first thread, testing 1-digit passwords, only has 10 possibilities. By the time you get to the last thread (8-bit passwords) it has 10<sup>8</sup> times as many possibilities as the first. Clearly the first will finish <em>much</em> more quickly than the last; most of the time will still be consumed by only one thread (running on only one core).</p>\n\n<p>Instead, you want to split your overall range into a set of equal-sized sub-ranges. Given 100000000 combinations, you want to test approximately 100000000/8 = 12500000 possibilities on each core. To do that, you have one thread test possibilities from 0 to 12500000, the next from 12500000 to 25000000, and so on until you reach 99999999. This way, each thread does approximately equal work, so all the cores share the work about equally.</p>\n\n<p>There are a couple of different ways to do that. One would be to explicitly create threads, one for each range of numbers. Another possibility would be to leave most of the code as a fairly simple loop, and use OpenMP to split that loop up into threads:</p>\n\n<pre><code>#pragma omp parallel for\nfor (long long i = 0; i<9999999ULL; i++) {\n std::string candidate = std::to_string(i);\n if (test_password(candidate)) \n std::cout<<\"We found it!\\n\"<<candidate<<\"\\n\";\n} \n</code></pre>\n\n<p>Doing a quick test on my laptop, this reduced the search time for a password from about 3 seconds to less than 1 second. Of course, the absolute speed will depend on how long it takes to test a password, but as long as you can test passwords concurrently from multiple threads (or testing a password is a lot faster than generating one) you can gain considerable speed from multithreading this way.</p>\n\n<p>If you want to do roughly the same thing, but with (for example) a mixture of letters and digits, you can still use the same basic idea. The only difference is the <em>base</em> in which you convert the numbers to a string. For example, to use only letters (not digits) you could do something like this:</p>\n\n<pre><code>std::string to_string(long long val) { \n std::string ret;\n while (val) { \n ret += ('a' + val % 26);\n val /= 26;\n }\n}\n</code></pre>\n\n<p>To create a mixture of digits and letters, it's generally easiest to start with an array of the characters you want to use, then index into that array:</p>\n\n<pre><code>char digits[] = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\nstd::string to_string(long long val) { \n std::string ret;\n static const size_t size = sizeof(digits) -1;\n while (val) { \n ret += digits[val % size];\n val /= size;\n }\n}\n</code></pre>\n\n<p>At some point, this won't work correctly any more, simply because a long long (or even an <code>unsigned long long</code>) is large enough to produce all the numbers in a given range. If you need/want to search that large of a range, you'll probably need to do other things to improve your search though. An <code>unsigned long long</code> has a range of at least 64 bits, and generating all 64-bit numbers will take longer than you're probably willing to wait (even if we ignore conversion and testing the results, just counting from 0 to 0xffffffffffffffff will take longer than most people are willing to wait.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:05:29.650",
"Id": "77529",
"Score": "0",
"body": "Here is the fix, if there are some people are having same problem with to_string and <string> : [to_string Fix](http://tehsausage.com/mingw-to-string)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:44:51.553",
"Id": "77634",
"Score": "0",
"body": "I've tried both letters only and the \"mixture of digits and letters\" , both are looping from 1 to 999999, I don't see any letter.\n\n`std::string to_string(long long val);\n\nint main(){\n\n std::string password;\n std::cin >> password;\n\n for (long long i = 0; i<9999999ULL; i++) {\n std::string candidate = std::to_string(i);\n\n if (password.compare(candidate))\n std::cout<<\"\\n\"<<candidate<<\"\\n\";\n }\n}\n\n\nstd::string to_string(long long val) {\n std::string ret;\n while (val) {\n ret += ('a' + val % 26);\n val /= 26;\n }\n}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:53:05.567",
"Id": "77640",
"Score": "0",
"body": "@daktari This is a letter, from the alphabet of lower-case letters: `('a' + val % 26)`; because `val % 26` is a number; when `val % 26` is `0` then the letter is `'a' + 0` which is `'a'`; when `val % 26` is `1` then the letter is `'a' + 1` which is `'b'`; etc. Alternatively, this is a letter from the dictionary which is named 'digits': `digits[val % size]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T21:16:06.650",
"Id": "77684",
"Score": "0",
"body": "Yeah but as I said it loops only numbers when I print them, even if it makes a,b,c does it add them together like: zz then aaa then aab then aac etc."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T06:17:20.603",
"Id": "44645",
"ParentId": "44620",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "44630",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:50:03.377",
"Id": "44620",
"Score": "26",
"Tags": [
"c++",
"performance",
"beginner"
],
"Title": "Brute force password-cracker"
} | 44620 |
<p>I wrote a little function which formats a ms timestamp in a human readable way. I know there are lots of scripts out there, but I needed a very simple one, which only outputs minutes and hours. </p>
<p>I was wondering if there is any way to shorten or improve this code snippet, because to me it seems to be very long for the few things it actually does.</p>
<pre><code>function prettyTime(ms) {
var sec = ms / 1000,
time,
timeUnit;
if(sec > 3600) {
// Hours
time = Math.round(sec / 3600);
timeUnit = ' hr';
} else if(sec > 60) {
// Minutes
time = Math.round(sec / 60);
timeUnit = ' min';
} else {
return 'less than 1 min';
}
if(time > 1) {
timeUnit += 's';
}
return 'about ' + time + timeUnit + 'ago';
}
alert(prettyTime(7600001));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T15:19:42.933",
"Id": "78317",
"Score": "1",
"body": "One of the scripts out there is [fromNow using moment.js](http://momentjs.com/docs/#/displaying/fromnow/)."
}
] | [
{
"body": "<p>Hope this might be helpful - </p>\n\n<pre><code>function getRelativeTime(ms){\n var SECOND_MS = 1000;\n var MINUTE_MS = 60 * SECOND_MS;\n var HOUR_MS = 60 * MINUTE_MS;\n var DAY_MS = 24 * HOUR_MS;\n var WEEK_MS = 7 * DAY_MS;\n var MONTH_MS = 30 * DAY_MS;\n\n var lookup = [\"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\"];\n var values = [];\n values.push(ms / MONTH_MS); ms %= MONTH_MS;\n values.push(ms / WEEK_MS); ms %= WEEK_MS;\n values.push(ms / DAY_MS); ms %= DAY_MS;\n values.push(ms / HOUR_MS); ms %= HOUR_MS;\n values.push(ms / MINUTE_MS); ms %= MINUTE_MS;\n values.push(ms / SECOND_MS); ms %= SECOND_MS;\n\n var pretty = \"about \"; \n for(var i=0 ; i <values.length; i++){\n var val = Math.round(values[i]);\n if(val <= 0) continue;\n\n pretty += val + \" \" + lookup[i] + \" ago\";\n break;\n }\n return pretty;\n}\n\n\ngetRelativeTime(10000);\n</code></pre>\n\n<p>Output : </p>\n\n<pre><code>about 10 seconds ago\n</code></pre>\n\n<p>You can easily customize above code for your \"xx hours and xx mins ago\" use-case. Just change the for loop like this - </p>\n\n<pre><code>for(var i=0 ; i <values.length; i++){\n var val = Math.round(values[i]);\n if(val <= 0) continue;\n\n pretty += val + \" \" + lookup[i];\n\n var nextval = Math.round(values[i+1]);\n if(i+1 < values.length && nextval > 0){\n pretty += \" and \" + nextval + \" \" + lookup[i+1] + \" ago\";\n }\n else {\n pretty += \" ago\";\n }\n break;\n}\n</code></pre>\n\n<p>Output</p>\n\n<p>getRelativeTime(100000);</p>\n\n<pre><code>about 2 minutes and 40 seconds ago\n</code></pre>\n\n<p>getRelativeTime(1000000);</p>\n\n<pre><code>about 17 minutes and 40 seconds ago\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<blockquote>\n <p><code>Math.round</code> is causing wrong result in above code, <code>Math.floor</code> is more\n appropriate.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T23:48:54.040",
"Id": "77475",
"Score": "0",
"body": "Thanks, that looks a lot cleaner to me, although I think `var SECOND = 1;` should be var `SECOND = 1000;`, shouldn't it? Is there any elegant way to use 'less than a minute ago' instead of seconds?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T23:54:41.317",
"Id": "77476",
"Score": "0",
"body": "You're right, updated the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:37:16.157",
"Id": "77488",
"Score": "3",
"body": "IMO, `SECOND`, `MINUTE`, etc. should be named `SECOND_MS`, `MINUTE_MS`, and so on so it's clear what units they're in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:14:55.783",
"Id": "77666",
"Score": "0",
"body": "Makes sense, you got it!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T23:25:46.473",
"Id": "44626",
"ParentId": "44623",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "44626",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:23:34.073",
"Id": "44623",
"Score": "11",
"Tags": [
"javascript",
"datetime"
],
"Title": "Output human readable time"
} | 44623 |
<p>I'm currently trying to develop some code that will handle parsing and building of a custom binary protocol. The protocol itself
is still fairly fluid but the basic core features are decided. These include</p>
<ul>
<li>It has a start and end deliminator</li>
<li>It contains a header and payload set of data. The header is standard and contains information such as the payload type, time of sending etc</li>
<li>Any strings or chars will be Ascii characters</li>
</ul>
<p>Basic format is: [STX][Header][Payload][Checksum][ETX]</p>
<blockquote>
<p>Note: I can't use libraries like proto-buf .net as the protocol
specification itself is outside of my control.</p>
</blockquote>
<p>Any comments on code styling, design, implementation, best practices etc welcome.</p>
<p>Here is what I have come up with so far:</p>
<h3>Data streams</h3>
<pre><code>public interface IDataInputStream
{
string ReadString(int count);
char ReadChar();
int ReadInt32();
short ReadIn16();
byte ReadByte();
}
public class DataInputStream : IDataInputStream, IDisposable
{
private readonly BinaryReader _reader;
public DataInputStream(Stream stream)
{
_reader = new BinaryReader(stream, System.Text.Encoding.UTF8);
}
public string ReadString(int count)
{
return new string(_reader.ReadChars(count));
}
public char ReadChar()
{
return _reader.ReadChar();
}
public int ReadInt32()
{
return _reader.ReadInt32();
}
public short ReadIn16()
{
return _reader.ReadInt16();
}
public byte ReadByte()
{
return _reader.ReadByte();
}
public void Dispose()
{
_reader.Dispose();
}
}
public interface IDataOutputStream
{
void Write(char value);
void Write(string value, int length);
void Write(int value);
void Write(short value);
void Write(byte[] value);
}
public class DataOutputStream : IDataOutputStream, IDisposable
{
private readonly BinaryWriter _writer;
public DataOutputStream(Stream stream)
{
_writer = new BinaryWriter(stream);
}
public void Write(string value, int length)
{
var valueMinLength = value ?? string.Empty;
if (valueMinLength.Length < length)
{
valueMinLength = valueMinLength.PadRight(length, '\0');
}
var bytes = System.Text.Encoding.UTF8.GetBytes(valueMinLength);
Write(bytes);
}
public void Write(byte value)
{
Write(new byte[] { value });
}
public void Write(char value)
{
// In this protocol a char represents one byte however GetBytes of bitconverter treats the byte as unicode
var bytes = BitConverter.GetBytes(value);
Write(new byte[] { bytes[0] });
}
public void Write(int value)
{
// 4 bytes
var bytes = BitConverter.GetBytes(value);
Write(bytes);
}
public void Write(short value)
{
var bytes = BitConverter.GetBytes(value);
Write(bytes);
}
public void Dispose()
{
_writer.Dispose();
}
public void Write(byte[] value)
{
WriteBytes(value);
}
private void WriteBytes(byte[] bytes)
{
_writer.Write(bytes);
}
}
</code></pre>
<h3>The main Packet envelope</h3>
<pre><code>public class Packet<T> : IPacketCheckSumWriter, IPacketReader where T : DataPayload
{
public char Stx { get; private set; }
public char Etx { get; private set; }
public byte CheckSum { get; private set; }
public HeaderPayload Header { get; private set; }
public T Data { get; private set; }
public Packet(
HeaderPayload header,
T payload)
: this()
{
Header = header;
Data = payload;
}
public Packet()
{
Stx = PacketConstants.Stx;
Etx = PacketConstants.Etx;
}
public void Write(IDataOutputStream outputStream, IChecksum checkSumAlgorithm)
{
outputStream.Write(Stx);
WritePacketData(outputStream);
WriteChecksum(outputStream, checkSumAlgorithm);
outputStream.Write(Etx);
}
public void Read(IDataInputStream inputStream)
{
Stx = inputStream.ReadChar();
Header.Read(inputStream);
Data.Read(inputStream);
CheckSum = inputStream.ReadByte();
Etx = inputStream.ReadChar();
}
private void WriteChecksum(IDataOutputStream outputStream, IChecksum algorithm)
{
var bytes = GetPacketData();
CheckSum = algorithm.GetCheckSum(bytes);
outputStream.Write(CheckSum);
}
private void WritePacketData(IDataOutputStream outputStream)
{
Header.Write(outputStream);
Data.Write(outputStream);
}
private byte[] GetPacketData()
{
using (var stream = new MemoryStream())
{
using (var outputStream = new DataOutputStream(stream))
{
// First get the packet data bytes as this is what the algorithm is calculated on
WritePacketData(outputStream);
return stream.ToArray();
}
}
}
</code></pre>
<h3>Payload classes for the Header and Data </h3>
<pre><code>public class HeaderPayload : IPacketWriter, IPacketReader
{
public char Identifier { get; set; }
public char Command { get; set; }
public int PacketId { get; set; }
public int UnixTimeStamp { get; set; }
public void Write(IDataOutputStream outputStream)
{
outputStream.Write(Identifier);
outputStream.Write(Command);
outputStream.Write(PacketId);
outputStream.Write(UnixTimeStamp);
}
public void Read(IDataInputStream inputStream)
{
Identifier = inputStream.ReadChar();
Command = inputStream.ReadChar();
PacketId = inputStream.ReadInt32();
UnixTimeStamp = inputStream.ReadInt32();
}
}
public class FieldLength : Attribute
{
public int Length { get; private set; }
public FieldLength(int length)
{
Length = length;
}
}
public abstract class DataPayload : IPacketWriter, IPacketReader
{
public abstract void Write(IDataOutputStream outputStream);
public abstract void Read(IDataInputStream inputStream);
protected DataPayload()
{
// We want all strings to at least be an empty string so that we don't have to check for null all the time
SetAllStringsEmpty();
}
protected void SetAllStringsEmpty()
{
var properties = GetType().GetProperties().Where(p => p.PropertyType == typeof(string));
properties.ForEach(p => p.SetValue(this, string.Empty));
}
protected int GetFieldLength<T>(Expression<Func<T>> expr)
{
var body = ((MemberExpression) expr.Body);
return GetFieldLength(body.Member.Name);
}
protected int GetFieldLength(string property)
{
var attribute = GetType().GetProperty(property).GetCustomAttribute<FieldLength>();
if (attribute == null) return 1;
return attribute.Length;
}
}
</code></pre>
<h3>Main Packet builder</h3>
<pre><code>public static class PacketConstants
{
public static char Stx { get { return '$'; } }
public static char Etx { get { return '*'; } }
}
public static class PacketCommands
{
public const char RegistrationRequest = 'R';
}
public class PacketBuilder
{
public Packet<T> CreateEmptyPayload<T>(char command, int packetId, DateTime dateCreated) where T: DataPayload
{
var payload = Activator.CreateInstance<T>();
return new Packet<T>(new HeaderPayload
{
Command = command,
Identifier = '1',
PacketId = packetId,
UnixTimeStamp = UnixTimeConverter.DateTimeToUnixTimestamp(dateCreated)
},
payload);
}
public byte[] Build<T>(Packet<T> packet, IChecksum checkSum) where T : DataPayload
{
using (var stream = new MemoryStream())
{
using (var dataWriter = new DataOutputStream(stream))
{
// First get the packet data bytes as this is what the checksum is calculated on
packet.Write(dataWriter, checkSum);
return stream.ToArray();
}
}
}
public Packet<T> Build<T>(byte[] data) where T : DataPayload
{
using (var stream = new MemoryStream(data))
{
using (var inputStream = new DataInputStream(stream))
{
var packet = new Packet<T>(new HeaderPayload(), Activator.CreateInstance<T>());
packet.Read(inputStream);
// TODO: Validation on packet?
return packet;
}
}
}
public char GetCommand(byte[] data)
{
return (char) data[1];
}
}
</code></pre>
<h3>Example data payload</h3>
<pre><code>public class RegistrationRequest : DataPayload
{
[FieldLength(2)]
public string FirmwareVersion { get; set; }
public char HardwareVersion { get; set; }
[FieldLength(15)]
public string Imei { get; set; }
[FieldLength(20)]
public string Sim { get; set; }
public char DeviceModel { get; set; }
public override void Write(IDataOutputStream outputStream)
{
outputStream.Write(FirmwareVersion, GetFieldLength(() => FirmwareVersion ));
outputStream.Write(HardwareVersion);
outputStream.Write(Imei, GetFieldLength(() => Imei));
outputStream.Write(Sim, GetFieldLength(() => Sim));
outputStream.Write(DeviceModel);
}
public override void Read(IDataInputStream inputStream)
{
FirmwareVersion = inputStream.ReadString(GetFieldLength(() => FirmwareVersion));
HardwareVersion = inputStream.ReadChar();
Imei = inputStream.ReadString(GetFieldLength(() => Imei));
Sim = inputStream.ReadString(GetFieldLength(() => Sim));
DeviceModel = inputStream.ReadChar();
}
}
</code></pre>
<h3>And finally a couple of Unit tests</h3>
<pre><code>[TestClass]
public class RegistrationRequestTest
{
[TestMethod]
public void SerializesStxAndEtx()
{
var builder = new PacketBuilder();
var packet = builder.CreateEmptyPayload<RegistrationRequest>(PacketCommands.RegistrationRequest, 1234, DateTime.Now);
var bytes = builder.Build(packet, new Checksum());
Assert.AreEqual(PacketConstants.Stx, (char)bytes[0]);
Assert.AreEqual(PacketConstants.Etx, (char)bytes[bytes.Length - 1]);
}
[TestMethod]
public void SerializesHeader()
{
var dateCreated = DateTime.Now;
var builder = new PacketBuilder();
var packet = builder.CreateEmptyPayload<RegistrationRequest>(PacketCommands.RegistrationRequest, 1234, dateCreated);
var bytes = builder.Build(packet, new Checksum());
Assert.AreEqual('1', (char)bytes[1]);
Assert.AreEqual('R', (char)bytes[2]);
Assert.AreEqual(1234, BitConverter.ToInt32(bytes, 3));
Assert.AreEqual(UnixTimeConverter.DateTimeToUnixTimestamp(dateCreated), BitConverter.ToInt32(bytes, 7));
}
[TestMethod]
public void SerializesDataPayloadToByteArray()
{
var builder = new PacketBuilder();
var request = builder.CreateEmptyPayload<RegistrationRequest>(PacketCommands.RegistrationRequest, 1, DateTime.Now);
request.Data.HardwareVersion = 'A';
request.Data.Imei = "123456789456789";
request.Data.Sim = "12345678901234567890";
request.Data.FirmwareVersion = "12";
request.Data.DeviceModel = '3';
var bytes = builder.Build(request, new Checksum());
var deserialized = builder.Build<RegistrationRequest>(bytes);
Assert.AreEqual(request.Data.HardwareVersion, deserialized.Data.HardwareVersion);
Assert.AreEqual(request.Data.FirmwareVersion, deserialized.Data.FirmwareVersion);
Assert.AreEqual(request.Data.Imei, deserialized.Data.Imei);
Assert.AreEqual(request.Data.Sim, deserialized.Data.Sim);
Assert.AreEqual(request.Data.DeviceModel, deserialized.Data.DeviceModel);
Assert.AreEqual(request.CheckSum, deserialized.CheckSum);
}
}
</code></pre>
<p>Example of a controller action</p>
<pre><code> [HttpPost]
public HttpResponseMessage BinaryRequest(byte[] data)
{
var builder = new PacketBuilder();
var command = builder.GetCommand(data);
switch (command)
{
case PacketCommands.RegistrationRequest:
var packet = builder.Build<RegistrationRequest>(data);
// Do stuff with this packet
default:
throw new NotImplementedException("The command [" + command + "] is not currently supported");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T00:42:36.490",
"Id": "77481",
"Score": "0",
"body": "Am I right in assuming that you don't want any comments on the format of the protocol/packets, because \"protocol specification itself is outside of my control\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:01:16.577",
"Id": "77482",
"Score": "0",
"body": "@ChrisW I guess comments won't hurt and if reasonable I might be able to sway the protocol writers, but in general yes, you are correct Chris. I'm mainly looking for comments on the code in regards to parsing the protocol."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:02:42.640",
"Id": "77483",
"Score": "0",
"body": "@Jamal Why was my statement on the type of feedback removed? In the Ask Question page it specifically says to specify what type of feedback you are looking for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:16:49.277",
"Id": "77485",
"Score": "0",
"body": "I didn't remove it. It was sort of in an odd place at the very top, so I moved it just before the code block. That's also helpful so that the post preview will show the program's purpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:24:53.673",
"Id": "77487",
"Score": "2",
"body": "You're welcome. Sorry for the confusion. :-)"
}
] | [
{
"body": "<h2>Protocol</h2>\n\n<p>It's strange to use a \"custom protocol\". Has no-one invented one you can reuse?</p>\n\n<p>In a binary protocol with STX and ETX I'm used to seeing DLE being used as well:</p>\n\n<pre><code><DLE><STX> <PAYLOAD> <DLE><ETX>.\n</code></pre>\n\n<p>... with DLE in the payload being escaped as <code><DLE><DLE></code>.</p>\n\n<p>I was surprised to find no \"total packet length\" or \"total payload length\" field in the packet header.</p>\n\n<p>Your protocol doesn't handle variable-length strings in the payload well.</p>\n\n<p>A one-byte checksum is pretty small.</p>\n\n<p>This protocol doesn't recover from transmission errors well: if you lose a byte, then because you don't use <code><DLE></code>, you can't reliably find the start of the next packet (unless you guarantee that the STX char i.e. '$' is unique and never found in the header, not the payload, nor the checksum).</p>\n\n<p><a href=\"https://stackoverflow.com/a/393416/49942\">Text-based protocols can be easier to work with</a>.</p>\n\n<h2>Code</h2>\n\n<p>Do you validate the received packet somewhere? Check that it starts with Stx, ends with Etx, and includes a valid checksum?</p>\n\n<p>Your test code uses strings whose lengths are equal to the maximum field length; the receive code shows that short string will be zero-padded, but you don't have a unit-test for that.</p>\n\n<p>BinaryReader is little-endian. Is your protocol little-endian too?</p>\n\n<p>GetCommand returns <code>data[1]</code>. Should it return <code>data[2]</code>: maybe <code>data[0]</code> is the STX and <code>data[1]</code> is the Identifier?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:59:32.263",
"Id": "77490",
"Score": "0",
"body": "1) Validation is yet to be implemented. I was thinking of doing it in the PacketBuilder class. 2) Yes you are right. I do not have a unit test for that. I have not completed all of the unit tests yet. 3) Yes, it's little-endian. 4) You are right. I think GetCommand() is a bug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:00:48.420",
"Id": "77491",
"Score": "0",
"body": "Good points on the protocol. Yeah we wanted to use binary to safe on packet size as there are a-lot sent. I'm not sure if we are going to allow variable length strings but that is something I might follow up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:01:48.647",
"Id": "77492",
"Score": "1",
"body": "Sorry, but What is DLE?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:10:41.510",
"Id": "77493",
"Score": "0",
"body": "@dreza DLE: see for example 2nd paragraph of page 2 of https://tools.ietf.org/html/rfc171 ... it's a way to ensure that your STX and ETX are unique in the stream: `<DLE><STX>` = start of packet; `<DLE><ETX>` are end of packet; `<DLE>` inside the packet is sent as `<DLE><DLE>` to ensure that `<DLE><STX>` and `<DLE><ETX>` are never sent within the packet. `<DLE>` is a byte value ('0x10'), and so are STX and ETX: http://en.wikipedia.org/wiki/Control_character"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:55:05.923",
"Id": "44634",
"ParentId": "44625",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T23:13:22.767",
"Id": "44625",
"Score": "11",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Writing and reading of a custom binary protocol"
} | 44625 |
<p>Should I have made a line break <code>convert_to_quick_mode(</code> and <code>from_exported_cdf,</code></p>
<pre><code> convert_to_quick_mode(
from_exported_cdf,
</code></pre>
<p>code:</p>
<pre><code>class QuickModeConverter(object):
def run(self,
from_exported_cdf,
from_exported_msword,
to_export_quick_mode_cdf,
to_export_quick_mode_msword
):
convert_to_quick_mode(
from_exported_cdf,
from_exported_msword,
to_export_quick_mode_cdf,
to_export_quick_mode_msword
)
pass
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T04:35:00.030",
"Id": "77504",
"Score": "0",
"body": "I suspect that you may have a deeper issue that causes you to have this unusual problem in the first place. Maybe it's a poor abstraction, maybe it's poor naming. Could you provide more context about what your function aims to accomplish, and what its parameters mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:09:38.870",
"Id": "77552",
"Score": "2",
"body": "Perhaps this is a red herring, but if you're looking to avoiding some typing, `run = staticmethod(convert_to_quick_mode)` should work."
}
] | [
{
"body": "<p>Best option would be to just use <code>*args</code> (or <code>**kwargs</code> if order does not matter), as follows:</p>\n\n<pre><code>class QuickModeConverter(object):\n def run(self, *args):\n convert_to_quick_mode(*args)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T03:36:47.883",
"Id": "77499",
"Score": "2",
"body": "but I think make parameters explicitly is more readable for maintaining code, and the order of the params is meaningful in my code :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T03:42:55.450",
"Id": "77500",
"Score": "1",
"body": "@poc It's a good point if it's a user-facing code. In this case, the way you describe is a correct, at least style-wise."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T02:29:21.627",
"Id": "44638",
"ParentId": "44632",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T01:40:41.317",
"Id": "44632",
"Score": "2",
"Tags": [
"python",
"formatting"
],
"Title": "Formatting the Lengthy Parameters in a better way"
} | 44632 |
<p>I am a beginner and I have made a Reservation Form in HTML. I'm pretty sure it will look horrible to any developer out there, but hey, that's why I've posted it.</p>
<p>I'd like a general review of this. I'm especially concerned about the quality and enhancements of this form. What should I do to add attractive looks and to upload the input data somewhere, So that I could read it?</p>
<pre><code><HTML><BODY>
<H1>RESERVATION FORM</H1>
<P>NAME<INPUT TYPE="TEXT" SIZE="20" MAXLENGTH="99" />
<P>AGE<INPUT TYPE="TEXT" SIZE="12" MAXLENGTH="99" />
<P>ADDRESS<INPUT
<TYPE="TEXT" SIZE="42" MAXLENGTH="99" />
<P>EMAIL<INPUT TYPE="TEXT" SIZE="30" MAXLENGTH="99" />
<P>TELEPHONE<INPUT TYPE="TEXT" SIZE="10" MAXLENGTH="99" />
<P>SELECT YOUR
BERTH
<SELECT NAME="CHOICES" SIZE="3">
<OPTION>TATKAL</OPTION>
<OPTION>LADIES</OPTION>
<OPTION>GENRAL</OPTION>
</SELECT></P>
<P>CITY<SELECT naME="CITY"><OPTION SELECTED>
DELHI</OPTION><OPTION>MUMBAI</OPTION><OPTION>KOLKATA</OPTION><OPTION>CHENNAI</OPTION></p><br><br>
<input type="submit" value="click here to submit" />
<input
type="reset" value="clear this form" /></BODY></HTML>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T05:14:20.397",
"Id": "77508",
"Score": "2",
"body": "\"What should I do to add attractive looks\" - Add a CSS stylesheet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T05:17:54.813",
"Id": "77509",
"Score": "2",
"body": "\"What should I do to upload the input data somewhere, so that I could read it?\"- Put the form on a web server, so that users can load the form in their web browser using HTTP. You'll also need [a `<form>` element](http://www.w3.org/TR/html401/interact/forms.html) in the page."
}
] | [
{
"body": "<ol>\n<li>You are missing ending paragraph tags</li>\n<li>your tags should be lowercase\n<ul>\n<li>I think that Uppercase is normal for straight HTML, but I suggest using something other than straight HTML. I suggest XHTML or HTML5, and in that case everything should be lowercase.</li>\n</ul></li>\n<li>be careful with your indentation.\n<ul>\n<li>When you go looking through code you want to be able to find things right away and know when one tag ends and another one starts.</li>\n</ul></li>\n</ol>\n\n<p>With that it should look like this </p>\n\n<pre><code><html>\n <body>\n <form>\n <h1>RESERVATION FORM</h1>\n <p>NAME<input type=\"TEXT\" size=\"20\" maxlength=\"99\" /></p>\n <p>AGE<input type=\"TEXT\" size=\"12\" maxlength=\"99\" /></p>\n <p>ADDRESS<input type=\"TEXT\" size=\"42\" maxlength=\"99\" /></p>\n <p>EMAIL<input type=\"TEXT\" size=\"30\" maxlength=\"99\" /></p>\n <p>TELEPHONE<input type=\"TEXT\" size=\"10\" maxlength=\"99\" /></p>\n <p>SELECT YOUR BERTH </p>\n <select name=\"CHOICES\" size=\"3\">\n <option>TATKAL</option>\n <option>LADIES</option>\n <option>GENRAL</option>\n </select>\n <p>CITY</p>\n <select name=\"CITY\">\n <option selected=\"selected\">DELHI</option>\n <option>MUMBAI</option>\n <option>KOLKATA</option>\n <option>CHENNAI</option>\n <br/><br/>\n <input type=\"submit\" value=\"click here to submit\" />\n <input type=\"reset\" value=\"clear this form\" />\n </form>\n </body>\n</html>\n</code></pre>\n\n<p>I don't like your <code>input</code> tags being nested inside of your paragraph tags either. You should replace this with label tags like this:</p>\n\n<pre><code><label text=\"Name\" />\n<input type=\"text\" size=\"20\" maxlength=\"99\" />\n<label text=\"age\" />\n<input type=\"text\" size=\"12\" maxlength=\"99\" />\n<label text=\"Address\" />\n<input type=\"text\" size=\"42\" maxlength=\"99\" />\n<label text=\"Email\" />\n<input type=\"text\" size=\"30\" maxlength=\"99\" />\n<label text=\"Telephone\" />\n<input type=\"text\" size=\"10\" maxlength=\"99\" />\n<label text=\"Select Your Birth\" />\n....\n</code></pre>\n\n<p>This is the perfect reason to use a label tag instead of a paragraph tag. you may want to use some <code><br/></code> in there too, but that depends on what you are going to do CSS wise, if you are going to use CSS that is.</p>\n\n<p>If you are going really old school you are going to want to set up some tables, but that wouldn't be good, so use CSS.</p>\n\n<hr>\n\n<p>With the CSS you might want to Add some ID's or classes for the input tags and maybe the label tags as well, so that you can add styling to them. It would also be difficult to use some sort of code behind with this HTML unless you have some ID's associated with the controls that you want to change dynamically.</p>\n\n<hr>\n\n<h1>UPDATE</h1>\n\n<p>I added the form tags to this answer after I saw @200_Success's answer. I can't believe I missed the missing tags.</p>\n\n<p>After all that, there are still many attributes missing in the other tags, and more things missing to make this fun registration form from working.</p>\n\n<hr>\n\n<p>I changed my <code>option</code> tags so that they validate, I don't know what I was thinking. Maybe I was still in C# mode thinking or something.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T02:29:51.590",
"Id": "77993",
"Score": "0",
"body": "`<option selected=\"true\">` fails validation. You can say `<option selected=\"selected\">` or `<option selected>`, depending on the HTML dialect."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T04:44:30.557",
"Id": "44641",
"ParentId": "44640",
"Score": "11"
}
},
{
"body": "<p>The most obvious mistake — which makes your code malformed HTML — is the extra <code><</code> before <code>TYPE</code>:</p>\n\n<pre><code><P>ADDRESS<INPUT\n\n<TYPE=\"TEXT\" … />\n</code></pre>\n\n<p>The next biggest issue, in my opinion, is that your <code><P></code> tags aren't consistently being closed. Only in the earliest days of HTML was it acceptable to use an unclosed <code><P></code> as a line break. These days, it's generally accepted that paragraphs should lie between <code><P></code> and <code></P></code>.</p>\n\n<p>The next thing you should do is to add a doctype declaration at the very beginning, which tells the browser which version of the HTML standard is being used. Without the doctype, browsers will interpret the document in slightly non-standard ways, especially if you use CSS. If you have no preference for any particular doctype, use HTML5:</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n ...\n</html>\n</code></pre>\n\n<p>Once you have declared a doctype, you can then run the code through an <a href=\"http://validator.w3.org/\">HTML validator</a>, which will tell you everything else that is syntactially incorrect. For example, it's OK to say</p>\n\n<pre><code><option selected=\"selected\">...</option\n</code></pre>\n\n<p>or</p>\n\n<pre><code><option selected>...</option>\n</code></pre>\n\n<p>but not</p>\n\n<pre><code><option selected=\"true\">\n</code></pre>\n\n<p>HTML is case-insensitive, but you should choose either uppercase or lowercase consistently anyway. Since XHTML mandates lowercase, I recommend using lowercase everywhere too, even if you are using HTML instead of XHTML.</p>\n\n<p>Oddly, your form has no <code><form></code> tag.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T05:06:10.260",
"Id": "77507",
"Score": "3",
"body": "I can't believe I missed the missing `<form></form>` tags..... *Face Palm*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:31:29.960",
"Id": "77896",
"Score": "0",
"body": "Why did you use `<P>` instead of `<p>` ? Should not all tags be lowercase ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:33:17.143",
"Id": "77897",
"Score": "2",
"body": "@Marc-Andre Yes, it should be lowercase. I only wrote `<P>` instead of `<p>` since I deferred mention of the lowercase issue until the end."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T04:58:20.750",
"Id": "44642",
"ParentId": "44640",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T04:00:43.813",
"Id": "44640",
"Score": "10",
"Tags": [
"beginner",
"html",
"form"
],
"Title": "Reservation Form in HTML"
} | 44640 |
<h3> Preamble </h3>
<p>So, as most of you have likely also noticed, chat components, at least at a basic level, are becoming very common with lots of apps. I found myself tweaking and redesigning the interface from my last project all the time, so I decided to just create an easy to drop in solution. I'd love to get some second opinions on the code, the design, the class interface, or whatever else you've got to say about it!</p>
<p>Full Project <a href="https://github.com/LoganWright/SimpleChat" rel="nofollow noreferrer">Here</a></p>
<h3> Usage </h3>
<p>ViewController.h</p>
<pre><code>#import <UIKit/UIKit.h>
#import "ChatController.h"
@interface ViewController : UIViewController <ChatControllerDelegate>
@property (strong, nonatomic) ChatController * chatController;
@end
</code></pre>
<p>Launch With This:</p>
<pre><code>if (!_chatController) _chatController = [ChatController new];
_chatController.delegate = self;
_chatController.chatTitle = @"Simple Chat";
_chatController.opponentImg = [UIImage imageNamed:@"tempUser.png"];
[self presentViewController:_chatController animated:YES completion:nil];
</code></pre>
<p>Receive Message (Delegate):</p>
<pre><code>- (void) sendNewMessage:(NSString *)messageString {
NSLog(@"Received msg: %@", messageString);
}
</code></pre>
<p>Add Message:</p>
<p>It receives a dictionary with the message set as a content key. We use the dictionary within the controller so we can pass additional information like userId's, to see who sent the message, or timestamps. This is just a demo.</p>
<pre><code>NSMutableDictionary * newMessageOb = [NSMutableDictionary new];
newMessageOb[kMessageContent] = @"Some Message To Send";
// Add Message Right To Collection
[_chatController addNewMessage:newMessageOb];
</code></pre>
<p>You'll also have to go into the controller and add some logic to assign who sent the message. Right now it's random just so you can see how it looks and works:</p>
<pre><code>int sentByNumb = arc4random() % 2;
message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:(sentByNumb == 0) ? kSentByOpponent : kSentByUser];
</code></pre>
<p>You can put whatever logic you'd want there, likely something similar to:</p>
<pre><code>NSString * sentById = message[@"sentById"];
if ([sentById isEqualToString:currentUserId]) {
message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:kSentByUser];
}
else {
message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:kSentByOpponent];
}
</code></pre>
<h3> Design </h3>
<p><img src="https://i.stack.imgur.com/OrRIO.png" alt="enter image description here"></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T11:42:58.253",
"Id": "77542",
"Score": "0",
"body": "Are you asking us to review the usage code from an end-user (as a developer who might use this class) perspective?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:10:55.140",
"Id": "77612",
"Score": "0",
"body": "@nhgrif - if interested, yes!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:45:18.150",
"Id": "77691",
"Score": "1",
"body": "Be sure the constants you're using as dictionary keys are `NSString * const` and not `#define`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:52:55.533",
"Id": "77692",
"Score": "0",
"body": "I don't think I used any `#define`'s in this proj. Already set up as const!"
}
] | [
{
"body": "<h1><code>[ChatController new];</code></h1>\n<p>This is perfectly fine syntax, but an Objective-C purists doesn't necessarily like the <code>new</code> method that much. <code>new</code> is simply an <code>NSObject</code> method that looks like this:</p>\n<pre><code>+ (instancetype)new {\n return [[self alloc] init];\n}\n</code></pre>\n<p>And as such, anything that inherits from <code>NSObject</code> will have this method. But the only reason it exists as far as I know is for something like a security blanket for people coming from other languages where object instantiation might look something like this:</p>\n<pre><code>ChatController *chatController = new ChatController();\n</code></pre>\n<p>They want to hang on to their <code>new</code> keyword--their clue that they're instantiating a new object. And while this is fine for those who choose to use it, a complete class would write its own factory method(s) in addition to the default one inherited from <code>NSObject</code>.</p>\n<p>NSArray, NSDictionary, NSNumber, NSDate, etc, etc, etc. Most of the Foundation classes have their own method that does something similar to what the <code>new</code> method does. You would be wise to follow suite with a method that looks something like this:</p>\n<pre><code>+ (instancetype)chatController {\n return [[self alloc] init];\n}\n</code></pre>\n<p>Now, someone like me who prefers doing things the real Objective-C way can do <code>[ChatController chatController]</code> in place of <code>new</code>.</p>\n<p>As someone who might use a library like yours, the existence of such a method tells me that you've paid some attention to your instantiation methods and aren't relying on those inherited from <code>NSObject</code>. This assures me that any instance variables that need to be set before I call any methods (if any at all) are definitely going to be set.</p>\n<p>As a note, if you override <code>init</code>, this instance variables will still be set when calling <code>new</code>, because remember, <code>new</code> is simply <code>return [[self alloc] init];</code> so it calls the <code>init</code> method you wrote.</p>\n<hr />\n<p>The fact of the matter is though, whether we use <code>[ChatController new];</code>, <code>[ChatController alloc] init];</code>, or <code>[ChatController chatController];</code>, your class isn't completely ready to use.</p>\n<p>What would happen if I presented an instance of your <code>ChatController</code> class before I set the <code>delegate</code>, <code>chatTitle</code>, and <code>opponentImg</code>? Hopefully, you've written the class in such a way that <code>nil</code> or an empty string is a perfectly fine title, and that <code>nil</code> for <code>opponentImg</code> causes no problems. But what about the delegate?</p>\n<p>Sometimes, objects that can have a delegate function somewhat fine without a delegate. For example, a tableview has a delegate property, but it also has a datasource property. The datasource fills the table with information. The delegate handles user interaction with the table. But if you don't need to respond to any of the user interactions and only need the table to display information to a user, your table will function just fine without a delegate. (And a table with static information doesn't need a datasource--the static cells can be completely created in IB).</p>\n<p>Is this the case with your <code>ChatController</code>? Can it function just fine without a delegate?</p>\n<p>If these three properties are all truly optional and the class works just fine if they're all set to <code>nil</code>, then you're fine as you are and the following information would be something optional to consider, purely a nicety (one which I always include in my classes). However, if these properties are not optional and it's not okay to set them to <code>nil</code>, then you really need to implement some factory methods.</p>\n<p>Assuming only the delegate is necessary, first we'll create a new <code>init</code> method:</p>\n<pre><code>- (id)initWithDelegate:(id<ChatControllerDelegate>)delegate {\n self = [super init];\n if (self) {\n _delegate = delegate;\n }\n return self;\n}\n</code></pre>\n<p>This method takes the delegate as an argument and sets this property upon while it's doing its initializing. But as is, we have to write:</p>\n<pre><code>ChatController *chatController = [[ChatController alloc] initWithDelegate:self];\n</code></pre>\n<p>So let's wrap it in a factory method:</p>\n<pre><code>+ (instancetype)chatControllerWithDelegate:(id<ChatControllerDelegate>)delegate {\n return [[self alloc] initWithDelegate:delegate];\n}\n</code></pre>\n<p>Now, it's as simple as this:</p>\n<pre><code>ChatController *chatController = [ChatController chatControllerWithDelegate:self];\n</code></pre>\n<p>Following this same pattern, you should include a factory method that sets all the properties that a user is likely to want to set before doing anything with the object. For example:</p>\n<pre><code>- (id)initWithDelegate:(id<ChatControllerDelegate>)delegate\n chatTitle:(NSString*)chatTitle\n opponentImage:(UIImage*)opponentImage {\n self = [super init];\n if (self) {\n _delegate = delegate;\n _chatTitle = chatTitle;\n _opponentImage = opponentImage;\n }\n return self;\n}\n\n+ (instancetype)chatControllerWithDelegate:(id<ChatControllerDelegate>)delegate\n chatTitle:(NSString*)chatTitle\n opponentImage:(NSString*)opponentImage {\n return [[self alloc] initWithDelegate:delegate\n chatTitle:chatTitle\n opponentImage:opponentImage];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:33:57.840",
"Id": "77689",
"Score": "0",
"body": "As far as setting properties, If you don't include an opponent image, it just orients the opponent chat bubbles to the edge. All of the properties are set to defaults in the Init call. Even without a delegate, it will run (I think I might have even put a NSLog notification). I just adopted the 'new' syntax because I liked the cleanliness of it, you're the second person to say something, so I guess I'll go back to the classic alloc]init] or a custom method as you suggest. I do like your init method suggestions overall because they make it even more clear, thanks for the suggestions!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:35:10.533",
"Id": "77690",
"Score": "0",
"body": "How you personally instantiate is up to you. I'm just making sure that a factory method exists."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:19:25.770",
"Id": "44710",
"ParentId": "44644",
"Score": "3"
}
},
{
"body": "<h1>ChatControllerDelegate</h1>\n<p>First and foremost, it's a little strange to see a <code>UIViewController</code> subclass that has a delegate. It's not entirely unheard of however, and can be justified. But let's talk about you situation and your delegate.</p>\n<pre><code>- (void) sendNewMessage:(NSString *)messageString\n</code></pre>\n<p>First of all, this is a bad method name. It's confusing and unclear as to when and why this message would be called. If the <code>ChatControllerDelegate</code> is calling this method on its delegate when the user sends an outbound message, a better method name might be:</p>\n<pre><code>- (void)chatController:(ChatController*)chatController didSendNewMessage:(NSString*)message;\n</code></pre>\n<p>However, if the <code>ChatControllerDelegate</code> is calling this method on its delegate when a new inbound message is received, a better method name would look more like this:</p>\n<pre><code>- (void)chatController:(ChatController*)chatController didReceiveNewMessage:(NSString*)message;\n</code></pre>\n<p>When the <code>ChatController</code> object calls this method on its delegate, it's going to send <code>self</code> for the first argument, and the message for the second argument. The reason for doing this is similar to the reason why the Foundation classes do this. A <code>UIViewController</code> can delegate multiple <code>UITableView</code> objects. Because they send <code>self</code> as part of the arguments in the method call, the <code>UIViewController</code> can distinguish which table is calling the method and respond appropriately.</p>\n<p>Imagine I've implemented your <code>ChatController</code> with a <code>UITabBarController</code> as the <code>ChatControllerDelegate</code>, and each <code>ChatController</code> is a different tab. Perhaps I want to automatically change tabs when the user receives a new message, or maybe just put one of the little red circles with the number in it to indicate the number of unread messages on any given tab. The <code>UITabBarController</code> could be delegating any number of <code>ChatController</code>s, and as such, it's important that it knows which one of them the method call is coming from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:57:18.003",
"Id": "77693",
"Score": "0",
"body": "I hadn't considered that situation with a nav controller, I'll add a self arg. There is no delegate method for receiving messages, this is only for UI. Do you suggest an alternative to delegate? I want to notify when the user inputs and tries to send a message. You could go into the chatController source code and handle it there if you want to, I just wanted to keep it simple so you could host all your chat logic somewhere and just update this as a UI element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:59:57.797",
"Id": "77694",
"Score": "0",
"body": "So, the already written `ChatController` will handle the sending of messages? I would definitely include the (optional) delegate method for receiving messages for the scenario I described. Are you wanting to give the delegate an opportunity to override the message being sent?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:03:12.400",
"Id": "77695",
"Score": "0",
"body": "I don't send the messages within the controller, I have no idea what type of backend you'll be uploading the messages to. When you type and press send, it passes it to the delegate so you can upload it to your server however you like. I can't really add a delegate for receiving messages because I don't have any contact with whatever server you're using. The controller only receives messages you send it by using `addMessage:`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:11:08.713",
"Id": "77698",
"Score": "0",
"body": "Okay, so in this case, you do only need the one delegate method. It should still include a reference to the `chatController` object that called it however. In this case though, I'd change the method name to something more like: `- (void)chatController:(ChatController*)cc didAddNewMessage:(NSString*)message;` The method is simply indicating that a new message has been added to the chat. And it matches the `addNewMessage:` method which you call on the `ChatController` to actually add a message. Your network object will receive a message, and call `addNewMessage:` on the chat controller..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:11:45.463",
"Id": "77699",
"Score": "0",
"body": "...which will in turn add the message to the view, then call `chatController:didAddNewMessage:` on its delegate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:12:10.430",
"Id": "77700",
"Score": "0",
"body": "Yea, I think self should definitely be returned as an arg, I'm adding that!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:26:07.350",
"Id": "77701",
"Score": "0",
"body": "Also, actually, instead of returning an `NSString` that just includes the message, you should return the `NSDictionary` that is passed in via the `addNewMessage:` argument so the delegate can pick whatever information out of this it needs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:28:41.273",
"Id": "77702",
"Score": "0",
"body": "Ya, I already changed that one, must not have sent it to Github! Good looking out though!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:44:05.640",
"Id": "44711",
"ParentId": "44644",
"Score": "3"
}
},
{
"body": "<h1>Some things that might be missing...</h1>\n<hr />\n<p>Your <code>addNewMessage:</code> method takes an <code>NSDictionary</code> argument because, as you say, you want the ability to be able to add other information such as user ID, etc. This is good forward thinking.</p>\n<p>However unfortunately, your <code>ChatController</code> class simply has an <code>opponentImage</code> property, which sets the image for messages sent by "opponent".</p>\n<p>I would recommend adding a handful of predefined constant NSString keys that users can use in their dictionary when adding messages to affect the look in a number of ways.</p>\n<ul>\n<li>A key for the image. Rather than an <code>opponentImage</code> property, we can pass in images with the dictionary for each message. This would allow chatrooms with multiple users.</li>\n<li>A key for the username. Add a way to allow the controller to display chatter's names if the user wants.</li>\n<li>A key for the chat bubble border color. Blue & green are nice, but you should be able to add any color the user wants, just have them pass in a <code>UIImage</code> constant here.</li>\n<li>A key for the timestamp. You've already consider this, but reserving a predefined constant value should be important as this will effect the way the message is displayed.</li>\n</ul>\n<hr />\n<p>You might consider some properties that the end user can easily set that will effect the overlook look and use of the chat.</p>\n<p>Some properties to consider:</p>\n<ul>\n<li>A UIFont property to allow the user to set the font the chat is displayed in</li>\n<li>UIColor properties to set various colors on the controller</li>\n<li>An NSDateFormatter property. Assuming time stamps are added, this property will allow the user to determine the format the timestamp appears in.</li>\n<li>A BOOL for auto-correct and a BOOL for auto-capitalize, properties that can easily be set the behavior for the keyboard.</li>\n<li>Another BOOL for timestamps on/off.</li>\n</ul>\n<hr />\n<p>Finally, something you might consider adding would be a method to get a log of all the chat messages in the controller. The method would return an <code>NSArray</code> of the <code>NSDictionary</code> objects so the user has all the information about every message in the controller.</p>\n<p>You might optionally also include a method for getting all messages that have timestamps occurring between two <code>NSDate</code> objects.</p>\n<p>Examples:</p>\n<pre><code>[chatController fullChatLog];\n[chatController chatLogFrom:startDate to:endDate];\n</code></pre>\n<p>These would allow the user to easily save the chat log to some sort of file format for long term storage.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:30:47.187",
"Id": "77703",
"Score": "0",
"body": "The borders are entirely customizable. If you set chatController.tintColor, this will change every iteration of blue for a quick fix. Or, you can go in and update whatever you want. I'm pretty sure it's opponentBubbleColor & userBubbleColor"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:32:03.567",
"Id": "77704",
"Score": "0",
"body": "I was looking for a good way to adapt for chat, passing an image key might be an easy way! I don't have support for names yet, I just display whoever I'm talking to on the chatTitle so it' right on top (like iMessage)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:33:08.243",
"Id": "77705",
"Score": "0",
"body": "Even if you don't yet have a way for displaying names, you should go ahead and include predefined constants for several obvious things that any sort of chat system will have. Username, userid, usericon, timestamp, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:34:04.183",
"Id": "77706",
"Score": "0",
"body": "UIFont - I set one up but was getting strange results, I just haven't spent enough time. UIColor properties - Already there. Date Formatter, I'm pretty sure I have an inline called TimeStamp(). I store all of my timestamps in milliseconds since epoch, so that is what it provides. If it's not there, it should be. BOOL toggles, I'll look into implementing these."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:34:16.017",
"Id": "77707",
"Score": "0",
"body": "I would also recommend allowing the `addNewMessage:` to send a value for the `timestamp` so if you're trying to load archived messages the timestamp is right, but if no timestamp argument is sent, default them all to `[NSDate date]` so if I'm adding in realtime, the timestamping is handled automatically by default."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:34:43.183",
"Id": "77708",
"Score": "0",
"body": "NSArray: Just get chatController.messages -- this will contain every message currently displayed. If you set it to an array of messages, it will automatically load that array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:35:18.963",
"Id": "77709",
"Score": "0",
"body": "How you store timestamps is one thing. The `NSDateFormatter` is for DISPLAYING the timestamps. Some users may want 24h. Some may want AM/PM. Some may want HH:mm, some may want HH:mm:dd:ss.SSS, etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:36:26.677",
"Id": "77710",
"Score": "0",
"body": "Oh yea, I haven't added that yet! I set it up for something pseudo: show time (1:30 am), then show day of week(Monday), then show date (11/12/14) depending on how old the message is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:40:11.000",
"Id": "77711",
"Score": "0",
"body": "Right. For all of these properties I've recommended, you need a default setting, but if you make them all public, you can allow the user to set their own settings, and for doing timestamps, you'd want an `NSDateFormatter` property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:46:38.887",
"Id": "77712",
"Score": "0",
"body": "Gotcha! Thanks man, a lot of good stuff on here for me!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:28:20.217",
"Id": "44712",
"ParentId": "44644",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T06:00:14.637",
"Id": "44644",
"Score": "5",
"Tags": [
"objective-c",
"ios",
"user-interface"
],
"Title": "Custom iOS chat interface design & functionality"
} | 44644 |
<p>Based on some code on internet, I implemented a dynamic array of structures in C.</p>
<p>I am really interested in some feedback on this. Maybe there are some places where it can cause memory leaks or other pitfalls? (I am also concerned if there can be situation that I free a pointer twice in my case, and how to avoid that)</p>
<pre><code>#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int ID;
char * name;
} Student;
// array of structs
typedef struct
{
Student *array;
size_t used;
size_t size;
} Array;
void initArray(Array *a, size_t initialSize)
{
// Allocate initial space
a->array = (Student *)malloc(initialSize * sizeof(Student));
a->used = 0; // no elements used
a->size = initialSize; // available nr of elements
// Initialize all values of the array to 0
for(unsigned int i = 0; i<initialSize; i++)
{
memset(&a->array[i],0,sizeof(Student));
}
}
// Add element to array
void insertArray(Array *a, Student element)
{
if (a->used == a->size)
{
a->size *= 2;
a->array = (Student *)realloc(a->array, a->size * sizeof(Student));
}
// Copy name
a->array[a->used].name = (char*)malloc(strlen(element.name) + 1);
strcpy(a->array[a->used].name, element.name);
// Copy ID
a->array[a->used].ID=element.ID;
a->used++;
}
void freeArray(Array *a)
{
// Free all name variables of each array element first
for(int i=0; i<a->used; i++)
{
free(a->array[0].name);
a->array[0].name=NULL;
}
// Now free the array
free(a->array);
a->array = NULL;
a->used = 0;
a->size = 0;
}
int main(int argc, const char * argv[])
{
Array a;
Student x,y,z;
x.ID = 20;
x.name=(char*)malloc(strlen("stud1") + 1);
strcpy(x.name,"stud1");
y.ID = 30;
y.name=(char*)malloc(strlen("student2") + 1);
strcpy(y.name,"student2");
z.ID = 40;
z.name=(char*)malloc(strlen("student3") + 1);
strcpy(z.name,"student3");
// Init array
initArray(&a, 5);
// Add elements
insertArray(&a, x);
insertArray(&a, y);
insertArray(&a, z);
// Print elements
printf("%d\n", a.array[0].ID);
printf("%s\n", a.array[0].name);
printf("%d\n", a.array[1].ID);
printf("%s\n", a.array[1].name);
printf("%d\n", a.array[2].ID);
printf("%s\n", a.array[2].name);
printf("%d\n", a.array[3].ID);
printf("%s\n", a.array[3].name);
// Free array
freeArray(&a);
free(x.name);
free(y.name);
free(z.name);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>I have 3 suggestions.</p>\n\n<ul>\n<li><p>If you need to allocate memory and initialize it to zero use <code>calloc</code>.<br/>\nUsing <code>calloc</code> is better than using <code>malloc + memset</code></p>\n\n<p>So change your <code>initArray</code> function like:</p>\n\n<pre><code>void initArray(Array *a, size_t initialSize)\n{\n // Allocate initial space\n a->array = (Student *)calloc(initialSize , sizeof(Student));\n\n a->used = 0; // no elements used\n a->size = initialSize; // available nr of elements\n}\n</code></pre></li>\n<li><p>Single character variable names are very bad. Use proper names for variables and follow naming conventions.</p></li>\n<li><p>In your code you are only creating and adding 3 objects. But you are trying to print the details of 4th object. (Array index is starting from zero, so index 3 means 4th object)</p>\n\n<pre><code>printf(\"%d\\n\", a.array[3].ID); \nprintf(\"%s\\n\", a.array[3].name); \n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T09:32:06.177",
"Id": "77526",
"Score": "0",
"body": "For your second point, you should add \"unless it is a loop index/iterator\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:51:25.220",
"Id": "77537",
"Score": "0",
"body": "Yes, I was also interested more from memory management point of view etc.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T09:14:27.030",
"Id": "44652",
"ParentId": "44649",
"Score": "5"
}
},
{
"body": "<p>It looks like you tried to fix a bug in <a href=\"https://codereview.stackexchange.com/revisions/44649/4\">Rev 4</a>. (Editing the question after asking it is discouraged on Code Review.) However, it's still wrong. Hint: <code>i</code> is an unused variable in the for-loop.</p>\n\n<p><code>malloc()</code> followed by <code>strcpy()</code> could be replaced by <code>strdup()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:31:38.330",
"Id": "77597",
"Score": "0",
"body": "Yes you are right, should be `i` instead of 0"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:43:23.373",
"Id": "77600",
"Score": "0",
"body": "Yes just I am more interested in cases when/if there can be for example freeing unallocated memory or freeing already freed memory ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:44:45.957",
"Id": "77601",
"Score": "2",
"body": "`strdup` is no standard C. If I'm not mistaken, it's a POSIX function. Since there is a `#include \"stdafx.h\"`, I bet that the system used is Windows, and `strdup` may not exist."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:29:55.653",
"Id": "44671",
"ParentId": "44649",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>I am also concerned if there can be situation that I free a pointer twice in my case</p>\n</blockquote>\n\n<p>... and ...</p>\n\n<blockquote>\n <p>Yes just I am more interested in cases when/if there can be for example freeing unallocated memory or freeing already freed memory ...</p>\n</blockquote>\n\n<p>After a quick inspection it doesn't appear that you free memory more than once:</p>\n\n<ul>\n<li><code>free</code> statements are only in the <code>freeArray</code> and <code>main</code> methods</li>\n<li>Each <code>free(a->array[0].name);</code> is different because each name is allocated using its own malloc</li>\n<li><code>free(a->array)</code> is only called once</li>\n<li><code>freeArray</code> is only called once</li>\n<li><code>free(x.name);</code> doesn't free the same memory as <code>free(a->array[0].name);</code> because <code>insertArray</code> allocates new memory for each name</li>\n</ul>\n\n<blockquote>\n <p>and how to avoid that</p>\n</blockquote>\n\n<p>Something which can help (though not guarantee) is to assign NULL to the pointer after you pass it to free.</p>\n\n<ul>\n<li>It can help, because calling free on a previously-nulled pointer will harmlessly do nothing</li>\n<li>It's not a guarantee, because you might have more than one pointer pointing to the same memory</li>\n</ul>\n\n<hr>\n\n<p>dmcr_code's comment below points out a bug. You wrote,</p>\n\n<pre><code>for(int i=0; i<a->used; i++)\n{\n free(a->array[0].name);\n a->array[0].name=NULL;\n}\n</code></pre>\n\n<p>This should be,</p>\n\n<pre><code>for(int i=0; i<a->used; i++)\n{\n free(a->array[i].name);\n a->array[i].name=NULL;\n}\n</code></pre>\n\n<p>Because you set <code>a->array[0].name=NULL;</code> after freeing it, you don't free it twice.</p>\n\n<p>But, you did fail to free the memory associated with <code>a->array[i].name</code> for values of <code>i</code> larger than 0.</p>\n\n<hr>\n\n<blockquote>\n <p>But then how do I protect against that - when array[i].name can contain random value and I try to free it?</p>\n</blockquote>\n\n<p>To protect yourself:</p>\n\n<ul>\n<li>Either, don't let it contain a random value (e.g. ensure that it's either a valid pointer, or zero)</li>\n<li>Or, don't use it (e.g. ensure that your <code>a->used</code> logic is correct so that you don't touch elements which you haven't used/initialized).</li>\n</ul>\n\n<blockquote>\n <p>is memset in the initArray method fine for that?</p>\n</blockquote>\n\n<p>memset is good:</p>\n\n<ul>\n<li>You could use calloc instead of malloc to avoid having to use memset as well</li>\n<li>You could use memset on the whole array at once instead of using memset on each element of the array</li>\n</ul>\n\n<p>memset in initArray isn't enough. It's enough to begin with, but there's a realloc in insertArray. So to be good enough, you'd also need to use memset after realloc (to memset the as-yet-unused end of the newly-reallocated array; without using memset on the beginning of the reallocated array, which already contains valid/initialized/used elements).</p>\n\n<blockquote>\n <p>the only unclear part that remains from your response is how to memset realloced array</p>\n</blockquote>\n\n<p>Your current code in initArray says,</p>\n\n<pre><code>// Initialize all values of the array to 0\nfor(unsigned int i = 0; i<initialSize; i++)\n{\n memset(&a->array[i],0,sizeof(Student));\n}\n</code></pre>\n\n<p>Another way to do that would be:</p>\n\n<pre><code>// Initialize all elements of the array at once: they are contiguous\nmemset(&a->array[0], 0, sizeof(Student) * initialSize);\n</code></pre>\n\n<p>The memset statement to add to insertArray would be:</p>\n\n<pre><code>if (a->used == a->size)\n{\n a->size *= 2;\n a->array = (Student *)realloc(a->array, a->size * sizeof(Student));\n // Initialize the last/new elements of the reallocated array\n for(unsigned int i = a->used; i<a->size; i++)\n {\n memset(&a->array[i],0,sizeof(Student));\n }\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>if (a->used == a->size)\n{\n a->size *= 2;\n a->array = (Student *)realloc(a->array, a->size * sizeof(Student));\n // Initialize the last/new elements of the reallocated array\n memset(&a->array[a->used],0,sizeof(Student) * (a->size - a->used));\n}\n</code></pre>\n\n<blockquote>\n <p>and this comment: \"It's not a guarantee, because you might have more than one pointer pointing to the same memory \" would be nice if you can address that too</p>\n</blockquote>\n\n<p>This is safe:</p>\n\n<pre><code>void* foo = malloc(10);\nfree(foo);\n// protect against freeing twice\nfoo = NULL;\n// this is useless and strange, but harmless\nfree(foo);\n</code></pre>\n\n<p>This is not safe:</p>\n\n<pre><code>void* foo = malloc(10);\nvoid* bar = foo;\nfree(foo);\n// protect against freeing twice\nfoo = NULL;\n// this is useless and strange, but harmless\nfree(foo);\n// but this is dangerous, illegal, undefined, etc.\n// because bar is now pointing to memory that has already been freed\nfree(bar);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:12:04.517",
"Id": "77614",
"Score": "0",
"body": "There should be `free(a->array[i].name);`. Also tricky case is if say `a->array[i].name` contains some random garbage value and I try to free it right? (here checking for NULL won't help). ps. and I didn't I think fully understand your last bullet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:13:02.590",
"Id": "77616",
"Score": "1",
"body": "@dmcr_code Well done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:15:10.920",
"Id": "77618",
"Score": "0",
"body": "Thanks for cheer up!. But then how do I protect against that - when array[i].name can contain random value and I try to free it? is `memset` in the `initArray` method fine for that? (probably not.. need to think a bit about it myself more)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:22:01.350",
"Id": "77620",
"Score": "0",
"body": "\"But, you did fail to free the memory associated with a->array[i].name for values of i larger than 0\" this I didn't get.. :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:24:58.337",
"Id": "77621",
"Score": "0",
"body": "You called `free(a->array[0].name);` but never call `free(a->array[1].name);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:25:23.277",
"Id": "77622",
"Score": "0",
"body": "@dmcr_code I updated my answer to talk about memset"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:33:00.173",
"Id": "77625",
"Score": "0",
"body": "aa yes but the realloced array I am not freeing then fully, I just free the `used` part .."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:29:54.427",
"Id": "77632",
"Score": "0",
"body": "the only unclear part that remains from your response is how to memset realloced array and this comment: \"It's not a guarantee, because you might have more than one pointer pointing to the same memory\n\" would be nice if you can address that too"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:45:21.863",
"Id": "77635",
"Score": "0",
"body": "@dmcr_code I edited my answer again"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:59:53.543",
"Id": "77643",
"Score": "0",
"body": "ok I think after incorporating your comments and my code, the code should be pretty safe right? I will check it a bit more later when implement it; thanks for feedback and effort"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:04:48.780",
"Id": "44674",
"ParentId": "44649",
"Score": "8"
}
},
{
"body": "<p>Don't forget that the <code>realloc</code> call in <code>insertArray()</code> can fail, and if it does, your array will be corrupt.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:03:43.177",
"Id": "44753",
"ParentId": "44649",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T07:58:55.887",
"Id": "44649",
"Score": "9",
"Tags": [
"c",
"array",
"memory-management"
],
"Title": "Dynamic array of structs in C"
} | 44649 |
<p>I'm building a virtualised grid in JS/HTML and finding browser performance with large grids fairly slow, particularly in IE10/11. The following jsfiddle roughly represents my worst case scenario, approx 1000 cells:</p>
<p><a href="http://jsfiddle.net/FGr7g/1/" rel="nofollow">http://jsfiddle.net/FGr7g/1/</a></p>
<pre><code>function test(count) {
var self = window;
var limit = 25;
if (count < limit) {
//settimeout to give ui chance to render
setTimeout(function () {
self.render(count);
count++;
test(count);
}, 0);
}
if (count >= limit) {
alert((1000 / ((performance.now() - self.startTime) / limit)) + " fps");
}
}
function render(count) {
for (var x = 0; x < this.cellCount; x++) {
this.cells[x].textContent = count + " _c_" + x;
}
}
window.render = render;
$().ready(function () {
var self = window;
self.cellCount = 1000;
self.cells = [];
self.grid = document.createElement("div");
self.grid.style.position = "relative";
self.grid.style.height = "100%";
self.grid.style.overflow = "hidden";
for (var c = 0; c < cellCount; c++) {
var cell = document.createElement("div");
cell.style.width = "49px";
cell.style.height = "24px";
cell.style.padding = "10px";
cell.style.position = "absolute";
cell.style.overflow = "hidden";
cell.style.borderTop = "1px solid lightgray";
cell.style.borderLeft = "1px solid lightgray";
cell.style.backgroundColor = "whitesmoke";
cell.style.left = (c % 28) * 50 + "px";
cell.style.top = (Math.floor(c / 28) * 25) + "px";
cell.className = cell.className += " test_cell";
var span = document.createElement("span");
cell.appendChild(span);
self.grid.appendChild(cell);
self.cells.push(span);
}
document.getElementById("grid").appendChild(self.grid);
self.startTime = performance.now();
self.count = 0;
test(self.count);
self.totalTime = 0;
});
<div id="grid" style="width: 1500px; height: 900px"></div>
.test_cell {
text-align: right;
font: 8pt Segoe UI, Tahoma, Arial, Verdana;
width: 49px;
height: 24px;
border-left: 1px solid lightgray;
border-top: 1px solid lightgray;
position: absolute;
overflow: hidden;
}
</code></pre>
<p>I get around 10fps in IE at full screen, and around 30 in Chrome, assuming my performance measurement code is correct, it is consistent with the fps tools in Chrome so I think it is.</p>
<p>So far I've tried different methods of DOM manipulation - building a HTML string of the whole grid and inserting into the DOM (slower), using DOM fragments (slower), using a table instead of an array of absolute divs (slower), various ways of setting the span's content - <code>innerHTML</code>, <code>textContent</code> etc (made little difference), using different fonts/sizes (no difference).</p>
<p>Based on profiling I suspect that the majority of the time is painting rather than any java script code so I think any large improvements would like come from optimising the HTML/CSS so it is quicker to render, but any suggestions/modifications would be hugely appreciated.</p>
<p>If it makes any difference I am not targeting older browser versions.</p>
| [] | [
{
"body": "<p>First off, your code doesn't seem very optimal. This doesn't effect the speed as far as I can see, but does effect the readability, which may limit the help you get here.</p>\n\n<ul>\n<li>Why do you create a second <code>div</code> inside <code>#grid</code>?</li>\n<li>Why do you assign the styles of the cells twice (inline to the <code>style</code> attribute and a second time via the class)?</li>\n<li>Why are you using a class at all? A selector such as `#grid > div > div' would be easier.</li>\n</ul>\n\n<p>Here is the simplified code I used: <a href=\"http://jsfiddle.net/jJa8L/2/\" rel=\"nofollow\">http://jsfiddle.net/jJa8L/2/</a></p>\n\n<p>Some experimentation show for me that the biggest speed hog seems to be the absolute positioning. When I comment it out, then I get speed improvements of 30 to 50% (40-45 fps) in Chrome. I haven't had a chance to try it out, but I'd try using a table layout (either using a <code><table></code> directly in the HTML, or using <code>display: table-*</code> in the CSS).</p>\n\n<p>EDIT: I just discovered one certain optimization: Moving the <code>font</code> property from the class to more global rule (<code>body</code> or <code>#grid</code>), raises the fps in Chrome to 35-38. See <a href=\"http://jsfiddle.net/jJa8L/3/\" rel=\"nofollow\">http://jsfiddle.net/jJa8L/3/</a></p>\n\n<p>EDIT 2: Ok, here's a version with table layout: <a href=\"http://jsfiddle.net/jJa8L/4/\" rel=\"nofollow\">http://jsfiddle.net/jJa8L/4/</a> It's still at 40-45 fps.</p>\n\n<p>EDIT 3: No idea why I didn't think of this before: Simply let the cells flow with <code>display: inline-block</code> giving <code>#grid</code> an appriopriate width. <a href=\"http://jsfiddle.net/jJa8L/5/\" rel=\"nofollow\">http://jsfiddle.net/jJa8L/5/</a> This is slightly faster (42-47 fps).</p>\n\n<p>EDIT 4:\nI just had another idea: There is a considerable speed up in Firefox and IE (but not Chrome for some reason) if you hide the grid while updating the cell texts: <a href=\"http://jsfiddle.net/jJa8L/8/\" rel=\"nofollow\">http://jsfiddle.net/jJa8L/8/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:35:36.830",
"Id": "77626",
"Score": "0",
"body": "Thanks for the reply - the second div is a hangover from another idea but yes it doesn't need to be there in this case. I didn't actually notice I was applying the styles twice so thanks for that. In the final version the column widths/row heights will be variable, which is why I was using absolute positioning. I've tried each of your fiddles and I'm still getting the same results - are you running it with the entire grid visible because that affects the result?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:52:51.430",
"Id": "77628",
"Score": "0",
"body": "That said, the second fiddle seems to get IE up to 15fps from 10 which is a little more respectable. Sadly in the final version I will need different css classes on different cells, so I can't simple do #grid > div. But interesting that that affects the rendering speed so much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:57:11.657",
"Id": "77770",
"Score": "0",
"body": "Hmm, I just retested my versions 2 and 5 in Chrome. 2 is actually running faster that I thought (~38 fps), but 5 is still faster at ~46fps. Firefox OTOH only achieves ~10fps in both version."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:12:49.070",
"Id": "44661",
"ParentId": "44651",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T09:08:51.093",
"Id": "44651",
"Score": "5",
"Tags": [
"javascript",
"performance",
"jquery"
],
"Title": "Optimise JavaScript DOM update"
} | 44651 |
<p>To check a win in my TicTacToe game, I have created a 2D array that contains all the combination that a game can be won in, like so: </p>
<pre><code> private int[][] winningCombinations = new int[][] {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
{0, 4, 8}, {2, 4, 6} //diagonal wins
};
JButton buttons[] = new JButton[9]; // This is what I had when working with 1D array
JButton buttons[][] = new JButton[3][3]; // This is what I have now
</code></pre>
<p>then I have used for loop to loop through this array like this:</p>
<pre><code>/*Determine who won*/
for(int i=0; i<=7; i++){
if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
!buttons[winCombinations[i][0]].getText().equals("")) {
win = true;
}
}
for(int i = 0; i < 3; i++){
if (buttons[i*3].getText().equals("X") && buttons[i*3+1].getText().equals("X") && buttons[i*3+2].getText().equals(""))
buttons[i*3+2].setText("O");
win = true;
}
</code></pre>
<p>Everything works, but now I am planning to convert my code from 1D to 2D array, but when I convert this to 2D, it does not work. I might be wrong, but this is how I attempted to convert to 2D:</p>
<pre><code>for(int i=0; i<=7; i++){
if( buttons[winCombinations[i][0]][winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]][winCombinations[i][1]].getText()) &&
buttons[winCombinations[i][1]][winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]][winCombinations[i][2]].getText()) &&
!buttons[winCombinations[i][0]][winCombinations[i][0]].getText().equals("")) {
win = true;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:22:38.387",
"Id": "77532",
"Score": "0",
"body": "I believe I may have mis-directed you in a previous answer of mine. The 'winning combinations' array should have zero-based indexes... like values `{0, 1, 2}, {3, 4, 5}, .....`"
}
] | [
{
"body": "<h2>Matrices ... 1D or 2D format</h2>\n\n<p>In computing it is common to have matrix-like problems. Graphics, mathematics, and Tic-Tac-Toe.</p>\n\n<p>It is often easier to have the matrix data stored as a 1D array, or 'flattened'.</p>\n\n<p>Whether you have it as a 1D or a 2D array does not really matter for the functional aspect, but it can often have a really big impact on the readability.</p>\n\n<p>A matrix of <code>M x N</code> dimension would be stored, for example, as :</p>\n\n<pre><code>int[][] matrix = new int[M][N];\n</code></pre>\n\n<p>To 'visit' all members of that matrix you need to:</p>\n\n<pre><code>for (int r = 0; r < M; r++) {\n for (int c = 0; c < N; c++) {\n // do someting with matrix[r][c];\n }\n}\n</code></pre>\n\n<p>As a flattened matrix, it would be:</p>\n\n<pre><code>int[] matrix = new int[M * N];\n</code></pre>\n\n<p>To visit the members, it is:</p>\n\n<pre><code>for (int i = 0; i < matrix.length; i++) {\n // do something with matrix[i];\n}\n</code></pre>\n\n<p>When you have complicated indexing, the flattene system can be more efficient.</p>\n\n<p>Additionally, the flattened matrix has interesting memory properties that often leads to better performance on High-Performing Computational clusters.</p>\n\n<p>Converting from one format to the other is relatively simple.</p>\n\n<pre><code>final int width = 3;\nmatrix1D[row * width + col] = matrix2D[row][col];\nmatrix2D[i / width][i % width] = matrix1D[i];\n</code></pre>\n\n<h2>Review</h2>\n\n<ul>\n<li><p>In your case, your matrix is small, and you should chose whichever format makes the code most readable.</p>\n\n<p>If you choose a 2D implementation, you should make sure your winning combinations array is expressed as a 2D format....</p>\n\n<pre><code>int[][][] winningcombinations = {\n { {0, 0}, {0, 1}, {0, 2} }, // Top\n { {1, 0}, {1, 1}, {1, 2} }, // Middle\n { {2, 0}, {2, 1}, {2, 2} }, // Bottom\n { {0, 0}, {1, 0}, {2, 0} }, // left\n .......\n}\n</code></pre></li>\n<li><p><strong>Magic Numbers</strong></p>\n\n<p>Java arrays have a length property. Use it. You have the code:</p>\n\n<blockquote>\n<pre><code>for(int i=0; i<=7; i++){ .... }\n</code></pre>\n</blockquote>\n\n<p>This should be:</p>\n\n<pre><code>for (int i = 0; i <= winCombinations.length; i++) { .... }\n</code></pre></li>\n<li><p><strong>Code Style</strong></p>\n\n<p>In Java recommended code style puts spaces around <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html#682\">operators and reserved words</a>.</p>\n\n<blockquote>\n<pre><code>for(int i=0; i<=7; i++){ .... }\n</code></pre>\n</blockquote>\n\n<p>should be (ignoring the <code>7</code>)</p>\n\n<pre><code>for (int i = 0; i <= 7; i++) { .... }\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:58:12.420",
"Id": "77538",
"Score": "0",
"body": "thanks for this, it is very detailed and informative and useful. You know at this line for (int i = 0; i <= winCombinations.length; i++), putting i <= winCombinations.length;, will this automatically go through the array that wincombination holds and also would i need to have nested for loop in this part?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:47:01.113",
"Id": "44654",
"ParentId": "44653",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T09:50:00.670",
"Id": "44653",
"Score": "2",
"Tags": [
"java",
"array",
"matrix",
"tic-tac-toe",
"ai"
],
"Title": "Turning 1D array to 2D array in TicTacToe"
} | 44653 |
<p>Recently I have been making an MVC application with a fluid, responsive design in mind. One of the views has been to implement a fast responsive active directory details page. This is the first time I've really gone head-first into using jQuery/JavaScript with JSON results. Usually I stick to backend coding and someone else does the front-end using Kendo/Telerik controls. I wanted to change it up a little by using jQuery/JavaScript and HTML5 whereever I can.</p>
<p>The page itself works as follows:</p>
<p>User types into <code>[input:project]</code>, which fires the autocomplete to the server, gets the persons/groups details and builds the autocomplete based on results. If the user then selects a person/group from results the details are loaded to the right of the page. If it's a group then I attempt to load the data so it builds the elements on the DOM dynamically and evenly.</p>
<p>Everything works as expected, but I would appreciate your views/comments on my JavaScript here on what I could have done better, if anything. I'm pretty new to jQuery/JavaScript so not sure if I'm writing the functions efficiently etc.</p>
<p><strong>Partial View</strong></p>
<pre class="lang-html prettyprint-override"><code><div class="tile-area">
<div class="grid fluid">
<div class="row">
<div class="span2">
<div style="margin: 20px; margin-top: 0px; margin-right: 0 !important; ">
<div class="ui-widget">
<input id="project">
<input type="hidden" id="project-id">
<span class="icon-search" id="icon-btn-search"></span><div id="cheight"></div>
</div>
</div>
</div>
<!-- Body container -->
<div class="span9 person-container scroll-vertical" id="person-container">
<!-- Force span to fix ul issue on autocomplete -->
<div class="container">
<div id="peopleList">
<div class="listview-outlook">
<header>
<div class="p-container">
<div class="p-sub-container" id="sub-container">
</div>
</div>
</header>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="bg-transparent no-overflow" id="overflow"></div>
</code></pre>
<p><strong>Styles</strong></p>
<pre class="lang-css prettyprint-override"><code><style>
ol, ul {
list-style: none;
}
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-icon {
float: left;
height: 32px;
width: 32px;
}
#project-description {
margin: 0;
padding: 0;
}
.ui-helper-hidden-accessible {
display: none;
}
.auto-list-content {
padding: 5px 0px 0px 5px;
position: relative;
display: block;
color: rgba(120,162,47,0.9);
height: 55px;
background-color: honeydew;
cursor:pointer;
}
.auto-data {
display: block;
padding: 0;
margin: 0;
margin-left: 45px;
min-width: 200px;
position: relative;
}
.auto-complete-title {
margin: 0 !important;
padding: 2px !important;
display: block !important;
overflow: hidden !important;
white-space: nowrap !important;
text-overflow: ellipsis !important;
}
.auto-complete-subtitle {
margin: 0 !important;
padding: 0px !important;
display: block !important;
overflow: hidden !important;
white-space: nowrap !important;
text-overflow: ellipsis !important;
}
.auto-complete-remark {
margin: 0 !important;
padding: 0px !important;
display: block !important;
overflow: hidden !important;
white-space: nowrap !important;
text-overflow: ellipsis !important;
}
/* !Important - overrides the inline left of 15px from jquery ui (ul) element*/
.metro ul,
.metro ol {
padding-left: 0px !important;
}
.ui-autocomplete {
width: 301px;
height: 55px;
display: block !important;
}
.ui-autocomplete li {
margin: 2px 0 2px 0;
padding: 5px 0 0 0;
width: 250px;
border: 1px solid rgba(120,162,47,0.9);
}
.tile-area {
padding: 0px !important;
}
.person-container {
padding: 5px;
/*background-image: url('images/ICO/large/User-No-Frame-Transparent.png');*/
background-repeat: no-repeat;
/*background-color: rgba(244,145,30,0.2);*/
background-color: rgba(120,162,47, 0.2);
}
/* CSS Partial view */
.p-container {
margin: 0px;
padding: 0px;
border: 1px solid #000;
}
.p-sub-container {
margin: 0px 0px 0px 0px;
padding: 5px 5px 5px 5px;
/*border: 1px solid rgba(120,162,47, 1);
background-color: rgba(120,162,47, 1);*/
}
.p-sub-container {
/*border: 1px solid green;*/
}
.p-floating {
position: relative;
top: -125px;
left: 130px;
}
.p-icon {
background-image: url('images/ICO/large/User-No-Frame-Transparent-125x135.png');
background-repeat: no-repeat;
height: 125px;
width: 125px;
}
.p-data {
text-align: left;
text-overflow: ellipsis;
display: block;
}
.p-list-item {
display: block;
position: relative;
}
.subChild {
position: relative;
top: 0px;
left: 0px;
padding: 5px;
}
.subChild {
height: 160px;
width: 500px;
border: 1px solid #000;
}
</style>
</code></pre>
<p><strong>JavaScript</strong></p>
<pre class="lang-js prettyprint-override"><code><script>
function setHeightOfContainer() {
var maxHeight = 800;
var wHeight = $(window).height();
var pContainerHeight = 700;
$('#person-container').css("height", pContainerHeight);
$('#overflow').css("height", calculateRemainder(wHeight, pContainerHeight));
};
function calculateRemainder(windowHeight, currentHeight) {
return (windowHeight - currentHeight - findAllNavBarElements());
}
function findAllNavBarElements() {
var numItems = $('.navigation-bar').length;
var heightTotal = 0;
if (numItems > 0) {
/* find height of elements */
for (var i = 0; i < numItems; i++) {
heightTotal += $('.navigation-bar').height();
}
}
return heightTotal;
}
$(function () {
var personData = null;
setHeightOfContainer();
findAllNavBarElements();
$("#project").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "GET",
url: '@Url.Action("SearchFilterSimple", "Person")',
data: { wildcard: request.term },
async: true,
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Sid,
desc: item.Department,
icon: item.Thumbnail
}
}));
},
error: function (error, txtStatus) {
}
});
},
create: function () {
$(this).autocomplete("search", '');
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $('<li>')
.append('<div class="auto-list-content">'
+ '<img id="project-icon" src=images/ICO/medium/' + item.icon + ' class="icon" style="width:32px; height:32px;">'
+ '<div class="auto-data">'
+ '<span class="auto-complete-subtitle">' + item.label + '</span>'
+ '<span class="auto-complete-remark">' + item.value + '</span>'
+ '</div></li>')
.appendTo(ul)
.click(function () {
getPersons(item.value);
})
;
};
function getPersons(sid) {
var e = 0;
$(".p-sub-container").empty();
$.ajax({
type: "GET",
url: '@Url.Action("GetSelectedData", "Person")',
data: { sid: sid },
async: false,
cache: false,
success: function (person) {
processData(person);
},
error: function (error, txtStatus) {
}
});
}
var nameprefix = "sub-c-";
var firstChild = null;
function processData(personData) {
if (personData.length > 0) {
for (var i = 0; i < personData.length; i++) {
createSubContainer(i);
}
var child = $(".p-sub-container").find("[id*=" + nameprefix + "]"); // checks the attribute
if (child.length > 0) {
for (var i = 0; i < child.length; i++) {
var c = $(child[i]);
createSubContainerChildren(c, personData[i]);
}
// reset firstChild
firstChild = null;
}
}
}
var prev = 0;
/* functions */
function createSubContainerChildren(c, pd) {
var currentPerson = pd;
var parent = $(c).parent(); // should be the sub container.
var containerPos = $(parent).position();
var containerMaxHeight = $(parent).outerHeight(true);
var containerMaxWidth = $(parent).outerWidth(true);
//find top
var eWidth = 450;
var currentElementPosition = $(c).position();
var totalWidth = currentElementPosition.left + eWidth;
var previousChild = $(c).prevAll();
if (previousChild.length > 0) {
// not first child
var currentElement = firstChild.position()
var currentNewElementPosition = currentElement.top - ($(c).outerHeight()) - (currentElement.top);//minus itself
var currentNewElementLeft = currentElement.left + ($(c).outerWidth());
var gutter = 10;
var mycurrentleftposition = currentElementPosition.left;
if (prev >= 1) {
c.css({
'top': "0px",
'left': "0px", //reset left
'border': "1px solid #0ff",
'float': "left"
});
//reset prev
prev = 0;
} else {
prev = 1;
c.css({
'top': currentNewElementPosition + "px",
'left': "0px",
'border': "1px solid #ff0faa",
'float': "right"
});
}
} else {
firstChild = c;
// set its top/left too
firstChild.css({
'top': "0px",
'left': "0px",
'border': "1px solid #0f0"
});
}
var call = callCard(currentPerson);
$(c).append(call.displayName).append(call.t).append(call.s);
}
function callCard(currentPerson) {
var vCard = {
s: null,
v: null,
t: null,
image: function () {
$.ajax({
type: "GET",
url: '@Url.Action("GetImageThumb", "Person")',
data: { sname: currentPerson.SamAccountName },
async: false,
cache: false,
success: function (img) {
vCard.v = img.nImage;
},
error: function (error, txtStatus) {
}
});
},
displayName: "<div>" + currentPerson.DisplayName + "</div>",
imageThumbnail: function () {
vCard.image();
vCard.t = "<img class='p-icon' id='pid' src='data:image/png;base64," + vCard.v + "' />"
},
wrapper: function () {
vCard.s = "<div class='p-floating'><div class='p-data'>" +
vCard.email + vCard.telephone + vCard.sid + vCard.accountED
},
email: "<span class=\"p-list-item\">" + currentPerson.Email + "</span>",
telephone: "<span class=\"p-list-item\">" + currentPerson.VoiceTelephoneNumber + "</span>",
sid: "<span class=\"p-list-item\">" + currentPerson.Sid + "</span>",
accountED: "<span class=\"p-list-item\">" + currentPerson.AccountExpirationDate + "</span>"
}
vCard.imageThumbnail();
vCard.wrapper();
return vCard;
}
function getImg(currentPerson){
$.ajax({
type: "GET",
url: '@Url.Action("GetImageThumb", "Person")',
data: { sname: currentPerson.SamAccountName },
async: false,
cache: false,
success: function (img) {
return img.nImage;
},
error: function (error, txtStatus) {
}
});
}
function createSubContainer(a) {
$(".p-sub-container").addClass('sub').append($('<div />', {
id: nameprefix + a
}).addClass('subChild'));
};
});
</script>
</code></pre>
| [] | [
{
"body": "<p>From a once over,</p>\n\n<ul>\n<li><code>s</code>, <code>v</code> and <code>t</code> are unfortunately named properties of <code>vCard</code></li>\n<li>I am confused between the code in <code>vCard.image</code> and <code>getImg</code>, they both call <code>'@Url.Action(\"GetImageThumb\", \"Person\")'</code>, room for de-duping code ? It seems you never call <code>getImg</code>.</li>\n<li><code>vCard</code> has data, data retrieval functions and formatting functions. That is too much for 1 object</li>\n<li>In <code>getPersons</code> you should have <code>function (persons) {</code> <- not <code>person</code> but <code>persons</code></li>\n<li>You never use <code>var e</code> in <code>getPersons</code> ( consider using JsHint.com ! )</li>\n<li>You have a number of semicolon warnings in JsHint</li>\n<li>You should clean up the commented out css lines</li>\n<li>Using <code>!important</code> sometimes must be done, but it is a code smell. I like how you put <code>/* !Important - overrides the inline left of 15px from jquery ui (ul) element*/</code> you should put a similar comment for the other places where you use <code>!important</code></li>\n<li>As reader, I see a lot of ( hard to follow ) code that is positioning elements. Automatically I wonder, did the author go all the way trying to solve this with css or did the author take the easy way out ? You should comment why you could not position your elements correctly without JavaScript ( or, try harder to place elements with css )</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:38:23.010",
"Id": "82591",
"Score": "0",
"body": "Thanks for your comments. Really appreciate them. As this is the first attempt really at writing javascript i'm please that your once over has deemed only a few results. Hopefully i'm heading in the right direction."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T19:43:11.247",
"Id": "46585",
"ParentId": "44655",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T10:51:52.637",
"Id": "44655",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"active-directory"
],
"Title": "Active Directory details page"
} | 44655 |
<p>I have to apply window leveling on Canvas Medical Image (CR). I have to get a pixel array from C# <code>Component.lutArr</code>, which is a lookup table array coming as a C# component and which I use in JavaScript. On click of the button, I have to call the function <code>ApplyWLCust()</code>. In this function, all process done getting result perfect. For window leveling, use bit shifting, which takes around 585ms. I have to reduce this time. What should I do?</p>
<pre><code>var imagewc = document.getElementById("text1").value;
var imageww = document.getElementById("text2").value;
pixelArr = [11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11..]
if (pixelArr != null)
{
for (var i = 0, n = pixelArr.length; i < n; i++)
{
pix = pixelArr[i];
pix = ApplyWL(pix, imagewc, imageww);
pix = lutArr[pix];
// var red = (pix & 0x00ff0000) >> 16;
v = i * 4;
imagedata[v] = pix & 0xff;
imagedata[v + 1] = (pix >>> 8) & 0xff;
imagedata[v + 2] = (pix >>> 16) & 0xff;
imagedata[v + 3] = 255;
}
// offscreenCtx.imageSmoothingEnabled = true;
offscreenCtx.putImageData(g, 0, 0);
}
function ApplyWL(value, _valwindowCenter, _valwindowWidth)
{
Recalculate(_valwindowCenter, _valwindowWidth);
if (value <= _windowStart)
value = _minimumOutputValue;
else if (value > _windowEnd)
value = _maximumOutputValue;
else
{
value = Math.round((((value - _windowCenterMin05) / _windowWidthMin1) + 0.5) * 255.0);
}
return value;
}
var _minimumOutputValue = 0;
var _maximumOutputValue = 255;
function Recalculate(_valwindowCenter, _valwindowWidth)
{
if (!_valid)
{
_windowCenterMin05 = _valwindowCenter - 0.5;
_windowWidthMin1 = _valwindowWidth - 1;
_windowWidthDiv2 = _windowWidthMin1 / 2;
_windowStart = (_windowCenterMin05 - _windowWidthDiv2);
_windowEnd = (_windowCenterMin05 + _windowWidthDiv2);
_valid = true;
}
}
Width<input id="text1" type="text" />
center<input id="text2" type="text" />
<input id="Button1" type="button" value="Apply" onclick="ApplyWLCust();" />
</br> time required<input id="text3" type="text" />
<canvas style="height: 500px; width: 500px; display1: none; background-color: black;
border: 1px solid red;" id="offscreenCanvas">
</code></pre>
| [] | [
{
"body": "<p>I think we need more code,</p>\n\n<ul>\n<li>Where are <code>imagewc</code>, <code>imageww</code>, and <code>lutArr</code> defined ? Those are all 3 unfortunate variable names by the way</li>\n</ul>\n\n<p>Regardless, I think a large speed up should be gained from calling <code>Recalculate</code> once before the loop on <code>pixelArr</code> since <code>imagewc</code> and <code>imageww</code> never change in that loop.</p>\n\n<p>Furthermore, since value is cut of between <code>0</code> and <code>255</code>, you should pre-calculate the array of values.</p>\n\n<pre><code>var lookup= [] , i;\nfor( var i = _minimumOutputValue ; i < _maximumOutputValue+1; i++ )\n lookup[i] = Math.round((((i- _windowCenterMin05) / _windowWidthMin1) + 0.5) * 255.0);\n</code></pre>\n\n<p>then your function would be:</p>\n\n<pre><code>function ApplyWL(value, _valwindowCenter, _valwindowWidth)\n{\n if (value <= _windowStart)\n return lookup[_minimumOutputValue ];\n if (value > _windowEnd)\n return lookup[_maximumOutputValue];\n return lookup[value]\n}\n</code></pre>\n\n<p>I might be wrong about the ranges of lookup, your table might have to be larger, but I am sure you realize the value of a lookup table at this point.</p>\n\n<p>EDIT:</p>\n\n<p>I wrote some code to look at it, some notes:\n* I moved the variables to the top, please make sure that all variables are declared with <code>var</code>\n* Only constructors should start with an uppercase letter</p>\n\n<pre><code>var imagewc = document.getElementById(\"text1\").value,\n imageww = document.getElementById(\"text2\").value,\n _minimumOutputValue = 0,\n _maximumOutputValue = 255, \n _valid,\n cacheWL = [],\n pixelArr = [11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11]; \n\nif (pixelArr != null)\n{\n //Move this out of the for loop\n recalculate(_valwindowCenter, _valwindowWidth);\n //Then set the cache which needs the results of `recalculate`\n cacheWL();\n for (var i = 0, n = pixelArr.length,v = 0,i < n; i++)\n {\n pix = pixelArr[i];\n pix = ApplyWL(pix, imagewc, imageww);\n pix = lutArr[pix];\n\n imagedata[v] = pix & 0xff;\n imagedata[v + 1] = (pix >>> 8) & 0xff;\n imagedata[v + 2] = (pix >>> 16) & 0xff;\n imagedata[v + 3] = 255;\n //Instead of doing a multiplication, you can keep adding 4\n v += 4; \n }\n offscreenCtx.putImageData(g, 0, 0);\n}\n\nfunction setCacheWL()\n{\n for( var i = _minimumOutputValue ; i <= _maximumOutputValue ; i++ )\n cacheWL[i] = Math.round((((i - _windowCenterMin05) / _windowWidthMin1) + 0.5) * 255.0);\n}\n\n\nfunction ApplyWL(value, _valwindowCenter, _valwindowWidth)\n{\n if (value <= _windowStart)\n return cacheWL[_minimumOutputValue];\n if (value > _windowEnd)\n return cacheWL[_maximumOutputValue];\n return cacheWL[value]\n}\n\nfunction recalculate(_valwindowCenter, _valwindowWidth)\n{\n if (!_valid)\n {\n _windowCenterMin05 = _valwindowCenter - 0.5;\n _windowWidthMin1 = _valwindowWidth - 1;\n _windowWidthDiv2 = _windowWidthMin1 / 2;\n _windowStart = (_windowCenterMin05 - _windowWidthDiv2);\n _windowEnd = (_windowCenterMin05 + _windowWidthDiv2);\n _valid = true;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:51:10.957",
"Id": "44664",
"ParentId": "44656",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T11:28:54.273",
"Id": "44656",
"Score": "5",
"Tags": [
"javascript",
"optimization",
"algorithm",
"performance",
"image"
],
"Title": "How to speed up window leveling (brightness, contrast)?"
} | 44656 |
<p>I have a list of opened nodes, with each step about 3000 nodes are opened and I want to put to the opened list only those nodes that are not already there. For now I'm just comparing each new one to all of the ones already in the opened list and only add it if it's not there. But that is around n*3000^2 comparisons for the nth step and makes the progress slower and slower each step. Is there a way to do it faster. Or at least is there a structure that would be better than ArrayList.</p>
<p>This is part of the bigger code, but basically the method I use:</p>
<pre><code>public void addEverything() {
List<gameState> list = current.neighbours;
for (gameState state : list) {
if (!isOpened(state)) {
opened.add(state);
}
}
}
public boolean isOpened(gameState state) {
for (int i = 0; i < opened.size(); i++) {
if (state.isSame(opened.get(i)))
return true;
}
return false;
}
</code></pre>
<p>As for the isSame() method from the gameState class, it just returns true when the two gameStates are considered the same.</p>
| [] | [
{
"body": "<ol>\n<li><p>Instead of implementing <code>isSame</code> implement <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)\" rel=\"nofollow noreferrer\"><code>equals</code></a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()\" rel=\"nofollow noreferrer\"><code>hashCode</code></a>. After that you could use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html\" rel=\"nofollow noreferrer\"><code>HashSet</code></a> (or <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html\" rel=\"nofollow noreferrer\"><code>LinkedHashSet</code></a> if the order of elements is important). Set is a collection that contains no duplicate elements and inserting/searching is much faster than searching in a list.</p>\n\n<pre><code>Set<GameState> opened = new LinkedHashSet<GameState>();\n\npublic void addEverything() {\n List<GameState> list = current.neighbours;\n for (GameState state : list) {\n opened.add(state);\n }\n}\n</code></pre>\n\n<p>If you need a list, you can convert it back after the loop:</p>\n\n<pre><code>List<GameState> openedList = new ArrayList<GameState>(opened);\n</code></pre>\n\n<p>See also: <a href=\"https://stackoverflow.com/a/27609/843804\">Overriding equals and hashCode in Java</a></p></li>\n<li><p>According to the Java Code Conventions, class names in Java usually starts with uppercase letters.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:08:11.370",
"Id": "77589",
"Score": "0",
"body": "+1. Conceptually two objects where \"isSame\" is true should also be \"equals\". If this would not be true, I would not change the \"equals\" semantics (and hashCode) just for performance issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:52:48.867",
"Id": "77605",
"Score": "0",
"body": "One more question about this: Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().\nThe opposite doesn't hold right? So would there be any consecunces if I were to implement hashCode() to always return 1 for example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:05:54.157",
"Id": "77609",
"Score": "0",
"body": "@Sunny: Yes, you're right. `hashCode` could be constant but performance will suffer (it won't be faster than the original code) so don't do it. You can generate good `hashCode` methods with Eclipse easily but there are libraries for that too. (See the linked Stack Overflow question.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:28:05.437",
"Id": "44666",
"ParentId": "44662",
"Score": "17"
}
},
{
"body": "<p>palacsint's answer is good, but it's missing just a few things.</p>\n\n<p>All in-built Java collection classes I can think of has copy-constructors, and an <code>addAll</code> method. So your <code>addEverything</code> method can be a one liner, when using a <code>Set<GameState></code>:</p>\n\n<pre><code>public void addEverything() {\n opened.addAll(current.neighbours);\n}\n</code></pre>\n\n<p>Or, if you would like to reset the contents and create an entirely new Set, use the copy-constructor:</p>\n\n<pre><code>public void replaceEverything() {\n opened = new LinkedHashSet<GameState>(current.neighbours);\n}\n</code></pre>\n\n<p>Since it can become a one-liner, you might not need to have it in it's own method.</p>\n\n<p>Most importantly, if you are not interested in the <strong>order</strong> of the <code>opened</code> set, use a <code>HashSet</code> rather than a <code>LinkedHashSet</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:30:10.927",
"Id": "44672",
"ParentId": "44662",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44666",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:24:19.113",
"Id": "44662",
"Score": "9",
"Tags": [
"java",
"performance"
],
"Title": "Comparing list elements in an effective way"
} | 44662 |
<p>I have a type that models the Arithmetic concept and use it as an opaque <code>typedef</code> (AKA strong <code>typedef</code>, see Note below) in some projects. </p>
<p>I've put the code into <a href="https://github.com/gnzlbg/arithmetic_type" rel="nofollow">its own repository</a> along with some tests and would like some eyes taking a look into it.</p>
<p><strong>Note:</strong> for opaque <code>typedef</code> I understand the definition given in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3515.pdf" rel="nofollow">N3515</a>.</p>
<ul>
<li>Prior art exist in <code>Boost.Serialization</code> <a href="http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/strong_typedef.html" rel="nofollow"><code>BOOST_STRONG_TYPEDEF</code></a>, where it seems that the opaque <code>typedef</code>s created model the Arithmetic concept (it is thought to be used for integers) but:
<ul>
<li>This is not clearly stated</li>
<li>It doesn't support C++11 features like <code>constexpr</code>, and move semantics</li>
<li>It does not inhibit implicit conversions</li>
</ul></li>
<li>On implicit conversions: I wanted to allow conversions, but prefer them to be explicit. This could be made configurable but I don't think it is worth the trouble.</li>
</ul>
<p>Some examples of usage:</p>
<ul>
<li><p>Example 1: disabling implicit conversions</p>
<pre><code>int a{2};
long b{3};
b = a; // works: the implicit conversion is safe
Arithmetic<int> a{2};
Arithmetic<long> b{3};
b = a; // error: implicit assignment requires implicit conversion
b = Arithmetic<long>{a}; // works: explicit construction
b = static_cast<Arithmetic<long>>(a); // works: explicit conversion
</code></pre></li>
<li><p>Example 2: opaque type-defs</p>
<pre><code>struct Tag1 {};
struct Tag2 {};
using Type1 = Arithmetic<int, Tag1>;
using Type2 = Arithmetic<int, Tag2>;
Type1 a{2};
Type2 b{3};
b = Type2{a}; // works: explicit construction
b = static_cast<Type2>(a); // works: explicit conversion
Type2 c{a}; // works: explicit construction
</code></pre></li>
</ul>
<p><strong>arithmetic_type.hpp:</strong></p>
<pre><code>#ifndef BOOST_UTILITIES_ARITHMETIC_TYPE_ARITHMETIC_TYPE_
#define BOOST_UTILITIES_ARITHMETIC_TYPE_ARITHMETIC_TYPE_
////////////////////////////////////////////////////////////////////////////////
#include <limits>
#include <type_traits>
////////////////////////////////////////////////////////////////////////////////
namespace boost {
////////////////////////////////////////////////////////////////////////////////
/// \name Index types
///@{
/// \brief Implements an integer type
template <class T, class B = void> struct Arithmetic {
using value_type = T;
using type = T;
/// \name Asignment operators
///@{
constexpr Arithmetic() noexcept(T{T{}}) : value{T{}} {}
constexpr Arithmetic(const Arithmetic& other) noexcept(T{T{}})
: value{other.value} {}
constexpr Arithmetic(Arithmetic&& other) noexcept(T{T{}})
: value{other.value} {}
constexpr explicit Arithmetic(const T& other) noexcept(T{T{}})
: value{other} {}
template <class U, class V>
constexpr explicit Arithmetic(const Arithmetic<U, V>& other) noexcept(T{T{}})
: value(other.value) {}
constexpr inline Arithmetic& operator=(const Arithmetic& other) noexcept {
value = other.value;
return *this;
}
constexpr inline Arithmetic& operator=(Arithmetic&& other) noexcept {
value = other.value;
return *this;
}
constexpr inline Arithmetic& operator=(const T& other) noexcept {
value = other;
return *this;
}
///@}
/// \name Conversion operators
///@{
explicit constexpr inline operator T() noexcept { return value; }
explicit constexpr inline operator const T() const noexcept { return value; }
template <class U, class V>
explicit constexpr inline operator Arithmetic<U, V>() noexcept {
return value;
}
template <class U, class V>
explicit constexpr inline operator const Arithmetic<U, V>() const noexcept {
return value;
}
///@}
/// \name Compound assignment +=, -=, *=, /=
///@{
constexpr inline Arithmetic& operator+=(const Arithmetic& other) noexcept {
value += other.value;
return *this;
}
constexpr inline Arithmetic& operator-=(const Arithmetic& other) noexcept {
value -= other.value;
return *this;
}
constexpr inline Arithmetic& operator*=(const Arithmetic& other) noexcept {
value *= other.value;
return *this;
}
constexpr inline Arithmetic& operator/=(const Arithmetic& other) noexcept {
value /= other.value;
return *this;
}
///@}
/// \name Arithmetic operators +,-,*,/,unary -
///@{
constexpr friend inline Arithmetic operator+(Arithmetic a,
const Arithmetic& b) noexcept {
return a += b;
}
constexpr friend inline Arithmetic operator-(Arithmetic a,
const Arithmetic& b) noexcept {
return a -= b;
}
constexpr friend inline Arithmetic operator*(Arithmetic a,
const Arithmetic& b) noexcept {
return a *= b;
}
constexpr friend inline Arithmetic operator/(Arithmetic a,
const Arithmetic& b) noexcept {
return a /= b;
}
constexpr inline Arithmetic operator-() noexcept {
static_assert(std::is_signed<T>::value, "Can't negate an unsigned type!");
return Arithmetic{-value};
}
///@}
/// \name Prefix increment operators ++(),--()
///@{
constexpr inline Arithmetic& operator++() noexcept {
++value;
return *this;
}
constexpr inline Arithmetic& operator--() noexcept {
--value;
return *this;
}
///@}
/// \name Postfix increment operators ()++,()--
///@{
constexpr inline Arithmetic operator++(int) noexcept {
Arithmetic tmp(*this);
++(*this);
return tmp;
}
constexpr inline Arithmetic operator--(int) noexcept {
Arithmetic tmp(*this);
--(*this);
return tmp;
}
///@}
/// \name Comparison operators ==, !=, <, >, <=, >=
///@{
constexpr friend inline bool operator==(const Arithmetic& a,
const Arithmetic& b) noexcept {
return a.value == b.value;
}
constexpr friend inline bool operator<=(const Arithmetic& a,
const Arithmetic& b) noexcept {
return a.value <= b.value;
}
constexpr friend inline bool operator<(const Arithmetic& a,
const Arithmetic& b) noexcept {
return a.value < b.value;
} // return a <= b && !(a == b) -> slower?
constexpr friend inline bool operator!=(const Arithmetic& a,
const Arithmetic& b) noexcept {
return !(a == b);
}
constexpr friend inline bool operator>(const Arithmetic& a,
const Arithmetic& b) noexcept {
return !(a <= b);
}
constexpr friend inline bool operator>=(const Arithmetic& a,
const Arithmetic& b) noexcept {
return !(a < b);
}
///@}
/// \brief swap
constexpr friend inline void swap(Arithmetic&& a, Arithmetic&& b) noexcept {
using std::swap;
swap(a.value, b.value);
}
/// \name Access operator
///@{
constexpr inline T& operator()() & noexcept { return value; }
constexpr inline T operator()() && noexcept { return value; }
constexpr inline T operator()() const& noexcept { return value; }
///@}
/// Data (wrapped value):
T value;
};
///@}
////////////////////////////////////////////////////////////////////////////////
} // namespace boost
////////////////////////////////////////////////////////////////////////////////
namespace std {
template <class T, class B>
class numeric_limits<boost::Arithmetic<T, B>> : public numeric_limits<T> {
public:
static const bool is_specialized = true;
};
} // namespace std
////////////////////////////////////////////////////////////////////////////////
#endif // BOOST_UTILITIES_ARITHMETIC_TYPE_ARITHMETIC_TYPE_
</code></pre>
<p>Furthermore, there is a <code>to_string</code> overload as well as <code>istream</code> / <code>ostream</code> operators in other header files. The rationale is, those who don't need them, shouldn't pay for <code><string></code>/<code><istream></code>/<code><ostream></code>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:05:05.863",
"Id": "77567",
"Score": "0",
"body": "I am no expert on arithmetic types so I might be mistaken, but wouldn't it be better to forward each `operator` to the exact same one on the underlying type?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:14:16.120",
"Id": "77569",
"Score": "1",
"body": "What is the `class B = void` template parameter used for? I don't see `B` being used anywhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:27:37.150",
"Id": "77570",
"Score": "0",
"body": "@ChrisW I've added two examples that show how the class should be used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:49:41.887",
"Id": "77581",
"Score": "0",
"body": "@Nobody if the type models the arithmetic concept this is not needed for all operators, just for some."
}
] | [
{
"body": "<p>Here are some small things you can improve:</p>\n\n<ul>\n<li><code>constexpr inline</code> isn't necessary: <code>constexpr</code> already implies <code>inline</code>.</li>\n<li><p>In the following function:</p>\n\n<pre><code>constexpr friend inline Arithmetic operator+(Arithmetic a,\n const Arithmetic& b) noexcept {\n return a += b;\n}\n</code></pre>\n\n<p>The <code>friend</code> keyword isn't useful: the only function you are calling is <code>operator+=</code> which is <code>public</code>. This note holds for all your <code>operator@=</code> and for all the operators that do not use <code>private</code> members.</p></li>\n<li><code>operator<=</code>, <code>operator></code> and <code>operator>=</code> are generally implemented in function of <code>operator<</code>. A decent level of optimization should get rid of what you seem to consider a overhead.</li>\n<li><p>The following member should be <code>constexpr</code>, not <code>const</code>:</p>\n\n<pre><code>static const bool is_specialized = true;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:46:22.200",
"Id": "77578",
"Score": "1",
"body": "Thanks for the answer! Made all the improvements already. Since value is a public data member, I guess I can make all operators that do not need to be class members non-friend non-member functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:47:36.643",
"Id": "77603",
"Score": "0",
"body": "@gnzlbg Well, you can do that. I don't know whether `value` being `public` is a good idea though; I don't really have an opinion on that question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T14:59:04.440",
"Id": "77606",
"Score": "0",
"body": "Neither do I. It seemed irrelevant so I left it public to avoid complicating the life of those who want to explicitly avoid the type-safety offered by the class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:00:50.907",
"Id": "77607",
"Score": "0",
"body": "@gnzlbg Then, what are the `operator()()` overloads for? They are kind of redundant if `value` is already `public` :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:05:12.283",
"Id": "77608",
"Score": "0",
"body": "They are for lazy people, 3 keystrokes less... no kidding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:07:59.833",
"Id": "77611",
"Score": "0",
"body": "@gnzlbg You could have made them `explicit operator value_type()` overload instead. I find it more explicit (haha) than using `operator()()` which I wouldn't intuitively use to get the underlying value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:11:22.257",
"Id": "77613",
"Score": "0",
"body": "What do you mean? I have an `explicit constexpr operator T() noexcept` but that forces you to do an e.g. `static_cast<T>(...)`. I hope I left all doors open to make getting the underlying value as easy as possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:12:35.180",
"Id": "77615",
"Score": "0",
"body": "@gnzlbg Oops. I overooked that one. My bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:13:32.620",
"Id": "77617",
"Score": "0",
"body": "thanks a lot for your input! I think it has significantly improved the class (commits are on github!)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T13:05:00.910",
"Id": "44665",
"ParentId": "44663",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44665",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:36:12.190",
"Id": "44663",
"Score": "7",
"Tags": [
"c++",
"c++11",
"boost"
],
"Title": "Model of Arithmetic concept for usage as Opaque typedef"
} | 44663 |
<p>I have some doubt when I should create an object in an Unit Test when the object needs to be stopped cleanly.</p>
<p>Usecase:
I have a class ComplexClass which has 3 functions:</p>
<ul>
<li>Start(): starts a Thread</li>
<li>Stop(): stops the thread</li>
<li>GetX(): which gets a value</li>
</ul>
<p>When I test this class I want to check if GetX() returns 42, but first I have to start the thread, and after it I want to stop the Thread. (During testing I don't want many dangling threads running).</p>
<p>Are fixtures the way to do this?:</p>
<pre><code>class TestComplexClass(object):
@pytest.fixture()
def complexclass(self, request):
print ("[setup] ComplexClass")
cc = ComplexClass()
def fin():
print ("[teardown] ComplexClass")
cc.stop()
request.addfinalizer(fin)
return cc
def test_GetX(self, complexclass):
// do some stuff
complexclass.start()
assert complexclass.GetX() == 42, "GetX() should return 42"
</code></pre>
<p>Or should I create the object in the Unit Test?:</p>
<pre><code>class TestComplexClass(object):
def test_GetX(self, complexclass):
// do some stuff
cc = ComplexClass()
try:
cc.start()
assert cc.GetX() == 42, "GetX() should return 42"
except AssertionError:
cc.stop
raise
</code></pre>
<p>(Note I'm using Py.Test)</p>
| [] | [
{
"body": "<p>This somewhat depends on which principle you value higher. Small repetition:</p>\n\n<h2>F.I.R.S.T</h2>\n\n<h3>F: Fast</h3>\n\n<p>Pretty self-explaining. Unit tests have to be as fast as possible for TDD to be viable. </p>\n\n<h3>I: Independent</h3>\n\n<p>Unit tests are not depending on anything else than the testing-framework and the class under test (cut). Not even on other tests. Unit tests prepare their own data and setup and clean up after themselves after evaluation. It must not matter in which order unit tests are executed!</p>\n\n<h3>R: Repeatable</h3>\n\n<p>Unit tests give the same result when they are repeatedly executed. Even on a new moon with low tide. They always look for the same results and perform the same operations.</p>\n\n<h3>S: Self-Validating</h3>\n\n<p>Unit tests validate the result of any operation themselves. They may not give any results to external classes for validation. Also they should be self-explaining as to why that result is expected.</p>\n\n<h3>T: Timely</h3>\n\n<p>Unit tests are to be written as close as possible before the implementation of a feature</p>\n\n<p><a href=\"http://agileinaflash.blogspot.de/2009/02/first.html\" rel=\"nofollow\" title=\"Tim Ottinger & Jeff Langr present the blog behind the versatile Pragmatic Programmers reference cards.\">principles freely adapted from Agile in a Flash</a>\n<hr>\nIn this case you will have to evaluate the fast principle against the independent principle\nIt will definitely be faster to create the instance of <code>ComplexClass</code> only once (on fixture setup), but that will undermine the independency of unit tests and <s>may</s> <strong>will</strong> cause problems when you depend on execution order.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:03:52.697",
"Id": "77748",
"Score": "0",
"body": "Thanks @Vogel612, but why will it cause problems on execution order? Each Unit Test will be run after each other, so the cleanup will be done correctly, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:53:16.157",
"Id": "77758",
"Score": "0",
"body": "@RvdK I don't really understand what you want to say. What I mean is, that if you depend on the execution order of tests, to get your results, you are doing something wrong. Most testing frameworks just take the tests as they come. Some may specify a position in testing, but that is against the \"Spirit\" of unit-testing. SetUp and TearDown of every test suite will be executed, and if the world ends and hell freezes over.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:34:15.960",
"Id": "77768",
"Score": "0",
"body": "Ah this will not be the case. The term 'Unit Test' is a bit flawed here what I want to achieve. We are testing a component which detects devices in a thread. I want to use Py.Test to achieve this. In each test case the same ComplexClass will be created and destroyed and test a different functionality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:05:59.173",
"Id": "77793",
"Score": "0",
"body": "@RvdK why not reuse the ComplexClass for the whole [Fixture] then?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:47:37.403",
"Id": "44678",
"ParentId": "44676",
"Score": "5"
}
},
{
"body": "<p>Yes fixture is a simple way to do it. I would add the start there too, to make ComplexClass ready to go and reduce code replication. </p>\n\n<p>The second example will not stop if the test succeed. Use finally instead of except. But, instead of duplicating the code each time, I'll use a <a href=\"http://docs.python.org/3.4/library/contextlib.html\" rel=\"nofollow\">contextmanager</a> like this: </p>\n\n<pre><code>from contextlib import contextmanager\n@contextmanager\ndef stoping_ComplexClass():\n try:\n cc = ComplexClass()\n cc.start()\n yield cc\n finally:\n cc.stop()\n\nclass TestComplexClass(object):\n def test_GetX(self, complexclass):\n # do stuff\n with stoping_ComplexClass() as cc:\n assert cc.GetX() == 42, \"GetX() should return 42\"\n</code></pre>\n\n<p>I'll use fixture when the initialization of ComplexClass is simple and not changing much with each test. But if you need to change the params every test, I think it will be easier to use a contextmanager. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:39:56.827",
"Id": "44758",
"ParentId": "44676",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44678",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T15:10:21.190",
"Id": "44676",
"Score": "6",
"Tags": [
"python",
"unit-testing"
],
"Title": "Create and destroy object in Unit Test"
} | 44676 |
<p>I'm not that experienced with PHP and I'm trying to make it so when I load a page, instead of directly browsing to the file, it will be "included" instead.</p>
<p>I have the code finished and it works. I just wanted to get an opinion of if it's safe (will people be able to exploit it in anyway?) and if I'm going about this the right way.</p>
<pre><code><?php
error_reporting(0); // I'm not expecting any errors and don't want users to see any.
$page = strtolower($_GET['page']); // File names will always be lowercase
if (isset($page))
{
$page .= ".php";
$page = basename($page); // Prevent users from entering a directory path to access other files.
if ((file_exists($page)) && ($page != "index.php")) // Check if exists and prevent infinite include loop.
{
die(include($page));
}
}
include("base.php");
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:10:47.280",
"Id": "77630",
"Score": "0",
"body": "what prevents a user to access /directory1/directory2/file2.php - is this code part of a routing code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:11:43.457",
"Id": "77631",
"Score": "0",
"body": "@azngunit81 $page = basename($page); // Prevent users from entering a directory path to access other files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T18:11:15.913",
"Id": "77649",
"Score": "0",
"body": "yes but that doesnt answer the fact that this file is your commanding index.php or not because if this is not a routing file i can go into a directory manually www.example.com/dir1/dir2/test.php - if no routing system is done your code wont be activated unless there is a check. I will obviously bounce if such directory is not present of course"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:38:10.480",
"Id": "77658",
"Score": "0",
"body": "@azngunit81 It is a routing file. I'm using get_included_files() within the other PHP scripts to ensure that there is no direct access."
}
] | [
{
"body": "<p>As it uses the <code>basename</code> function it should be safe enough.</p>\n\n<p>One note though: I would personally <em>always</em> have a lookup table (PHP \"array\") for whitelisting files unless there is a very specific reason <em>not</em> to do so. That way I will have full control and the result should be the same for the user - as a side effect it is way way more easy to have shorter names and/or aliases for files later on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T17:56:54.387",
"Id": "44683",
"ParentId": "44679",
"Score": "1"
}
},
{
"body": "<p>Ok with all that routing question out of the way - I agree with mbanzon with basename being fine to check for internal directory structure to block people out...</p>\n\n<p>If you want extra security you can run a short alpha numeric check to make sure nothing funny is included.</p>\n\n<p>As for the white list - since this is a routing file and a static one a white list can also help speed things up as long as its minimal, one problem though with that is if you file system becomes extensive it maybe best to not have a whitelist at that point (you dont want your lookup to be too large to maintain and add.</p>\n\n<p>Side note: if your looking for interesting ideas symfony2 routing is pretty good (its being use at core with laravel). It is more extensive than your solution of course but still interesting to look at.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:57:36.377",
"Id": "44720",
"ParentId": "44679",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "44683",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T16:01:07.963",
"Id": "44679",
"Score": "5",
"Tags": [
"php",
"beginner"
],
"Title": "Including a file (is this safe and effective?)"
} | 44679 |
<p>I have the following code, which works as I need it to, however, it repeats itself over and over.</p>
<p>I'm relatively new to PHP and haven't grasped recursive functions yet. Which I've been told I'll need to understand as this function could potentially have many levels.</p>
<pre><code>if ($_POST['parent'] == "None") {
$parent = "";
} else {
$parent = $connection->real_escape_string($_POST['parent']);
}
if (!empty($parent)) {
$query = $connection->query("SELECT * FROM pages WHERE filename='$parent'");
while($row = $query->fetch_array()) {
$path_arr = explode('/',$row['path_to']);
end($path_arr);
$key = key($path_arr)-1;
$parent1 = $path_arr[$key];
if (!empty($parent1)) {
$query = $connection->query("SELECT * FROM pages WHERE filename='$parent1'");
while($row = $query->fetch_array()) {
$path_arr = explode('/',$row['path_to']);
end($path_arr);
$key = key($path_arr)-1;
$parent2 = $path_arr[$key];
if (!empty($parent2)) {
$query = $connection->query("SELECT * FROM pages WHERE filename='$parent2'");
while($row = $query->fetch_array()) {
$path_arr = explode('/',$row['path_to']);
end($path_arr);
$key = key($path_arr)-1;
$parent3 = $path_arr[$key];
if (!empty($parent3)) {
$query = $connection->query("SELECT * FROM pages WHERE filename='$parent3'");
while($row = $query->fetch_array()) {
$path_arr = explode('/',$row['path_to']);
end($path_arr);
$key = key($path_arr)-1;
$parent4 = $path_arr[$key];
}
}
}
}
}
}
}
}
$path_to = rtrim(ltrim($parent4.'/'.$parent3.'/'.$parent2.'/'.$parent1.'/'.$parent.'/'.$filename,'/'),'/');
</code></pre>
<p>As you can see there are minimal differences within the nested while loops, but I'm really not sure how to make the function loop for each level.</p>
<p>I was pointed to <a href="https://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php"><strong>this</strong></a>, and while I understand what the factorial is, I still am unsure on how to refactor my code into a looping function.</p>
<p>Any pointers?</p>
<p><strong><em>UPDATE</em></strong></p>
<p>Certainly moving in the right direction of what I'm hoping to achieve with <a href="https://codereview.stackexchange.com/a/44685/38996">Simon André Forsberg's suggestion</a></p>
<p>However (I probably should have made this clearer in my explanation), The loop(s) determine whether a 'file' (a database entry, masquerading as a file) has a parent 'file', returns that parent 'file', then checks that parent 'file' for a parent 'file' and returns it and so on and so on until there are no more parents.</p>
<p>It is used to create a dynamic path directory.</p>
<p>like so <strong><em>/parent4/parent3/parent2/parent1/filename/</em></strong></p>
<p>The line of code that follows the loops (again, I probably should have included this), is below...</p>
<pre><code>$path_to = rtrim(ltrim($parent4.'/'.$parent3.'/'.$parent2.'/'.$parent1.'/'.$parent.'/'.$filename,'/'),'/');
</code></pre>
<p>So each level of the loop outputs to this string.</p>
<p>I have a feeling I may have to do this using <a href="https://codereview.stackexchange.com/a/44686/38996">palacsint's method</a> of taking the working part of each loop and creating that as a function.</p>
<p>I may be wrong but could Simon's method output to an array? first parent in pos 0, second in pos 1, etc?</p>
<p>However, then the query would have to have the <code>filename='$parent'</code> updated to look at the last array entry.</p>
<p><code>$query = $connection->query("SELECT * FROM pages WHERE filename='$parent'");</code></p>
<p>Have I bitten off more than I can chew?</p>
| [] | [
{
"body": "<p>You seem to always end with the check: Is there another parent? Or as it can be formulated, <strong>while</strong> there is another parent, grab that parent.</p>\n\n<p>Luckily for you, there are <strong>while</strong> loops.</p>\n\n<pre><code>while (!empty($parent)) {\n $query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent'\"); \n while($row = $query->fetch_array()) {\n $path_arr = explode('/',$row['path_to']);\n end($path_arr);\n $key = key($path_arr)-1;\n $parent = $path_arr[$key];\n break; // break from the inner loop that fetches each row\n }\n}\n</code></pre>\n\n<p>This code will continue looping while there is a parent available. Note that the new parent uses the same variable as the previous one, this is an important part in making this loop work.</p>\n\n<p>Other suggestions:</p>\n\n<ul>\n<li><p><strong>Use prepared statements!</strong> It is good that you seem to sanitize your inputs by using the <code>real_escape_string</code> method. But prepared statements is always better. And then you wouldn't have to use the <code>real_escape_string</code> call.</p></li>\n<li><p>Since this code only gets the first result, you don't need the inner while loop and can replace it by a <code>if</code> instead.</p>\n\n<pre><code>while (!empty($parent)) {\n $query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent'\"); \n if ($row = $query->fetch_array()) {\n $path_arr = explode('/',$row['path_to']);\n end($path_arr);\n $key = key($path_arr)-1;\n $parent = $path_arr[$key];\n }\n}\n</code></pre></li>\n<li><p>I do have to ask though: What's the point in just grabbing the parent until there are no more parents? To store all the parents in an array, let's do like this:</p>\n\n<pre><code>$parents = array();\nwhile (!empty($parent)) {\n $parents[] = $parent; // add parent to the array\n $query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent'\"); \n if ($row = $query->fetch_array()) {\n $path_arr = explode('/',$row['path_to']);\n end($path_arr);\n $key = key($path_arr)-1;\n $parent = $path_arr[$key];\n }\n}\n</code></pre></li>\n</ul>\n\n<p>Now, when this loop finishes, <code>$parents</code> contains all the parents that was not empty. Now you can loop through that using a <code>foreach</code> loop, or use it with <code>implode</code> or whatever you'd like :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:09:53.887",
"Id": "77772",
"Score": "0",
"body": "Thanks for this Simon, it's certainly moving toward what I'm trying to achieve. I've updated a couple of points on the question to try to explain better what I am trying to achieve. Basically, the code isn't just trying to find the last parent, it's outputting each parent that it finds, checking that parent for a parent and so on..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:04:13.657",
"Id": "77783",
"Score": "0",
"body": "@Dijon Updated last part of my answer to use an array."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T18:11:03.823",
"Id": "44685",
"ParentId": "44682",
"Score": "7"
}
},
{
"body": "<p>If it's a function in itself, use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clauses</a> to make it flatten. If it's not, extract it out to separate function and use guard clauses in that. You can invert the <code>!empty</code> conditions and <code>return</code> or <code>continue</code> if it's true. With that you can reduce the indentation levels from nine to six.</p>\n\n<pre><code>if ($_POST['parent'] == \"None\") {\n $parent = \"\";\n} else {\n $parent = $connection->real_escape_string($_POST['parent']);\n}\n\nif (empty($parent)) {\n return;\n}\n\n$query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent'\"); \n\nwhile($row = $query->fetch_array()) {\n $path_arr = explode('/',$row['path_to']);\n end($path_arr);\n $key = key($path_arr)-1;\n\n $parent1 = $path_arr[$key];\n\n if (empty($parent1)) {\n continue;\n }\n ...\n}\n</code></pre>\n\n<p>As the second step, you could create a function for</p>\n\n<blockquote>\n<pre><code>$path_arr = explode('/', $row['path_to']);\nend($path_arr);\n$key = key($path_arr)-1;\n$parent1 = $path_arr[$key];\n</code></pre>\n</blockquote>\n\n<p>For example:</p>\n\n<pre><code>function get_parent_folder($filename) {\n $path_arr = explode('/', $filename);\n end($path_arr);\n $key = key($path_arr)-1;\n\n $parent1 = $path_arr[$key];\n return $parent1;\n}\n</code></pre>\n\n<p>I guess instead of the array manipulation you could use PHP's built-in filename functions here which are probably well-tested and handle corner cases better than reinvented code:</p>\n\n<pre><code>function get_parent_folder($filename) {\n $dirname = dirname($filename);\n $parent_basename = basename($dirname);\n return $parent_basename;\n}\n</code></pre>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> It's a Java book and the author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p>\n\n<p>Usage:</p>\n\n<pre><code>$query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent'\"); \nwhile($row = $query->fetch_array()) {\n $parent1 = get_parent_folder($row['path_to']);\n\n if (empty($parent1)) {\n continue;\n }\n\n $query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent1'\");\n while($row = $query->fetch_array()) {\n $parent2 = get_parent_folder($row['path_to']);\n\n if (empty($parent2)) {\n continue;\n }\n\n $query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent2'\");\n while($row = $query->fetch_array()) {\n $parent3 = get_parent_folder($row['path_to']);\n\n if (empty($parent3)) {\n continue;\n }\n\n $query = $connection->query(\"SELECT * FROM pages WHERE filename='$parent3'\");\n\n while($row = $query->fetch_array()) {\n $parent4 = get_parent_folder($row['path_to']);\n\n }\n }\n }\n}\n</code></pre>\n\n<p>After that it's easier to see the pattern and comes Simon's solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:12:58.913",
"Id": "77774",
"Score": "0",
"body": "Thanks @palacsint, I'm thinking this may be the way I have to do it. I've updated the question to better explain the scenario, have a look and see what you think. I might be wrong but I can't use PHP's built in filename functions as the files are not real files, but database entries, masquerading as files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:17:23.443",
"Id": "77775",
"Score": "1",
"body": "@Dijon: Not all of the filename functions require real files. IIRC I've tried the code above and it worked without real files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:22:31.073",
"Id": "77776",
"Score": "1",
"body": "Great, I'll read the [**docs**](http://uk1.php.net/dirname) and implement it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T18:20:27.343",
"Id": "44686",
"ParentId": "44682",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44685",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T17:20:55.477",
"Id": "44682",
"Score": "6",
"Tags": [
"php"
],
"Title": "Need to condense the following into a looping function"
} | 44682 |
<p>I am learning algorithms in graphs. I have implemented topological sort using Java. Kindly review my code and provide me with feedback. </p>
<pre><code>import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class TopologicalSortGraph {
/**
* This Topological Sort implementation takes the example graph in
* Version 1: implementation with unweighted
* Assumption : Graph is directed
*/
TopologicalSortGraph Graph = new TopologicalSortGraph();
//public LinkedList<Node> nodes = new LinkedList<Node>();
public static void topologicalSort(Graph graph) {
Queue<Node> q = new LinkedList<Node>();
int vertexProcessesCtr = 0;
for(Node m : graph.nodes){
if(m.inDegree==0){
++vertexProcessesCtr;
q.add(m);
System.out.println(m.data);
}
}
while(!q.isEmpty()) {
Node m = q.poll();
//System.out.println(m.data);
for(Node child : m.AdjacenctNode){
--child.inDegree;
if(child.inDegree==0){
q.add(child);
++vertexProcessesCtr;
System.out.println(child.data);
}
}
}
if(vertexProcessesCtr > graph.vertices) {
System.out.println();
}
}
public static void main(String[] args) {
Graph g= new Graph();
g.vertices=8;
Node TEN = new Node("10");
Node ELEVEN = new Node("11");
Node TWO = new Node("2");
Node THREE = new Node("3");
Node FIVE = new Node("5");
Node SEVEN = new Node("7");
Node EIGHT = new Node("8");
Node NINE = new Node("9");
SEVEN.AdjacenctNode.add(ELEVEN);
ELEVEN.inDegree++;
SEVEN.AdjacenctNode.add(EIGHT);
EIGHT.inDegree++;
FIVE.AdjacenctNode.add(ELEVEN);
ELEVEN.inDegree++;
THREE.AdjacenctNode.add(EIGHT);
EIGHT.inDegree++;
THREE.AdjacenctNode.add(TEN);
TEN.inDegree++;
ELEVEN.AdjacenctNode.add(TEN);
TEN.inDegree++;
ELEVEN.AdjacenctNode.add(TWO);
TWO.inDegree++;
ELEVEN.AdjacenctNode.add(NINE);
NINE.inDegree++;
EIGHT.AdjacenctNode.add(NINE);
NINE.inDegree++;
g.nodes.add(TWO);
g.nodes.add(THREE);
g.nodes.add(FIVE);
g.nodes.add(SEVEN);
g.nodes.add(EIGHT);
g.nodes.add(NINE);
System.out.println("Now calling the topologial sorts");
topologicalSort(g);
}
}
</code></pre>
<p>Graph class:</p>
<pre><code>class Graph {
public int vertices;
LinkedList<Node> nodes = new LinkedList<Node>();
}
</code></pre>
<p>Node Class:</p>
<pre><code>class Node {
public String data;
public int dist;
public int inDegree;
LinkedList<Node> AdjacenctNode = new LinkedList<Node>( );
public void addAdjNode(final Node Child){
AdjacenctNode.add(Child);
Child.inDegree++;
}
public Node(String data) {
super();
this.data = data;
}
}
</code></pre>
| [] | [
{
"body": "<pre><code>class Graph {\n public int vertices;\n LinkedList<Node> nodes = new LinkedList<Node>();\n}\n</code></pre>\n\n<h2><code>Graph</code></h2>\n\n<p><code>Graph</code>, as other data structures in general, should be declared \n<code>public</code>. Because you want them to be able to be used outside of the \npackage they are declared in. </p>\n\n<p><code>nodes</code>, <code>vertices</code> should be <code>private</code> so that you <em>can</em> know that they \nare not changed outside the <code>Graph</code> class. </p>\n\n<p><code>nodes</code> should not be a <code>LinkedList</code>. You must depend on abstractions as \nmuch as possible. You should prefer <code>interface</code>s such as <code>List</code> over \nspecific implementations <code>LinkedList</code>.</p>\n\n<p>Nodes of a graph is not a <code>List</code>, it is a <code>Set</code>. A standard graph cannot \nhave multiple copies of a node. You should prefer a <code>Set</code> to represent a \nset unless you have a good reason. </p>\n\n<h2><code>Node</code></h2>\n\n<p>All of the above points also apply to <code>Node</code>. Apart from those: </p>\n\n<p><code>AdjacenctNode</code> should be named <code>adjacentNode</code> by Java naming \nconvention. </p>\n\n<p>Feel free to remove parameterless call to <code>super();</code>, although Eclipse \nadds it by default, it's just noise. </p>\n\n<h2><code>TopologicalSortGraph</code></h2>\n\n<p>Remove unused code : </p>\n\n<pre><code>TopologicalSortGraph Graph = new TopologicalSortGraph();\n</code></pre>\n\n<p>Always remove commented code. If you need to see previous versions of a \ncode use a version control system. : </p>\n\n<pre><code>//public LinkedList<Node> nodes = new LinkedList<Node>();\n</code></pre>\n\n<p>Do not put more than one space between tokens, use autoformat of your \nIDE to fix formatting after changing a piece of code: </p>\n\n<pre><code>public static void topologicalSort(Graph graph) {\n</code></pre>\n\n<p>The snippets :</p>\n\n<pre><code>if(child.inDegree==0){\n q.add(child);\n ++vertexProcessesCtr;\n System.out.println(child.data);\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>if(m.inDegree==0){\n ++vertexProcessesCtr;\n q.add(m);\n System.out.println(m.data);\n}\n</code></pre>\n\n<p>are duplicates. They should be extracted to a <code>private</code> method. You are \nmissing some kind of abstraction there. </p>\n\n<p>You are changing the internals of an object passed in as a parameter: \n<code>--child.inDegree;</code> I do not expect my graph to change after I ask to \nsee its nodes printed in topological order. What if I want to print \nthem again?</p>\n\n<p>You are mixing the calculation and the printing out of the calculation result, \nI do not expect to see <code>println</code>s in a method implementing an algorithm: </p>\n\n<p><code>System.out.println( .... );</code></p>\n\n<p>What if I want the result to be printed somewhere other than <code>System.out</code>? \nWhat if I do not want the result to be printed at all and want it to be \nused as an intermediate step in a bigger calculation instead? </p>\n\n<p>You probably want to return a <code>List<Node></code> from a topological sort \nalgorithm. <code>List</code> is the standard return type when you are sorting some \ncollection, that is when the result is a collection whose order is \nimportant. You can then print that list as many times as you want or \npass it as a parameter to wherever you like. </p>\n\n<h2><code>public static void main(String[] args) {</code></h2>\n\n<p>You should separate test code from your main code. If your actual class \nis named <code>TopologicalSortGraph</code> put your test code in \n<code>TopologicalSortGraphTest</code>. </p>\n\n<p>Use de facto standard <code>JUnit</code> so that instead of one big <code>main</code> you can \nhave many small tests. You can run any one of them or all of them easily \nfrom within your IDE or from the command line. </p>\n\n<p>You should try to separate the test code into separate source \ndirectories or even into separate projects. Your implementation code \nshould not need or know about your test code to compile. </p>\n\n<p>Another spacing (indentation) problem : </p>\n\n<pre><code>Node TEN = new Node(\"10\");\n</code></pre>\n\n<p>Your code should align well. So that it reads neatly top to bottom and \nscopes in it are easily identified. </p>\n\n<p><code>TEN</code> should be <code>ten</code> by Java naming convention.</p>\n\n<p>Instead of these two you should use your <code>addAdjNode</code> method instead:</p>\n\n<pre><code>SEVEN.AdjacenctNode.add(ELEVEN);\nELEVEN.inDegree++;\n</code></pre>\n\n<p>Also access chains like <code>node.AdjacenctNode.add(otherNode)</code> or <code>x.y.z</code> \nare usually a sign that your encapsulation is not good enough. In this \ncase you are modifying a collection of one class from another class. \nIt's a problem waiting to happen. Same encapsulation problem is present \nin <code>ELEVEN.inDegree++</code>, too. </p>\n\n<p>The root problem here is adjacency is a property of the graph -Remember \n<code>G = (V, E)</code> from school?- and not of the nodes themselves. Instead of \n<code>node.addAdjNode(otherNode)</code>, you should use a method like \n<code>graph.addEdge(node, otherNode)</code>. </p>\n\n<p>Same problem also exists here: <code>g.nodes.add(TWO);</code> You should have a\n<code>Graph.addNode(node)</code> method instead. </p>\n\n<p>Coming back to <code>G = (V, E)</code>; it says, if you listen carefully, you need \na set of vertices and a set of edges to have a graph and should not add \nnodes one by one. Ideally, <code>Graph</code> would have a constructor like this \n<code>public Graph(Set<Node> vertices, Set<Edge> edges)</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:13:18.480",
"Id": "44736",
"ParentId": "44689",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "44736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T18:59:41.857",
"Id": "44689",
"Score": "15",
"Tags": [
"java",
"algorithm",
"graph"
],
"Title": "Topological sort in Java"
} | 44689 |
<p>I have a program that has to initialize a few big things (connect to a few databases, parse some XML) and without the initialization being successful the program would not be able to continue.<br>
Right now I have my main method throwing just a general Exception</p>
<pre><code>public static void main(String[] args) throws Exception
{
//Throws numerous types of Exceptions
WhateverObject we = WhateverObject.getInstance();
we.doSomething();
}
</code></pre>
<p>My question is, is there a better way to handle this? Should I catch the exception and then print out that it failed an exit? Something else maybe? Note, there's no hope of program recovery at this point.</p>
| [] | [
{
"body": "<ol>\n<li><p>What would the users like? It's usually an error message and a log file with the details and stacktraces for bug reports/support calls/debugging. You can throw exceptions out from <code>main</code> but it's not user-friendly (unless the users are the people who develop the software).</p></li>\n<li><p>Please note that singleton nowadays is rather an antipattern. (<code>WhateverObject.getInstance()</code> looks like a singleton.) They make testing harder and often hide dependencies which leads to spaghetti code which is really hard to work with. </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/138012/843804\">What is so bad about singletons?</a></li>\n<li><a href=\"http://googletesting.blogspot.co.uk/2008/05/tott-using-dependancy-injection-to.html\" rel=\"nofollow noreferrer\">TotT: Using Dependency Injection to Avoid Singletons</a></li>\n<li><a href=\"http://blogs.msdn.com/b/nickmalik/archive/2005/09/07/462054.aspx\" rel=\"nofollow noreferrer\">Eliminating static helper classes</a></li>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/37249/the-singleton-pattern\">The Singleton Pattern</a></li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:22:10.793",
"Id": "77669",
"Score": "0",
"body": "The users would just be me and the code maintainers as this is a backend prototype of a system so I think a log file will suffice. As for the singleton, I am actually using a singleton. The main arguments seem to be the coupling (new term for me) and for testing (I've never actually done formal unit testing before) where I can really see the appeal of not having a singleton pattern. Thanks for the info :D. I'll keep this in mind the next time I'm looking at a singleton pattern."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:52:27.447",
"Id": "44694",
"ParentId": "44690",
"Score": "2"
}
},
{
"body": "<p>For many (small) applications, what you are doing is OK. Not great, but OK.</p>\n\n<p>The problems come with the following:</p>\n\n<ol>\n<li>exception traces will be printed to STDERR (the console, not a file). If the console output is discarded, the error is lost (eg. <code>.... >& /dev/null</code>)</li>\n<li>the exit code of the application may or may not be set to an error code</li>\n<li>if one of your sub-systems succeeds before another one fails, and it starts a non-daemon thread, then your application may not even terminate at all.</li>\n</ol>\n\n<p>For any robust application I recommend using an uncaught-exception handler. This handler should log the uncaught exception to a logical place, and it should <code>System.exit(1)</code> (or some other exit code).</p>\n\n<p>This may complicate things with threads that do not trap their exceptions, but that is bad pracitce as well....</p>\n\n<p>See the documentation for <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler%28java.lang.Thread.UncaughtExceptionHandler%29\" rel=\"nofollow\">the uncaught exception handler</a>, and <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=229\" rel=\"nofollow\">some tutorials</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:09:14.747",
"Id": "77663",
"Score": "0",
"body": "As of now, the console output should go to a file (the library I'm using for my FastCGI interfacing routes all System.err to the Apache log file but only if it's be initialized and System.out to the webserver to display to the client). The application is also single-threaded but that may change. For now I'll catch the exceptions and exit and I'll use the handler if it becomes multi-threaded. Thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:59:08.990",
"Id": "44695",
"ParentId": "44690",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44695",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:15:35.203",
"Id": "44690",
"Score": "5",
"Tags": [
"java",
"exception-handling"
],
"Title": "Proper action when a Java program fails"
} | 44690 |
<p>This code has a method that I call for in <code>main</code>.</p>
<p>I am given a list with temperatures. What I need to do is to write out the biggest absolute difference of 2 neighbour numbers. For example, if I have {1, 3, 4, 10, 7, 4}, the result is 6 (between 4 and 10) and also all other pairs that have the same difference.</p>
<p>I have this code written down but I feel it looks kind of clumsy. I'd be very grateful for any suggestions and improvements.</p>
<pre><code>public class DN4 {
static void najvecjaZaporednaRazlika(double stevila[]){
double maxRaz = 0;
double[] tStevil = new double[0];
for (int i = 0; i < stevila.length - 1; i++){
double a = stevila[i];
double b = stevila[i+1];
double absRaz = a - b;
if (absRaz < 0){
absRaz = -1 * absRaz;
}
if (absRaz == maxRaz){
double tStevilStara[] = tStevil;
tStevil = new double[tStevilStara.length+2];
tStevil[tStevil.length - 2] = a;
tStevil[tStevil.length - 1] = b;
for (int t = 0; t < tStevilStara.length; t++){
tStevil[t] = tStevilStara[t];
}
}
else if (absRaz > maxRaz){
maxRaz = absRaz;
tStevil = new double[2];
tStevil[0] = a;
tStevil[1] = b;
}
}
System.out.printf("Najvecja razlika: %.2f\n",maxRaz);
System.out.printf("Pari,ki dosezejo maksimalno razliko: ");
for (int i = 0; i < tStevil.length - 1; i = i+2){
if (i == 0){
System.out.printf("(%.2f, %.2f)",tStevil[i],tStevil[i+1]);
}
else{
System.out.printf(", (%.2f, %.2f)",tStevil[i],tStevil[i+1]);
}
}
System.out.println();
}
public static void main (String args[]){
double kredarica2011[] = {-7.8, -6.5, -5.7, -1.3, 1.7, 5,
5.6, 9.2, 7.1, 0.5, 0.3, -6.3};
najvecjaZaporednaRazlika(kredarica2011);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:24:44.837",
"Id": "77654",
"Score": "0",
"body": "@Vogel612: I got it now. It just needed CTRL+K."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:26:09.827",
"Id": "77656",
"Score": "0",
"body": "@Jamal I hate to put such stuff throught edit-queue and not even notify OP about it... It feels so intrusive.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:27:16.970",
"Id": "77657",
"Score": "0",
"body": "@Vogel612: That's just the nature of it. In most cases, others will review the edits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:17:10.530",
"Id": "77765",
"Score": "0",
"body": "@user2956514 The most obvious advice would be just use an `ArrayList` save yourself a lot of trouble, but I'm guessing this is a homework and you are supposed to use arrays. Your naming is probably bad but you can't get them reviewed because you didn't care to translate them."
}
] | [
{
"body": "<h2>General</h2>\n\n<ul>\n<li><p>Your code style is neat. I like that you are using <code>System.out.printf</code> instead of concatenating strings. You should consider using <code>%n</code> instead of <code>\\n</code>in the format because it is platform independent.</p></li>\n<li><p>Math.abs() - <code>Math.abs()</code> is a core function that you should use instead of doing it yourself.</p></li>\n<li><p>Growing the tStevil array - you do this manually, and you increase and decrease the size often. This can be inefficient. It may be better to keep a big-enough version, and have a separate <code>int tStevillength</code> variable to keep track of how much is actually populated.</p></li>\n<li><p>This code here:</p>\n\n<blockquote>\n<pre><code> for (int i = 0; i < tStevil.length - 1; i = i+2){\n if (i == 0){\n System.out.printf(\"(%.2f, %.2f)\",tStevil[i],tStevil[i+1]);\n }\n else{\n System.out.printf(\", (%.2f, %.2f)\",tStevil[i],tStevil[i+1]);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>would be better done with less code repeated:</p>\n\n<pre><code>for (int i = 0; i < tStevil.length - 1; i = i+2){\n if (i > 0){\n System.out.print(\", \");\n }\n System.out.printf(\"(%.2f, %.2f)\",tStevil[i],tStevil[i+1]);\n}\n</code></pre></li>\n</ul>\n\n<h2>Algorithm.</h2>\n\n<p>Your algorithm is close to what I would have done. The only difference is that I would keep an array of indexes of the first member of a temperature pair....</p>\n\n<p>Also, sometimes it is easier to loop from <code>i = 1</code>, instead of looping to <code>i < length - 1</code></p>\n\n<p>My code would look something like:</p>\n\n<pre><code>int pairlen = 0;\nint[] pairs = new int[stevila.length];\ndouble maxdiff = Double.MIN_VALUE;\nfor (int i = 1; i < stevila.length; i++) {\n double diff = Math.abs(stevila[i] - stevila[i - 1]);\n if (diff > maxdiff) {\n maxdiff = diff;\n pairlen = 0;\n }\n if (diff == maxdiff) {\n pairs[pairlen++] = [i - 1];\n }\n}\n</code></pre>\n\n<p>This way, at the end of the loop, you have the index to the first pair of <code>pairlen</code> indexes for values with the largest diff.</p>\n\n<p>You can then loop through that list using <code>for (i = 0; i < pairlen; i++) { .... }</code> and pull the actual values back from the <code>stevila</code> array.</p>\n\n<p>This is not actually very different fdrom the way you have done it, but it is a bit neater.</p>\n\n<p>Nice job.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:11:03.013",
"Id": "77773",
"Score": "0",
"body": "I really appreciate you taking time and for giving me a great answer :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:47:58.003",
"Id": "44692",
"ParentId": "44691",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "44692",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:17:04.780",
"Id": "44691",
"Score": "4",
"Tags": [
"java",
"array"
],
"Title": "Working with list in Java"
} | 44691 |
<p>I've implemented a simple linked list in C# using generic <code>T</code> for values. I did not inherit from any of .Net's fun and helpful classes like <code>IEnumerable<T></code>, or <code>IList<T></code> :D. This is just after an hours worth of work. I've tested everything and I believe it all works well enough, but before I go on to add more methods, or make the actual data-structure more complex I'm looking for some feedback on what I have. Critiques on everything are welcome, perhaps there is some glaring issue that I have not addressed.</p>
<p>As far as my nodes having a previous and next value, that is because I did intend to have quicker searching iterating backwards through, and some other stuff that is not yet implemented. While right now do use both properties of the node, I know I could avoid it. But I have kept it in and use it because I do plan to implement more stuff later.</p>
<p>This is supposed to emulate the List class. I've called mine Jist to not confuse anyone. I also have considered taking away the <code>JNode</code> constructor, because all the properties are public anyway, but I've decided against that, because I don't want any accidentally <code>null</code> values... while <code>default</code> values are fine, I don't want any in there by accident.</p>
<pre><code>class JNode<T>
{
public T Value { get; set; }
public JNode<T> Next { get; set; }
public JNode<T> Previous { get; set; }
public JNode(T value) { Value = value; }
}
public class Jist<T>
{
#region Private Members
private JNode<T> _first;
private JNode<T> _last;
#endregion
#region Public Properties
public UInt64 Count { get; private set; }
public T this[UInt64 index]
{
get { return NodeAtIndex(index).Value; }
set { NodeAtIndex(index).Value = value; }
}
#endregion
#region Constructor
public Jist()
{
Count = 0;
_first = new JNode<T>(default(T));
_last = new JNode<T>(default(T));
LinkNodes(_first, _last);
}
#endregion
#region Public Methods
public void Add(T value)
{
InsertBeforeNode(_last, value);
}
public void Clear()
{
LinkNodes(_first, _last);
Count = 0;
}
public bool Contains(T value)
{
return FirstNodeWithValue(value) != null;
}
public void Insert(T value, UInt64 index)
{
if (index > Count)
throw new IndexOutOfRangeException("Index(" + index + ") cannot be greater than Count(" + Count + ")");
InsertBeforeNode(NodeAtIndex(index), value);
}
public UInt64? IndexOf(T value)
{
return IndexOfFirstNodeWithValue(value);
}
public bool Remove(T value)
{
var node = FirstNodeWithValue(value);
if (node != null)
LinkNodes(node.Previous, node.Next);
return node != null;
}
#endregion
#region Private Methods
private void InsertBeforeNode(JNode<T> node, T value)
{
if (Count == UInt64.MaxValue)
throw new ArgumentException("List can not grow larger than " + UInt64.MaxValue + " nodes large.");
var nn = new JNode<T>(value);
LinkNodes(node.Previous, nn);
LinkNodes(nn, node);
Count++;
}
private void LinkNodes(JNode<T> first, JNode<T> second)
{
first.Next = second;
second.Previous = first;
}
private JNode<T> NodeAtIndex(UInt64 index)
{
if (index > Count - 1)
throw new IndexOutOfRangeException("Index(" + index + ") cannot be greater than Count(" + Count + " - 1)");
JNode<T> node = _first.Next;
for (UInt64 i = 0; i < index; i++)
node = node.Next;
return node;
}
private JNode<T> FirstNodeWithValue(T value)
{
JNode<T> node = _first.Next;
for (UInt64 i = 0; i < Count; i++)
if (EqualityComparer<T>.Default.Equals(node.Value, value))
return node;
else
node = node.Next;
return null;
}
private UInt64? IndexOfFirstNodeWithValue(T value)
{
UInt64 i = 0;
for (JNode<T> node = _first.Next; !EqualityComparer<T>.Default.Equals(node.Value, value); node = node.Next)
if (i >= Count) return null;
else i++;
return i;
}
#endregion
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:00:05.927",
"Id": "77659",
"Score": "0",
"body": "I'd have named them `LinkedList` and `LinkedListNode` if my goal was to not be confusing. Otherwise it sounds like something Java related. A namespace will already keep it apart from anything that ends up having the same name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:03:33.450",
"Id": "77660",
"Score": "0",
"body": "but Jist looks like List, so I thought it was fitting. I know namespaces keep things separate very well. I could have called it a List<> and just made sure to always say MyNameSpace.List.... but that would have been annoying"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:13:23.450",
"Id": "77665",
"Score": "0",
"body": "Well, you certainly could name all your namespaces things like `§ystem.Coll3ctions.G3neric` to avoid collisions just as easily, but that isn't a better way of avoiding name collisions either. The bigger point is that the name `List` C# belongs to what is essentially a generic arraylist. Giving something that acts differently and implements none of the same interfaces a name that looks similar but isn't is a very bad idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:16:10.043",
"Id": "77667",
"Score": "0",
"body": "The point of this coding contest is to make a linked list. There were no naming specifications. You yourself just said to name it LinkedList... but there is already a LinkedList<T> in the .Net library. I just named it something unique, that wasn't incredibly off base"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:24:22.563",
"Id": "77670",
"Score": "2",
"body": "My point is not about collisions, but about naming. Naming something `Jist` implies nothing, even that it is a list. Naming it `LinkedList` may create a collision, however that's less of a code quality issue than a bad name. You know not only that it is a list, but what kind and presumably how to use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:30:37.157",
"Id": "77671",
"Score": "0",
"body": "While this is currently a linked list it may not be when I am done with it, it might be a B+ tree... its just some data structure to me. Right now it is a linked list. It doesn't need to be called a LinkedList to be used like a container."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:35:56.093",
"Id": "77672",
"Score": "0",
"body": "Then maybe that should be some sort of data structure interface. Concrete types should have names that convey what they are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:39:44.397",
"Id": "77673",
"Score": "0",
"body": "FirstNodeWithValue and IndexOfFirstNodeWithValue use different conventions for if else. I might consider using a standard here to help with code reading.... I personally like using {} around these or if it's simple using ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:41:10.357",
"Id": "77674",
"Score": "0",
"body": "@Magus If you would like to write a review, feel free to make a remark about my naming convention there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:42:00.380",
"Id": "77675",
"Score": "1",
"body": "@dreza you are correct. It just looked so pretty doing it the way I did in `IndexOfFirstNodeWithValue` :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:43:52.527",
"Id": "77676",
"Score": "2",
"body": "@BenVlodgi ha, yes. I always fall into the same trap myself!"
}
] | [
{
"body": "<p>Overall, this isn't bad. I do see a few things that bug me though.</p>\n\n<ol>\n<li>Regions - I find they clutter up the code and don't add much value. I would not use them.</li>\n<li><p>Code blocks, regardless how many lines they are should be surrounded by <code>{}</code>. This makes it much easier for your eyes to line code up. There are a few cases where I think this can be ignored (see point 3)</p>\n\n<pre><code>if (node != null)\n{\n LinkNodes(node.Previous, node.Next);\n}\n\nfor (UInt64 i = 0; i < index; i++)\n{\n node = node.Next;\n}\n</code></pre></li>\n<li><p>The else statement in the following code is redundant because of the <code>return</code>. This is one of those cases I'm on the fence about having <code>{}</code> around code blocks.</p>\n\n<pre><code>for (UInt64 i = 0; i < Count; i++)\n{\n if (EqualityComparer<T>.Default.Equals(node.Value, value)) return node;\n\n node = node.Next;\n}\n</code></pre></li>\n<li><p>Add <a href=\"http://msdn.microsoft.com/en-us/library/t98873t4.aspx\">UL</a> to numbers to avoid having to use the type declaration. This will allow you to use var instead.</p>\n\n<pre><code>for (var i = 0UL; i < Count; i++)\n{\n if (EqualityComparer<T>.Default.Equals(node.Value, value)) return node;\n\n node = node.Next;\n}\n</code></pre></li>\n<li><p>The variable <code>nn</code> is not named very well. Try something like <code>newNode</code> to make the intent more visible.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:55:45.663",
"Id": "44705",
"ParentId": "44693",
"Score": "10"
}
},
{
"body": "<p>Well done for making it a doubly-linked list (i.e. Next and Prev members of JNode): that improves performance of insert and remove in the middle of the list.</p>\n\n<p>However that performance improvement is wasted by the fact that you always need to search through the list in the first place (so you know, from searching, what the previous node is), to find the node you want to insert or delete.</p>\n\n<hr>\n\n<p>I suspect it would be neater to use a nested class:</p>\n\n<pre><code>public class Jist<T>\n{\n class JNode\n {\n public T Value { get; set; }\n public JNode Next { get; set; }\n public JNode Previous { get; set; }\n\n public JNode(T value) { Value = value; }\n }\n\n #region Private Members\n private JNode _first;\n private JNode _last;\n\n ... etc ...\n</code></pre>\n\n<p>JNode doesn't presently appear in the public API.</p>\n\n<p>It would be dangerous to add JNode to the public API (e.g. to implement a method which returns the JNode in which a value is contained) because JNode has public Prev and Next properties which the user code should be allowed to set.</p>\n\n<hr>\n\n<p>I'm not sure about using <code>UInt64</code> as your counter type: standard System.Collection types make do with <code>int</code>.</p>\n\n<hr>\n\n<p>The performance of the indexer ...</p>\n\n<pre><code>public T this[UInt64 index]\n</code></pre>\n\n<p>... is potentially very slow: because you need to iterate to find the requested node. IOW the API looks like an array but its performance doesn't. Equivalent System.Generic classes such as <code>Queue<></code> don't implement this API, perhaps (or IMO, probably) because they cannot implement it well/performantly.</p>\n\n<hr>\n\n<p>NodeAtIndex doesn't ensure that index is smaller than Count.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:48:13.930",
"Id": "77755",
"Score": "0",
"body": "I disagree with one of you last statements - `Queue` doesn't implement an indexer API because it' not part of the ADT. Same for `Stack`. They could implement an indexer as they are backed by an array - so an indexer would be trivial and fast to do."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T21:23:01.927",
"Id": "44708",
"ParentId": "44693",
"Score": "6"
}
},
{
"body": "<p>In your public Insert method, the argument check</p>\n\n<pre><code>if (index > Count)\n throw new IndexOutOfRangeException(\"Index(\" + index + \") cannot be greater than Count(\" + Count + \")\");\n</code></pre>\n\n<p>is off by one. It should be <code>Count - 1</code>. Your current code will forgive this oversight, because the <code>NodeAtIndex</code> method it calls to retrieve the node also has an argument check, with the correct max value. But if you're going to put in an argument check, it should be correct.</p>\n\n<p>If my assumption is wrong, and you intended to allow inserting at Count (i.e. after the last item), then you have a different problem, because <code>NodeAtIndex</code> will throw an exception when you try that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T23:56:12.497",
"Id": "44918",
"ParentId": "44693",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44705",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T19:50:49.147",
"Id": "44693",
"Score": "16",
"Tags": [
"c#",
".net",
"linked-list"
],
"Title": "Simple Linked List"
} | 44693 |
<p>For the record, this is part of a homework assignment, but I have already implemented a solution. I am simply wondering if there is a better way to do it.</p>
<p>Background: I am asked to write a procedure, (complete ls), that takes a list of elements and creates a fully connected graph from them, i.e. complete. I am able to write helper functions to assist in my solution.</p>
<p>A sample graph is defined as <code>'((a (b c)) (b (a c)))</code>. Where the <code>car</code> of each sub-list is a vertex and the <code>cdr</code> of each sub-list is a list of vertices that vertex is connected to.</p>
<p>For example:</p>
<pre><code>(complete? '((a (b c)) (b (a c)) (c (a b)))) => #t
(complete? '((a (b)) (b (a c)) (c ()))) => #f
</code></pre>
<p>My working solution:</p>
<pre><code>(define (complete ls)
(helpComplete ls ls)
)
(define (helpComplete origLst ls)
(if (null? ls)
'()
(cons
(list
(car ls)
(remove-first (car ls) origLst))
(helpComplete origLst (cdr ls)))))
(define (remove-first element ls)
(cond
[(null? ls) '()]
[(eqv? element (car ls)) (cdr ls)]
[else (cons (car ls) (remove-first element (cdr ls)))]
))
</code></pre>
<p>I am not allowed to change the inputs for the <code>complete</code> procedure, as our grading server is expecting it to look like it is now. I am also not allowed to use and <code>!</code> procedures. We are running Petite Chez Scheme Version 8, if anyone cares.</p>
<p>The above code does work, but I was wondering if there is a better way to do it?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:02:48.937",
"Id": "44696",
"Score": "1",
"Tags": [
"recursion",
"scheme",
"graph"
],
"Title": "Completing a Graph in Scheme"
} | 44696 |
<p>I'm writing a small text-based game in Java to learn the language. I'm concerned that I may be making some poor design decisions. I'll introduce 2 elements: A character and monsters. A singleton character should be able to fight a wide array of monsters.</p>
<p>Here is the monster class:</p>
<pre><code>public abstract class Monster {
protected static Random random = new Random();
protected static int STATS_PER_LEVEL = 3;
public int combatLvl;
public int defense, strength, attack, hp;
protected String name;
protected Monster(int defense, int strength, int attack, int hp) {
this.defense = defense;
this.strength = strength;
this.attack = attack;
this.hp = hp;
this.combatLvl = (int) (defense+strength+attack+Math.round((double)hp/10)-4)/STATS_PER_LEVEL;
}
public int attack() {
//removed the body
}
public String toString(String name) {
return this.name;
}
}
</code></pre>
<p>Here's a subclass:</p>
<pre><code>public class Bandit extends Monster {
public static double averageLevelDouble = -1;
public static String averageLevelString = "dummy";
public static int minDefense = 1;
public static int maxDefense = 1;
public static int minStrength = 1;
public static int maxStrength = 3;
public static int minAttack = 1;
public static int maxAttack = 3;
public static int maxHp = 4;
public Bandit() {
super(random.nextInt(maxDefense-minDefense+1) + minDefense,
random.nextInt(maxStrength-minStrength+1) + minStrength,
random.nextInt(maxAttack-minAttack+1) + minAttack,
random.nextInt(maxHp-minHp+1) + minHp);
double min = minDefense+minStrength+minAttack+((double)minHp/10);
double max = maxDefense+maxStrength+maxAttack+((double)maxHp/10);
double avg = ((max+min)/2)-4;
averageLevelDouble = (double)Math.round((avg/STATS_PER_LEVEL)*10)/10;
averageLevelString = (Math.round(min)-4)/STATS_PER_LEVEL + "-" +
(Math.round(max)-4)/STATS_PER_LEVEL;
name = "Bandit";
}
}
</code></pre>
<p>My main concern is that I should be able to easily expand the game with arbitrarily many monsters. The way I'd do it now is to copy paste Bandit into a new class: Change the class name to f.i. Skeleton, initiate 'name' variable in the constructor, customize all the <code>static</code> <code>int</code>s. Is this a wrong approach?</p>
<p>Also a very obvious thing that comes to mind is that I should be able to display information on a particular monster without having to instantiate it. From a Swing.JComboBox I should be able to choose all monsters, display their information, and at the moment I decide to fight a monster it should be instantiated. I can't find a solution to represent monsters on a JList or JComboBox without having to manually add Bandit.name (pretend it's static) as a line of code in the JList/JComboBox class when I define the Bandit class.</p>
<p>I'm just assuming that I shouldn't be instantiating my subclasses. Again, that is the question: What am I doing wrong and right? I really don't how to ask but; What's wrong with my code?</p>
| [] | [
{
"body": "<p>You don't need a separate class for it!</p>\n\n<p>I don't see any <strong>real</strong> difference between a Bandit and a Skeleton and a regular monster. You don't add or change any methods in the subclasses, and you don't add any new variables (other than the static ones).</p>\n\n<p>The most important change you can make here is to only use one class. And then you'd want different <em>methods</em> to instanciate that class. This can be considered <strong>factory methods</strong></p>\n\n<p>A current smell of your code is that your call to the <code>super</code> constructor is a very long one and it's using many variables and some calculations on them. Factory methods will deal with this.</p>\n\n<p>I also think that you are overusing static variables. There are a bunch of ways to deal with this but in this example I will just put them as local variables in a method. A future extension would be to create a <code>MonsterConfiguration</code> class that keeps these variables as <em>fields</em>, then you can create several MonsterConfigurations, and perhaps read some MonsterConfigurations from XML?</p>\n\n<p>In your Monster class, add <code>String name</code> as a parameter to the constructor and remove the <code>abstract</code> keyword from it.</p>\n\n<pre><code>public Monster createBandit() {\n int minDefense = 1; \n int maxDefense = 1;\n int minStrength = 1;\n int maxStrength = 3;\n int minAttack = 1;\n int maxAttack = 3;\n int maxHp = 4;\n\n int defense = random.nextInt(maxDefense-minDefense+1) + minDefense;\n int strength = random.nextInt(maxStrength-minStrength+1) + minStrength;\n int attack = random.nextInt(maxAttack-minAttack+1) + minAttack;\n int hp = random.nextInt(maxHp-minHp+1) + minHp;\n return new Monster(\"Bandit\", defense, strength, attack, hp);\n}\n</code></pre>\n\n<p>I would suggest moving these things to <em>fields</em> in the class or perhaps preferably, <em>methods</em> of the <code>Monster</code> class:</p>\n\n<pre><code> double min = minDefense+minStrength+minAttack+((double)minHp/10);\n double max = maxDefense+maxStrength+maxAttack+((double)maxHp/10);\n double avg = ((max+min)/2)-4;\n averageLevelDouble = (double)Math.round((avg/STATS_PER_LEVEL)*10)/10;\n averageLevelString = (Math.round(min)-4)/STATS_PER_LEVEL + \"-\" + \n (Math.round(max)-4)/STATS_PER_LEVEL;\n</code></pre>\n\n<p>These methods could be called something like: getMin, getMax, getAvg, getAverageLevelDouble, getAverageLevelString.</p>\n\n<p>Now if you want to have a Skeleton, just make a <code>createSkeleton</code> method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:29:28.533",
"Id": "77726",
"Score": "0",
"body": "I almost don't understand anything from your post other than -> Don't make a subclass if it doesn't add functionality. I don't at all understand how putting the calculations of averageLevel(Bandit) outside the creating method would work? I'm not very happy about the duplicate create methods either and I'll still need call createNewMonster on my JList class every time I define a new monster. Have you read rolfl's answer below? It seems very solid, I'm going to try implementing it tomorrow. After reading his post, is there anything you would do different than him?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:12:08.490",
"Id": "77785",
"Score": "0",
"body": "@user2651804 His answer is just a further extension of what I'm doing here. His `MonsterDefinition` is exactly the `MonsterConfiguration` I mentioned. I also don't know how different your monsters will be, if they all match the pattern then stick to rolfl's answer. I honestly don't know what you plan on using your averageLevel variables for, so I can't answer you properly there. I don't know your skill level, but I suggest that you learn about the **Factory pattern** and the proper Java terminology (especially what a *field* is). Once you've improved your code, post a follow-up question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:29:38.837",
"Id": "44700",
"ParentId": "44698",
"Score": "12"
}
},
{
"body": "<p>Your Monster class should have very few, even no static fields. All static fields, if any, should be constants only ( <code>private static final ....</code>).</p>\n\n<p>What you want to do is separate the definition of a monster from it's implementation. Also, the implementation of the monster should be based on a template that sets it's characteristics. The Definition can be that template too.</p>\n\n<p>So, consider a class that is something like:</p>\n\n<pre><code>public class MonsterDefinition {\n private String monsterType;\n private double maxDefense\n .....\n\n public MonsterDefinition(.......) {\n .. set up the definition\n }\n\n // getters for the templates.\n\n}\n</code></pre>\n\n<p>Then, you will need one instance of the MonsterDefinition for each of your monster types. This is what you will use in your ListViews, etc. They will be things like:</p>\n\n<pre><code>private static final MonsterDefintion[] MONSTERS = {\n new MonsterDefintion(\"Skeleton\", .....),\n new MonsterDefintion(\"Bandit\", .....),\n new MonsterDefintion(\"CodeGolf\", .....),\n new MonsterDefintion(\"Zombie\", .....),\n ......\n }\n</code></pre>\n\n<p>Then, you can have a class called something like <code>Monster</code>... which will take a definition to initialize itself:</p>\n\n<pre><code>public class Monster {\n\n private final MonsterDefinition definition;\n private final int id;\n private final String name;\n\n public Monster(String name, int id, MonsterDefinition definition) {\n\n this.definition = definition;\n this.name = name;\n this.id = id;\n }\n\n ......\n\n\n public String toString() {\n return String.format(\"I am monster %d with name %s of type %s, id, name, definition.getMonsterType());\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:29:05.797",
"Id": "77718",
"Score": "0",
"body": "\"you will need one instance of the MonsterDefinition for each of your monster types\". You mean one MonsterDefinition for each monster, right? So MonsterDefinition will take something like 10+ arguments?\nMonster will store the MONSTERS variable? So MonsterDefinition should include a monster's name, as their id for the JList? Could you read your answer over to see if you have made any errors, there seems to be inconsistency. I hope that's what it is and not me understand it wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:30:21.040",
"Id": "77719",
"Score": "1",
"body": "I mean 1 monsterdeginition for each monster type, 1 definition for 'zombie', 1 definition for 'skeleton', etc. Then you use that to make a 'copy', like a template for each Monster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:38:32.547",
"Id": "77720",
"Score": "0",
"body": "I don't think I quite understand. My only reference to Skeleton would be MONSTERS[0], right? Is that what you call a template? It means that all skeletons would be exactly identical; But they should have some randomness in stat-generation from instance to instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:41:22.417",
"Id": "77721",
"Score": "0",
"body": "The reason I asked if you meant one MonsterDefinition for each monster is that you seem to differentiate between monstertype and monstername"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:49:20.380",
"Id": "77722",
"Score": "0",
"body": "Oh okay, I see I wouldn't have that problem since it's the Monster class I want to instantiate using MonsterDefinition. I still have some questions, but this answer really helps me a lot and achieves what I want, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:16:04.237",
"Id": "77837",
"Score": "0",
"body": "Can you please elaborate why Monster constructor takes 'name' and 'id' as parameters?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:39:18.417",
"Id": "44701",
"ParentId": "44698",
"Score": "7"
}
},
{
"body": "<p>You have four similar structures here:</p>\n\n<blockquote>\n<pre><code>super(random.nextInt(maxDefense-minDefense+1) + minDefense, \n random.nextInt(maxStrength-minStrength+1) + minStrength, \n random.nextInt(maxAttack-minAttack+1) + minAttack,\n random.nextInt(maxHp-minHp+1) + minHp);\n</code></pre>\n</blockquote>\n\n<p>Creating a <a href=\"https://stackoverflow.com/q/363681/843804\"><code>randomInt(int lower, int upper)</code></a> method (or using <a href=\"http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/random/RandomDataGenerator.html#nextInt%28int,%20int%29\" rel=\"nofollow noreferrer\"><code>RandomGenerator.nextInt(int lower, int upper)</code></a> from <a href=\"http://commons.apache.org/proper/commons-math/\" rel=\"nofollow noreferrer\">Apache Commons Math</a>) would improve readability of the code and remove some duplication:</p>\n\n<pre><code>super(randomInt(minDefense, maxDefense), \n randomInt(minStrength, maxStrength), \n randomInt(minAttack, maxAttack),\n randomInt(minHp, maxHp));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:30:30.553",
"Id": "77788",
"Score": "0",
"body": "I've never used any library that wasn't prefixed with java: `import java...`, the oracle library I suppose?\nhow can my code import RandomGenerator?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:08:57.573",
"Id": "77795",
"Score": "0",
"body": "@user2651804: You can download it from http://commons.apache.org/proper/commons-math/download_math.cgi and you can add the jar to your classpath. The exact way mainly depends on your development environment. Are you using Eclipse, Netbeans or something similar? What is your build tool? Is it plain `javac` or something else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:17:37.850",
"Id": "77809",
"Score": "0",
"body": "I'm using Eclipse, so that renders the question of my build tool mood, doesn't it? I'm still curious what the difference would be. If you could point me towards an article explaining it I would love that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:18:16.323",
"Id": "77824",
"Score": "0",
"body": "@user2651804: I guess you need that: http://stackoverflow.com/questions/179024/adding-a-jar-to-an-eclipse-java-library (For example, if you were using [Maven](http://maven.apache.org/index.html), you would need to add a new dependency XML tag to its `pom.xml` configuration file.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T09:09:01.980",
"Id": "44735",
"ParentId": "44698",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44701",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:11:38.013",
"Id": "44698",
"Score": "12",
"Tags": [
"java",
"game"
],
"Title": "Making additional subclasses at any time should be as painless as possible"
} | 44698 |
<p>This is one of my first useful scripts. I run it on a highlighted text selection within Notepad++, but I've provided a sample formula and commented out the Scintilla-specific references.</p>
<p>I'm a rank amateur: Am I using good idiom? Is my approach to a state machine sensible?</p>
<pre><code># input_text = editor.getSelText()
input_text = '=HLOOKUP(TablePeriods[[#Headers],[YearMonth]],TablePeriods[[#All],[YearMonth]],MATCH([@Date],INDIRECT("TablePeriods[[#All],["&[@Account]&"]]"),-1))'
# initialize the state table
EVENTS = 11
STATES = 7
state_table = [[[0,0] for x in range(EVENTS)] for x in range(STATES)]
# event list and corresponding state table
event_list = [ "\"", "&", "(", ")", ",", "\n\r\t ", "[", "]", "{", "}" ] # last event is anything that doesn't match one of the other actions
state_table[0] = [[1,0], [0,1], [5,0], [0,3], [0,4], [0,5], [2,0], [0,0], [6,0], [0,0], [0,0]] # normal state
state_table[1] = [[0,0], [1,0], [1,0], [1,0], [1,0], [1,0], [1,0], [1,0], [1,0], [1,0], [1,0]] # double-quote comment
state_table[2] = [[2,0], [2,0], [2,0], [2,0], [2,0], [2,0], [3,0], [0,0], [2,0], [2,0], [2,0]] # inside bracketed table reference
state_table[3] = [[3,0], [3,0], [3,0], [3,0], [3,0], [3,0], [4,0], [2,0], [3,0], [3,0], [3,0]] # inside double-bracketed table reference
state_table[4] = [[4,0], [4,0], [4,0], [4,0], [4,0], [4,0], [-1,0], [3,0], [4,0], [4,0], [4,0]] # inside triple-bracketed table reference (I don't think this exists)
state_table[5] = [[1,2], [0,2], [5,2], [0,0], [0,2], [0,5], [2,2], [0,2], [0,2], [0,2], [0,2]] # found left-paren; only wrap and insert if not empty, like =row()
state_table[6] = [[6,0], [6,0], [6,0], [6,0], [6,0], [6,0], [6,0], [6,0], [6,0], [0,0], [6,0]] # inside curly-braced array
# initialize the state, parenthesis depth, and output text
current_state = 0
paren_depth = 0
output_text = ""
# define the tab and new line characters
TAB_CHAR = "\t"
NEW_LINE = "\r\n"
for z in input_text:
for a in range(len(event_list)):
if z in event_list[a]:
takeaction = state_table[current_state][a][1]
current_state = state_table[current_state][a][0]
break
else:
takeaction = state_table[current_state][-1][1] # this sets takeaction to the value when the test character does not match any event
current_state = state_table[current_state][-1][0] # this sets current_state to the value when the test character does not match any event
if current_state == -1:
current_state = 5 # -1 is an error and should be handled with some sort of error operation
if takeaction == 0: # just pass the characters along
output_text += z
elif takeaction == 1: # place character at same depth as only one on line
output_text += NEW_LINE + TAB_CHAR*paren_depth + z + NEW_LINE + TAB_CHAR*paren_depth
elif takeaction == 2: # previous character was a left paren and this one is not a right-paren
paren_depth = paren_depth + 1
output_text += NEW_LINE + TAB_CHAR*paren_depth + z
elif takeaction == 3: # character is a right paren not immediately following a left paren
paren_depth = paren_depth - 1
output_text += NEW_LINE + TAB_CHAR*paren_depth + z
elif takeaction == 4: # character is a comma, so start a new line at the paren depth
output_text += z + NEW_LINE + TAB_CHAR*paren_depth
elif takeaction == 5: # strip whitespace from the input outside of quotes
pass
else:
pass # should raise error, since the state table includes more actions than are defined
# editor.replaceSel(output_text)
print(output_text)
</code></pre>
<p>My code, without sample, is on <a href="https://gist.github.com/Fluffums/9550351#file-npp-py-analyzeexcelformula" rel="nofollow">Gisthub</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:06:39.993",
"Id": "77941",
"Score": "0",
"body": "I just found this question that seems related and that I intend to look through: http://stackoverflow.com/questions/5492980/what-are-the-best-python-finite-state-machine-implementations"
}
] | [
{
"body": "<p>You can use <a href=\"http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists\">list unpacking</a> to transform :</p>\n\n<pre><code> takeaction = state_table[current_state][a][1]\n current_state = state_table[current_state][a][0]\n</code></pre>\n\n<p>into the more concise :</p>\n\n<pre><code> current_state, takeaction = state_table[current_state][a]\n</code></pre>\n\n<p>. Also, it shows that the type you should be using to convey <code>current_state</code> and <code>takeaction</code> should probably be something more like a tuple than like a list.</p>\n\n<hr>\n\n<p>The pythonic way to loop is not to use <code>range</code> and <code>len</code> but just to go through your iterable with <code>for i in my_iterable:</code>. If you do need the index, <a href=\"http://docs.python.org/2.7/library/functions.html#enumerate\">enumerate</a> is what you need.</p>\n\n<pre><code> for a in range(len(event_list)):\n if z in event_list[a]:\n takeaction = state_table[current_state][a][1]\n current_state = state_table[current_state][a][0]\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code>for i,event in enumerate(event_list):\n if z in event:\n current_state, takeaction = state_table[current_state][i]\n break\n</code></pre>\n\n<hr>\n\n<p>Remove whatever code is not needed. </p>\n\n<pre><code>elif takeaction == 5: # strip whitespace from the input outside of quotes\n pass\n else:\n pass # should raise error, since the state table includes more actions than are define\n</code></pre>\n\n<p>is roughly the same as nothing. If you want to ensure the value is correct, you can use <a href=\"http://docs.python.org/2/reference/simple_stmts.html#the-assert-statement\">assert</a>.</p>\n\n<hr>\n\n<p>From <a href=\"http://legacy.python.org/dev/peps/pep-0008/#id40\">PEP 8</a> : </p>\n\n<blockquote>\n <p>For example, do not rely on CPython's efficient implementation of\n in-place string concatenation for statements in the form a += b or a =\n a + b. This optimization is fragile even in CPython (it only works for\n some types) and isn't present at all in implementations that don't use\n refcounting. In performance sensitive parts of the library, the\n ''.join() form should be used instead. This will ensure that\n concatenation occurs in linear time across various implementations.</p>\n</blockquote>\n\n<hr>\n\n<p>Remove duplicated logic :</p>\n\n<pre><code> takeaction = state_table[current_state][a][1]\n current_state = state_table[current_state][a][0]\n</code></pre>\n\n<p>and </p>\n\n<pre><code> takeaction = state_table[current_state][-1][1] # this sets takeaction to the value when the test character does not match any event\n current_state = state_table[current_state][-1][0] # this sets current_state to the value when the test character does not match any event\n</code></pre>\n\n<p>are quite similar and probably can be factorised out.</p>\n\n<hr>\n\n<p>Do not repeat yourself (bis) : you do not need to define the state table twice. Just do it once and for all and everything should be ok :</p>\n\n<pre><code>state_table = [\n [(1,0), (0,1), (5,0), (0,3), (0,4), (0,5), ( 2,0), (0,0), (6,0), (0,0), (0,0)], # normal state\n [(0,0), (1,0), (1,0), (1,0), (1,0), (1,0), ( 1,0), (1,0), (1,0), (1,0), (1,0)], # double-quote comment\n [(2,0), (2,0), (2,0), (2,0), (2,0), (2,0), ( 3,0), (0,0), (2,0), (2,0), (2,0)], # inside bracketed table reference\n [(3,0), (3,0), (3,0), (3,0), (3,0), (3,0), ( 4,0), (2,0), (3,0), (3,0), (3,0)], # inside double-bracketed table reference\n [(4,0), (4,0), (4,0), (4,0), (4,0), (4,0), (-1,0), (3,0), (4,0), (4,0), (4,0)], # inside triple-bracketed table reference (I don't think this exists)\n [(1,2), (0,2), (5,2), (0,0), (0,2), (0,5), ( 2,2), (0,2), (0,2), (0,2), (0,2)], # found left-paren; only wrap and insert if not empty, like =row()\n [(6,0), (6,0), (6,0), (6,0), (6,0), (6,0), ( 6,0), (6,0), (6,0), (0,0), (6,0)], # inside curly-braced array\n]\n</code></pre>\n\n<hr>\n\n<p><strong>Final result :</strong></p>\n\n<p>This is what my code is like at the end. I am too lazy to change the string concatenations for a better solution. Also, I'm still not quite happy with the multiple <code>if</code> statements but I have nothing better to suggest at the moment. </p>\n\n<pre><code>#!/usr/bin/python\n\n# input_text = editor.getSelText()\ninput_text = '=HLOOKUP(TablePeriods[[#Headers],[YearMonth]],TablePeriods[[#All],[YearMonth]],MATCH([@Date],INDIRECT(\"TablePeriods[[#All],[\"&[@Account]&\"]]\"),-1))'\n\n# initialize the state table\n# event list and corresponding state table\nevent_list = [ \"\\\"\", \"&\", \"(\", \")\", \",\", \"\\n\\r\\t \", \"[\", \"]\", \"{\", \"}\" ] # last event is anything that doesn't match one of the other actions\nstate_table = [\n [(1,0), (0,1), (5,0), (0,3), (0,4), (0,5), ( 2,0), (0,0), (6,0), (0,0), (0,0)], # normal state\n [(0,0), (1,0), (1,0), (1,0), (1,0), (1,0), ( 1,0), (1,0), (1,0), (1,0), (1,0)], # double-quote comment\n [(2,0), (2,0), (2,0), (2,0), (2,0), (2,0), ( 3,0), (0,0), (2,0), (2,0), (2,0)], # inside bracketed table reference\n [(3,0), (3,0), (3,0), (3,0), (3,0), (3,0), ( 4,0), (2,0), (3,0), (3,0), (3,0)], # inside double-bracketed table reference\n [(4,0), (4,0), (4,0), (4,0), (4,0), (4,0), (-1,0), (3,0), (4,0), (4,0), (4,0)], # inside triple-bracketed table reference (I don't think this exists)\n [(1,2), (0,2), (5,2), (0,0), (0,2), (0,5), ( 2,2), (0,2), (0,2), (0,2), (0,2)], # found left-paren; only wrap and insert if not empty, like =row()\n [(6,0), (6,0), (6,0), (6,0), (6,0), (6,0), ( 6,0), (6,0), (6,0), (0,0), (6,0)], # inside curly-braced array\n]\n\n# initialize the state, parenthesis depth, and output text\ncurrent_state = 0\nparen_depth = 0\noutput_text = \"\"\n\n# define the tab and new line characters\nTAB_CHAR = \"\\t\"\nNEW_LINE = \"\\r\\n\"\n\nfor z in input_text:\n for i,event in enumerate(event_list):\n if z in event:\n break\n else:\n i = -1\n current_state, takeaction = state_table[current_state][i]\n if current_state == -1:\n current_state = 5 # -1 is an error and should be handled with some sort of error operation\n if takeaction == 0: # just pass the characters along\n output_text += z\n elif takeaction == 1: # place character at same depth as only one on line\n output_text += NEW_LINE + TAB_CHAR*paren_depth + z + NEW_LINE + TAB_CHAR*paren_depth\n elif takeaction == 2: # previous character was a left paren and this one is not a right-paren\n paren_depth = paren_depth + 1\n output_text += NEW_LINE + TAB_CHAR*paren_depth + z\n elif takeaction == 3: # character is a right paren not immediately following a left paren\n paren_depth = paren_depth - 1\n output_text += NEW_LINE + TAB_CHAR*paren_depth + z\n elif takeaction == 4: # character is a comma, so start a new line at the paren depth\n output_text += z + NEW_LINE + TAB_CHAR*paren_depth\n else:\n assert(takeaction == 5) # strip whitespace from the input outside of quotes\n pass # should raise error, since the state table includes more actions than are defined\n\n# editor.replaceSel(output_text)\nprint(output_text)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:41:42.127",
"Id": "77814",
"Score": "0",
"body": "This is terrific. Thank you! `enumerate()` was definitely something I've been looking for, but didn't know how to find it (or even that it existed). Also, I should probably think of tuples more. On that note: shouldn't the whole state_table become nested tuples? Also the event_list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:49:18.300",
"Id": "77816",
"Score": "0",
"body": "Reusing Raymond Hettinger, I usually try to go for \"Loopy lists and structy tuples\". In your case, state_table and event_list are things you are iterating on so list makes perfect sense to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:25:54.853",
"Id": "77826",
"Score": "0",
"body": "Hmm, perhaps, but on the other hand, my state_table should not be altered, so the immutable quality of tuples is perhaps more appropriate for the whole thing. Either way, I've learned several valuable lessons here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:58:13.100",
"Id": "77832",
"Score": "0",
"body": "As per http://stackoverflow.com/questions/1708510/python-list-vs-tuple-when-to-use-each different people will give you different answers, some based on mutability, some based on the way you want to use your container (position has relevance)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:01:23.217",
"Id": "44732",
"ParentId": "44699",
"Score": "7"
}
},
{
"body": "<p>Josay's suggestions are good; I only mention where I have a different idea:</p>\n\n<ul>\n<li><p>The way you create <code>state_table</code> is a bit of an anti-idiom, but in this case I see a benefit too: seeing the number in <code>state_table[2] = ...</code> improves the readability of the state machine as a whole. However, initializing the variable to the nested list comprehension is redundant. I suggest changing <code>state_table</code> to a dictionary. The rest of the code works as is if you use</p>\n\n<pre><code>state_table = {}\n</code></pre></li>\n<li><p>Use <code>zip</code> to iterate over two lists in parallel. Instead of this</p>\n\n<pre><code>for a in range(len(event_list)):\n if z in event_list[a]:\n takeaction = state_table[current_state][a][1]\n current_state = state_table[current_state][a][0]\n</code></pre>\n\n<p>do this (using also sequence unpacking)</p>\n\n<pre><code>for event, next_state in zip(event_list, state_table[current_state]):\n if z in event:\n current_state, takeaction = next_state\n</code></pre></li>\n<li><p>...except in this case don't. Instead, avoid the inner loop altogether by first creating a mapping</p>\n\n<pre><code>char_to_event = {char: i for i, event_chars in enumerate(event_list) \n for char in event_chars}\n</code></pre>\n\n<p>which allows you to replace the loop (including the else clause) with this:</p>\n\n<pre><code>event = char_to_event.get(z, -1)\ncurrent_state, takeaction = state_table[current_state][event]\n</code></pre></li>\n<li><p>You can avoid the lengthy <code>elif</code> chains with dictionary lookup and string formatting. Given these dictionaries</p>\n\n<pre><code>action_table = {\n 0: \"{z}\",\n 1: \"{newline}{indent}{z}{newline}{indent}\",\n 2: \"{newline}{indent}{z}\",\n 3: \"{newline}{indent}{z}\",\n 4: \"{z}{newline}{indent}\"\n}\ndepth_table = {\n 2: +1,\n 3: -1\n}\n</code></pre>\n\n<p>the <code>if takeaction ... elif</code> statement can be replaced with this:</p>\n\n<pre><code>paren_depth += depth_table.get(takeaction, 0)\noutput_text += action_table.get(takeaction, \"\").format(\n z=z, \n indent=TAB_CHAR*paren_depth,\n newline=NEW_LINE)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:07:51.660",
"Id": "77894",
"Score": "0",
"body": "Nice trick! I didn't see that coming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:01:33.657",
"Id": "77904",
"Score": "0",
"body": "Sweet. Now, why shouldn't I go a step further and eliminate the `event = ...` line: `current_state, takeaction = state_table[current_state][char_to_event.get(z, -1)]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:15:52.333",
"Id": "77910",
"Score": "0",
"body": "@Dane You can do that too. It's a choice between an extra line+variable and a longer line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T17:18:29.910",
"Id": "78327",
"Score": "0",
"body": "@Dane Added a way to skip the long `elif` chain."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:02:05.970",
"Id": "44774",
"ParentId": "44699",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44774",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:25:15.270",
"Id": "44699",
"Score": "10",
"Tags": [
"python",
"excel",
"state-machine"
],
"Title": "Excel-formula-analysis state machine"
} | 44699 |
<p>I have a <code>DelayQueue</code> in Java, which multiple threads will read from. They will then perform a task, and call a requeue method which performs some mathematical logic (no odd concurrent access), and then calls <code>queue.put(this)</code>. I'm aware that both <code>take</code> and <code>put</code> are blocking methods on the queue, so will this risk any deadlocks?</p>
<p>Here's the processing code (to be run on 8 threads concurrently):</p>
<pre><code> Task task;
try {
task = queue.take();
} catch (InterruptedException e) {
logger.error("InterruptedException in futures processor trying to take from queue.");
continue rLoop;
}
task.getCallback().run();
task.requeue();
</code></pre>
<p><code>task.requeue()</code>, again, makes a blocking call of <code>queue.put()</code> but the queue is unbounded and I'm not expecting any more than 10,000 actual queue elements over application lifetime, and no more than 100 or so at once.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:46:49.060",
"Id": "77677",
"Score": "0",
"body": "are your queue operations thread safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:49:07.270",
"Id": "77679",
"Score": "0",
"body": "@KevindraSingh Yes, they are thread-safe, and block if there is no room to add an element for put, and will block if no elements exist for `get`."
}
] | [
{
"body": "<p>Why are you requeueing the instance instead of completing the operation...... ? Just asking...</p>\n\n<p>If you really have to reque the instance, and if there is no other locking happening around the code you have shown, then there should be no problems with deadlocks.</p>\n\n<p>Once you have <code>taken</code> the instance from the queue, your lock on the queue is relinqished. There is nothing you can do at this point to deadlock against anything else.</p>\n\n<p>When you requeue the task, it is not going to deadlock either because it is not currently locking the queue.</p>\n\n<p>So, you are fine.... technically.</p>\n\n<p>Your code is a little awkard though. Why do you have part of your logic outside the try/catch? It would be neater if you put it inside the try/catch.</p>\n\n<p>Also, your handling of InterruptedException is not great..... The InterruptedException is a real PITA, but you have to just deal with it. The <a href=\"https://stackoverflow.com/questions/3976344/handling-interruptedexception-in-java\">minimum you can/should do is</a>:</p>\n\n<pre><code>Thread.currentThread().interrupt();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:50:25.380",
"Id": "77682",
"Score": "0",
"body": "As for the logic outside try/catch, that's an artifact of creating a smaller sample that illustrates the actual question at hand. The tip on InterruptedException is helpful, though. (Also, requeueing is necessary as the task may need to be repeated with a delay due to unacceptable data from a physical sensor, and the task's internal state will change if that is the case)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:49:16.703",
"Id": "44704",
"ParentId": "44703",
"Score": "4"
}
},
{
"body": "<p>I noticed that DelayQueue is from the concurent package so in the <strong>put</strong> and <strong>take</strong> methods should not be a problem. </p>\n\n<p>From this piece of code I believe you cannot arrive to a deadlock. </p>\n\n<p>The reason is: \nyou hold only maximum of one resource at any time (and never request to hold second one). So you dont have a circular dependence in a terms that \"I am holding nail and requesting a hammer\"</p>\n\n<p>What would be worth checking is the logic that you have in requeue, but the presented piece of code looks fine.</p>\n\n<p>Interesting link for deadlock possibilities:\n<a href=\"http://en.wikipedia.org/wiki/Deadlock#Necessary_condition\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Deadlock#Necessary_condition</a></p>\n\n<p>Your code does not fulfill (at least) the second \"Hold and Wait\" so it prelude the deadlock from happening, based on the definition. It does not fulfill even the circular dependency condition</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:59:16.147",
"Id": "44706",
"ParentId": "44703",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "44704",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:39:31.700",
"Id": "44703",
"Score": "1",
"Tags": [
"java",
"concurrency"
],
"Title": "Am I risking a deadlock in this manner of re-queueing up events?"
} | 44703 |
<p>I have quickly wrote a Perl script to convert a mediawiki to a dokuwiki. I know there's an existing script to make that, but I would have a simpler usage code and some use of the API from mediawiki. It was also a good occassion to use pQuery module. I know I can improve some things and I'm going to make a generic command and use Moo and MooX::Options for the next version. I may also write a parser to convert the syntax, but I did make a first version quickly and an easy script some can easily maintain for no Perl programmers.</p>
<p>I would like to know what you think about the code:</p>
<pre><code>#!/usr/bin/env perl
use strict;
use warnings;
use IO::File;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use MediaWiki::API;
use pQuery;
use Text::Unidecode;
sub generate_file_name {
my $title = shift;
$title =~ s/\s/_/g;
$title =~s/'/_/g;
return unidecode($title) . '.txt';
}
sub set_content_file {
my ( $file, $content ) = @_;
my $fh = IO::File->new($file, "w");
if ( defined($fh) ) {
print $fh $content;
undef $fh;
}
return;
}
sub mediawiki_login {
my $mediawiki = MediaWiki::API->new({
api_url => 'http://vim-fr.org/api.php'
});
$mediawiki->login({
lgname => 'login',
lgpassword => 'mypassword'
}) || die $mediawiki->{error}->{code} . ': ' . $mediawiki->{error}->{details};
return $mediawiki;
}
my $mediawiki = mediawiki_login();
my $all_articles = $mediawiki->list({
action => 'query',
list => 'allpages'
});
my $user_agent = LWP::UserAgent->new();
foreach my $page (@{$all_articles}) {
my $article = $mediawiki->get_page({
title => $page->{title}
});
my $request = POST 'http://johbuc6.coconia.net/mediawiki2dokuwiki.php', [ mediawiki => $article->{'*'} ];
my $response = $user_agent->request($request);
my $file = generate_file_name($page->{title});
print 'Export de la page ' . $page->{title} . " dans le fichier $file", "\n";
pQuery($response->content)
->find('textarea[name=dokuwiki]')
->each(sub {
my $count = shift;
set_content_file($file, pQuery($_)->html());
});
}
</code></pre>
<p>It was a long time ago when I did not use Perl my favorite language AND I'm going to use more. I hope it was not so bad.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:47:02.730",
"Id": "77728",
"Score": "0",
"body": "The code looks good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:20:20.540",
"Id": "77767",
"Score": "0",
"body": "Hi zdd, ok cool and thanks for your answer."
}
] | [
{
"body": "<p>This looks fairly good, which is why I'll be fairly harsh.</p>\n\n<h2><code>generate_file_name</code></h2>\n\n<p>Even with single arguments, I'd suggest using a line like <code>my ($title) = @_;</code> rather than <code>shift</code>: Using <code>@_</code> is the dominant idiom, and it will be less confusing for non-Perl programmers.</p>\n\n<p>The two substitutions can be performed in one go: <code>s/[\\s']/_/g</code> – but why are you removing unacceptable characters <em>before</em> the <code>unidecode</code> step, which might introduce them. I find it interesting that you do not prevent characters like <code>\"</code>, <code>\\</code>, <code>/</code>. It might be more sensible to specifically allow a certain set of characters rather than disallowing some other set (where you are bound to forget something important).</p>\n\n<p>But why are you even using <code>Text::Unidecode</code>? Not only is this module extremely limited in what it can do, but most filesystems also have some degree of support for Unicode filenames. If we ignore this last point, I would write:</p>\n\n<pre><code>sub generate_file_name {\n my ($title) = @_;\n my $ascii_title = unidecode($title); # transliterate Unicode\n $ascii_title =~ s/[^a-zA-z0-9.-]+/_/g; # remove unwanted characters\n return $ascii_title;\n}\n</code></pre>\n\n<h2><code>set_content_file</code></h2>\n\n<p>The first problem is the word order in this function's name, it should be <code>set_file_contents</code>. But this still isn't a terribly good name, I'd rather say <code>write_file</code>. By the way, a function with this name and functionality is already provided by <a href=\"https://metacpan.org/pod/File%3a%3aSlurp#write_file\" rel=\"nofollow\"><code>File::Slurp</code></a>, but we might as well write it ourselves.</p>\n\n<p>Using the object oriented <code>IO::File</code> instead of the builtin <code>open</code> is OK. I don't like it, but it probably makes it easier for non-Perl programmers to understand.</p>\n\n<p>But there is one problem: While a file may only contain bytes, the input string may contain Unicode: You have to encode the string either explicitly, or through a PerlIO encoding layer.</p>\n\n<p>The <code>undef $fh</code> is highly unusual. The <code>$fh</code> is a lexical variable – once the variable goes out of scope, the contained data's refcount is decremented and the object destroyed. Destroying a file handle will close it. <code>undef $fh</code> resets the scalar, which will effectively do the same thing. So it is a very confusing way of doing nothing, or saying <code>$fh->close</code>. Leave it.</p>\n\n<p>Instead of ignoring any errors when opening a file handle fails, you should probably terminate an error or at least output a warning message.</p>\n\n<p>Performing the <code>generate_file_name</code> transformation should happen inside this code, the details of storage are irrelevant for the other code.</p>\n\n<p>We should not overwrite a file if our normalization produces the same name twice. Instead: detect this error, and at the very least produce an error message.</p>\n\n<pre><code>sub write_file {\n my ($file, $contents) = @_;\n # technically, we have a concurrency bug here between the `-e` and the `open`, but I'd ignore it.\n die qq(The file \"$file\" already exists. Will not overwrite) if -e $file;\n open my $fh, \"<:utf8\", $file or die qq(Can't open \"$file\": $!);\n print { $fh } $contents;\n return;\n}\n\n...\n\nuse Try::Tiny;\n\n...\n\ntry {\n write_file($title, pQuery($_)->html);\n}\ncatch {\n warn $_;\n};\n</code></pre>\n\n<h2><code>mediawiki_login</code></h2>\n\n<p>Does this function add any abstraction to the code? I think not, considering also its proximity to its only point of use.</p>\n\n<h2>main code</h2>\n\n<p>For some reason, you are using <code>HTTP::Request::Common</code> instead of the available <code>LWP::UserAgent</code> methods (which admittedly are just a wrapper).</p>\n\n<pre><code>my $response = $user_agent->post('http://johbuc6.coconia.net/mediawiki2dokuwiki.php', [ mediawiki => $article->{'*'} ]);\n</code></pre>\n\n<p>You should also at least check for success:</p>\n\n<pre><code>if (not $response->is_success) {\n warn qq(Request for article \"$page->{title}\" failed: ), $response->status_line;\n next;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T20:23:44.037",
"Id": "45014",
"ParentId": "44707",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "45014",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T21:14:58.550",
"Id": "44707",
"Score": "6",
"Tags": [
"perl",
"converting"
],
"Title": "Convert a mediawiki to dokuwiki script"
} | 44707 |
<p>I sometimes hear people say how they can distinguish between good and bad coders of a certain programming language or even programming in general simply by looking at the code they write.</p>
<p>I'm relearning C, and I was just wondering whether my program follows best practices in terms of my commenting, the way I set it up, and generally the way I've incorporated the <code>for</code> and <code>while</code> loops along with macros (whether it be better to use a <code>goto</code> statement here, or a <code>while</code> loop instead of a <code>for</code> loop there, etc).</p>
<pre><code>#include <stdio.h>
#define SIZE (sizeof(words[0])/sizeof(words[0][1]))
#define ROWS 10
#define COLUMNS 20
int main()
{
//The maxmimum letters in a words is 20 and the max words is 10
char words[ROWS][COLUMNS]={0},character;
int count_1=0,count_2=0,i,j;
printf("Enter something: ");
character=getch();
putch(character);
while(character!='\r')
{
words[count_1][count_2]=character;
//Allows the next index to contain the value of the next inputted character
count_2++;
if(character==' ')
{
//index of inputted characters reset to 0
count_2=0;
//Allows the next row in array to be changed as one row will already satisfy a word
count_1++;
}
character=getch();
putch(character);
}
printf("\n");
//Starts from the last word
for(i=count_1;i>=0;i--)
{
for(j=0;j<SIZE;j++)
{
if(words[i][j]!=0)
printf("%c",words[i][j]);
}
}
}
</code></pre>
<p>I know the next bit is a bit opinionated, but does my code give an idea of where I'm at with logic and programming as a whole, or is the first part just some kind of myth (i.e. you can't judge a person by such a small piece of code)?</p>
<p><strong>Note:</strong> I deliberately avoided the use of functions and strings. I got this task from <em>C Programming: A Modern Approach</em>, and I'm only attempting to solve a programming task simply by using only the features I've learned thus far in the book.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:09:12.310",
"Id": "77687",
"Score": "4",
"body": "Does your original code not have indentation? You should add it here, so that your code is clearer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:10:45.447",
"Id": "77697",
"Score": "0",
"body": "Does this program work as intended? It isn't reversing the sentence for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:48:59.803",
"Id": "77713",
"Score": "0",
"body": "@syb0rg It echoes the input until you enter `'\\r'`. Note that `'\\r'` is difficult to type via keyboard on some machines (on Windows, pressing the Enter key gives `'\\n'`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:49:57.527",
"Id": "77714",
"Score": "0",
"body": "@ChrisW I know; I modified the program to use `\\n` instead, and it didn't reverse my input sentence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:54:24.973",
"Id": "77715",
"Score": "1",
"body": "@syb0rg If I enter `abc def ghi .` it echoes that and then prints `.ghi def abc` which is what I'd expect from inspection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T19:37:35.720",
"Id": "78184",
"Score": "0",
"body": "just to clarify, it doesn't reverse the letters in the words, just the order of the words. E.g: Hello how are you, would you you are how hello? It was a programming task I thought I'd do in C Progamming: S Modern Approach"
}
] | [
{
"body": "<blockquote>\n <p>I sometimes hear people say how they can distinguish between good and bad coders of a certain programming language or even programming in general simply by looking at the code they write.</p>\n</blockquote>\n\n<p>I think that's true, to some extent. How else (except by the code they write) would you judge a programmer's ability?</p>\n\n<p>Distinguishing programmers from their code is just the beginning though: see <a href=\"https://softwareengineering.stackexchange.com/a/14972/19237\">this answer</a> for example.</p>\n\n<p>Professional-level programming might also be categorized e.g. with <a href=\"http://sijinjoseph.com/programmer-competency-matrix/.\" rel=\"nofollow noreferrer\">Programmer Competency Matrix</a></p>\n\n<blockquote>\n <p>I was just wondering whether my program follows best practices</p>\n</blockquote>\n\n<p>Not all the best practices; it could still be improved, for example:</p>\n\n<ul>\n<li>Avoid macros (<code>#define</code>)</li>\n<li>Format it well (use indentation)</li>\n<li>Give good user output (better than <code>\"Enter something: \"</code>)</li>\n<li>Use subroutines (don't put everything in <code>main</code>)</li>\n<li>Don't overflow your input buffer (e.g. if the end-user enters more than 10 words, or words more than 20 characters long)</li>\n<li>Use library methods appropriately (e.g. not <code>printf(\"%c\"</code> when you want to output a whole string and not just one character)</li>\n<li>Use good identifier names (e.g. I'd prefer <code>row</code> and <code>col</code>, or <code>x</code> and <code>y</code>, or <code>imax</code> and <code>jmax</code>, instead of <code>count_1</code> and <code>count_2</code>)</li>\n<li>Be flexible in handling input correctly (e.g. I'd prefer arbitrary-length words and arbitrary-many words, which would require you to use a heap-based list or array of variable/infinite-length strings, instead of a fixed-size array)</li>\n</ul>\n\n<blockquote>\n <p>I know the next bit is a bit opinionated, but does my code give an idea of where I'm at with logic and programming as a whole</p>\n</blockquote>\n\n<p>I think so. The code matches where you said you're at, which is that you are \"relearning C\".</p>\n\n<p>Working a 40-hour week makes about 2000 hours per year.</p>\n\n<p>So an adult professional programmer will have spent many 1000s of hours of practice and studying.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T03:10:27.613",
"Id": "77739",
"Score": "0",
"body": "The only thing here that makes me wonder is how to \"use subroutines here\"... the entire code can be written as (bare functionals here only) \"char* words[WORD_MAX]; int i; for( i = 0; i < WORD_MAX; i++ ) if ( scanf( \"%ms\", &words[i] ) == EOF ) break; for( i--; i >= 0; i-- ) printf( \"%s \", words[i] );\" - I don't see much space for subroutines here..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T23:36:49.100",
"Id": "44713",
"ParentId": "44709",
"Score": "10"
}
},
{
"body": "<ul>\n<li><p>Prefer to have logically-unrelated variables once per line, which helps improve readability and allows you to add separate comments if necessary.</p>\n\n<p>From <em>Code Complete, 2d Edition</em>, p. 759: </p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, \n instead of top to bottom and left to right. When you’re looking for a \n specific line of code, your eye should be able to follow the left \n margin of the code. It shouldn't have to dip into each and every line \n just because a single line might contain two statements.</p>\n</blockquote>\n\n<p>This line of yours, for instance:</p>\n\n<pre><code>int count_1=0,count_2=0,i,j;\n</code></pre>\n\n<p>would look like this (grouped):</p>\n\n<pre><code>int count_1=0, count_2=0;\nint i, j;\n</code></pre>\n\n<p>or this (un-grouped):</p>\n\n<pre><code>int count_1=0;\nint count_2=0;\nint i;\nint j;\n</code></pre>\n\n<p>For <code>i</code> and <code>j</code> in particular, you should instead have them initialized inside the <code>for</code> loop statement if you're using C99 (which you should). If you're not, then declare them in the lowest scope possible, right above the outer loop.</p></li>\n<li><p>Prefer to add whitespace as needed, primarily between operators and after commas. Going back to the aforementioned line:</p>\n\n<pre><code>int count_1=0,count_2=0,i,j;\n</code></pre>\n\n<p>At a glance, that could easily look like one long variable name. It's quite unreadable, and the line length savings isn't worth it.</p>\n\n<p>That line would now look like this:</p>\n\n<pre><code>int count_1 = 0, count_2 = 0, i, j;\n</code></pre>\n\n<p><em>Now</em> it's clear that you have four separate <code>int</code> variables. Make sure you do this in every instance, not in just this particular line.</p></li>\n<li><p>@ChrisW has already mentioned this, but it's well worth repeating: <em>indent your code</em>. There's <em>zero</em> indentation here, so it makes me think that you've missed one of the basics of writing code. There are plenty of resources that mention how indentation should be done in a given language.</p></li>\n<li><p>In C, a function should have a <code>void</code> as a parameter if it has no others:</p>\n\n<pre><code>int main(void) {}\n</code></pre></li>\n<li><p>Unlike in C++, where <code>return 0</code> at the end of <code>main()</code> is implied, it should be present in C.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:11:30.020",
"Id": "77716",
"Score": "0",
"body": "My guess is that the OP isn't using an IDE; many programmers use a [source code editor](http://en.wikipedia.org/wiki/Source_code_editor), which understands the source code syntax and indents semi-automatically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:48:34.573",
"Id": "77729",
"Score": "0",
"body": "What's wrong with \"int count_1 = 0, count_2 = 0; int i, j;\"? Splitting the variables to logically-related groups is one thing, but declaring i and j on separate lines is an overkill in my opinion..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:50:39.653",
"Id": "77730",
"Score": "0",
"body": "@vaxquis: Although this was mainly used as an example, that is true, and I meant to add that `i` and `j` can be initialized in the `for` loop statement (assuming C99). I'll do that shortly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:53:19.060",
"Id": "77731",
"Score": "0",
"body": "yup, and that's the preferred way of doing it so that their scope is limited to the loop (which is the usual case here);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:54:03.527",
"Id": "77732",
"Score": "0",
"body": "@vaxquis: Indeed. Thanks for reminding me!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:03:52.990",
"Id": "44715",
"ParentId": "44709",
"Score": "10"
}
},
{
"body": "<p>You, mainly:</p>\n\n<ul>\n<li>chose non-optimal algorithm do to the task at hand,</li>\n<li>used non-standards-conformant functions/declarations (getch, #define for constants),</li>\n<li>didn't use indentation,</li>\n<li>used an unusual naming scheme for variables,</li>\n<li>used an initializer for an array that should be used for 1-D arrays only (size mismatch otherwise),</li>\n<li>didn't use scanf() or any other sensible (buffer-overflow protected) input</li>\n</ul>\n\n<p>So yes, that gives the reader an idea of your coding skills and experience.</p>\n\n<p>As for the braces, as Linus Thorvalds (AFAIR) once said, \"They are matter of style. Everybody who does them in a way different than me has none.\" (obvious irony here) - Brace Wars are over for me, I know the One True Brace may be nice, but I still omit extraneous braces in short snippets like this one.</p>\n\n<p>Let us say we'd like to use char-by-char input here. The following is a rewritten version of your program: compare this with yours to understand what the differences are.</p>\n\n<pre><code>// hopefully we're getting somewhere...\n\n#include <stdio.h>\n\nconst int WORD_MAX = 10,\n CHAR_MAX = 20;\n\nint main() {\n char words[WORD_MAX][CHAR_MAX];\n char ch;\n int word_idx = 0, char_idx = 0;\n memset( words, 0, sizeof(char)*WORD_MAX*CHAR_MAX );\n\n printf( \"Enter a phrase: \" );\n ch = getchar();\n putchar(ch);\n\n while( ch != '\\n' ) {\n words[word_idx][char_idx] = ch;\n if( ch == ' ' ) {\n char_idx = 0;\n word_idx++;\n } else\n char_idx++;\n ch = getchar();\n putchar(ch);\n }\n words[word_idx][char_idx] = ' ';\n\n printf( \"Reversed input: \" );\n\n for( int i = word_idx; i >= 0; i-- )\n printf( \"%s\", words[i] );\n\n putchar( \"\\n\" );\n\n return 0;\n}\n</code></pre>\n\n<p>However, the example above still has an important problem, which is that the end-user can overrun the input array by entering words that are too long, or by entering too many words.</p>\n\n<p>That (failing to detect 'invalid' data entered by the user) is usually considered a major (unacceptable) bug in commercial-grade software, so you should probably need to fix that too.</p>\n\n<p>Here's another version, which fixes that, and which is even simpler because it handles words (strings) instead of individual characters; note that since the char* used for strings and alloc'ed by scanf points to data is no longer after the output, the end of the code should be the place to free() the memory alloc'ed; the free() call is not explicitly needed here, but the required code is still attached in comments for the reference.</p>\n\n<pre><code>// GNU CC required || use a port of libc with scanf supporting 'm' format\n\n#include <stdio.h>\n\nconst int WORD_MAX = 10;\n\nint main() {\n char* words[WORD_MAX];\n\n printf( \"Enter a phrase: \" );\n\n int i;\n for( i = 0; i < WORD_MAX; i++ )\n if ( scanf( \"%ms\", &words[i] ) == EOF )\n break;\n else\n printf( \"%s \", words[i] );\n i--;\n // int j = i;\n\n printf( \"\\nReversed input: \" );\n\n for( ; i >= 0; i-- )\n printf( \"%s \", words[i] );\n // for( ; j >= 0; j-- )\n // free(words[j]);\n putchar( '\\n' );\n\n return 0;\n}\n</code></pre>\n\n<p>Like a wise man once said, \"learn through discovery\". Try to find <em>why</em> and <em>how</em> you can improve.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T02:44:27.497",
"Id": "77734",
"Score": "2",
"body": "Something wrong with your example is that it still allows the user to overrun the array if the input is too long."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T02:45:58.177",
"Id": "77735",
"Score": "0",
"body": "that's why I stated \"didn't use scanf() or any other sensible input\" and then \"let us say we'd like to use...\" but true, this shouldn't be hanging like this, fix in a sec."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T02:49:17.047",
"Id": "77736",
"Score": "0",
"body": "If the input is too long you could truncate the input, split the input, print an error message and abort; or use the heap to support 'infinite' length input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T02:51:28.570",
"Id": "77737",
"Score": "0",
"body": "Yup, but either of those would increase the complexity here and/or produce unexpected behaviour, *and* I didn't have any exact specification on the input provided, so I assumed the I/O contract is binding the user here, not the application. Still, fix incoming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T03:03:29.587",
"Id": "77738",
"Score": "0",
"body": "fixed; 4am at my place, so it took a bit longer than usual... but now it's soooooo C++-ish that I'm honestly surprised with myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T04:29:12.870",
"Id": "77740",
"Score": "2",
"body": "You have a memory leak, and it might be nice to mention *which* standards have been \"broken.\" (In particular, I'm eyeing the `m` modifier in scanf`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:04:49.120",
"Id": "77784",
"Score": "0",
"body": "'m' modifier is widely supported in GCC, the most common compiler in existence, for almost a decade (you can use 'a' on some older version), and there is no other portable way to do that in C that doesn't require defining 'safe' scanf functions. As far as the memory leak - there ain't any; you don't have to \"int j = i; for(;j<=0;j--) free(words[j]);\" (change the last for() from code from i to j) since it's the main() - all alloc'ed memory will be freed on return... it would require free()-ing only if it were in an actual function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:14:05.067",
"Id": "77786",
"Score": "0",
"body": "btw, @Corbin - the main idea was to provide a *puzzle* to OP - since he asked \"how we can spot the difference in the 'level' of a coder\", I've done this one in a couple of ways, firstly and foremostly by providing a version that only fixed his most obvious errors (without changing the actual code's behaviour), and later by creating this one, portable to C++ by only the simplest printf/scanf -> cout/cin substitutions... it was meant to be a *puzzle*, not a definite answer to the problem (it's not **stackoverflow** but **codereview** after all)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:17:16.760",
"Id": "77787",
"Score": "0",
"body": "[also, there ain't any 'int main(void)' here, for the very reason that in 99% of the cases in C and in 100% of the cases in C++ you can skip the void parameter list at all; putchar('\\n'); is also quite \"exotic\", since most of the people actually use \"printf(\"\\n\"); for this task (there was a putchar(\"\\n\"); there as a trap, but since OP is obviously not interested in this question's answers and I guessed everybody else would probably find this one without effort, I changed it back]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:13:54.040",
"Id": "77873",
"Score": "6",
"body": "@vaxquis What happens when 6 months from now someone pulls the input reading into a function, the run time of the program is extended to more than 1 run, and suddenly they have a mysterious memory leak? (A very contrived situation, but the principle is the same--bad habits bite you down the road.) Trade offs between academic purity and real-world concerns are certainly valid, but I believe you should explicitly point out when those trade offs are being made rather than silently putting them into example code. The OP probably isn't as knowledge as you and doesn't know the drawbacks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:33:41.880",
"Id": "77933",
"Score": "0",
"body": "all in all, good point, so a comment added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:48:00.090",
"Id": "77937",
"Score": "0",
"body": "btw, thanks to everyone for the input here, I hope the current one is definite enough to provide complex view on the matter at hand."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T02:26:45.617",
"Id": "44722",
"ParentId": "44709",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44713",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T22:01:03.987",
"Id": "44709",
"Score": "11",
"Tags": [
"c",
"strings"
],
"Title": "Reversing an inputted sentence"
} | 44709 |
<p>If the number is present, the output should show the numbers that are not present.</p>
<pre><code>.model small
.Stack 100
.data
array db 5, 12, 23, 45, 60, 67, 96, 100
len equ $-array
key db 100
msg1 db "found$"
msg2 db "not found$"
.code
mov ax, @data
mov ds, ax
mov si, 00h
mov di, len-1
mov cl, key
again: mov bx, si
add bx, di
shr bx, 1
cmp cl, array[bx]
je found
ja down
mov di, bx
dec di
jmp up
down: mov si, bx
inc si
up: cmp si, di
jle again
lea dx, msg2
jmp display
found: lea dx, msg1
display: mov ah, 09h
int 21h
int 3
end
</code></pre>
| [] | [
{
"body": "<pre><code>.model small\n</code></pre>\n\n<p>Hard to imagine somebody writing new code for DOS, but okay...</p>\n\n<pre><code> msg1 db \"found$\"\n msg2 db \"not found$\"\n</code></pre>\n\n<p>Seems to me these deserve better names:</p>\n\n<pre><code>fnd_msg db \"found$\"\nnot_fnd_msg db \"not found$\"\n</code></pre>\n\n<p>Or, you can get kind of tricky to save a little space:</p>\n\n<pre><code>not_fnd_msg db \"not \"\nfnd_msg db \"found$\"\n</code></pre>\n\n<p>I'm somewhat hesitant to suggest overlapping the storage for the two strings this way. Under almost any other circumstances I'd probably frown on it, but if you're going to write for MS-DOS, using otherwise ugly tricks to save a little space is often nearly a necessity.</p>\n\n<pre><code> mov si, 00h \n</code></pre>\n\n<p>You typically want to use <code>xor</code> or <code>sub</code> to clear a register:</p>\n\n<pre><code>xor si, si\n</code></pre>\n\n<p>In this case, however, you can probably skip that entirely -- you don't really need to use <code>si</code> at all. Especially in 16-bit mode, you typically get some real benefit from using the registers as they were designed, such as a <code>count</code> in <code>cx</code>.</p>\n\n<pre><code> mov di, len-1 \n mov cl, key \n</code></pre>\n\n<p>As such, I'd probably use:</p>\n\n<pre><code>mov cx, len-1\nmov al, key\nmov di, array\n</code></pre>\n\n<p>This improves readability considerably (at least for others who know what they're doing). If you're going to put the value to compare in <code>cl</code>, the count in <code>di</code>, and so on, you just about need to add a comment to point out that you're doing something unusual (and preferably, why). If you use the registers as intended, there's no real need for those comments, because the values are exactly where anybody reading the code will expect them to be. If you explicitly stated that you'd stored the count in <code>cx</code>, there's a pretty fair chance somebody reading it would think you were insulting their intelligence by pointing out the painfully obvious.</p>\n\n<p>Then you can do the search with:</p>\n\n<pre><code>repne scasb\n</code></pre>\n\n<p>Once that's finished, you can use the <code>z</code> flag to see if the data was found or not. To avoid ugly jumps on both legs of an if/then/else type of construction, you can use a little trick. It depends on the fact that on an x86, a <code>mov</code> does't affect the flags. As such, you can do a <code>mov</code> of a default value, then do a conditional branch, and afterwards load the other possible value:</p>\n\n<pre><code> mov bx, offset fnd_msg\n jz prnt_msg\n mov bx, offset not_fnd_msg\nprnt_msg:\n mov ah, 09h\n int 21h\n</code></pre>\n\n<p>Although the logic here may not be immediately apparent to \"outsiders\", almost anybody accustomed to assembly language will recognize this very quickly (and if you don't use it, they'll wonder why, or just assume you don't know what you're doing).</p>\n\n<p>Then you probably want to exit normally, not via a debug interrupt:</p>\n\n<pre><code>mov ax, 4c00h\nint 21h\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T06:25:06.757",
"Id": "77745",
"Score": "0",
"body": "Good answer concerning code itself, not just formatting. Alternatively to using 4C DOS service, one could just do `int 20h` for normal termination."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T04:38:31.763",
"Id": "44724",
"ParentId": "44723",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>It's important to provide comments in assembly, especially for register usage. Since registers cannot have unique names like variables, readers are left to deduce their purpose.</p>\n\n<p>You may, for instance, state the value set to a register in a certain line, and what that register is supposed to represent at that time. That way, you can keep track of the register's usage as it changes throughout the program.</p></li>\n<li><p>Your variable initializations should have equal whitespace on both sides of the variable size:</p>\n\n<pre><code>array db 5, 12, 23, 45, 60, 67, 96, 100\n</code></pre></li>\n<li><p>This part is misaligned:</p>\n\n<pre><code>.code\n mov ax, @data \n mov ds, ax\n</code></pre>\n\n<p>it should be:</p>\n\n<pre><code>.code\n mov ax, @data \n mov ds, ax\n</code></pre>\n\n<p>Same thing here:</p>\n\n<pre><code>found: lea dx, msg1 \ndisplay: mov ah, 09h \n int 21h \n int 3 \n end\n</code></pre>\n\n<p>it should be:</p>\n\n<pre><code>found: lea dx, msg1 \ndisplay: mov ah, 09h \n int 21h \n int 3 \nend\n</code></pre>\n\n<p>I'd also add a linebreak between those two procedures.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T05:04:35.837",
"Id": "44725",
"ParentId": "44723",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T04:14:42.913",
"Id": "44723",
"Score": "4",
"Tags": [
"strings",
"assembly"
],
"Title": "Alp in MASM 8086"
} | 44723 |
<p>Basically, I'm trying to make a Simplifier that can take inputs in the form of a <code>String</code> and print out the solution step-by-step. Now that I've got it working, I think it has some cleanliness issues.</p>
<pre><code>public static void test(String eqn) {
char[] order = { '^', '*', '/', '+'}; //order of precendece
int found, i, j;
eqn = eqn.replace("-", "+-"); //Subtracting = Adding (-)ve number.
eqn = eqn.replace(" ", ""); //Spaces can cause a lot of trouble.
String eqnC, left, right;
System.out.println("=>\t"+eqn);
for(char op : order) {
while ((found = eqn.indexOf(op)) > -1) {
left = eqn.substring(0, found);
right = eqn.substring(found + 1);
//keep 'walking' up and down the String till a non-number encoutered.
for( i = left.length() - 1; i >= 0; i--)
if(!isPONumber(left.charAt(i)))
break;
for( j = 0; j < right.length(); j++)
if(!isPONumber(right.charAt(j)))
break;
double lV = Double.parseDouble(left.substring(++i)); //left operand
double rV = Double.parseDouble(right.substring(0, j)); //right operand
eqn = left.substring(0, i) + putV(lV, rV, op) + right.substring(j);
System.out.println("=\t" + eqn);
}
}
}
private static String putV(double a, double b, char op) {
switch(op) {
case '^': return Math.pow(a, b) + "";
case '/': return (a / b) + "";
case '*': return (a * b) + "";
case '+': return (a + b) + "";
}
return null;
}
/*
* Limit (for now) : decimal support.
*/
private static boolean isPONumber(char c) {
return Character.isDigit(c) || c == '.' || c == '-';
}
</code></pre>
<p>Here are some outputs:</p>
<pre><code>=> 2*84/6+7^2
= 2*84/6+49.0
= 168.0/6+49.0
= 28.0+49.0
= 77.0
=> 3^3/3^2
= 27.0/3^2
= 27.0/9.0
= 3.0
=> 400^0.5
= 20.0
</code></pre>
<p>I'd be grateful if anyone would comment and criticize and help me to clean-up my code. I also invite suggestions for making it better, improvising it and so on.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T05:33:50.590",
"Id": "77741",
"Score": "0",
"body": "@Jamal Thanks for the edit... (I see that you had edited my previous post as well, thanks for that too) :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T05:36:40.410",
"Id": "77742",
"Score": "3",
"body": "No problem! Feel free to change something back if an edit introduces misleading information (I don't think that's the case here)."
}
] | [
{
"body": "<h2>Algorithm</h2>\n<p>The algorithm works well enough. You have captured the essence of the problem in your code, and reading your code it is apparent what it does, and why.</p>\n<p>This is a good thing. It is not very often that the intent of the code is so easy to discern.</p>\n<p>The draw-back of your algorithm is that it is not going to be able to support the more esoteric operations like parenthesis e.g. <code>( 123 - 45 ) ^ 2</code> .... That sort of support will require a preprocessing step.</p>\n<p>Keeping the equation as a string is convenient for some things, but i would have preferred to see the process broken down in to components, for example, a parse step could break the input down to <code>List<String> eqnParts = parse(eqn)</code>. at the same time, it could be trimming the white-space. Then, you just need to scan the <code>List<String></code> and find 3 items separated by the highest precedence operator, and swap all three with the resulting value.</p>\n<h2>Code Style</h2>\n<p>You should read through the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\" rel=\"nofollow noreferrer\">Code Style Guidelines for Java</a>.</p>\n<p>This code, for example, <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html#682\" rel=\"nofollow noreferrer\">has a number of faults</a>:</p>\n<blockquote>\n<pre><code> for( i = left.length() - 1; i >= 0; i--)\n if(!isPONumber(left.charAt(i)))\n break;\n for( j = 0; j < right.length(); j++)\n if(!isPONumber(right.charAt(j)))\n break;\n</code></pre>\n</blockquote>\n<p>It should rather look something like:</p>\n<pre><code> for (int i = left.length() - 1; i >= 0; i--) {\n if(!isPONumber(left.charAt(i))) {\n break;\n }\n }\n for (int j = 0; j < right.length(); j++) {\n if(!isPONumber(right.charAt(j))) {\n break;\n }\n }\n</code></pre>\n<p>Notes:</p>\n<ol>\n<li>declare <code>int i</code> and <code>int j</code> <em><strong>inside</strong></em> the loop.</li>\n<li>space after the keyword <code>for</code>.</li>\n<li>braces even for '1-liner' conditional statements.</li>\n</ol>\n<h2>Double.parseDouble</h2>\n<p><code>Double.parseDouble()</code> throws the unchecked exception <code>NumberFormatException</code>.</p>\n<p>The exception thrown does not give great deals of information about why the number is not valid.</p>\n<p>I always recommend wrapping Double.parseDouble (and <code>Integer.parseInteger()</code>, etc.) in a try-catch that reports what value was parsed, as well as the exception that was thrown. Otherwise debugging is a pain.</p>\n<p>I often have a helper function like:</p>\n<pre><code>public static final double parseDouble(String value) {\n try {\n return Double.parseDouble(value);\n } catch (NumberFormatException nfe) {\n throw new IllegalArgumentException("Unable to Double.parseDouble(" + value + ")", nfe);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:00:27.413",
"Id": "77747",
"Score": "0",
"body": "This is only a _part_ of the real thing... I'll add the ability to detect brackets later. See [this](http://programmers.stackexchange.com/questions/232875/should-a-calculator-support-curly-braces-and-box-braces) to understand what I mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:04:03.843",
"Id": "77749",
"Score": "0",
"body": "I forgot to say thanks... As for the `NumberFormatException`, should I define a _custom_ `Exception` like `EquationError` or something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:10:40.597",
"Id": "77750",
"Score": "0",
"body": "@ambigram_maker Normally what I have is a helper function. I edited my answer to give an example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:27:55.013",
"Id": "77753",
"Score": "3",
"body": "@rolfl If he declares `i, j` in the for loop the program won't compile. He uses them in the next two lines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:07:43.953",
"Id": "77761",
"Score": "0",
"body": "@rofl The `try..catch` is not exactly what I want... I want to _throw_ an `Exception`, in case of ___any___ kind of error that may arise in this code (the full code I mean)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:12:40.007",
"Id": "77763",
"Score": "1",
"body": "@ambigram_maker why not add a throws new Exception(\"more information\") in the catch block, then?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T06:58:19.520",
"Id": "44728",
"ParentId": "44726",
"Score": "4"
}
},
{
"body": "<p>I love the replacement of <code>-</code> with <code>+-</code>. It's simple and effectful. I'd like to see a similar use of <code>*</code> and <code>/</code> by introducing an operator for the reciprocal, e.g. <code>~</code>. This would of course require using a custom function for parsing the numbers instead of <code>parseDouble</code> (or the introduction of real unary operators), so that may cancel out any advantages.</p>\n\n<p>EDIT: Just like <code>a - b</code> is equal to <code>a + -b</code>, <code>a / b</code> is equal <code>a * 1/b</code>. <code>1/b</code> is called the <a href=\"http://en.wikipedia.org/wiki/Multiplicative_inverse\" rel=\"nofollow\">reciprocal</a> of <code>b</code>. You could define an operator (such as <code>~</code> or any other character, that you aren't using) to represent the reciprocal, and replace <code>/</code> with <code>*~</code>, so that <code>4/2</code> becomes <code>4*~2</code>. That requires you to add <code>~</code> as a valid character to <code>isPONumber</code>, and replace <code>parseDouble</code>since it doesn't know what <code>~</code> is (I just invented it). See next edit.</p>\n\n<p>I'm not really a fan of using <code>parseDouble</code> directly anyway. I'd at least replace it with a custom function that possibly uses <code>parseDouble</code> internally.</p>\n\n<p>EDIT: By using <code>parseDouble</code> you are saying \"my programm uses the same syntax for number literals as Java\". That is not a problem, until you realize that the Java syntax may not support every thing you need, for example because you just decided to support the reciprocal operator, or you want the program to be international and some countries use a comma instead of a period for the decimal mark, e.g. <code>1,2</code> instead of <code>1.2</code>, but <code>parseDouble</code> doesn't support this. And instead of needing to search your whole code and replace each occurance of <code>parseDouble</code>, you should have one function</p>\n\n<pre><code>static public double parseNumber(String number) {\n return Double.parseDouble(number);\n}\n</code></pre>\n\n<p>Now if you need to change the syntax of your numbers, then you only have one defined place where you need to do it. For example to support the reciprocal:</p>\n\n<pre><code>static public double parseNumber(String number) {\n if (number.charAt(0) == '~') {\n return 1 / parseNumber(number.substring(1));\n }\n return Double.parseDouble(number);\n}\n</code></pre>\n\n<p>(END EDIT)</p>\n\n<p>I also don't like the use of the variable names <code>i</code> and <code>j</code> here, since they are used outside the <code>for</code> loop. Something like <code>leftOffset</code>/<code>rightOffset</code> may be more appropriate.</p>\n\n<p>You could drop the variables <code>left</code> and <code>right</code> and search the original string with <code>i</code> and <code>j</code> starting at <code>found</code>/<code>found + 1</code>.</p>\n\n<p>The use of a <code>enum</code> for the operators would also be useful. Something like:</p>\n\n<pre><code>interface DoubleOperation {\n public double calc(double a, double b);\n}\n\nenum Operator {\n POWER(\"^\", new DoubleOperation() { public double calc(double a, double b) { return Math.pow(a, b); } }),\n DIVISION(\"/\", new DoubleOperation() { public double calc(double a, double b) { return a / b; } });\n // ...\n\n public String op; // Use private and a getter in real code\n public DoubleOperation calc;\n\n Operator(String op, DoubleOperation calc) {\n this.op = op;\n this.calc = calc;\n }\n}\n</code></pre>\n\n<p>(Look into the just released JDK 8 for <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html\" rel=\"nofollow\">lamba expressions</a> to simplify this.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:04:05.710",
"Id": "77821",
"Score": "0",
"body": "And what do you mean by _similar use of * and / by introducing an operator for the reciprocal_? Could you please elaborate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:19:10.340",
"Id": "77825",
"Score": "1",
"body": "Don't dismiss rofl's answer. All his remarks are correct too (except regarding the scope of `i`/`j`). My remarks are just additions. I'll do some edits to expand on your comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T03:25:42.067",
"Id": "78242",
"Score": "0",
"body": "No, I didn't dismiss off @rofl's answer, I applied his `ArrayList<>` approach. So I guess it's _Bye bye offset_! But how do I _apply_ the `enum`? Should I use an enhanced `for-loop` for this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T03:28:48.503",
"Id": "78243",
"Score": "0",
"body": "Also (after reading your approach about reciprocals) is it really efficient? I mean, we'll have to divide it anyway... why add [extra] overhead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T12:45:01.657",
"Id": "78280",
"Score": "0",
"body": "No. Forget the reciprocals. It was just a wild idea that jumped into my head :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:07:20.067",
"Id": "44748",
"ParentId": "44726",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44748",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T05:24:59.040",
"Id": "44726",
"Score": "8",
"Tags": [
"java",
"optimization",
"design-patterns"
],
"Title": "Optimizing \"simplifier\""
} | 44726 |
<p>I am a beginner and I have made a Fare Chart in HTML. I'm pretty sure it will look horrible to any developer out there, but hey, that's why I've posted it.</p>
<p>I'd like a general review of this. I'm especially concerned about the quality and enhancements of this form. What should I do to add attractive looks and show that fare & time which is allotted by me?</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body BACKGROUND=1.gif TEXT=green><table border="1"><font face=comic sans ms><h1>Fare Chart</h1>
<tr>
<td>
<table border="1" align=center>
<tr>
<th>Train Number</th>
<th>Timings</th> <th><b>Fare</b></th>
</tr>
<tr>
<td>104845</td>
<td>4:50 to
23:21</td><td>Fare- Rs.122</td>
</tr>
<tr>
<td>105454</td>
<td>5:47 to 8:11</td><td>Fare- Rs.342</td>
</tr>
<tr>
<td>1054555</td>
<td>2:42 to 2:12</td><td>Fare- Rs.652</td>
</tr>
<tr>
<td>105454</td>
<td>2:27 to 5:51</td><td>Fare-
Rs.772</td>
</tr>
<tr>
<td>133354</td>
<td>2:43 to 1:11</td><td>Fare- Rs.762</td>
</tr> <tr>
<td>104845</td>
<td>4:50
to 23:21</td><td>Fare- Rs.562</td>
</tr>
<tr>
<td>105454</td>
<td>5:47 to 8:11</td><td>Fare- Rs.477</td>
</tr>
<tr>
<td>1054555</td>
<td>2:42 to 2:12</td><td>Fare- Rs.999</td>
</tr>
<tr>
<td>105454</td>
<td>2:27 to 5:51</td><td>Fare-
Rs.933</td>
</tr>
<tr> </code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>HTML is a markup language. The only thing bad here is the missing closing tags for <code>body</code> and <code>html</code>, and your indentation.</p>\n\n<blockquote>\n <p>What should I do to add attractive looks and show that fare & time which is allotted by me?</p>\n</blockquote>\n\n<p>CodeReview only reviews your code. We won't write it for you (this also includes CSS and various forms of design and styling). \"Attractive looks\" is also subjective, you'd have to decide what \"attractive\" is for you since it's your website.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T02:21:58.643",
"Id": "77991",
"Score": "0",
"body": "CodeReview also reviews [tag:html] and even [tag:css]: http://codereview.stackexchange.com/a/41785/23788"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T08:02:31.707",
"Id": "78027",
"Score": "1",
"body": "@Mat'sMug I did not mean we do not review HTML, I meant that we do not write code (including markup). Sorry for any confusion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T08:14:28.650",
"Id": "44733",
"ParentId": "44727",
"Score": "3"
}
},
{
"body": "<h3>Errors</h3>\n\n<p><code><font face=comic sans ms></code> would fail to parse properly: since the attribute value is unquoted, the tag would be interpreted as having three attributes:</p>\n\n<ul>\n<li><code>face=\"comic\"</code></li>\n<li><code>sans</code></li>\n<li><code>ms</code></li>\n</ul>\n\n<p><code><h1></code> is not allowed to appear inside a <code><table></code>, but could be permissible in HTML5 (but not HTML 4.01) if it appears inside a <code><caption></code> element.</p>\n\n<h3>Separation of content and presentation</h3>\n\n<p>Including presentation markup in your HTML is so last millennium. Ever since the introduction of Cascading Style Sheets, the accepted practice is to do all styling using CSS. Therefore, the following markup should be relegated to CSS:</p>\n\n<ul>\n<li>In <code><body></code>, <code>BACKGROUND=1.gif</code> and <code>TEXT=green</code></li>\n<li>In <code><table></code>, <code>border=1</code> and <code>align=center</code></li>\n<li>The entire <code><font></code> tag</li>\n<li>Any <code><b></code> tag</li>\n</ul>\n\n<p>Furthermore, you have a table within a table. The outer table appears to be used not to present tabular data, but for grouping the inner table with its caption. Such abuse of the outer table for layout purposes is frowned upon.</p>\n\n<h3>Miscellaneous</h3>\n\n<p>You need a doctype declaration at the top to specify which version of the HTML standard should be used to interpret your page. These days, you should probably use the HTML5 doctype, which is just <code><!DOCTYPE html></code>.</p>\n\n<p><strong>Run your HTML through a <a href=\"http://validator.w3.org/\" rel=\"nofollow\">validator</a>.</strong> It will automatically point out many problems. For example, a <code><head></code> with a <code><title></code> is mandatory.</p>\n\n<p>Put your heading row in a <code><thead></code> element.</p>\n\n<p>\"Fare- \" in the Fare column is redundant.</p>\n\n<p>Take care to use consistent indentation.</p>\n\n<h3>Recommendation</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html>\n <head>\n <title>Fare Chart</title>\n <style type=\"text/css\">\n body {\n background-image: url(1.gif);\n color: green;\n /* Seriously? https://google.com/search?q=%22comic+sans%22&tbm=isch */\n font-family: \"comic sans ms\";\n }\n table {\n /* Centers table in the page, like align=center */\n margin: auto;\n }\n table, th, td {\n /* Equivalent to table border=1 */\n border: 1px solid black;\n }\n h1 {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <table>\n <caption><h1>Fare Chart</h1></caption>\n <thead>\n <tr> \n <th>Train Number</th> \n <th>Timings</th>\n <th>Fare</th>\n </tr>\n </thead>\n <tbody>\n <tr> \n <td>104845</td>\n <td>4:50 to 23:21</td>\n <td>Fare- Rs.122</td> \n </tr> \n <tr> \n <td>105454</td>\n <td>5:47 to 8:11</td>\n <td>Fare- Rs.342</td> \n </tr> \n <tr>\n <td>1054555</td>\n <td>2:42 to 2:12</td>\n <td>Fare- Rs.652</td> \n </tr>\n <tr> \n <td>105454</td>\n <td>2:27 to 5:51</td>\n <td>Fare- Rs.772</td> \n </tr> \n <tr> \n <td>133354</td>\n <td>2:43 to 1:11</td>\n <td>Fare- Rs.762</td> \n </tr>\n <tr> \n <td>104845</td>\n <td>4:50 to 23:21</td>\n <td>Fare- Rs.562</td> \n </tr>\n <tr> \n <td>105454</td>\n <td>5:47 to 8:11</td>\n <td>Fare- Rs.477</td> \n </tr>\n <tr>\n <td>1054555</td>\n <td>2:42 to 2:12</td>\n <td>Fare- Rs.999</td> \n </tr>\n <tr> \n <td>105454</td>\n <td>2:27 to 5:51</td>\n <td>Fare- Rs.933</td> \n </tr>\n </tbody>\n </table>\n </body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Here, I've put the CSS styles inline within the <code><style></code> element. Ideally, the stylesheet would be in its own <code>.css</code> file, shared among all pages in your website, and included by reference using <code><link rel=\"stylesheet\" type=\"text/css\" href=\"/path/to/stylesheet.css\"></code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:34:12.613",
"Id": "44860",
"ParentId": "44727",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T05:59:19.267",
"Id": "44727",
"Score": "8",
"Tags": [
"html"
],
"Title": "Fare Chart in HTML"
} | 44727 |
<p>I want a review of this code.</p>
<pre><code><?php
$array = $_POST['array']; //array holding numbers
$array = array_reverse($array); // reversing the array
echo "<br> Credit card Before :- ";
for($i=0;$i<sizeof($array);$i++)
echo $array[$i];
echo "<br>";
echo "<br> Credit card after applaying mod 10 Algorthim :- ";
//start converting the number
for($i=0;$i<sizeof($array);$i++){
if($i%2==1){
$array[$i] += $array[$i];
if($array[$i]> 9 ){
$array[$i] -= 9;
}
}
//suming all the resulted number
$total +=$array[$i];
if($i%2==1)
echo "<b>".$array[$i]."</b>";
else
echo $array[$i];
}
echo "<br>";
if($total % 10 ==0){
echo "This creidet card is valid";
}else{
echo "This creidet card is not valid";
}
?>
</code></pre>
| [] | [
{
"body": "<p>There's a few glaring issues with your code. Namely your lack of consistent styling. Secondly, you're not doing certain things correctly (iterating over an array rather than imploding it). As this is a code review, I will not be touching on the correctness of the algorithm. Below you'll find two pieces of code - one which I've commented and corrected, and a second which I've removed my comments and old code. </p>\n\n<p>With comments:</p>\n\n<pre><code><?php\n\n# Grab the numbers array and reverse it. \n# Don't just name your variable $array. Name it something meaningful.\n$numbers_array = array_reverse( $_POST['array'] );\n\necho \"<br> Credit card Before :- \";\n\n# No need to do a for loop, just use implode to make the array into a string\n/*for ( $i = 0; $i < sizeof( $array ); $i++ ){\n echo $array[$i];\n}*/\necho implode(\"\", $numbers_array);\n\n# Just do one echo instead of two\n/*echo \"<br>\";*/\necho \"<br><br> Credit card after applaying mod 10 Algorthim :- \";\n\n# Start converting the number\n# You're doing a sizeof() on every single loop. Just cache it in a $size variable\n$size = count($numbers_array);\nfor ( $i = 0; $i < $size; $i++ ) {\n if ( $i % 2 == 1 ) {\n $numbers_array[$i] += $numbers_array[$i];\n if ( $numbers_array[$i] > 9 ) {\n $numbers_array[$i] -= 9;\n }\n\n echo \"<b>\" . $numbers_array[$i] . \"</b>\";\n } else {\n echo $numbers_array[$i]\n }\n\n $total += $numbers_array[$i];\n\n # You're doing the same calculation twice (as above). Why not just echo it up there?\n /*if ( $i % 2 == 1 ){\n echo \"<b>\" . $numbers_array[$i] . \"</b>\";\n } else {\n echo $numbers_array[$i];\n }*/\n}\n\necho \"<br>\";\nif ( $total % 10 == 0 ) {\n echo \"This credit card is valid\";\n} else {\n echo \"This credit card is not valid\";\n}\n</code></pre>\n\n<p>With no comments:</p>\n\n<pre><code><?php\n\n# Grab the numbers array and reverse it. \n$numbers_array = array_reverse( $_POST['array'] );\n\necho \"<br> Credit card Before :- \" . implode(\"\", $numbers_array) . \n \"<br><br> Credit card after applaying mod 10 Algorthim :- \";\n\n# Start converting the number\n$size = count($numbers_array);\nfor ( $i = 0; $i < $size; $i++ ) {\n if ( $i % 2 == 1 ) {\n $numbers_array[$i] += $numbers_array[$i];\n if ( $numbers_array[$i] > 9 ) {\n $numbers_array[$i] -= 9;\n }\n\n echo \"<b>\" . $numbers_array[$i] . \"</b>\";\n } else {\n echo $numbers_array[$i]\n }\n\n $total += $numbers_array[$i];\n}\n\nif ( $total % 10 == 0 ) {\n echo \"<br>This credit card is valid\";\n} else {\n echo \"<br>This credit card is not valid\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T08:26:33.377",
"Id": "78029",
"Score": "0",
"body": "lol thanks dude when i look to your way of coding it make me feel loser thanks for this tips and thank you for teaching me some new things about php :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T14:28:54.387",
"Id": "78105",
"Score": "0",
"body": "Definitely do NOT feel like a loser. I still learn new things every day. With programming, its a constant evolution and learning new things comes with the career. Cheers! :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:30:44.193",
"Id": "44763",
"ParentId": "44731",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:56:33.000",
"Id": "44731",
"Score": "3",
"Tags": [
"php",
"validation",
"finance"
],
"Title": "Credit card validation with reversed array"
} | 44731 |
<p>I'm using Kohana's routing with the route being defined as domain/controller/action. To demonstrate my question let's consider sign-in flow. Currently, if I want to sign-in user I need to return form first and then proceed with data sent by user. Do I need to have two actions, each for the corresponding flow (returning flow and proceeding with user data), or it can be done with one action by differentiating between POST and GET requests? I have one action now which returns form template if GET request is made and proceeds with signing in if POST request is made, but I question that architecture. Here is the sample of code:</p>
<pre><code>public function action_signUp() {
if (HTTP_Request::POST == $this->request->method()) {
//proceed with user sent data
} else if (HTTP_Request::GET == $this->request->method()) {
//return form template
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:53:04.347",
"Id": "77790",
"Score": "0",
"body": "Can you not route get and post requests to different actions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:14:04.207",
"Id": "77796",
"Score": "0",
"body": "Sure I can, I just want to know the best practice :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:55:07.597",
"Id": "77803",
"Score": "0",
"body": "Is there any difference in the controller logic for each branch (except rendering different content)? It would be helpful to post the code inside the conditionals."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:41:12.310",
"Id": "77812",
"Score": "0",
"body": "The difference is that GET branch simply renders log-in view, while the POST branch logs in user and returns redirect"
}
] | [
{
"body": "<p>The <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility principle</a> also extends to methods. By using one action, you are creating a method which does two entirely unrelated things, which violates this principle.</p>\n\n<p>Also, you are making the controller concerned with which http verbs map to which action, which is responsibility of the router. By splitting the method up, you can later make different urls or verbs point to each action, without changing your controller. See <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">separation of concerns</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:07:16.203",
"Id": "44755",
"ParentId": "44738",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44755",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T10:11:49.527",
"Id": "44738",
"Score": "-1",
"Tags": [
"php",
"http"
],
"Title": "get and post in one action do different stuff - is it OK?"
} | 44738 |
<p>My JavaScript is fairly new and want to learn new ways to create clean, fast code. Can you have a look at this code and guide me on how to optimise this code to improve my skills? I have provided the HTML even though I am not able to edit the actual html as its generated but lets pretend I could..</p>
<p>What I am doing is pulling data from a Product JSON file and manipulating the data to be shown in the website.</p>
<pre><code>function Details(el){
var sku = $(el).attr("data");
$.getJSON("/micro/"+sku, function(json) {
if (json.price!=null) {
$(el+' .p_img img').attr({src:json.images[2].url, alt:json.images[2].altText});
$(el+' .p_img_lrg').attr("src",json.images[1].url);
$(el+' .p_name').text(json.name);
$(el+' .p_url').attr("href",json.url);
$(el+' .p_p').text("£"+Number(json.p.value).toFixed(2));
$(el+' .p_pu').text(json.pu);
$(el+' .p_b_name').text(json.categories[0].name);
$(el+' .p_b_url').attr("href",json.categories[0].url);
if (json.oldPrice != null) {
var pWas = ' .p_was',
pSave = ' .p_save';
$(el+pWas).text("was £"+json.old.value);
$(el+pSave).text("save £"+(json.old.value-json.value));
$(el+pSave).hide();
$(el+pWas).css('margin-left',0).css('padding-left',0).addClass('clr').removeClass('left').css('float','none');
}else{
$(el+pSave,el+pWas).hide();
}
}
if (json.stockLevel==0) {
$(el+' form.add').attr({'action':'/notification','method':'post'}).html('<input type=\"hidden\" name=\"productCodePost\" value=\"'+sku+'\"><input type="submit" value="Out">');
} else {
$(el+' form.add').attr({'action':'/add','method':'post'}).html('<input type=\"hidden\" name=\"productCodePost\" value=\"'+sku+'\"><input type=\"hidden\" name=\"maxOrderQuantity\" value=\"\"><input type="submit" value="Add">');
}
});
}
</code></pre>
<p>HTML:</p>
<pre><code><li data-sku="100000" class="item1">
<div class="bullet">
<sup class="hash">#</sup>
<span>test</span>
</div>
<div class="image">
<a class="p_url" title="" href="#"><img class="p_img_lrg" border="0" alt="" src="" width="210" height="210" /></a>
</div>
<div class="prodinfo">
<h2 class="nomargin"><a class="p_name p_url" href="#"></a></h2>
<div class="more-less">
<div class="more-block"><p></p></div>
</div>
<div class="price">
<div class="now pink bold large-text">
<span class="pricename">now</span>
<span class="p_price">&pound;</span>
</div>
<div class="p_price_unit margin10bottom"></div>
<form class="add_to_cart_form">&nbsp;</form>
</div>
<div class="morefrom">View All <a class="p_brand_name p_brand_url" title="" href="#"></a> Products</div>
</div>
</li>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:12:40.640",
"Id": "77822",
"Score": "0",
"body": "Could you please describe what this code does, and edit the title accordingly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:07:09.583",
"Id": "77851",
"Score": "0",
"body": "And why can't you provide the HTML? It would help a lot to judge if the the selectors are optimal."
}
] | [
{
"body": "<p>Caching the jquery set for $(el) and using it to make subqueries should be a little faster, and I usually find it to be more readable. For example:</p>\n\n<pre><code>var $el = $(el);\n//snip\n$el.find('.p_img img').attr({src : json.images[2].url, alt : json.images[2].altText});\n</code></pre>\n\n<p>I always use the identity operator unless I specifically want type conversion to happen. You might get some unexpected results using the equality operator to compare against values like 0 or null (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators\" rel=\"nofollow\">MDN equality operator docs</a>) :</p>\n\n<pre><code>if (json.price !== null) { \n\nif (json.stockLevel === 0) { \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:16:39.127",
"Id": "44812",
"ParentId": "44739",
"Score": "4"
}
},
{
"body": "<p>Functions in JavaScript, by convention, begin with a lowercase letter, unless they're constuctors. So <code>Details()</code> should be <code>details()</code></p>\n\n<p>You've got some missing indentation, which makes the code harder to read. In general your code could probably benefit from a bit more whitespace to help legibility.</p>\n\n<p>You also have some funky-looking strings, like: <code>'<input type=\\\"hidden\\\" name=\\\"productCodePost\\\" value=\\\"'</code> \nYou use single quotes around the string, but still escape the double-quotes inside the string. This is unnecessary: A single-quoted string can contain double-quotes just fine, and a double-quoted string can contain single-quotes (like so <code>'double-quotes (\") work fine here'</code> or <code>\"single-quotes (') work fine here\"</code>). You only need to escape if your string contains the same type of quote that you're using to delimit the string.<br>\nIn fact, you're already doing that in your code. The rest of the line I used as example looks like this <code>'\\\"><input type=\"submit\" value=\"Out\">'</code> and works just fine with out any backslashes.</p>\n\n<p>You can also use jQuery to build those elements for you, i.e.</p>\n\n<pre><code>form.append($(\"<input>\").attr({\n type: hidden,\n name: productCodePost,\n value: sku\n});\n</code></pre>\n\n<p>which gives you a more structured and readable source code, instead of giant strings.</p>\n\n<p>There's also a lot of repetition - or semi-repetition in this case: The <code>el+\"...\"</code>. I'd advice something like what <a href=\"https://codereview.stackexchange.com/a/44812/14370\">Matt suggested</a> which is to store the result of <code>$(el)</code> once, and from there using <a href=\"http://api.jquery.com/find/\" rel=\"nofollow noreferrer\"><code>.find()</code></a> to locate the individual elements you want to update.</p>\n\n<p>For the actual element updating there isn't that much that can be improved, since there's no discernible commonalities between, say, element IDs and JSON keys (in fact, the JSON seems very messy!)</p>\n\n<p>There are some minor things you could do like define a <code>renderAmount</code> function to make sure you're always printing prices the same way:</p>\n\n<pre><code>function renderAmount(amount) {\n return \"£\" + Number(amount).toFixed(2);\n}\n</code></pre>\n\n<p>Right now, you only use the <code>.toFixed()</code> in one place, although you have 3 different places where you need to write amounts.</p>\n\n<p>Similarly, you could add a function to update images, since you do it at least twice. Not a great savings, but it helps break up the code.</p>\n\n<pre><code>function updateImage(element, info) {\n element.attr({\n src: json.url,\n alt: json.altText\n });\n}\n\n// ...\n\nupdateImage(container.find(\".p_img img\"), json.images[2]);\n</code></pre>\n\n<p>Lastly, what's going on the element that shows the savings? If there's no old price, it's just hidden, which makes sense. But if there is an old price, you update the <code>.p_save</code> element... and then hide it anyway?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T14:07:40.847",
"Id": "78093",
"Score": "0",
"body": "Thanks both for you help. Another question, after apply your changes I have alot of `$el.find('selector')`, which to me seems like there should be a way to loop this? The code still looks bulky.. Any suggestions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T17:04:38.990",
"Id": "78159",
"Score": "1",
"body": "@Nirajpaul Not really. The trouble is that the JSON keys don't match up with the element IDs/attributes. You have to _manually_ match the JSON content to the HTML elements. It can't, as far as I can tell, be automated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T01:18:50.993",
"Id": "44820",
"ParentId": "44739",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T10:39:39.507",
"Id": "44739",
"Score": "7",
"Tags": [
"javascript",
"optimization",
"performance",
"beginner"
],
"Title": "Pulling JSON using jQuery and manipulating the Front-end"
} | 44739 |
<p>I built this as a simple example of using raw JS to perform a simple GET request with a data callback.</p>
<p>Suggestions on how this could be improved in any way, while keeping it simple, would be much appreciated.</p>
<p>JS:</p>
<pre><code>/*jslint unparam: true, white: true */
var app = (function() {
"use strict";
return {
ajax: function(url, callback) {
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
var data;
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
data = xmlhttp.responseText;
if(typeof callback === 'function') {
callback(data);
}
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
};
}());
</code></pre>
<p>Example usage:</p>
<pre><code>app.ajax('file.json', function(data) {
data = JSON.parse(data);
console.log(data.name);
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:08:04.267",
"Id": "77794",
"Score": "0",
"body": "you are aware this is not cross-browser compatible? [here's something I used when I did something similar](http://stackoverflow.com/a/15640875/1803692)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:14:40.430",
"Id": "77797",
"Score": "0",
"body": "@Vogel612 Do you mean with regards to IE6/7?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:15:35.083",
"Id": "77798",
"Score": "0",
"body": "yea. Don't expect ppl. on public websites to have current browsers. no offense if you don't implement it though ;) It's just a hassle for that minimal helpfulnes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:24:21.607",
"Id": "77799",
"Score": "1",
"body": "I don't really care that much about IE6/7 support. Thanks for pointing this out anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:41:22.623",
"Id": "77813",
"Score": "0",
"body": "I rolled back your edit, it is considered bad form to update this question because it puts answer <> question out of sync."
}
] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>There should be a way to handle errors, this is only good for sunny day scenarios</li>\n<li>It would be more useful if you also passed the <code>xmlhttp</code> object to the callback : <code>callback(data, xmlhttp);</code></li>\n<li>As stated by Vogel612, it wont work for some versions of IE, it's not hard to add support for those</li>\n<li>There is no need at all to declare <code>data</code>, you can pass <code>xmlhttp.responseText;</code> straight to <code>callback</code>, it would make the code tighter</li>\n<li>A comment as to what <code>4</code> and <code>200</code> stand for could be useful for the unaware reader</li>\n</ul>\n\n<p>Other than that, looks good.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:04:53.990",
"Id": "77806",
"Score": "0",
"body": "Here at Code Review we don't like magic numbers +1 !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:39:21.990",
"Id": "77810",
"Score": "0",
"body": "Thanks for the feedback. I've updated the solution in the original question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:40:06.373",
"Id": "44746",
"ParentId": "44742",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44746",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:25:09.707",
"Id": "44742",
"Score": "4",
"Tags": [
"javascript",
"ajax",
"reinventing-the-wheel"
],
"Title": "Raw JS AJAX method"
} | 44742 |
<p>This is my first model RSpec test:</p>
<pre><code>require 'spec_helper'
describe CashFlow do
context 'DB Fields' do
it { should have_db_column :amount_cents }
it { should have_db_column :amount_currency }
it { should have_db_column :user_id }
it { should have_db_column :target_date }
it { should have_db_column :created_at }
it { should have_db_column :updated_at }
end
context 'Associations' do
it { should belong_to :user }
it { should have_and_belong_to_many :tags }
end
context 'Validation' do
it { should validate_presence_of :amount_cents }
it { should validate_numericality_of :amount_cents }
it { should ensure_exclusion_of(:amount_cents).in_array([0,]) }
it { should validate_presence_of :amount_currency }
it { should validate_presence_of :target_date }
it { should validate_presence_of :user }
end
context 'Scopes' do
subject { CashFlow }
context 'Incoming/Outcoming flows' do
let(:incoming_cash_flows) { 4.times.map { create :cash_flow } }
let(:outcoming_cash_flows) { 4.times.map { create :cash_flow, negative: true } }
it 'should be able to return all and only incomings cash_flows' do
expect(subject.incoming).to include *incoming_cash_flows
expect(subject.incoming).not_to include *outcoming_cash_flows
end
it 'should be able to return all and only outcomings cash_flows' do
expect(subject.outcoming).to include *outcoming_cash_flows
expect(subject.outcoming).not_to include *incoming_cash_flows
end
end
context 'Past/Future flows' do
[-1, nil, 1].each do |num|
_threshold = num ? Date.today + num.year : nil
let(:threshold) { _threshold }
let(:future_cash_flows) { 4.times.map { create :cash_flow, threshold: threshold } }
let(:past_cash_flows) { 4.times.map { create :cash_flow, past: true, threshold: threshold } }
it "should be able to return all and only past cash_flows with #{_threshold || 'current date (default)'} threshold" do
expect(subject.past(threshold)).to include *past_cash_flows
expect(subject.past(threshold)).not_to include *future_cash_flows
end
it "should be able to return all and only future cash_flows with #{_threshold || 'current date (default)'} threshold" do
expect(subject.future(threshold)).to include *future_cash_flows
expect(subject.future(threshold)).not_to include *past_cash_flows
end
end
end
end
it 'should save specified currency' do
%w(GEL RUB USD EUR).each do |currency|
cash_flow_id = create(:cash_flow, currency: currency).id
cash_flow = CashFlow.find(cash_flow_id)
expect(cash_flow.amount.currency).to eq currency
end
end
end
</code></pre>
<p>Model: </p>
<pre><code>class CashFlow < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :tags
monetize :amount_cents, with_model_currency: :amount_currency
validates_presence_of :user, :target_date, :amount_cents, :amount_currency
validates_exclusion_of :amount_cents, in: [0, ]
scope :incoming, -> { where 'amount_cents > 0' }
scope :outcoming, -> { where 'amount_cents < 0' }
scope :past, lambda { |date = nil | where 'target_date < ?', date || Date.today}
scope :future, lambda { |date = nil | where 'target_date > ?', date || Date.today}
end
</code></pre>
<p>Factory:</p>
<pre><code>FactoryGirl.define do
factory :cash_flow do
association :user
ignore do
negative false
past false
threshold nil
currency 'USD'
end
after :build do |cash_flow, evaluator|
sign = evaluator.negative ? -1 : 1
cash_flow.amount = Money.new((rand(10000) + 1) * sign, evaluator.currency || currency)
sign = evaluator.past ? -1 : 1
cash_flow.target_date = (evaluator.threshold || Date.today) + ((rand(60 * 24 * 30) + 1) * sign).minutes
end
end
end
</code></pre>
<p>What can you tell me about its readability, flexibility and coverage fullness?</p>
<p>I use <em>factory girl</em>, <em>shoulda</em> and <em>money</em> gems.</p>
| [] | [
{
"body": "<p>First thing: congratulations on starting with rspec! Way to go. </p>\n\n<p>My first remark would be to <strong>remove your three first contexts</strong> (Fields, Associations & Validations). </p>\n\n<p>Why? Because <strong>those are not testing any parts of your code - they are testing ActiveModel functionalities</strong>. You want to test your code, not your librairies - at least, not without a very good reason to think that there is a problem there. This is time spent to write specs that do not provide any benefits.</p>\n\n<p>On the other side, while your model don't have much logic yet, I like the fact that you tested your scopes - this is your logic, and it should be tested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T13:31:23.353",
"Id": "78295",
"Score": "0",
"body": "I would keep the validation tests. In terms of spec'ing a model, I'd say it's valid (no pun intended) to specify that it should perform certain validations. A model may well have an attribute that's not used anywhere in the business logic (and thus won't be tested indirectly), but its presence is required for external reasons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T14:26:26.497",
"Id": "78309",
"Score": "0",
"body": "I would test the validations - but not as \"is there validations\" but as \"should refuse an amount without currency\" with an appropriate fixture. Now agree this maybe a question of preferences."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T14:51:43.170",
"Id": "78314",
"Score": "1",
"body": "That's an even better way to go. But your answer didn't give an example of a spec that could _replace_ or improve upon the `shoulda` tests (you did that in your comment just now, however), so it could be interpreted as simply \"don't test validation\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T14:52:41.130",
"Id": "78315",
"Score": "0",
"body": "You are right. I'll update my answer accordingly. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T04:03:15.117",
"Id": "78463",
"Score": "0",
"body": "Thank you guys, I myself thought that DB fields testing is excessive, but as for validation, in terms of TDD I think it should be done, especially with help of shoulda matchers, because they check is there a particular validation or not."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T13:09:50.590",
"Id": "44968",
"ParentId": "44743",
"Score": "2"
}
},
{
"body": "<p>Sounds quite complete. I just do not like to have any logic in my tests that make it hard to debug, like you did when executed some test using array [-1, nil, 1] . Also make sense what first comment says, to do not test the framework, but do test your code. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T04:35:33.620",
"Id": "78573",
"Score": "0",
"body": "I used loop (iterating through array) in place of 3 quite similar tests, is this bad approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T06:05:12.107",
"Id": "78578",
"Score": "0",
"body": "I woundn't say bad, but just more complext. I just like my tests as simple as possible, that's why I don't like to use. Some books says that every test case should have only one assert, so when you iterate in a array you are creating multiple asserts. Let suppose you are considering a range of [-1, 0, 1], and that represents a negative, neutral and positive account balance, so I think is more clear if you create three different tests."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T19:57:10.660",
"Id": "45096",
"ParentId": "44743",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "44968",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:25:49.113",
"Id": "44743",
"Score": "4",
"Tags": [
"beginner",
"ruby",
"unit-testing",
"ruby-on-rails",
"rspec"
],
"Title": "RSpec tests for a cash flow model"
} | 44743 |
<p>My project is written in node JS + Express and has the following architecture:</p>
<ul>
<li>routes (e.g controllers)</li>
<li>models (stateless functional modules)</li>
<li>app</li>
</ul>
<p>Models objects only doing SQL queries like this:</p>
<pre><code>exports.setPassword = function (id, password, callback) {
pg.connect(conString, function (err, client, done) {
if (err) callback(err);
else {
client.query('UPDATE users SET password=$1 WHERE id=$2', [password, id], function (err) {
done();
if (err) callback(err);
else callback(null);
});
}
});
};
exports.setStatus = function (id, status, callback) {
pg.connect(conString, function (err, client, done) {
if (err) callback(err);
else {
client.query('UPDATE users SET status=$1 WHERE id=$2', [status, id], function (err) {
done();
if (err) callback(err);
else callback(null);
});
}
});
};
exports.getStayInTouch = function (userId, callback) {
pg.connect(conString, function (err, client, done) {
if (err) callback(err);
else {
client.query('SELECT * FROM stay_in_touch_contacts WHERE user_id=$1', [userId], function (err, results) {
done();
if (err) callback(err);
else callback(null, results.rows[0]);
});
}
});
};
</code></pre>
<p>and many many functions connected with the user in that user.js module.
The only thing I can do with that architecture is to place functions to the different module.</p>
<p>I'd appreciate any critiques of that architecture. How can I do better?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T10:48:23.397",
"Id": "78259",
"Score": "1",
"body": "Don't store plaintext passwords in the database. Use a proper password hash, like bcrypt, scrypt or PBKDF2. See [How to securely hash passwords?](http://security.stackexchange.com/questions/211/how-to-securely-hash-passwords) for details."
}
] | [
{
"body": "<p>That does not look very DRY ( Dont repeat yourself ), not to mention that it does not look good that every function must be aware of the connection string.</p>\n\n<p>For updates, you could do something like this:</p>\n\n<pre><code>exports.setPassword = function (id, password, callback) {\n genericUpdate('UPDATE users SET password=$1 WHERE id=$2', [password, id], callback );\n};\n\nexports.setStatus = function (id, status, callback) {\n genericUpdate('UPDATE users SET status=$1 WHERE id=$2', [status, id], callback );\n};\n\nfunction genericUpdate( queryString, parameters, callback )\n{\n callback = callback || function(){};\n pg.connect(conString, function (err, client, done) {\n if (err){ \n callback(err);\n } else {\n client.query(queryString, parameters, function (err) {\n done();\n callback(err || null);\n });\n }\n });\n}\n</code></pre>\n\n<p>I added curly braces and newlines to your <code>if</code> statements, other than that your code seems fine.</p>\n\n<p>EDIT: some thoughts on selects, you probably want a few generic selection functions, if you create one that is meant for selecting on an id, then you can get away with always returning the first data record if any.</p>\n\n<pre><code>exports.getStayInTouch = function (userId, callback) {\n selectById( 'SELECT * FROM stay_in_touch_contacts WHERE user_id=$1' , userId , callback );\n};\n\nfunction selectById( queryString, id, callback )\n{\n callback = callback || function(){};\n pg.connect(conString, function (err, client, done) {\n if (err){ \n callback(err);\n } else {\n client.query(queryString, id, function (err,results) {\n done();\n if(err)\n callback(err)\n else\n callback(null, results.rows[0] );\n });\n }\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T05:12:19.133",
"Id": "78015",
"Score": "0",
"body": "Thank you. Nice answer. How can I make the same for get by id for example ? Now I have something like this\n`db.execute('SELECT device_id, platform FROM users WHERE id=$1', [id], function (err, rows) {` ..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:08:58.830",
"Id": "44775",
"ParentId": "44744",
"Score": "4"
}
},
{
"body": "<p>I think the most important thing to improve on would be what konjin's answer already alluded to which is to keep DRY. The pooling interface of your driver seems a bit lacking to me and might be making it difficult to write DRYer code. I prefer the pooling interface that the <a href=\"https://github.com/felixge/node-mysql#pooling-connections\" rel=\"nofollow\">MYSQL</a> driver has. </p>\n\n<pre><code>var pool = mysql.createPool({\n host : 'example.org',\n user : 'bob',\n password : 'secret'\n});\n\npool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {\n if (err) throw err;\n\n console.log('The solution is: ', rows[0].solution);\n});\n</code></pre>\n\n<hr>\n\n<p>One improvement I would make would be to have the same signature for your exports. Currently they follow <em>arg1 arg2 callback, arg1 arg2 callback, arg1 callback</em>. Having the callback as the first argument can avoid confusion. I would consider moving the arguments just an object and have all of the signatures match (callback, args). Having params on an object would make it easier for consumers of the exports not have to be concerned about the order of the arguments.</p>\n\n<p>For example:</p>\n\n<pre><code>updateUser(5, 'Patrick', '123456', 1)\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>updateUser({id: 5, name: 'Patrick', password: '123456', status: 1})\n</code></pre>\n\n<p>The second example is much easier to understand without looking at the implementation for updateUser.</p>\n\n<hr>\n\n<p>One other thing I would consider is looking to using an ORM. It could help with the tedious writing DBMS specific queries and help add functionality. For example if I was using an ORM I could probably could update attributes on a user with only a little bit of code.</p>\n\n<p>For example:</p>\n\n<pre><code>new User(id).update({status: 1, password: '123456'}, callback)\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>setStatus(id, status, function() { setPassword(id, password, callback })\n</code></pre>\n\n<p>Besides being less code and less complex which is the most important the first chunk of code will have twice as many DB hits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:27:23.287",
"Id": "78005",
"Score": "0",
"body": "it is actually sharp decision to use ORM, there can be new question about use it or not. So I am not ready to make it. The another thing you said was right, especially about objects instead of ordinary arguments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:25:22.070",
"Id": "78049",
"Score": "0",
"body": "I was going to write something about pooling, however pooling is inherent with `pg`, all that must be done is call `done` so that the connection is returned to the pool which the OP does."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:06:36.810",
"Id": "44800",
"ParentId": "44744",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T11:44:49.873",
"Id": "44744",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"express.js"
],
"Title": "Node exports, architecture"
} | 44744 |
<p>I've written a function to call with the deferred library to generate a large task queue, and at first without the recursion it timed out (deadlineexceeded) so now I'm trying with a recursion but is it safe that the function will terminate? I actually ran it with GAE and it did the correct task - deleted all the empty blobs that were written previously because of a bug. (It seems that empty blobs with 0 bytes get written several times a day and the code is to delete those blobs.)</p>
<pre><code>def do_blobs_delete(msg=None, b=None, c=None):
logging.info(msg)
edge = datetime.now() - timedelta(days=750)
statmnt = "WHERE size < 1" # size in bytes
logging.debug(statmnt)
try:
gqlQuery = blobstore.BlobInfo.gql(statmnt)
blobs = gqlQuery.fetch(999999)
for blob in blobs:
if blob.size < 1 or blob.creation < edge:
blob.delete()
continue
except DeadlineExceededError:
# Queue a new task to pick up where we left off.
deferred.defer(do_blobs_delete, "Deleting empty blobs", 42, c=True)
return
except Exception, e:
logging.error('There was an exception:%s' % str(e))
</code></pre>
| [] | [
{
"body": "<p>Yes, that function terminate (unless the semantics of <code>blobstore</code> are stranger than expected and <code>blobs</code> is an infinite generator). One thing to be concerned about might be that, should your query take a very long time, you would not delete a single blob before a <code>DeadlineExceededError</code> is thrown, and so schedule another task without doing any work. This is a <strong>bad thing</strong>, as you may end up with many jobs that simply get half way through a query, give up and then schedule themselves to run again. The worst part is that your only indication would be that your log would be full of <code>info</code> level messages (i.e. messages that will be ignored), giving you no idea that this travesty was unfolding in your task queue.</p>\n\n<p>I would recommend you add some kind of limit to make sure you are decreasing the number of blobs towards zero each time. You could think of it as an inductive proof almost; see <a href=\"http://comjnl.oxfordjournals.org/content/12/1/41.short\" rel=\"nofollow\">Burstall's 69 paper</a> on structural induction if you feel like formulating a mathematical proof. However, that is probably not necessary in this case. My suggested rewrite would be something like:</p>\n\n<pre><code># The number of times one call to do_blobs_delete may `recurse`, should probably be\n# made a function of the count of all blobs\nMAX_ATTEMPTS = 10\n\ndef do_blobs_delete(msg=None, b=None, c=None, attempt=0):\n logging.info(msg)\n edge = datetime.now() - timedelta(days=750)\n statmnt = \"WHERE size < 1\" # size in bytes\n logging.debug(statmnt)\n try:\n gqlQuery = blobstore.BlobInfo.gql(statmnt)\n blobs = gqlQuery.fetch(999999)\n for blob in blobs:\n if blob.size < 1 or blob.creation < edge:\n blob.delete()\n except DeadlineExceededError:\n if MAX_ATTEMPTS <= attempt:\n logging.warning(\"Maximum blob delete attempt reached\")\n return\n # Queue a new task to pick up where we left off.\n attempt++\n deferred.defer(do_blobs_delete, \"Deleting empty blobs\",\n 42, c=True,\n attempts=attempt)\n return\n except Exception, e:\n logging.error('There was an exception:%s' % str(e))\n</code></pre>\n\n<p>Note that this does not explicitly address the lack of an inductive variable, though it does limit any damage done.</p>\n\n<p>Another thing to note is that you have a race condition on the <code>.delete</code>. Should the method be called concurrently, say by process A and B, then the call to <code>.fetch</code> could return the same set of bobs to each. They would then attempt to delete the elements twice, which would raise an error on the <code>.delete</code> call, leading to fewer blob deletions than expected. This problem gets a lot worse when we consider more processes and things like unspecified ordering. The correct way to handle this is to treat any exceptions thrown by the <code>.delete</code> in a more nuanced way than you are currently, and accommodate multiple attempted deletes without prejudice.</p>\n\n<p>Your current code will work fine at the moment, the problems will manifest themselves when things get more complicated. While I am sure Google's infrastructure can handle these upsets, your bottom line may be less flexible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T01:08:13.130",
"Id": "44819",
"ParentId": "44745",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T12:28:41.083",
"Id": "44745",
"Score": "5",
"Tags": [
"python",
"recursion",
"error-handling",
"google-app-engine"
],
"Title": "Generating a large task queue"
} | 44745 |
<p>I created a console program that tests report results from JasperReport. It retrieves the list of reports, splits it, and passes each sublist to a new thread. Each thread executes its own reports and compares the results with reference files.</p>
<p>My colleague says multithreading is wrong, but as usual he doesn't explain why. Any hint on what is not correct? He just spouts off something about using an inner class but was not clear, and it's hard to get more details.</p>
<p>This is how the code looks. I've omitted some irrelevant functions (with no side effects anyway). Every local variable is final.</p>
<pre><code>public class ReportTester {
private class ThreadTest implements Runnable {
final List<Report> reports;
final Configuration config;
public ThreadTest(final List<Report> reports, Configuration config)
this.reports = reports;
this.config = config;
}
@Override
public void run() {
runTest(this.reports, this.config);
}
}
private final String format = "xml";
private final String directoryReport = "\var\reports";
private final JasperRestfulClient restClient = new JasperRestfulClient();
private final List<Report> reportsToBeTested = restClient.getReports();
volatile private errors = false; // SIDE EFFECT HERE. Public getter omitted.
private void runTest(List<Report> reports, Configuration config) {
for (Report report : reports) {
try {
String fileName = getFilePath(directoryReport, report, config);
restClient.runReport(report.getPath(), format,config, fileName);
compareWithReference(fileName, report, config);
}
catch(Exception ex){
ex.printStack();
}
}
}
public void runTestMultithreading(Configuration config, int numThread){
ExecutorService es = Executors.newCachedThreadPool();
List<List<Report>> splitted = splitReports(reportsToBeTested, numThread);
for (List<Report> reportsOfThread : splitted) {
ThreadTest thread = new ThreadTest(reportsOfThread, config);
es.execute(thread);
}
es.shutdown();
es.awaitTermination(8, TimeUnit.HOURS);
}
}
</code></pre>
<p>EDIT: This are the methods omitted. Actually there is a side effect, a boolean variable is assigned to true if there is at least one report that isn't identical with reference. But there is not race conditions, even without synchronization, because it can be only assigned to true, the value assigned doesn't depend on previous value of variable and it is and never read by threads.</p>
<pre><code>private boolean filesAreIdentical(String filenameFirst, String filenameSecond) {
File file1 = new File(filenameFirst);
File file2 = new File(filenameSecond);
if (!file1.exists() || !file2.exists()) {
return false;
}
if (file1.length() != file2.length()) {
return false;
}
InputStream stream1 = null;
InputStream stream2 = null;
try {
stream1 = new FileInputStream(file1);
stream2 = new FileInputStream(file2);
final int BUFFSIZE = 1024;
int read1 = -1;
int read2 = -1;
byte buffer1[] = new byte[BUFFSIZE];
byte buffer2[] = new byte[BUFFSIZE];
do {
int offset1 = 0;
while (offset1 < BUFFSIZE && (read1 = stream1.read(buffer1, offset1, BUFFSIZE - offset1)) >= 0) {
offset1 += read1;
}
int offset2 = 0;
while (offset2 < BUFFSIZE && (read2 = stream2.read(buffer2, offset2, BUFFSIZE - offset2)) >= 0) {
offset2 += read2;
}
if (offset1 != offset2) {
return false;
}
if (offset1 != BUFFSIZE) {
Arrays.fill(buffer1, offset1, BUFFSIZE, (byte) 0);
Arrays.fill(buffer2, offset2, BUFFSIZE, (byte) 0);
}
if (!Arrays.equals(buffer1, buffer2)) {
return false;
}
} while (read1 >= 0 && read2 >= 0);
return read1 < 0 && read2 < 0;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (stream1 != null) {
stream1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (stream2 != null) {
stream2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private List<List<Report>> splitReports(List<Report> original, int number) {
List<List<Report>> sublists = new ArrayList<List<Report>>(number);
int reportsPerThread = original.size() / number;
for (int i = 0; i < number; i++) {
int start = reportsPerThread * i;
int stop = (i == number - 1)
? original.size() - 1
: reportsPerThread * (i + 1) - 1;
List<Report> sublist = createSublist(original, start, stop);
sublists.add(sublist);
}
return splits;
}
private List<Report> createSublist(final List<Report> original, int start, int stop)
{
List<Report> copy = new ArrayList<>(original.size());
if (stop > original.size() - 1) {
stop = original.size() - 1;
}
for (int ii = start; ii <= stop; ii++) {
copy.add(original.get(ii));
}
return copy;
}
private void compareWithReference(String filename, Report report, Configuration config) {
String filenameReference = directoryReport + config.subfolder() + filename;
if (filesAreIdentical(filename, filenameReference)) {
System.out.println(filename + " OK");
} else {
// SIDE EFFECT
errors = true;
System.err.println(filename + " FAILED");
}
}
</code></pre>
<p>This is the the client.</p>
<pre><code>private final String server; //assigned by constructor
protected final CloseableHttpClient httpclient; //assigned by constructor; threadsafe
public void runReport(String url, String destinazione) throws IOException {
HttpGet httpget = null;
InputStream instream = null;
try {
File file = new File(destinazione);
file.getParentFile().mkdirs();
file.createNewFile();
httpget = new HttpGet(server + url);
HttpResponse response = httpclient.execute(httpget);
writeResponceToFile(response, file);
}
finally {
if (httpget != null) {
httpget.abort();
}
}
}
private void writeResponceToFile(HttpResponse response, File file) throws IOException {
HttpEntity entity = response.getEntity();
InputStream instream = null;
try {
if (entity != null) {
instream = entity.getContent();
BufferedInputStream bis = new BufferedInputStream(instream);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
int inByte;
while ((inByte = bis.read()) != -1) {
bos.write(inByte);
}
bis.close();
bos.close();
}
} finally {
if (instream != null) {
instream.close();
}
}
}
</code></pre>
| [] | [
{
"body": "<p>I can only see one 'bug' problem with this code, but there are a few other 'style' and 'simplicity' issues.</p>\n\n<h2>reportsDaTestare</h2>\n\n<p>What is this? It appears out of nowhere:</p>\n\n<blockquote>\n<pre><code>for (Report report : reportsDaTestare) {\n ....\n}\n</code></pre>\n</blockquote>\n\n<p>I am worried that this is a typo for <code>reportsToBeTested</code> as you tanslated the code.... If it is, then you will be repeating all the reports in each thread..... it should be:</p>\n\n<pre><code>for (Report report : reports) {\n ....\n}\n</code></pre>\n\n<h2>Style</h2>\n\n<ul>\n<li><p><code>Test</code> and class and method names derived from it typically relate to unit testing, like jUnit, etc. By common convention you should not use these method names for anything other than test code.</p>\n\n<p>Use words like <code>Validate</code>, or <code>Check</code> instead.</p></li>\n<li><p>Error handling.... I presume you have removed the actual error handling from this method, because this code will not compile... it is <code>ex.printStackTrace()</code> and not <code>ex.printStack()</code>. I hope the error-handling code you removed is 'better'.</p>\n\n<blockquote>\n<pre><code> catch(Exception ex){\n ex.printStack();\n }\n</code></pre>\n</blockquote></li>\n<li><p><code>ThreadTest</code> is not a Thread, it is a Runnable. Call it something else.</p></li>\n</ul>\n\n<h2>Simplifications.</h2>\n\n<p>There are some tricks you can play that will simplify your code a bit.</p>\n\n<p>Firstly, the <code>ThreadTest</code> class (which is a Runnable), does not need to exist at all. It is just a very light-weight container.</p>\n\n<p>Consider the following multi-threaded loop method:</p>\n\n<pre><code>public void runTestMultithreading(final Configuration config, int numThread){\n ExecutorService es = Executors.newCachedThreadPool();\n List<List<Report>> splitted = splitReports(reportsToBeTested, numThread);\n\n for (final List<Report> reportsOfThread : splitted) {\n es.execute(new Runnable(){\n public void run() {\n runTests(reportsOfThread, config);\n }\n });\n }\n\n es.shutdown();\n es.awaitTermination(8, TimeUnit.HOURS);\n}\n</code></pre>\n\n<p>Note how we use an anonymous class in here, and we can do it by making the config parameter final, as well as the relatively unknown final inside the for-each loop <code>for (final List<...> ....)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:16:28.583",
"Id": "77823",
"Score": "0",
"body": "Of course this answer is assuming that the multithreading as implemented by OP is correct, isn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:43:25.023",
"Id": "77827",
"Score": "0",
"body": "Thank you, the first is a cut&paste error. The correct code is for(Report report : reports), where reports is the parameter of the function (edited the answer). The code is simplified, actual error handling is different. Good point about names (but company convention apply too) and anonymous class. I will pay attention to your suggestions next time. Anyway, apart style improvement and simplification (always useful), is there anything wrong that could make the program fail?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:25:31.600",
"Id": "78001",
"Score": "0",
"body": "@robermann I can see only one bug.... including concurrency issues.... (I have assumed that the called methods that are not documented in the question, are thread-safe)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:26:35.990",
"Id": "78003",
"Score": "0",
"body": "@holap - there is nothing in the code you posted here that would indicate a multi-threading problem. unholysampler pointerd out the method calls which you have not posted here may in fact have problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T08:53:56.087",
"Id": "78035",
"Score": "0",
"body": "Added the other methods. Hope it make more clear."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:02:49.963",
"Id": "44752",
"ParentId": "44749",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination%28long,%20java.util.concurrent.TimeUnit%29\" rel=\"nofollow noreferrer\"><code>ExecutorService.awaitTermination</code></a> has a return value:</p>\n\n<blockquote>\n <p>true if this executor terminated and false if the timeout elapsed before termination</p>\n</blockquote>\n\n<p>You should check that and at least print a warning to log if it's <code>false</code>.</p></li>\n<li><p>Consider setting an <code>UncaughtExceptionHandler</code> for the executor (through a <code>ThreadFactory</code>). (<a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/ThreadFactoryBuilder.html\" rel=\"nofollow noreferrer\"><code>ThreadFactoryBuilder</code></a> from <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\">Guava</a> has a great API for that.)</p></li>\n<li><p>It's a little bit surprising that field declarations call probably complicated methods:</p>\n\n<blockquote>\n<pre><code>final JasperRestfulClient restClient = new JasperRestfulClient();\nfinal List<Report> reportsToBeTested = restClient.getReports();\n</code></pre>\n</blockquote>\n\n<p>I'd put them into a constructor.</p></li>\n<li><p>These fields could be private:</p>\n\n<blockquote>\n<pre><code>final String format = \"xml\";\nfinal String directoryReport = \"\\\\var\\\\reports\";\nfinal JasperRestfulClient restClient = new JasperRestfulClient();\nfinal List<Report> reportsToBeTested = restClient.getReports();\n</code></pre>\n</blockquote>\n\n<p>(<a href=\"https://stackoverflow.com/q/5484845/843804\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><p><a href=\"https://english.stackexchange.com/a/5463/13023\"><code>fileName</code> is rather one word</a>, I'd not capitalize the <code>n</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-28T04:09:37.943",
"Id": "97350",
"Score": "0",
"body": "Curious, why should complicated methods be moved to a constructor? If they're in the field initialization, they're still invoked in the same sequence as a constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-28T06:53:00.437",
"Id": "97364",
"Score": "0",
"body": "@Kirby: I think (so it's more or less subjective) they're easier to follow and debug, especially when the called method throws an exception and you have to analyze the stacktrace. `JasperRestfulClient` seems to be an object which uses network calls, so I guess its `getReports()` method could throw exceptions. Thanks for the good question! I guess I'll update the answer too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:24:29.193",
"Id": "44793",
"ParentId": "44749",
"Score": "5"
}
},
{
"body": "<p>The contents of <code>getFilePath()</code>, <code>compareWithReference()</code> and <code>restClient.runReport()</code> were not posted, so we can't say if the code is or isn't thread safe. The call to <code>runRport()</code> would be my first thought of a problem since the same instance is used in each thread.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:54:16.047",
"Id": "77939",
"Score": "0",
"body": "You are right, I wanted to keep the code short in the question. That functions use only final members or local variables, shouldn't have side effects. I will add them tomorrow when at work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:12:04.443",
"Id": "77943",
"Score": "2",
"body": "@holap: `final` ensures the reference doesn't change. However, if the reference is to a mutable object, more needs to be done to make it thread safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T09:00:57.120",
"Id": "78036",
"Score": "0",
"body": "Unfortunately didn't find immutable collection in standard java api. One side effect is actually present (edited the question), but it should be thread-safe. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T09:01:58.690",
"Id": "78037",
"Score": "0",
"body": "Added missing methods."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:37:46.157",
"Id": "44794",
"ParentId": "44749",
"Score": "4"
}
},
{
"body": "<p>You don't need to split the reports - you should use a fixed thread pool to control your 'split'</p>\n\n<pre><code> public void runTestMultithreading(final Configuration config, int numThread){\n ExecutorService es = Executors.newFixedThreadPool(numThread);\n for (final Report report : restClient.getReports()) {\n es.execute(new Runnable() {\n public void run() {\n String fileName = getFilePath(directoryReport, report, config);\n restClient.runReport(report.getPath(), format,config, fileName);\n compareWithReference(fileName, report, config);\n }\n );\n }\n\n es.shutdown();\n es.awaitTermination(8, TimeUnit.HOURS);\n }\n</code></pre>\n\n<p>if you need the result of each thread you should futures - and gather the result at the end.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:46:04.913",
"Id": "44814",
"ParentId": "44749",
"Score": "3"
}
},
{
"body": "<p>Notes for the edit:</p>\n\n<ol>\n<li><p>You really should replace the complex <code>filesAreIdentical</code> with <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#contentEquals%28java.io.File,%20java.io.File%29\" rel=\"nofollow\"><code>FileUtils.contentEquals</code></a> (from <a href=\"http://commons.apache.org/proper/commons-io/\" rel=\"nofollow\">Apache Commons IO</a>).</p>\n\n<p>It probably well-tested and it contains some further optimizations:</p>\n\n<blockquote>\n <p>This method checks to see if the two files are different\n lengths or if they point to the same file, before resorting\n to byte-by-byte comparison of the contents.</p>\n</blockquote></li>\n<li><p>As far as I see you are using Apache HTTP Client 4.x which looks thread-safe but make sure that the actual <code>httpclient</code> instance you are using is really thread-safe.</p></li>\n<li><p><code>instream</code> is unused here, you could remove it:</p>\n\n<blockquote>\n<pre><code>public void runReport(String url, String destinazione) throws IOException {\n HttpGet httpget = null;\n InputStream instream = null;\n try {\n File file = new File(destinazione);\n file.getParentFile().mkdirs();\n file.createNewFile();\n httpget = new HttpGet(server + url);\n HttpResponse response = httpclient.execute(httpget);\n writeResponceToFile(response, file);\n }\n finally {\n if (httpget != null) {\n httpget.abort();\n }\n }\n}\n</code></pre>\n</blockquote></li>\n<li><p>You could also restructure the loop and be able to remove the null check:</p>\n\n<pre><code>File file = new File(destinazione);\nfile.getParentFile().mkdirs();\nfile.createNewFile();\nfinal HttpGet httpget = new HttpGet(server + url);\ntry {\n HttpResponse response = httpclient.execute(httpget);\n writeResponceToFile(response, file);\n} finally {\n httpget.abort();\n}\n</code></pre>\n\n<p>If <code>new HttpGet()</code> throws an exception the reference will be <code>null</code>, so can't call <code>abort</code> anyway.</p></li>\n<li><p>In <code>writeResponceToFile</code> you could do the same (I suppose <code>getContent()</code> never returns null but check this, I'm not sure about that), and using a <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clause would make the code flatten</a>:</p>\n\n<pre><code>private void writeResponceToFile(HttpResponse response, File file) throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n final InputStream instream = entity.getContent();\n try {\n BufferedInputStream bis = new BufferedInputStream(instream);\n BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));\n int inByte;\n while ((inByte = bis.read()) != -1) {\n bos.write(inByte);\n }\n bis.close();\n bos.close();\n } finally {\n if (instream != null) {\n instream.close();\n }\n }\n}\n</code></pre></li>\n<li><p>The loop above could be slow since it copies the content in one byte chunks. There are better alternatives:</p>\n\n<ul>\n<li>In Java 7: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy%28java.io.InputStream,%20java.nio.file.Path,%20java.nio.file.CopyOption...%29\" rel=\"nofollow\"><code>Files.copy(InputStream in, Path target, CopyOption... options)</code></a></li>\n<li>In <a href=\"http://commons.apache.org/proper/commons-io/\" rel=\"nofollow\">Apache Commons IO</a> <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyInputStreamToFile%28java.io.InputStream,%20java.io.File%29\" rel=\"nofollow\"><code>FileUtils.copyInputStreamToFile(InputStream source, File destination)</code></a></li>\n</ul>\n\n<p><code>copyInputStreamToFile</code> uses a more efficient 4 kbyte buffer and I guess it contains other optimizations, solutions to corner cases etc.</p>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>You should close the output stream in a <code>finally</code> block or use try-with-resources. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><p>I agree with <em>@user39078</em> that you don't need the <code>splitReports</code>. Anyway, it's good to know that there is an existing method for that: <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Guava</a>'s <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Lists.html#partition%28java.util.List,%20int%29\" rel=\"nofollow\"><code>Lists.partition</code></a></p>\n\n<pre><code>List<List<T>> Lists.partition(List<T> list, int size)\n</code></pre></li>\n<li><p><code>createSublist</code> also could be replaced with <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/List.html#subList%28int,%20int%29\" rel=\"nofollow\"><code>List.subList</code></a>.</p></li>\n<li><p>This flag should be properly synchronized (or probably could be <code>volatile</code>):</p>\n\n<blockquote>\n<pre><code>errors = true;\n</code></pre>\n</blockquote>\n\n<p>(Or you could use an <code>AtomicBoolean</code>.)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T12:46:02.167",
"Id": "78282",
"Score": "1",
"body": "Thank you very much. You gave me some very interesting tips. Well.. shame on me I forgot the volatile keyword. Sorry, as I have to translate the code from my mother language to english I can't just cut and paste the original code. According to www.ibm.com/developerworks/java/library/j-jtp06197 volatile should suffice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T11:57:43.480",
"Id": "44954",
"ParentId": "44749",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T13:21:53.240",
"Id": "44749",
"Score": "10",
"Tags": [
"java",
"multithreading"
],
"Title": "Inner class calling outer class method"
} | 44749 |
<p>I recently wrote code that would query a collection of objects and rank them according to a given criteria and then filter based on an object property. I attach the code below. I would like to know if my approach can be improved upon such as made more efficient and extensible. Is there a better approach or just another approach?</p>
<p>I know that lambdas in Java 8 would make the code much cleaner. What other improvements are available?</p>
<p><strong>Here's the scenario:</strong></p>
<p>Rank journals numerically by score, those with a shared rank ordered lexicographically and filter out journals that are review journals.</p>
<p><strong>Here's the data:</strong></p>
<p>Given the following journals have scores:</p>
<pre><code>Journal A = 2.2
Journal B = 6.2
Journal C = 6.2
Journal D = 1.2
</code></pre>
<p>And Journal D is a review journal.</p>
<p>The result should be:</p>
<pre><code>Rank Journal Name Score
1 Journal B 6.2
1 Journal C 6.2
3 Journal A 2.2
</code></pre>
<p>Note: Journal D is filtered out of the list.</p>
<p><strong>Here's my code:</strong></p>
<p>This code produces the actual sort and filter:</p>
<pre><code>List<Journal> journals = // add journals to collection.
Collate<Journal> collateJournals = new Collate<>();
Collate<Journal> collatedJournals = collateJournals.from(journals).filter(new OutReview()).sort(new ByScoreThenName(Direction.ASC)).rank(new Numerical());
</code></pre>
<p>This code controls the collation of sorted and filtered data.</p>
<pre><code>public class Collate<T> {
List<T> collection = new ArrayList<>();
public Collate<T> sort(Comparator<T> sortComparator) {
Collections.sort(collection, sortComparator);
return this;
}
public T get(int i) {
return this.collection.get(i);
}
public boolean contains(T element){
return collection.contains(element);
}
public Collate<T> from(List<T> collection) {
this.collection = collection;
return this;
}
public Collate<T> filter(Predicate<T> predicate) {
List<T> result = new ArrayList<T>();
for (T element : (Collection<T>) collection) {
if (predicate.apply(element)) {
result.add(element);
}
}
this.collection = result;
return this;
}
public Collate<T> rank(Rank<T> rankEngine) {
rankEngine.doRank(collection);
return this;
}
}
</code></pre>
<p>This code implements a Comparator interface and is used to sort the collection:
NOTE: there is also an Enum called direction that I have omitted.</p>
<pre><code>public class ByScoreThenName implements Comparator<Journal> {
Direction direction;
public ByScoreThenName(){
this.direction = Direction.ASC;
}
public ByScoreThenName(Direction direction){
this.direction = direction;
}
@Override
public int compare(Journal j1, Journal j2) {
int comparatorValue = 0;
if (j1.getScore() == j2.getScore()) {
comparatorValue = j2.getName().compareToIgnoreCase(j1.getName());
} else {
if ((j1.getScore() < j2.getScore())) {
comparatorValue = -1;
} else if (j1.getScore() > j2.getScore()) {
comparatorValue = 1;
}
}
return direction.coefficent() * comparatorValue;
}
}
</code></pre>
<p>This code ranks numerically the journals based on their score, setting the journals rank in the journal object:</p>
<pre><code>public class Numerical implements Rank<Journal> {
@Override
public void doRank(List<Journal> journals) {
for(Journal journal : journals){
int index = journals.lastIndexOf(journal);
if(index != 0 && journals.get(index-1).getScore() == journal.getScore()){
journal.setRank(journals.get(index-1).getRank());
} else {
journal.setRank(++index);
}
}
}
}
</code></pre>
<p>This filters out the review journals. It implements a predicate interface:</p>
<pre><code>public class OutReview implements Predicate<Journal>{
@Override
public boolean apply(Journal j) {
return !j.isReview();
}
}
</code></pre>
<p>And finally the journal object:</p>
<pre><code>public class Journal implements Serializable{
private static final long serialVersionUID = 8964756258469682390L;
private String name;
private float score;
private boolean review;
private int rank;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public boolean isReview() {
return review;
}
public void setReview(boolean review) {
this.review = review;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int hashCode() {
// Code omitted for brevity
}
public boolean equals(Object obj) {
// Code omitted for brevity
}
@Override
public String toString() {
// Code omitted for brevity
}
}
</code></pre>
<p>I would appreciate any kind of feedback big or small.</p>
<p><strong>EDIT:</strong></p>
<p>I have followed the advise given below and implemented the from() method as a static factory method as follows:</p>
<pre><code>public static <T> Collation<T> from(List<T> items) {
return new Collation<T>(new ArrayList<T>(items));
}
</code></pre>
<p>I have changed the names of the class and variables following the given advice:</p>
<p>The Direction Enum class is now imported as a static import. This cleans the code a bit.</p>
<p>And the array list field is now private.</p>
| [] | [
{
"body": "<h2>Lambdas</h2>\n<blockquote>\n<p>I know that lambdas in Java 8 would make the code much cleaner. What other improvements are available?</p>\n</blockquote>\n<p>I am not sure I agree with the Lambdas in J8 statement. They have their place, but clean code is readable code, and only a small subset of problems have improved readability from Lambdas, and also, Lambdas are a 'meta level' function.... Implementing 'foundation logic' using Lambdas would be a mistake because then integrating with traditional Java would be harder.</p>\n<p>Right tool for the job, etc. In this case, I don't think Lambdas would necessarily be the right tool, even in Java8.</p>\n<p>Specifically, your code requires cross-referencing Journals against each other (to sort them), and this would be very messy in a Stream.</p>\n<h2>Generics</h2>\n<p>You have collections of <code>Journal</code> throughout your code.... This is not a problem, but what I have a concern about is the inconsistency of your own Generic classes. For example, you have:</p>\n<pre><code>public class OutReview implements Predicate<Journal>{\n</code></pre>\n<p>and</p>\n<pre><code>public class Numerical implements Rank<Journal> {\n</code></pre>\n<p>Which make specific implementations of generic Interfaces.</p>\n<p>I have no problem with this, it is nice, and clean.</p>\n<p>Then you also have:</p>\n<pre><code>public class Collate<T> {\n</code></pre>\n<p>This is a generic class that has this neat ability to collate generically typed data based on matching Rank and Predicate instances....</p>\n<p>On it's own, it is nice, clean, and general purpose.</p>\n<p>But, you put them together, and you have a bit of a mess:</p>\n<blockquote>\n<pre><code>List<Journal> journals = // add journals to collection.\nCollate<Journal> collateJournals = new Collate<>();\nCollate<Journal> collatedJournals = collateJournals.from(journals)\n .filter(new OutReview())\n .sort(new ByScoreThenName(Direction.ASC))\n .rank(new Numerical());\n</code></pre>\n</blockquote>\n<p>For consistency, the Collate class should be hard-coded to work with Journal, or your actual OutReview and other classes should be generic too.</p>\n<h2>Naming</h2>\n<blockquote>\n<pre><code>List<T> collection = new ArrayList<>();\n</code></pre>\n</blockquote>\n<p>Don't call a List <code>collection</code>. It makes the following line very confusing:</p>\n<blockquote>\n<pre><code>Collections.sort(collection, sortComparator);\n</code></pre>\n</blockquote>\n<p>Because <code>Collections.sort( .... )</code> has only got a <code>List<></code> version of the argument.</p>\n<p>I would recommend a name like "journals" if you make the Collate class Journal specific instead of generic. Alternatively, something that describes the content, not the structure... like 'data', or 'values'.</p>\n<h2>Leaks</h2>\n<p>You have a few encapsulation leaks. The biggest is this one:</p>\n<blockquote>\n<pre><code>public Collate<T> from(List<T> collection) {\n this.collection = collection;\n return this;\n}\n</code></pre>\n</blockquote>\n<p>you initialize your class with an empty <code>ArrayList</code> but then you throw it away and replace it with the from()'s argument.</p>\n<p>Any changes outside your class to that <code>collection</code> (bad name) will now also be reflected in your class. For example, you may sort your collection, but then someone can add stuff out of order.....</p>\n<p>You should be copying the collection content, not the actual reference:</p>\n<pre><code>public Collate<T> from(List<T> input) {\n data.clear();\n data.addAll(input);\n return this;\n} \n</code></pre>\n<p>This will also save some interesting and embarrassing bugs like when someone calls your from method with:</p>\n<pre><code>collate.from(Collections.unmodifiableList(somedata));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T08:27:44.730",
"Id": "78030",
"Score": "0",
"body": "Thank you very much for your answer, especially the point about the leaks. I learnt a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T02:31:45.237",
"Id": "44823",
"ParentId": "44756",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>When using a generic name for a field (which is often fine), avoid the names of the actual type's superclasses: <code>collection -> items</code> since <code>Collection</code> lacks the ordering semantics of <code>List</code>.</p></li>\n<li><p>Name classes as nouns instead of verbs: <code>Collate -> Collation</code>.</p></li>\n<li><p><code>Collate.from</code> should be a static factory method. There's no reason to overwrite the existing collation to save creating a new one. There's no guarantee that the given list is sorted correctly, but at least make a defensive copy.</p>\n\n<pre><code>public static Collation<T> from(List<T> items) {\n return new Collation(new ArrayList<>(items));\n}\n</code></pre>\n\n<p>Otherwise you risk encapsulation bugs:</p>\n\n<pre><code>List<Book> books = ...;\nCollation<Book> booksByAuthor = Collation.from(books);\nbooksByAuthor.order(Journal.BY_AUTHOR);\nbooks.add(new Book(... \"Aaron Adams Anderson\" ...);\nUI.displayLastPage(booksByAuthor); // oops\n</code></pre></li>\n<li><p>Make use of <a href=\"https://code.google.com/p/guava-libraries/wiki/OrderingExplained\" rel=\"nofollow\"><code>Ordering</code></a> from Guava for easy comparator creation. If not, spell out <code>ASCENDING</code> and <code>DESCENDING</code>; add some constants; and employ static imports to reduce clutter.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T08:45:51.173",
"Id": "78034",
"Score": "0",
"body": "Thanks for your answer. I implemented the static factory method. See edit to question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:37:19.333",
"Id": "44835",
"ParentId": "44756",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "44823",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:26:03.647",
"Id": "44756",
"Score": "6",
"Tags": [
"java",
"collections"
],
"Title": "Clean, efficient and extensible code for querying collections"
} | 44756 |
<p>I am getting list of <code>badCatsNames</code> from webservices, now I have two asp.net bulleted lists here,</p>
<ul>
<li>Bulleted List 1 - Available Cats</li>
<li>Bulleted List 2 - Purchasing Cats</li>
</ul>
<p>Now I need to check each bad cat name if bad cat is in available cats list, if bad cat name is then take her out of Available Cats and put in Purchasing Cats ;), but if Cat is already in purchasing Cats list then put them in Available Cats list.</p>
<p>If bad cat name is not in any list then ignore it.</p>
<pre><code>if(badCatsNames.length > 0)
{
for (var i = 0; i < badCatsNames.length; i++) {
var badCatName = badCatsNames[i];
$("[id$=listAvailableCats] li").each(function (index) {
if ($(this).text() == badCatName) {
$(this).appendTo($("[id$=listPurchasingCats]"));
}
else {
$("[id$=listPurchasingCats] li").each(function (index) {
if ($(this).text() == badCatName) {
$(this).appendTo($("[id$=listAvailableCats]"));
}
});
}
});
}
}}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:50:39.097",
"Id": "77829",
"Score": "3",
"body": "Can anyone what? Please edit the title to best reflect the code's *purpose*. Any requests can be in the post body."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:51:42.560",
"Id": "77830",
"Score": "0",
"body": "@Jamal Done now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:09:37.450",
"Id": "77853",
"Score": "0",
"body": "Could you add the relevant HTML?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:45:38.257",
"Id": "77978",
"Score": "0",
"body": "Checking that the length is greater than zero avails you nothing; if you iterate over an empty list, nothing happens. The test just complicates your code."
}
] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Naming: <code>badCatNames</code> not <code>badCatsNames</code>, <code>listPurchasingCats</code> -> I have no clue what this means, is this a list of cats for sale ?</p></li>\n<li><p>Searching on a text : please consider the <code>contains</code> selector: <a href=\"https://api.jquery.com/contains-selector/\" rel=\"nofollow\">https://api.jquery.com/contains-selector/</a> This way you do not have to loop over every <code>\"[id$=listAvailableCats] li\"</code></p></li>\n<li><p><code>$(\"[id$=listPurchasingCats] li\").each(function (index) {</code> should not be part of the other <code>.each()</code> loop, are you sure this code works ?</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:36:27.997",
"Id": "44779",
"ParentId": "44759",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:45:50.977",
"Id": "44759",
"Score": "5",
"Tags": [
"javascript",
"jquery"
],
"Title": "Bad cats for sale"
} | 44759 |
<p>I have written the following code to get <code>ImageColorPicker</code> child:</p>
<pre><code>foreach (CustomTabItem customTabItem in SelectedWindowsTabControl.Items)
{
TabItem ti = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;
Popup popup = (Helpers.FindVisualChild<Popup>(ti) as Popup);
ImageColorPicker icp = (popup.Child as StackPanel).Children[0] as ImageColorPicker;
...
}
public class Helpers
{
/// <summary>
/// Return the first visual child of element by type.
/// </summary>
/// <typeparam name="T">The type of the Child</typeparam>
/// <param name="obj">The parent Element</param>
public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
}
</code></pre>
<p>Here's the control template XAML of the <code>TabItem</code> (the relevant part):</p>
<pre><code><ControlTemplate TargetType="{x:Type local:CustomTabItem}">
<Grid Height="26" Background="{TemplateBinding Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ContentPresenter Margin="5,0" HorizontalAlignment="Left" VerticalAlignment="Center" ContentSource="Header">
</ContentPresenter>
<StackPanel Grid.Column="1" Height="16" Margin="0,0,1,0" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
<ToggleButton x:Name="Edit" Width="16" Content="&#xE104;" Style="{StaticResource CustomizedMetroTabItemToggleButton}" ToolTip="Edit" />
<Popup HorizontalOffset="{Binding Width, ElementName=Edit}" IsOpen="{Binding IsChecked, Mode=TwoWay, ElementName=Edit}" Placement="Left" PlacementTarget="{Binding ElementName=Edit}" PopupAnimation="Slide" StaysOpen="False" VerticalOffset="{Binding ActualHeight, ElementName=Edit}">
<StackPanel>
<local:ImageColorPicker x:Name="ColorPicker" Width="100" Height="100" HorizontalAlignment="Center" Source="Images/ColorWheel.png" />
</StackPanel>
</Popup>
</StackPanel>
</Grid>
</ControlTemplate>
</code></pre>
<p>Is there a better way to get the <code>ImageColorPicker</code> than what I've done? (getting the <code>TabItem</code>, then the <code>Popup</code> and then the <code>ImageColorPicker</code>, I am sure there's a shorter way)</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:05:14.517",
"Id": "77833",
"Score": "7",
"body": "You should try to find a woman that also wants a child this will increase chances. Now seriously: Try to find more descriptive (and less ambiguous) titles :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:07:49.763",
"Id": "77834",
"Score": "3",
"body": "nah, title is ok - funny titles draw attention ;) (`pill.Forget();` would be a good way!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:12:36.697",
"Id": "77907",
"Score": "2",
"body": "We do have a [parenting site on StackExchange](http://parenting.stackexchange.com/) for those interested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:11:11.403",
"Id": "77928",
"Score": "2",
"body": "Hot Network Questions pitcher plant title of the week!"
}
] | [
{
"body": "<p>I don't like a class that's just called <code>Helpers</code> - that's generally a code smell, something that ends up a big dumping ground for anything that doesn't quite fit anywhere else. Be more specific when naming things, perhaps <code>VisualHierarchyHelper</code> would be a better name?</p>\n<p>I'm using a very similar method - the main difference is essentially the number ot <code>return</code> statements, and the <code>childName</code> parameter; I found this code on <a href=\"https://stackoverflow.com/a/1759923/1188513\">Stack Overflow</a> a little while ago:</p>\n<pre><code> /// <summary>\n /// Finds a Child of a given item in the visual tree. \n /// </summary>\n /// <param name="parent">A direct parent of the queried item.</param>\n /// <typeparam name="T">The type of the queried item.</typeparam>\n /// <param name="childName">x:Name or Name of child. </param>\n /// <returns>The first parent item that matches the submitted type parameter. \n /// If not matching item can be found, \n /// a null parent is being returned.</returns>\n /// <remarks>\n /// https://stackoverflow.com/a/1759923/1188513\n /// </remarks>\n public static T FindChild<T>(this DependencyObject parent, string childName)\n where T : DependencyObject\n {\n if (parent == null) return null;\n\n T foundChild = null;\n\n var childrenCount = VisualTreeHelper.GetChildrenCount(parent);\n for (var i = 0; i < childrenCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n var childType = child as T;\n if (childType == null)\n {\n foundChild = FindChild<T>(child, childName);\n if (foundChild != null) break;\n }\n else if (!string.IsNullOrEmpty(childName))\n {\n var frameworkElement = child as FrameworkElement;\n if (frameworkElement != null && frameworkElement.Name == childName)\n {\n foundChild = (T)child;\n break;\n }\n }\n else\n {\n foundChild = (T)child;\n break;\n }\n }\n\n return foundChild;\n }\n</code></pre>\n<p>Notice the <em>guard clause</em> preventing a <code>NullReferenceException</code> that your method would throw if <code>obj</code> was <code>null</code>. I think this is a pretty neat way of finding a child node in the visual tree.</p>\n<p>That said, it might be personal preference, but I think the readability of your code could benefit from implicit typing (<code>var</code>), especially in cases like this where the type is already pretty obvious:</p>\n<pre><code>TabItem ti = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;\nPopup popup = (Helpers.FindVisualChild<Popup>(ti) as Popup);\nImageColorPicker icp = (popup.Child as StackPanel).Children[0] as ImageColorPicker;\n</code></pre>\n<p>Becomes:</p>\n<pre><code>var ti = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;\nvar popup = (Helpers.FindVisualChild<Popup>(ti) as Popup);\nvar icp = (popup.Child as StackPanel).Children[0] as ImageColorPicker;\n</code></pre>\n<p>And here you would have to make sure <code>popup</code> isn't <code>null</code> before accessing its <code>Child</code> member, if you want to avoid that possible <code>NullReferenceException</code>.</p>\n<p>Also, you're casting too much - <code>T</code> should be of the type you've specified, so the return type of <code>FindChild<ImageColorPicker></code> is <code>ImageColorPicker</code>, casting it to <code>ImageColorPicker</code> is redundant.</p>\n<hr />\n<h3>Update</h3>\n<p>The <code>ImageColorPicker</code> child has a <code>Popup</code> parent, which has a <code>StackPanel</code> parent, which has a <code>Grid</code> parent, which has a <code>TabItem</code> parent.</p>\n<p>You're not fully using the recursiveness of your function when you're getting the color picker. I'd believe you could get it like this:</p>\n<pre><code>var tab = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;\nvar picker = VisualHierarchyHelper.FindChild<ImageColorPicker>(tab, "ColorPicker");\n</code></pre>\n<p>That should work, because the search is recursive; you don't need to get everything in-between.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:40:52.790",
"Id": "77845",
"Score": "0",
"body": "Thats not exactly what I meant. Right now I use 3 lines to get the ImageColorPicker (btw, the Popup will never be null).\nWhy cant I just do something like `TabItem ti = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem; ImageColorPicker icp = Helpers.FindVisualChild<ImageColorPicker(ti) as ImageColorPicker;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:54:27.897",
"Id": "77846",
"Score": "0",
"body": "There's one `ImageColorPicker` control in the `TabItem` but still, the picker variable is null, why is that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:55:45.190",
"Id": "77848",
"Score": "0",
"body": "Even with this `FindVisualChild<T>` implementation? (I'm investigating it right now)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:58:53.093",
"Id": "77849",
"Score": "0",
"body": "Yes, even with the `FindVisualChild<T>` implementation. Something is weird and I cant understand what"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:07:27.540",
"Id": "77852",
"Score": "0",
"body": "@Ron that's weird, I'm using it to find a named `ComboBox` in a templated `ListViewItem` (has `Border` and `Grid` parents), no issues, but the ComboBox has a `x:Name`. Have you tried giving an `x:Name` to the color picker element? Other than that, I'm afraid *telling you why the code doesn't work as expected* is beyond the scope of this site (Stack Overflow can certainly help there)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:29:50.357",
"Id": "77855",
"Score": "0",
"body": "Yes, the ColorPicker has `x:Name` `<local:ImageColorPicker x:Name=\"ColorPicker\" Width=\"100\" Height=\"100\" HorizontalAlignment=\"Center\" Source=\"Images/ColorWheel.png\" />` The control is based on Image control, maybe thats the issue.. I will investigate it my self"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:36:02.733",
"Id": "77857",
"Score": "0",
"body": "Maybe there's something to do with that `Popup` is `System.Controls.Primitives`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:38:57.547",
"Id": "77858",
"Score": "0",
"body": "`Image` and `Popup` are both `FrameworkElement` derivatives, it shouldn't matter. Wow you just got me scratching my head now!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:42:50.240",
"Id": "77862",
"Score": "2",
"body": "From MSDN: When you add content to a Popup control, the Popup control becomes the logical parent to the content. Similarly, the Popup content is considered to be the logical child of the Popup. The child content is not added to the visual tree that contains the Popup control. Instead, the child content is rendered in a separate window that has its own visual tree when the IsOpen property is set to true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-01T07:01:59.067",
"Id": "376635",
"Score": "0",
"body": "i was looking around on SO and google for far too long. this did the trick tough, thx!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:27:15.447",
"Id": "44762",
"ParentId": "44760",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "44762",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T14:53:31.817",
"Id": "44760",
"Score": "14",
"Tags": [
"c#",
"wpf",
"xaml"
],
"Title": "Is there a better way to get a child?"
} | 44760 |
<p>I'm new to PHP and web development in general. Is this a good coding style for me as a beginner? I don't care about password hashing. I use MD5 which is, as far as I know, not a good encryption method, and I'm trying to create just the login for now.</p>
<p><strong>connection.php:</strong></p>
<pre><code><?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=akar","akar","raparen");
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
</code></pre>
<p><strong>index.php:</strong> </p>
<pre><code><?php
session_start();
include "connection.php";
if(isset($_SESSION['logged_in']) == true){
//Redirect the user to members
header("Location: member.php");
exit();
} else {
?>
<?php
}
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if(empty($username) or empty($password)) {
//Display Errors
$error = "All fields are required!";
} else {
//Verify the user
$sql = "SELECT * FROM `users` WHERE user_name = ? AND user_password = ?";
$query = $pdo->prepare($sql);
$query->bindValue(1,$username);
$query->bindValue(2,$password);
$query->execute();
if ($query->rowCount() > 0) {
//User details right
$_SESSION['logged_in'] = true;
header("Location: member.php");
} else {
//User details wrong
$error = "Wrong username or password";
}
}
}
?>
<?php if (isset($error)) { ?>
<small style="color:#aa0000; font-weight:bold;">
<?php echo $error; ?>
</small>
<?php } ?>
</code></pre>
<p><strong>member.php:</strong></p>
<pre><code><?php
session_start();
if($_SESSION['logged_in']) {
echo "You're logged in";
} else {
header("Location: index.php");
}
?>
<a href="logout.php">Logout</a>
</code></pre>
<p><strong>logout.php</strong></p>
<pre><code><?php
session_start();
session_destroy();
header("Location: index.php");
?>
</code></pre>
<p>Here is my form:</p>
<pre><code> <form action="index.php" method="POST" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" name="submit" value="Login" />
</form>
</code></pre>
| [] | [
{
"body": "<p>Here are few things I observed:</p>\n\n<ol>\n<li><p>You repeated <code>session_start()</code> twice in your <code>member.php</code> - you can only do that once in order to start the session</p></li>\n<li><p>You are not sanitizing your input for bad values - its best practice to do so to avoid SQL injection - however as a beginner its a good idea that you started with <code>PDO</code> and not legacy <code>mysql_query</code></p></li>\n<li><p>After a redirect you should <code>exit();</code> because your script will continue to process until end of the file. Why let a script continue when you're done.</p></li>\n<li><p>I know you are trying to section your code but if PHP code continues don't close it un-necessarily. (referring to <code>index.php</code> and to the <code>if</code> error part).</p></li>\n<li><p>You should use <code>require</code> or <code>require_once</code>. <code>include</code> causes an error if <code>include</code> is invoked (by mistake) more than one time.</p></li>\n<li><p>Last observation would be in your <code>member.php</code> it should be a blacklist <code>if</code> and not <code>if</code>/<code>else</code>. You should basically tell the user that you shouldn't be here if you are not logged in..if not just proceed to the rest of the script (ask question if you didn't understand this part)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:25:54.720",
"Id": "77854",
"Score": "0",
"body": "Oh, Sorry. for #1 the repeated session_start was for login.php. edited the post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:39:39.893",
"Id": "77859",
"Score": "0",
"body": "@AkarMuhamad I will edit my post with one more notice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:18:08.613",
"Id": "44766",
"ParentId": "44764",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44766",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:04:38.340",
"Id": "44764",
"Score": "5",
"Tags": [
"php",
"beginner",
"html"
],
"Title": "Trying to create login"
} | 44764 |
<p>I created a linked server in SSMS so that I could run reports on a SpiceWorks SQLite database. there are a few quirks in the whole system.</p>
<p>These simple queries are becoming some of the most expensive queries on my reporting SQL Server, I kind of know why, is there a way that I can do this differently?</p>
<hr>
<h3>The Code</h3>
<p>I have two queries.</p>
<ol>
<li><p>TimeToCloseByAssignee </p>
<pre><code>SELECT
id AS ticketNum
, Summary
, Assignee
, closed_at
, created_at
, ROUND((DATEDIFF(Hour, created_at, closed_at))/24. , 2) AS DaysOpen
FROM OPENQUERY(SPICEWORKS,'
SELECT tickets.id
, users.email as Assignee
, substr(tickets . summary, 1,100) AS Summary
, tickets.closed_at
, tickets.created_at
FROM tickets
INNER JOIN users ON tickets.assigned_to = users.id
WHERE status=''closed''
AND
master_ticket_id IS NULL;')
</code></pre></li>
<li><p>GetCreatorByTicketID</p>
<pre><code>SELECT * FROM OPENQUERY(SPICEWORKS, '
SELECT users.email
, tickets.id
FROM tickets
INNER JOIN users ON tickets.created_by = users.id')
WHERE id = @TicketID
</code></pre></li>
</ol>
<p>I am using SSRS to handle the nice presentation of the data.</p>
<p>the problem with this, is that I can't give the underlying SQLite query boundaries from SSRS Parameters, it just doesn't like it. There are some questions on StackOverflow with answers and ways to do it, but this was the only way that I could make it work the way I wanted it to. perhaps I wasn't interpreting the answers correctly. either way I don't think it would have been clean and straightforward anyway.</p>
<p>Any thoughts? </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:14:41.123",
"Id": "77874",
"Score": "0",
"body": "Just a minor suggestion, but maybe you could specify the columns to retrieve from the second query."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:28:26.350",
"Id": "77879",
"Score": "1",
"body": "I mean, instead of using `SELECT *`, write the column names (http://stackoverflow.com/questions/1867946/sql-wildcard-performance-overhead). I'm well aware it's probably the least of the problems, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:31:38.547",
"Id": "77881",
"Score": "0",
"body": "why would I type more code that could contain bugs than I have to? @ArthurChamz ? I don't need to write out all the column names, this is a pass-through query. I know what I am getting, and it is going straight into a report from here. I don't need more places where my dumb fingers can mistype something and cause issues on this. thanks I like the idea but it isn't a good one (if that makes sense)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T15:30:32.277",
"Id": "78125",
"Score": "0",
"body": "@ArthurChamz, I would agree with you if I was only writing the query in one spot, but I need all the fields that I select from the SQLite database and that won't change in this case"
}
] | [
{
"body": "<p>Ouch.... you are not filtering the data you are selecting from the OPENQUERY source....</p>\n\n<p>But, let's get some things straight first.... you say:</p>\n\n<blockquote>\n <p>either way I don't think it would have been clean and straightforward anyway</p>\n</blockquote>\n\n<p>Using OPENQUERY automatically excludes any pretext of <em>'clean and straightforward'</em>. They are incompatible.</p>\n\n<p>So, as soon as you use OPENQUERY you can assume that you have already got ugly code (with a fat ass).</p>\n\n<p>The trick is to use makeup - to cover up the blemishes.</p>\n\n<p>In this case, you <em>can</em> filter the records, but you need to be creative.... you have:</p>\n\n<blockquote>\n<pre><code>SELECT * FROM OPENQUERY(SPICEWORKS, '\n SELECT users.email\n , tickets.id\n FROM tickets\n INNER JOIN users ON tickets.created_by = users.id')\nWHERE id = @TicketID\n</code></pre>\n</blockquote>\n\n<p>I would suggest the following:</p>\n\n<pre><code>declare @ticketsql as nvarchar(1024)\n;\n\nset @ticketsql = '\n SELECT users.email\n , tickets.id\n FROM tickets\n INNER JOIN users ON tickets.created_by = users.id\n WHERE tickets.id = ' + @TicketID\n;\n\nselect * FROM OPENQUERY(SPICEWORKS, @ticketsql)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:43:51.333",
"Id": "77865",
"Score": "0",
"body": "I tried this and couldn't get it to work, but I use a `VARCHAR(8000)` and not a `NVARCHAR(1024)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:47:03.430",
"Id": "77867",
"Score": "0",
"body": "I am going to try nesting queries to get rid of the second query altogether."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:22:47.643",
"Id": "77876",
"Score": "0",
"body": "it doesn't like that @rolfl, says `Incorrect syntax near '@TicketID`, Expecting STRING, or TEXT_LEX.`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:25:54.677",
"Id": "77878",
"Score": "0",
"body": "`Convert(NVarchar(50), @TicketID)` instead when doing the concatenation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:35:22.663",
"Id": "77882",
"Score": "0",
"body": "`OPENQUERY` doesn't like being passed a Variable there @rolfl if I just put a string in there without the reference to a parameter it still doesn't like it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:48:38.400",
"Id": "77886",
"Score": "0",
"body": "I found a way to get rid of the one query, but I have no way of restricting the Date range if I want to go that route. I will have to do it on the returned set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:37:06.693",
"Id": "77934",
"Score": "0",
"body": "I wonder why this doesn't work for me?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:37:11.813",
"Id": "44769",
"ParentId": "44767",
"Score": "6"
}
},
{
"body": "<p>I was able to remove the second query and merge it with the first one like this, I don't know why I didn't try it like this to begin with, probably because I wanted to tread lightly on this shaky bridge. I still don't have a solid way of passing variables to the <code>OPENQUERY</code>, but that is a question perhaps for StackOverflow when I have more time to work on this project.</p>\n\n<h1>Code:</h1>\n\n<pre><code>SELECT \n id AS ticketNum\n , Summary\n , Assignee\n , closed_at\n , created_at\n , Round((DATEDIFF(HOUR,created_at, closed_at))/24. , 2) AS DaysOpen\n , Creator\nFROM OPENQUERY(SPICEWORKS, '\n SELECT tickets.id\n , users.email AS Assignee\n , substr(tickets . summary, 1,100) AS Summary\n , tickets.closed_at\n , tickets.created_at\n , table2.email AS Creator\n FROM\n tickets\n INNER JOIN users ON tickets.assigned_to = users.id\n INNER JOIN users AS table2 ON tickets.created_by = table2.id \n WHERE tickets.status = ''closed'' AND tickets.master_ticket_id IS NULL;')\n</code></pre>\n\n<p>what I did here was turn the other query into a separate join to the <code>users</code> table but joined the aliased table on another field in the <code>tickets</code> table. this way I can get both the creator and the assigned user (<code>Assignee</code>) from this single query. </p>\n\n<p>getting rid of the second Query reduced the amount of queries to the SQLite database to just one, the other way was executing the second query an outrageous amount of times because the second query would run once for every row in the first query, <strong>THIS IS HORRIBLY INEFFICIENT</strong>, do not do this unless you absolutely have to.</p>\n\n<p>I should have explained more, the second query had to be a sub-report of the first one in order for it to work the way I wanted it to. I didn't think I could alias tables in a query run this way, I wasn't fully qualifying the names of all my columns once I put an alias in, and that is why I didn't do that the first go round, but now I know that I can do this on SQLite as long as I fully qualify all the columns I select in the query run on the SQLite database </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:55:26.110",
"Id": "44773",
"ParentId": "44767",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44773",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:22:40.560",
"Id": "44767",
"Score": "10",
"Tags": [
"sql",
"sql-server",
"sqlite"
],
"Title": "Another way to run reports on a SpiceWorks SQLite database using a linked server in SSMS?"
} | 44767 |
<p>I have two queries; one runs <em>significantly</em> faster than the other, but the faster one is the one that I would have bet money on to be less efficient. These are both being executed through a front end C# console based application and are stored as procedures in SQL Server 2008 R2.</p>
<p>Basically, I have the first one I wrote, which is depreciating a store VIEW that I didn't think needed to be there any more, and the second one, which was replacing the VIEW in a store procedure that I had. What I don't get, is the second one is about 15 times faster, as in, it executes instantaneously and the other takes about 15 seconds</p>
<p>Is this something I don't know about T-SQL or just a fluke? Anyone able to drop some knowledge on me and possibly help me speed up some similar queries in the future?</p>
<p>The only real difference is that the faster one is making a table and selecting from it, where as the slower one is just making the table! It doesn't make sense that when you just make the table it takes longer than making and querying it... or does it? Info on this would be awesome if nothing else for my own personal knowledge. </p>
<hr>
<h3>Slower, but significantly smaller query <em>(this replaced the view that was being stored)</em>:</h3>
<pre><code>SELECT DISTINCT [ModelRequests].[RequestID] AS 'Request ID',
([usr_].[firstname] + ' ' + [usr_].[lastname]) AS 'Full Name',
[usr_].[company_name] AS 'Company Name',
[usr_].[city] AS 'City',
[usr_].[state] AS 'State',
ISNULL([Branch].[BranchName], [BranchCanada].[BranchName]) AS 'Branch Name',
ISNULL([Branch].[BranchID], [BranchCanada].[BranchID]) AS 'Branch ID',
LEFT((REPLACE (REPLACE([Zip], ' ', ''), '-', '')), 6) AS 'Zip'
FROM [Products].[dbo].[Requests] [Requests]
LEFT JOIN [HOST].[dbo].[usr] [usr] ON
CONVERT(varchar(50), [usr].[user_id]) = [ModelRequests].[username]
LEFT JOIN [Location].[dbo].[CountryToContinent] [CountryToContinent]
ON [CountryToContinent].[CountryCode] = [usr].[country]
LEFT JOIN [Location].[dbo].[Continent] [Continent]
ON [Continent].[ContinentCode] = [CountryToContinent].[ContinentCode]
LEFT JOIN [Location].[dbo].[ZipCode] [ZipCode]
ON [ZipCode].[ZipCode] = [usr].[zip]
LEFT JOIN [Location].[dbo].[Branch] [Branch]
ON [Branch].[BranchID] = [ZipCode].[BranchID]
LEFT JOIN [Location].[dbo].[ZipCode] [ZipCodeCanada]
ON LEFT([ZipCodeCanada].[ZipCode], 3) = LEFT([usr].[zip], 3)
LEFT JOIN [Location].[dbo].[Branch] [BranchCanada]
ON [BranchCanada].[BranchID] = [ZipCodeCanada].[BranchID]
WHERE ([ModelRequests].[cached] IN (1) OR
[ModelRequests].[cached] IS NULL) AND
[ModelRequests].[RequestDateTime] BETWEEN @DateStart AND @DateEnd
OPTION (OPTIMIZE FOR (@DateStart UNKNOWN , @DateEnd UNKNOWN));
</code></pre>
<h3>Larger query that runs insanely fast:</h3>
<pre><code>DECLARE @DateStart datetime,
@DateEnd datetime
SELECT [Request ID]
,[Full Name]
,[Company Name]
,[City]
,[State]
,[Branch Name]
,[Branch ID]
,[Zip]
FROM (SELECT DISTINCT [ModelRequests].[RequestID] AS 'Request ID',
([usr_].[firstname] + ' ' + [usr_].[lastname]) AS 'Full Name',
[usr_].[company_name] AS 'Company Name',
[usr_].[city] AS 'City',
[usr_].[state] AS 'State',
ISNULL([Branch].[BranchName], [BranchCanada].[BranchName]) AS 'Branch Name',
ISNULL([Branch].[BranchID], [BranchCanada].[BranchID]) AS 'Branch ID',
LEFT((REPLACE (REPLACE([Zip], ' ', ''), '-', '')), 6) AS 'Zip'
FROM [Products].[dbo].[Requests] [Requests]
LEFT JOIN [HOST].[dbo].[usr] [usr] ON
CONVERT(varchar(50), [usr].[user_id]) = [ModelRequests].[username]
LEFT JOIN [Location].[dbo].[CountryToContinent] [CountryToContinent]
ON [CountryToContinent].[CountryCode] = [usr].[country]
LEFT JOIN [Location].[dbo].[Continent] [Continent]
ON [Continent].[ContinentCode] = [CountryToContinent].[ContinentCode]
LEFT JOIN [Location].[dbo].[ZipCode] [ZipCode]
ON [ZipCode].[ZipCode] = [usr].[zip]
LEFT JOIN [Location].[dbo].[Branch] [Branch]
ON [Branch].[BranchID] = [ZipCode].[BranchID]
LEFT JOIN [Location].[dbo].[ZipCode] [ZipCodeCanada]
ON LEFT([ZipCodeCanada].[ZipCode], 3) = LEFT([usr].[zip], 3)
LEFT JOIN [Location].[dbo].[Branch] [BranchCanada]
ON [BranchCanada].[BranchID] = [ZipCodeCanada].[BranchID]
WHERE ([ModelRequests].[cached] IN (1) OR
[ModelRequests].[cached] IS NULL) AND
[ModelRequests].[RequestDateTime] BETWEEN @DateStart AND @DateEnd) AS [LeadsGeneration_ViewAllModelRequests]
WHERE [LeadsGeneration_ViewAllModelRequests].[Request Date Time] BETWEEN @DateStart AND @DateEnd
OPTION (OPTIMIZE FOR (@DateStart UNKNOWN , @DateEnd UNKNOWN));
</code></pre>
<hr>
<h3>Execution Plan For Fast Query</h3>
<p><img src="https://i.stack.imgur.com/tR7iP.png" alt="enter image description here"></p>
<hr>
<p><img src="https://i.stack.imgur.com/aD5Vd.png" alt="enter image description here"></p>
<hr>
<p><img src="https://i.stack.imgur.com/ZBOVR.png" alt="enter image description here"></p>
<hr>
<p><img src="https://i.stack.imgur.com/JZycc.png" alt="enter image description here"></p>
<h3>Execution Plan for Slow Query</h3>
<p><img src="https://i.stack.imgur.com/idPMT.png" alt="enter image description here"></p>
<hr>
<p><img src="https://i.stack.imgur.com/mCt2g.png" alt="enter image description here"></p>
<hr>
<p><img src="https://i.stack.imgur.com/I2w0n.png" alt="enter image description here"></p>
<hr>
<p><img src="https://i.stack.imgur.com/B7MkK.png" alt="enter image description here"></p>
<hr>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-08T18:36:06.780",
"Id": "314635",
"Score": "0",
"body": "there is not ModelRequests table in the queries"
}
] | [
{
"body": "<p>You have </p>\n\n<blockquote>\n<pre><code>OPTION (OPTIMIZE FOR (@DateStart UNKNOWN, @DateEnd UNKNOWN));\n</code></pre>\n</blockquote>\n\n<p>in the second query.</p>\n\n<p>Add it to the first one and see what happens, but I am guessing that it might speed that one up as well.</p>\n\n<hr>\n\n<p>This is not needed.</p>\n\n<pre><code>WHERE [LeadsGeneration_ViewAllModelRequests].[Request Date Time] BETWEEN @DateStart AND @DateEnd \n</code></pre>\n\n<p>These values will never be outside of the range between <code>@DateStart</code> and <code>@DateEnd</code> because that same expression is in the nested Select statement, so you don't even need that. <strong>It won't slow down your query</strong></p>\n\n<h2>Really the outside query isn't doing anything</h2>\n\n<p>It is just regurgitating the inside <code>SELECT</code> statement.<br>\nso that shouldn't slow it down either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:04:23.227",
"Id": "77869",
"Score": "0",
"body": "`Optimize for` was in the original query, sorry, missed it on the copy/paste. The query does run properly though, not sure which parenthesis you're referring to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:43:50.317",
"Id": "77883",
"Score": "0",
"body": "That's where you are *incorrect* though. The 2nd where increases performance! It makes no sense. Just tested it. With the redundant `where` clause... 1.018 seconds on average over 10 test runs. Without the redundant `where` clause... 3.084 seconds! Makes no sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:45:51.133",
"Id": "77884",
"Score": "0",
"body": "**Comment on Question**. something is different that you aren't showing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:52:48.307",
"Id": "77887",
"Score": "0",
"body": "Nope, all there. Just copy/paste Executed it. Query plan posted."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:56:24.030",
"Id": "44771",
"ParentId": "44770",
"Score": "7"
}
},
{
"body": "<p>Looks like your <code>SELECT DISTINCT</code> is scanning a much larger result set (resources 81% as opposed to 21%) in your slower query. Also I noticed your slower query is missing <code>DECLARE @DateStart datetime, @DateEnd datetime</code> that may affect how SQL optimizes it, for example if the SQL server was sorting and truncating out all dates outside those dates right off the bat instead of at the end perhaps, since it knows those values already? I'd be curious to add that to the slower statement and see what happens.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-16T18:31:40.213",
"Id": "50949",
"ParentId": "44770",
"Score": "3"
}
},
{
"body": "<p>try this as it gets rid of an <code>OR</code> </p>\n\n<pre><code>SELECT DISTINCT [ModelRequests].[RequestID] AS 'Request ID',\n ([usr_].[firstname] + ' ' + [usr_].[lastname]) AS 'Full Name',\n [usr_].[company_name] AS 'Company Name',\n [usr_].[city] AS 'City',\n [usr_].[state] AS 'State',\n ISNULL([Branch].[BranchName], [BranchCanada].[BranchName]) AS 'Branch Name',\n ISNULL([Branch].[BranchID], [BranchCanada].[BranchID]) AS 'Branch ID',\n LEFT((REPLACE (REPLACE([Zip], ' ', ''), '-', '')), 6) AS 'Zip'\n\n FROM [Products].[dbo].[Requests] [ModelRequests]\n\n LEFT JOIN [HOST].[dbo].[usr] [usr] ON\n CONVERT(varchar(50), [usr].[user_id]) = [ModelRequests].[username]\n\n LEFT JOIN [Location].[dbo].[CountryToContinent] [CountryToContinent]\n ON [CountryToContinent].[CountryCode] = [usr].[country]\n\n LEFT JOIN [Location].[dbo].[Continent] [Continent] \n ON [Continent].[ContinentCode] = [CountryToContinent].[ContinentCode]\n\n LEFT JOIN [Location].[dbo].[ZipCode] [ZipCode]\n ON [ZipCode].[ZipCode] = [usr].[zip]\n\n LEFT JOIN [Location].[dbo].[Branch] [Branch]\n ON [Branch].[BranchID] = [ZipCode].[BranchID]\n\n LEFT JOIN [Location].[dbo].[ZipCode] [ZipCodeCanada]\n ON LEFT([ZipCodeCanada].[ZipCode], 3) = LEFT([usr].[zip], 3)\n\n LEFT JOIN [Location].[dbo].[Branch] [BranchCanada]\n ON [BranchCanada].[BranchID] = [ZipCodeCanada].[BranchID]\n\n WHERE isnull([ModelRequests].[cached], 1) = 1 \n AND [ModelRequests].[RequestDateTime] BETWEEN @DateStart AND @DateEnd\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-20T21:21:27.370",
"Id": "316536",
"Score": "0",
"body": "Really a DV for this?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-08T18:36:55.970",
"Id": "165284",
"ParentId": "44770",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:45:32.983",
"Id": "44770",
"Score": "7",
"Tags": [
"performance",
"sql",
"sql-server",
"t-sql"
],
"Title": "Inefficient query actually more efficient?"
} | 44770 |
<p>While writing <a href="https://codereview.stackexchange.com/a/44090/9357">this review</a>, I saw a need for a <code>Counter</code> object similar to <a href="http://docs.python.org/3.3/library/collections.html#collections.Counter" rel="noreferrer">Python's</a>. It seemed like it would be easy to write such a class, but it turned out to be surprisingly complicated.</p>
<h3>Counter.java</h3>
<pre><code>import java.util.*;
public class Counter<T> implements Map<T, Integer>,
Iterable<Map.Entry<T, Integer>> {
private final Map<T, Integer> c = new HashMap<T, Integer>();
/**
* Comparator to sort entries by decreasing count. In case of a tie,
* arbitrary but deterministic tie-breakers are used.
*/
private final Comparator<Map.Entry<T, Integer>> DESC_FREQ_COMPARATOR =
new Comparator<Map.Entry<T, Integer>>() {
@Override
public int compare(Map.Entry<T, Integer> a, Map.Entry<T, Integer> b) {
int aValue = a.getValue().intValue();
int bValue = b.getValue().intValue();
int diff;
if (0 != (diff = bValue - aValue)) {
return diff;
} else if (0 != (diff = b.hashCode() - a.hashCode())) {
return diff;
} else {
T aKey = a.getKey();
T bKey = b.getKey();
if (aKey == null && bKey == null) {
return 0;
} else if (aKey == null) {
return 1;
} else if (bKey == null) {
return -1;
} else if (bKey instanceof Comparable) {
@SuppressWarnings("unchecked")
Comparable<T> bKeyCmp = (Comparable<T>)bKey;
return bKeyCmp.compareTo(aKey);
} else {
return bKey.toString().compareTo(aKey.toString());
}
}
}
};
/**
* Creates an empty counter.
*/
public Counter() {}
/**
* Copy constructor.
*/
public Counter(Map<T, Integer> counter) {
this();
this.putAll(counter);
}
/**
* Returns the number of key-value mappings in this map, including entries
* that have a zero count.
*/
@Override
public int size() {
return this.c.size();
}
/**
* Returns whether there are no entries. Any entry, even an entry with a
* zero count, makes the counter non-empty.
*/
public boolean isEmpty() {
return this.c.isEmpty();
}
/**
* Returns whether the key exists. A key with a zero count exists until it
* is removed or the entire counter is cleared.
*/
@Override
public boolean containsKey(Object key) {
return this.c.containsKey(key);
}
/**
* Returns whether any key has the specified count.
*/
@Override
public boolean containsValue(Object integralNumber) {
return integralNumber instanceof Number &&
this.c.containsValue(((Number)integralNumber).intValue());
}
/**
* Returns whether any key has the specified count.
*/
public boolean containsValue(int value) {
return this.c.containsValue(value);
}
/**
* Returns the value to which the specified key is mapped, or null if this
* map contains no mapping for the key.
*/
@Override
public Integer get(Object key) {
Integer i = this.c.get(key);
return i == null ? 0 : i.intValue();
}
/**
* Sets the count for a key.
*/
@Override
public Integer put(T key, Integer value) {
Integer prev = this.c.put(key, value);
return (prev == null) ? 0 : prev;
}
/**
* Removes a key.
*/
@Override
public Integer remove(Object key) {
Integer prev = this.c.remove(key);
return (prev == null) ? 0 : prev;
}
@Override
public void putAll(Map<? extends T, ? extends Integer> m) {
for (Map.Entry<? extends T, ? extends Integer> entry : m.entrySet()) {
this.put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
this.c.clear();
}
/**
* Returns the keys in an arbitrary order.
*/
@Override
public Set<T> keySet() {
return this.c.keySet();
}
/**
* Returns the values in an arbitrary order.
*/
@Override
public Collection<Integer> values() {
return this.c.values();
}
/**
* Compares the specified object with this map for equality. Returns true
* if the given object is also a map and the two maps have the same
* counts.
*
* For this equality test, an entry with a zero count is treated the same
* as no entry at all.
*/
public boolean equals(Object o) {
if (!(o instanceof Counter) || this.hashCode() != o.hashCode()) {
return false;
}
Counter other = (Counter)o;
Map.Entry<T, Integer>[] a = this.mostCommon();
@SuppressWarnings("unchecked")
Map.Entry<?, Integer>[] b = other.mostCommon();
int i = 0;
for (; i < Math.min(a.length, b.length); i++) {
int aCount = (a[i] == null) ? 0 : a[i].getValue();
int bCount = (b[i] == null) ? 0 : b[i].getValue();
if (aCount == 0 && bCount == 0) {
return true;
} else if (aCount != bCount) {
return false;
}
Object aKey = a[i].getKey();
Object bKey = b[i].getKey();
if (!aKey.equals(bKey)) {
return false;
}
}
// Nothing left over
int aCount = (i >= a.length || a[i] == null) ? 0 : a[i].getValue();
int bCount = (i >= b.length || b[i] == null) ? 0 : b[i].getValue();
return aCount == 0 && bCount == 0;
}
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* entrySet() view. This ensures that m1.equals(m2) implies that
* m1.hashCode()==m2.hashCode() for any two maps m1 and m2, as required by
* the general contract of Object.hashCode().
*/
@Override
public int hashCode() {
int sum = 0;
for (Map.Entry<T, Integer> e : this) {
if (e == null || e.getValue() == 0) {
break;
}
sum += e.hashCode();
}
return sum;
}
public void increment(T key, int delta) {
Integer prev = this.c.put(key, delta);
if (prev != null) {
this.c.put(key, prev + delta);
}
}
/**
* Increments the count of the specified key by 1.
*/
public void increment(T key) {
this.increment(key, 1);
}
/**
* Increments the count of each element in the collection by 1.
*/
public void increment(Collection<T> elements) {
for (T e : elements) {
this.increment(e, 1);
}
}
/**
* Increments the count of each element by some number.
*/
public void increment(Iterable<Map.Entry<T, Integer>> elements) {
for (Map.Entry<T, Integer> e : elements) {
this.increment(e.getKey(), e.getValue());
}
}
/**
* Decrements the count of the specified key by 1.
*/
public void decrement(T key) {
this.increment(key, -1);
}
/**
* Decrements the count of each element in the collection by 1.
*/
public void decrement(Collection<T> elements) {
for (T e : elements) {
this.increment(e, -1);
}
}
/**
* Decrements the count of each element by some number.
*/
public void decrement(Iterable<Map.Entry<T, Integer>> elements) {
for (Map.Entry<T, Integer> e : elements) {
this.increment(e.getKey(), -e.getValue());
}
}
/**
* Returns an iterator over <tt>entrySet()</tt>.
*/
@Override
public Iterator<Map.Entry<T, Integer>> iterator() {
return this.entrySet().iterator();
}
/**
* Returns a <tt>SortedSet</tt> of the entries in descending order of
* frequency. Entries with the same frequency are returned in an
* arbitrary order.
*/
@Override
public Set<Map.Entry<T, Integer>> entrySet() {
SortedSet<Map.Entry<T, Integer>> ss = new TreeSet<Map.Entry<T, Integer>>(DESC_FREQ_COMPARATOR);
ss.addAll(this.c.entrySet());
return ss;
}
/**
* Returns the entries in descending order of frequency. Entries with the
* same frequency are returned in an arbitrary order.
*/
public Map.Entry<T, Integer>[] mostCommon() {
return this.mostCommon(this.size());
}
/**
* Returns the <em>n</em> entries with the highest count in descending
* order of frequency. Entries with the same frequency are returned in an
* arbitrary order.
*
* @return An array of length <em>n</em>. If <em>n</em> exceeds the number
* of entries that exist, the result is padded with nulls.
*/
@SuppressWarnings("unchecked")
public Map.Entry<T, Integer>[] mostCommon(int n) {
Map.Entry[] top = new Map.Entry[n];
int i = 0;
for (Map.Entry<T, Integer> e : this) {
top[i++] = e;
if (i == n) break;
}
return (Map.Entry<T, Integer>[])top;
}
}
</code></pre>
<h3>CounterTest.java</h3>
<pre><code>import static org.junit.Assert.*;
import static org.junit.Assume.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.Map;
import java.util.Scanner;
// javac -cp .:junit.jar Counter.java CounterTest.java
// java -cp .:junit.jar:hamcrest-core.jar org.junit.runner.JUnitCore CounterTest
@RunWith(JUnit4.class)
public class CounterTest {
private static String SHAKESPEARE_CORPUS;
@BeforeClass
public static void downloadShakespeare() throws MalformedURLException {
URL shakespeare = new URL("http://norvig.com/ngrams/shakespeare.txt");
try (Scanner s = new Scanner(shakespeare.openStream(), "UTF-8")) {
SHAKESPEARE_CORPUS = s.useDelimiter("\\A").next();
} catch (IOException e) {
assertNull(SHAKESPEARE_CORPUS);
}
}
@Test
public void increment() {
Counter<String> c = new Counter<String>();
c.increment("duck");
assertEquals("One duck", 1, (int)c.get("duck"));
c.increment("duck");
c.increment("goose");
assertEquals("Two ducks", 2, (int)c.get("duck"));
assertEquals("One goose", 1, (int)c.get("goose"));
assertEquals("No pheasant", 0, (int)c.get("pheasant"));
}
@Test
public void incrementCollectionRemoveCopy() {
Counter<String> c = new Counter<String>();
c.increment(Arrays.asList(new String[] { "duck", "duck", "goose" }));
assertEquals("Two ducks", 2, (int)c.get("duck"));
assertEquals("One goose", 1, (int)c.get("goose"));
assertEquals("No pheasant", 0, (int)c.get("pheasant"));
Counter<String> cc = new Counter<String>(c);
c.remove("goose");
assertEquals("No goose", 0, (int)c.get("goose"));
assertEquals("Two ducks", 2, (int)cc.get("duck"));
assertEquals("One goose", 1, (int)cc.get("goose"));
assertEquals("No pheasant", 0, (int)cc.get("pheasant"));
}
@Test
public void incrementPutSubtractRemove() {
Counter<String> c = new Counter<String>();
c.increment("duck");
assertEquals("One duck", 1, (int)c.get("duck"));
c.increment("duck", 98);
assertEquals("99 ducks", 99, (int)c.get("duck"));
c.put("duck", 200);
assertEquals("200 ducks", 200, (int)c.get("duck"));
c.increment("duck", -50);
assertEquals("150 ducks", 150, (int)c.get("duck"));
c.remove("duck");
assertEquals("No duck", 0, (int)c.get("duck"));
}
@Test
public void nullSemantics() {
Counter<Integer> c = new Counter<Integer>();
assertFalse("does not contain key null", c.containsKey(null));
assertFalse("does not contain value 0", c.containsValue(0));
c.put(null, 0);
assertEquals("0 nulls", 0, (int)c.get(null));
assertTrue("contains key null", c.containsKey(null));
assertTrue("contains value 0", c.containsValue(0));
c.increment((Integer)null);
assertEquals("1 null", 1, (int)c.get(null));
assertTrue("contains key null", c.containsKey(null));
assertTrue("contains value 1", c.containsValue(1));
c.decrement((Integer)null);
assertEquals("no nulls", 0, (int)c.get(null));
assertTrue("contains key null", c.containsKey(null));
assertTrue("contains value 0", c.containsValue(0));
assertFalse("contains no value 1", c.containsValue(1));
}
@Test
public void mostCommon() {
Counter<String> c = new Counter<String>();
c.increment(Arrays.asList(new String[] { "duck", "duck", "goose" }));
Map.Entry<String, Integer>[] common = c.mostCommon();
assertEquals("2 entries", 2, common.length);
assertEquals("2 ducks first", "duck", common[0].getKey());
assertEquals("2 ducks first", 2, (int)common[0].getValue());
assertEquals("1 goose last", "goose", common[1].getKey());
assertEquals("1 goose last", 1, (int)common[1].getValue());
}
@Test
public void mostCommonTooMany() {
Counter<String> c = new Counter<String>();
c.increment("duck");
Map.Entry<String, Integer>[] common = c.mostCommon(3);
assertEquals("3 entries", 3, common.length);
assertEquals("1 duck first", "duck", common[0].getKey());
assertNull("null", common[1]);
assertNull("null", common[2]);
}
@Test
public void emptinessAndSizeSemantics() {
Counter<Integer> c = new Counter<Integer>();
assertTrue("new counter is empty", c.isEmpty());
assertEquals("new counter has 0 entries", 0, c.size());
c.put(0, 1);
assertFalse("entry makes it non-empty", c.isEmpty());
assertEquals("(0, 1) has 1 entry", 1, c.size());
c.decrement(0);
assertFalse("entry with zero count makes it non-empty", c.isEmpty());
assertEquals("(0, 0) has 1 entry", 1, c.size());
c.remove(0);
assertTrue("removed sole entry makes it empty", c.isEmpty());
assertEquals("removed sole entry has 0 entries", 0, c.size());
c.increment((Integer)null);
assertFalse("null entry makes it non-empty", c.isEmpty());
c.clear();
assertTrue("clearing makes it empty", c.isEmpty());
}
@Test
public void equality() {
Counter<String> a = new Counter<String>();
Counter<String> b = new Counter<String>();
assertEquals("nothing == nothing", a, b);
a.increment("duck");
assertNotEquals("1 duck != nothing", a, b);
a.decrement("duck");
a.put(null, 0);
assertEquals("0 duck + 0 null == nothing", a, b);
assertEquals("nothing == 0 duck + 0 null", b, a);
b.put("goose", 2);
assertNotEquals("0 duck != 2 geese", a, b);
a.increment("goose", 2);
assertEquals("2 geese + 0 duck == 2 geese", a, b);
assertEquals("2 geese == 2 geese + 0 duck", b, a);
}
@Test(timeout=500)
public void performance() throws IOException {
Counter<String> c = new Counter<String>();
assumeTrue(null != SHAKESPEARE_CORPUS);
StreamTokenizer tok = new StreamTokenizer(new StringReader(SHAKESPEARE_CORPUS));
tok.ordinaryChar('\'');
tok.ordinaryChar('"');
int type;
String word = "Ophelia";
int KNOWN_COUNT = 19, myCount = 0;
while (StreamTokenizer.TT_EOF != (type = tok.nextToken())) {
if (StreamTokenizer.TT_WORD == type) {
c.increment(tok.sval);
if (word.equals(tok.sval)) {
myCount++;
}
}
}
assumeTrue(KNOWN_COUNT == myCount);
assertEquals(word, myCount, (int)c.get(word));
}
}
</code></pre>
<p>Please critique both the <code>Counter</code> and its unit tests in general.</p>
<p>Some concerns I have include:</p>
<ol>
<li>Is there a common Java library that serves a similar purpose, or am I <a href="/questions/tagged/reinventing-the-wheel" class="post-tag" title="show questions tagged 'reinventing-the-wheel'" rel="tag">reinventing-the-wheel</a>?</li>
<li>Are the semantics for <code>null</code> keys and zero counts reasonable?</li>
<li>Is it useful to implement the <code>Map<T, Integer></code> and <code>Iterable</code> interfaces? Or does that unnecessarily complicate things?</li>
<li>I wrote many <code>increment()</code> and <code>decrement()</code> methods. Do they make the class convenient to use, or are they too redundant?</li>
<li>What do you think of the method signatures for <code>mostCommon()</code> and <code>mostCommon(int)</code>? Is there too much redundancy with <code>entrySet()</code> and <code>iterator()</code>?</li>
<li>I had to use <code>@SuppressWarnings("unchecked")</code> in three places. How can I avoid those warnings in the first place?</li>
<li>I increment a count using two calls to <code>put()</code> of a <code>HashMap</code>. Is there a more efficient way?</li>
<li>To support <code>entrySet()</code> and <code>mostCommon()</code>, I build a <code>SortedSet</code> from scratch. Is there a better data structure I could have used that could support <code>entrySet()</code> and <code>mostCommon()</code> efficiently?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T10:09:54.487",
"Id": "78041",
"Score": "1",
"body": "NB: This data structure is generally known as a [Multiset or Bag](http://en.wikipedia.org/wiki/Set_(abstract_data_type)#Multiset)."
}
] | [
{
"body": "<blockquote>\n <p>Is there a common Java library that serves a similar purpose, or am I\n reinventing-the-wheel?</p>\n</blockquote>\n\n<p>As far as I know the JRE doesn't offer this out of the box.</p>\n\n<blockquote>\n <p>Are the semantics for null keys and zero counts reasonable?</p>\n</blockquote>\n\n<p>Would it be typical to be counting <code>null</code>s? I guess it's nice that it's possible, even though it opens the possibility for exceptions. Personally I'd disallow it.</p>\n\n<p>What is reasonable is that getting a count for keys that are not present, simply returns 0.</p>\n\n<blockquote>\n <p>Is it useful to implement the <code>Map<T, Integer></code> and <code>Iterable</code> interfaces?\n Or does that unnecessarily complicate things?</p>\n</blockquote>\n\n<p>Implementing the Map interface is unnecessary, it requires a lot of code that adds nothing to the intended responsibility of this class. In fact you do not fully abide to the Map interface contract. Honoring the Single Responsibility Principle mandates dropping this.</p>\n\n<p>Implementing the <code>Iterable</code> interface is way more useful, as it exposes the results in a standard way.</p>\n\n<blockquote>\n <p>I wrote many <code>increment()</code> and <code>decrement()</code> methods. Do they make the\n class convenient to use, or are they too redundant?</p>\n</blockquote>\n\n<p>I would extract an interface from this class that captures its API, and you can make alternative implementations later on as needed.</p>\n\n<pre><code>public interface Counter<T> extends Iterable<Map.Entry<T, Integer>> {\n void increment(T key);\n\n void decrement(T key);\n\n int getCount(T key);\n\n Set<T> getKeys();\n}\n</code></pre>\n\n<p>I would even replace <code>Map.Entry<T, Integer></code> by a <code>Counter</code> specific interface. </p>\n\n<p>Try to resist the urge to add convenience methods, You can always use the Decorator pattern to add candy as needed. In the mean time focus on making a great core implementation.</p>\n\n<blockquote>\n <p>What do you think of the method signatures for <code>mostCommon()</code> and\n <code>mostCommon(int)</code>? Is there too much redundancy with <code>entrySet()</code> and\n <code>iterator()</code>?</p>\n</blockquote>\n\n<p>These are superfluous, again decorators are the way to go in this case.</p>\n\n<blockquote>\n <p>I had to use <code>@SuppressWarnings(\"unchecked\")</code> in three places. How can I\n avoid those warnings in the first place?</p>\n</blockquote>\n\n<p>First occurrence is :</p>\n\n<pre><code>CounterImpl other = (CounterImpl)o;\nMap.Entry<T, Integer>[] a = this.mostCommon();\n@SuppressWarnings(\"unchecked\")\nMap.Entry<?, Integer>[] b = other.mostCommon();\n</code></pre>\n\n<p>You declare the <code>other</code> variable without type parameter. Rule 1 to avoiding unchecked warnings is to specify the type parameter on classes that have one. After all, the only reason you can omit them, is that this was needed for backwards compatibility when generics were introduced.</p>\n\n<pre><code>CounterImpl<?> other = (CounterImpl)o;\nMap.Entry<T, Integer>[] a = this.mostCommon();\nMap.Entry<?, Integer>[] b = other.mostCommon();\n</code></pre>\n\n<p>A likewise case happens in <code>mostCommon()</code></p>\n\n<p>Next case :</p>\n\n<pre><code>} else if (bKey instanceof Comparable) {\n @SuppressWarnings(\"unchecked\")\n Comparable<T> bKeyCmp = (Comparable<T>)bKey;\n</code></pre>\n\n<p>Reflection code and generics is bound to get you into trouble with unchecked warnings. In fact this cast actually isn't safe when <code>T</code> implements <code>Comparable<S></code> where <code>S</code> is a supertype of <code>T</code>.</p>\n\n<blockquote>\n <p>I increment a count using two calls to <code>put()</code> of a <code>HashMap</code>. Is there a\n more efficient way?</p>\n</blockquote>\n\n<p>Yes there is. Instead of using <code>Integer</code> as the value in your <code>Map</code>, use a mutable count representation. You can easily write one yourself, or use <code>AtomicInteger</code> (although you may not need the thread safety). Then define :</p>\n\n<pre><code>private final Map<T, AtomicInteger> c = new HashMap<T, AtomicInteger>();\n</code></pre>\n\n<p>Now you'll only need to do a put if the key isn't in the <code>Map</code> yet :</p>\n\n<pre><code>public void increment(T key, int delta) {\n Integer prev = this.c.put(key, delta);\n if (!c.containsKey(key)) {\n c.put(key, new AtomicInteger());\n }\n c.get(key).addAndGet(delta);\n}\n</code></pre>\n\n<p>In java 8 it becomes even simpler using <code>java.util.Map#computeIfAbsent</code></p>\n\n<pre><code>c.computeIfAbsent(key, k -> new AtomicInteger()).addAndGet(delta);\n</code></pre>\n\n<blockquote>\n <p>To support <code>entrySet()</code> and <code>mostCommon()</code>, I build a <code>SortedSet</code> from\n scratch. Is there a better data structure I could have used that could\n support <code>entrySet()</code> and <code>mostCommon()</code> efficiently?</p>\n</blockquote>\n\n<p>Why not use a <code>SortedMap</code> internally?</p>\n\n<pre><code>private final Map<T, Integer> c = new TreeMap<T, Integer>(DESC_FREQ_COMPARATOR);\n</code></pre>\n\n<p>this way <code>c.entrySet()</code> will return a set of which the iterator will return the keys in order. Although this <code>Set</code> isn't actually a <code>SortedSet<T></code> it probably fulfills what you need anyway.</p>\n\n<hr>\n\n<p>General remarks : </p>\n\n<p><strong>Counter</strong></p>\n\n<ul>\n<li>avoid abbreviations as variable names.</li>\n</ul>\n\n<p><strong>CounterTest</strong></p>\n\n<ul>\n<li>write seperate tests per assertion : e.g. equality() can be split into 7 different tests. You'll find that you won't need the String argument in your assertions any more.</li>\n<li>do performance tests in a different class than your unit tests. Unit tests should be as lightweight as possible.</li>\n</ul>\n\n<hr>\n\n<p>Finally consider how I would approach this (JDK8) </p>\n\n<p>EDIT : updated this code to use LongAdder instead of AtomicInteger, as LongAdder performs even better than AtomicInteger for this case.</p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.LongAdder;\nimport java.util.stream.Collectors;\n\npublic interface Counter<T> extends Iterable<Counter.Count<T>> {\n void increment(T key);\n\n void decrement(T key);\n\n int getCount(T key);\n\n Set<T> getKeys();\n\n interface Count<T> {\n T getKey();\n\n int getCount();\n }\n}\n\nclass SimpleCounter<T> implements Counter<T> {\n public static final LongAdder DEFAULT_VALUE = new LongAdder();\n\n private final Map<T, LongAdder> counts = new HashMap<>();\n\n @Override\n public void increment(T key) {\n counts.computeIfAbsent(key, k -> new LongAdder()).increment();\n }\n\n @Override\n public void decrement(T key) {\n counts.computeIfAbsent(key, k -> new LongAdder()).decrement();\n }\n\n @Override\n public int getCount(T key) {\n return counts.getOrDefault(key, DEFAULT_VALUE).intValue();\n }\n\n @Override\n public Set<T> getKeys() {\n return counts.keySet();\n }\n\n @Override\n public Iterator<Count<T>> iterator() {\n return counts.entrySet().stream().map(e -> new SimpleCount<T>(e)).collect(Collectors.<Count<T>>toSet()).iterator();\n }\n\n private static class SimpleCount<E> implements Count<E> {\n private final Map.Entry<E, LongAdder> entry;\n\n SimpleCount(Map.Entry<E, LongAdder> entry) {\n this.entry = entry;\n }\n\n @Override\n public E getKey() {\n return entry.getKey();\n }\n\n @Override\n public int getCount() {\n return entry.getValue().intValue();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:40:48.520",
"Id": "77917",
"Score": "0",
"body": "The `TreeMap` would not rearrange itself when the `AtomicInteger` mutates, would it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:42:06.093",
"Id": "77918",
"Score": "0",
"body": "I believe I'm obligated to implement `.equals(Object other)` rather than `.equals(Counter<T> other)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:45:32.303",
"Id": "77920",
"Score": "0",
"body": "TreeMap is sorted by keys, not by values. If you introduce the Count interface I suggested, you can make that Comparable, and you can simply sort those, or use max()/min()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:46:30.400",
"Id": "77921",
"Score": "0",
"body": "You're obligated to implement equals(Object), but only if you implement the Map interface. Personally I wouldn't bother about equality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:01:12.603",
"Id": "77926",
"Score": "0",
"body": "`TreeMap` wouldn't be able to work with `DESC_FREQ_COMPARATOR`, then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-30T18:09:48.057",
"Id": "90228",
"Score": "0",
"body": "Since you are suggesting Java 8 either way (which is great!), I'd urge you to also incorporate `LongAdder` in the answer. It's essentially the new `AtomicInteger` when you are only adding and retrieving."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-31T15:35:49.730",
"Id": "90320",
"Score": "1",
"body": "@skiwi : I have updated the answer. I had only learnt about the new `LongAdder` class after I've submitted this answer, and I hadn't gone back to it since. Thanks for pointing out the possible improvement."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:34:35.733",
"Id": "44784",
"ParentId": "44772",
"Score": "17"
}
},
{
"body": "<p><code>containsValue()</code> can return true when you pass in a <code>Double</code> that isn't a whole number. The implementation should be equivalent to the following for any value.</p>\n\n<pre><code>public boolean containsValue(Object integralNumber) {\n for (Integer i : values()) {\n if (i.equals(integralNumber) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p>Your documentation matches that of the <code>Map</code> interface, not what the <code>Counter</code> is actually doing. Example: <code>get()</code> never returns <code>null</code>.</p>\n\n<hr>\n\n<p>Is there a reason <code>mostCommon()</code> returns an array instead of a <code>List</code>? Everything else lines up with the collections library, so this seems out of place.</p>\n\n<hr>\n\n<p>Your tests are doing edit-check-repeat. This can hide information about what the bug is. When the first assert in <code>equality()</code> fails, you only know that two empty counters aren't equivalent. However, if you break it up into 5 different tests, you might find that some of them pass, but not all. This will save you time when you start to debug the code.</p>\n\n<hr>\n\n<p>Do you really need to access the internet to run your tests? If the internet connection drops out at just the right time, your tests fail even if there is nothing wrong with your code.</p>\n\n<hr>\n\n<p>Your questions:</p>\n\n<ol>\n<li>I don't know of one.</li>\n<li>For the most part, the use of <code>null</code> seems to be minimized to interacting with other api's that force you to, not you using it yourself. This is fine, but see question 5.</li>\n<li>I do think that implementing <code>Map<T, Integer></code> makes some things unclean. There are cases where you have to take <code>Object</code> as an argument when it should be <code>T</code> or just an int and it adds methods to deal with what you would want the api to be.</li>\n<li>Adding on to question 3, I would just have <code>increment()</code> and <code>decrement()</code>.</li>\n<li>Having <code>null</code>s in the array seems wrong. I would have the method return a <code>List</code> of at most <code>n</code> elements.</li>\n<li>This is just something you have to deal with when casting to a generic class. <sup>1</sup></li>\n<li>This is what profilers are for. You can try different implementations and see witch is faster or if it makes a difference.</li>\n<li>It seems fine, but this is another case where a profiler can answer questions.</li>\n</ol>\n\n<hr>\n\n<p>Last note: <code>equals()</code> and <code>hashCode()</code> seem overly complicated, but I didn't look deeply to see if there are any real issues.</p>\n\n<p><sup>1</sup> bowmore's answer is better in dealing with this question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:51:50.637",
"Id": "77922",
"Score": "0",
"body": "Thanks for finding the `containsValue()` bug — +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:52:42.480",
"Id": "77923",
"Score": "0",
"body": "I believe that `assumeTrue(null != SHAKESPEARE_CORPUS)` should prevent the test from failing if Internet is unavailable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:00:06.997",
"Id": "77925",
"Score": "1",
"body": "@200_success: Actually, that is true. I still don't like the fact that the test might not run based on factors unrelated to the code base. In a corporate environment, the build server might not have access to the external internet. In that case, you are missing a valuable regression test. You also don't control the resource and won't know if it changes. If the site decides to host a different play, now you test fails even if your code is correct. Downloading the resource once and saving it with the tests solves all of these problems."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:47:52.710",
"Id": "44785",
"ParentId": "44772",
"Score": "8"
}
},
{
"body": "<h2>Your concerns</h2>\n\n<ol>\n<li><p>Re-inventing the wheel: I am not familiar with anything that does this functionality, but my knowledge of Apache Commons and Guava is a little limited .... @palacsint?</p></li>\n<li><p>null-keys looks OK. You sort null first, which is neither here nor there, but you may want to document that. As for the int values... this code has me confused:</p>\n\n<blockquote>\n<pre><code>/**\n * Returns the value to which the specified key is mapped, or null if this\n * map contains no mapping for the key.\n */\n@Override\npublic Integer get(Object key) {\n Integer i = this.c.get(key);\n return i == null ? 0 : i.intValue();\n}\n</code></pre>\n</blockquote>\n\n<p>The Javadoc says it returns null if the key is not mapped, but it actually returns 0. Further, if the value <strong><em>is</em></strong> mapped, you extract the int value, then autobox it back to Integer.</p>\n\n<p>Similarly, in the <code>put()</code> method you return 0 instead of null for a not-previously-mapped value</p></li>\n<li><p>Implementing <code>Map<...></code> - is it useful? I will dedicate a whole section to that.... ;-)</p></li>\n<li><p>I have no particular concern about the number of increment/decrement methods. They are mostly convenient in conceptual cases. Some may argue YAGNI... but I am not in that camp... there is nothing worse than needing a convenient tool and discovering that it just isn't there.</p></li>\n<li><p>Interesting question.... my initial reaction was that I do not like those methods (mostCommon* ). I figure it would be easy enough to iterate and break.</p></li>\n<li><p>Unchecked warnings - actually, they are raw-type warnings too. This is related to the use of the <code>Map<...></code> interface.</p></li>\n<li><p>Yes. there are better ways.... not to use Map....</p></li>\n<li><p>the big question.... I am sure there is, but not sure how to describe it until I do it ....</p></li>\n</ol>\n\n<h2>Using Map class</h2>\n\n<p>My big beef with the java.util.* collection interfaces is how complicated they are to implement (not to use).</p>\n\n<p>Your code is full of bugs in this regard.</p>\n\n<p>Consider this documentation for <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#entrySet%28%29\" rel=\"nofollow\"><code>Map.entrySet()</code></a>:</p>\n\n<blockquote>\n <p>Returns a Set view of the mappings contained in this map. The set is\n backed by the map, so changes to the map are reflected in the set, and\n vice-versa. If the map is modified while an iteration over the set is\n in progress (except through the iterator's own remove operation, or\n through the setValue operation on a map entry returned by the\n iterator) the results of the iteration are undefined. The set supports\n element removal, which removes the corresponding mapping from the map,\n via the Iterator.remove, Set.remove, removeAll, retainAll and clear\n operations. It does not support the add or addAll operations.</p>\n</blockquote>\n\n<p>Because you implement the entrySet as a distinct data TreeMap's <code>entrySet()</code>, you fail pretty much all of those requirements....</p>\n\n<p>It is my experience that implementing Collection interfaces is <strong>hard</strong> (and I have some successful implementations that prove it). It gets especially hard when you want to do things 'right' with respect to things like <code>ConcurrentModificationException</code>.</p>\n\n<p>My recommendation is for you not to expose it at all. That way you define your own simpler specification.</p>\n\n<h2>Bugs</h2>\n\n<p>There are a number of bugs I can see.</p>\n\n<ol>\n<li><p>The constructor <code>public Counter(Map<T, Integer> counter) {...}</code> opens you up to a lot of problems:</p>\n\n<ul>\n<li>people can supply null values for the <code>Integer</code> values in a HashMap, for example. This will cause your code to throw null-pointer exceptions in your Comparator.</li>\n<li>people using the <code>Counter.get(key)</code> method will get a 0 value for a null-mapped Integer, but if they get the Map.Entry instance for the same key, the getValue() will be null.</li>\n<li>all the increment/decrement methods will throw null-pointer-exception when un-autoboxing.</li>\n</ul></li>\n<li><p>The Comparator has a bug on the sorting if the values are extreme:</p>\n\n<blockquote>\n<pre><code> if (0 != (diff = bValue - aValue)) {\n return diff;\n</code></pre>\n</blockquote>\n\n<p>If the <code>aValue</code> has been incremented to say +1000 and the <code>bValue</code> has been decremented to -2000 then we would want to sort the aValue first (return a negative number) because it has the larger count. The function -2000 - (+1000) will return -3000, which is right. But, if aValue was incremented to say +1,000,000,000 and the bValue was decremented to -2,000,000,000 then the result will underflow the int value, and will end up as a positive result.... leading to incorrect sorting.</p>\n\n<p>The right way to do this is with plain-jane comparisons:</p>\n\n<pre><code>if (aValue != bValue) {\n return aValue < bValue ? 1 : -1;\n</code></pre></li>\n</ol>\n\n<h2>Conclusion</h2>\n\n<p>The concept is good, but exposing the Map is a net-negative. Too many things to go wrong.</p>\n\n<p>It also makes it almost impossible to have a Concurrent version later.</p>\n\n<p>I would implement it with a custom interface that does not expose the internal classes at all... leave the interface as a simple (primitive based):</p>\n\n<pre><code>public int getCount(T key) { ... }\n\npublic int incrementAndGet(T key) { .... } // similar to AtomicInteger\npublic int getAndIncrement(T key) { .... } // similar to AtomicInteger\n\ndecrement options too\n\npublic Iterator<T> iterator() { ... } // simple iterator of keys in decreasing count order.\n\nequals and hashCode.\n</code></pre>\n\n<p>That's it....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:55:26.497",
"Id": "44787",
"ParentId": "44772",
"Score": "8"
}
},
{
"body": "<p>I don't really have time to read through the whole code and the existing reviews now but as far I see no-one mentioned Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multiset.html\" rel=\"nofollow noreferrer\"><code>Multiset</code></a> and its <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/AtomicLongMap.html\" rel=\"nofollow noreferrer\"><code>AtomicLongMap</code></a> yet.</p>\n\n<p>I've been able to change <code>Counter</code> to <code>HashMultiset</code> in the test methods with very few issues while the bar remained green:</p>\n\n<ul>\n<li><code>Multiset</code> does not store keys (elements) with zero occurrences. (<code>AtomicLongMap</code> might be a better choice if it's a requirement.)</li>\n<li><code>mostCommon</code> is not supported by <code>Multiset</code> out of box but <a href=\"https://stackoverflow.com/a/7576512/843804\"><code>Multisets</code></a> supports it. (You might also need <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html#limit%28java.lang.Iterable,%20int%29\" rel=\"nofollow noreferrer\"><code>Iterables.limit</code></a> here.)</li>\n<li>Minor method name changes.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:38:43.900",
"Id": "44804",
"ParentId": "44772",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "44784",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T17:43:57.453",
"Id": "44772",
"Score": "30",
"Tags": [
"java",
"unit-testing",
"collections",
"null",
"junit"
],
"Title": "Just a lowly counter that turned out to be surprisingly complicated"
} | 44772 |
<p>I'm building a media viewer web app for a kiosk in node that uses data in mongo. To render the viewer, it gathers together all the Asset objects (representing video files), each of which belong to a Category, each of which belong to a Medium.</p>
<p>This is my first time using mongo and node together, so I decided to use async.js to organize the code, but I don't know if I'm doing things efficiently or not. Is there a better way to organize the data or perform the queries? Does this look remotely sane?</p>
<p>Additionally, I commented out some code I thought looked correct but would mysteriously overwrite the object simply by adding another key to it. What am I doing wrong?</p>
<p>models.js : mongoose models</p>
<pre><code>var mongoose = require('mongoose');
/* Mediums... Film, Video, TV */
var mediumSchema = mongoose.Schema({
name: String,
id: String,
description: String
});
var Medium = mongoose.model('mediums', mediumSchema);
/* Categories ... */
var categorySchema = mongoose.Schema({
medium: String, // refers to medium.id, not medium._id
name: String,
shortName: String,
years: String,
description: String
});
var Category = mongoose.model('categories', categorySchema);
/* Assets */
var assetSchema = mongoose.Schema({
title: String
, year: Number
, duration: Number
, medium_info: String
, copyright: String
, extended_info: String
, filename: String
, category_id: mongoose.Schema.Types.ObjectId
});
var Asset = mongoose.model('assets', assetSchema);
exports.Medium = Medium;
exports.Category = Category;
exports.Asset = Asset;
</code></pre>
<p>viewer.js : the handler that retrieves all the data and renders the html</p>
<pre><code>exports.index = function(req, res){
res.render('index');
};
exports.viewer = function(req, res) {
var models = require('./models');
var async = require("async");
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {});
// provide category object, returns assets in that category
function getAssetsForCategory(category, callback) {
console.log("Looking for assets for category:" + category.name);
models.Asset.find({category_id: category._id}, function(err, assets) {
callback(err, assets);
});
}
// provide medium label ("FILM","VIDEO","TV") returns list of categories
function getCategoriesForMedium(medium, callback) {
console.log("finding categories for " + medium);
models.Category.find({medium: medium}, function(err, categories) {
callback(err, categories);
});
}
data = {};
async.each(
["FILM","VIDEO","TV"],
function(mediumName, mediumLookupComplete) {
var mediumResults = {};
var categoryResults = {};
var assetResults = {};
async.waterfall(
[
function(findMediumComplete) {
// get medium object for its additional metadata
models.Medium.findOne({id: mediumName}, findMediumComplete)
},
function(medium, findCategoriesComplete) {
mediumResults.name = medium.name;
mediumResults.description = medium.description;
getCategoriesForMedium(medium.id, findCategoriesComplete);
},
function(categories, assetFetchComplete) {
async.each(
categories,
function(category, categoryAssetLookupDone) {
categoryResults[category._id] = category;
/* I originally wanted to just insert the list of assets
into their appropriate category object here, but doing so
would overwrite the entire object--explanations? */
// categoryResults[category._id].assets = [];
getAssetsForCategory(category, function(err, assets) {
/* instead I have to use a separate temp object to store the
asset results, rather than just saying
categoryResults[category._id].assets = assets; */
assetResults[category._id] = assets;
categoryAssetLookupDone();
});
},
assetFetchComplete
);
}
],
function(err) {
console.log("asset fetch complete");
data[mediumName] = {};
data[mediumName]["categories"] = categoryResults;
data[mediumName]["description"] = mediumResults.description;
data[mediumName]["name"] = mediumResults.name;
data[mediumName].categories = [];
for (var catId in assetResults) {
data[mediumName].categories.push({info: categoryResults[catId], assets: assetResults[catId]});
//data[mediumName]["categories"][catId] = {info: data[mediumName].categories[catId], assets: assetResults[catId]};
}
//data[mediumName]["assets"] = assetResults;
//{medium: mediumResults, ass: assetResults};
mediumLookupComplete(err);
}
);
},
function(err) {
mongoose.connection.close();
//res.send({data:data});
res.render('viewer', {data:data});
}
);
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:42:05.260",
"Id": "77900",
"Score": "0",
"body": "Welcome to Code Review! Your question looks good to me if your code work as is, without the commented code. We don't fix broken code, since your question is asking for a review it looks on-topic to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T19:08:47.343",
"Id": "78178",
"Score": "0",
"body": "Yes, it works as provided, just seems convoluted. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T19:10:49.547",
"Id": "78179",
"Score": "0",
"body": "Thanks you for the confirmation! I hope you'll get good review!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-02T13:40:12.980",
"Id": "91509",
"Score": "0",
"body": "Instead of using the _id of the other objects you could use a reference. See http://mongoosejs.com/docs/populate.html Then it would allow you to populate the fields"
}
] | [
{
"body": "<p>A short review;</p>\n\n<ul>\n<li>Consider using JsHint</li>\n<li>Declare <code>data</code> with <code>var</code>, otherwise you are polluting the global namespace</li>\n<li>Consider <code>err</code> more often, the assumption that there will be no error will bite you</li>\n<li>Do not simply log to <code>console.log</code>, it is one of the most common bottlenecks</li>\n<li>Remove your commented out code, it keeps things clean</li>\n<li><p>My assumption is that</p>\n\n<ul>\n<li>The meta data of <code>[\"FILM\",\"VIDEO\",\"TV\"]</code> does not change often</li>\n<li>The categories do no change often</li>\n</ul>\n\n<p>I would generate a javascript file with the meta data and categories in 1 big Object Notation assignment, and re-generate it whenever mediums/categories change, this would greatly simplify your code, and make it way faster. </p></li>\n<li><p>With Object Notation, this</p>\n\n<pre><code> data[mediumName] = {};\n data[mediumName][\"categories\"] = categoryResults;\n data[mediumName][\"description\"] = mediumResults.description;\n data[mediumName][\"name\"] = mediumResults.name;\n</code></pre>\n\n<p>would be</p>\n\n<pre><code> data[mediumName] = {\n categories : [];\n description : mediumResults.description;\n name : mediumResults.name;\n };\n</code></pre>\n\n<p>note that you override the results of <code>data[mediumName][\"categories\"] = categoryResults;</code> with <code>data[mediumName].categories = [];</code></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-11T18:57:19.917",
"Id": "59719",
"ParentId": "44776",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T18:22:27.430",
"Id": "44776",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"mongodb",
"mongoose"
],
"Title": "Optimizing async joins for mongodb (mongoose) using async.js"
} | 44776 |
<p>In 8-puzzle I want to count the number of moves it would take to move a specific tile to it's goal place. The problem is my method for this is >100 lines long which is obviously way too much. I'll only include part of that method that counts steps to move the piece to the right row if the goal row is higher. It gives the idea, it is probably hard to read even with that piece of it only, I did comment profusely though.</p>
<p>To further illustrate what the code does - for state {{0,2,3},{4,1,6},{7,8,5}} the count of steps for moving the 1 tile to first spot would be 5:</p>
<pre><code> 2 3 2 3 2 1 3 2 1 3 1 3 1 3
4 1 6 => 4 1 6 => 4 6 => 4 6 => 2 4 6 => 2 4 6
7 8 5 7 8 5 7 8 5 7 8 5 7 8 5 7 8 5
</code></pre>
<p>And for the code ( or bits and pieces of it):</p>
<pre><code> // Finding the nr of steps it would take to move tile to it's goal place
public int countSteps(int tileNr) {
int steps = 0;
int[] goal = findGoal(tileNr);
int[] current = findTile(tileNr);
int[] empty = findTile(0);
GameState copy = new GameState(this);
while (goal[0] != current[0] && goal[1] != current[1]) {
// If the tile needs to be moved upwards (row coord is smaller in
// goal)
if (goal[0] < current[0]) {
if (empty[0] == current[0] - 1 && empty[1] == current[1]) {
// If empty above current tile, switch them
steps++;
current = empty;
empty[0]++;
} // Else have to move the empty tile to above current
else if (empty[1] == current[1]) {
if (empty[0] < current[0] - 1) {
// If empty too high in the right column, move empty
// tile down
steps++;
empty[0]++;
}
if (empty[0] > current[0]) {
// If empty below current, move out from that that
// column
steps++;
if (empty[1] < 2)
empty[1]++;
else
empty[1]--;
}
} else if (empty[0] == current[0]) {
if (empty[1] < current[1]) {
// If empty to the right in right row
// move to the left
steps++;
empty[1]++;
}
if (empty[1] > current[1]) {
// If empty to the left in right row move to the right
// column
steps++;
empty[1]--;
}
}
}
}
return steps;
}
// Finding coords for the tile in goal state
public int[] findGoal(int tileNr) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (goalState[i][j] == tileNr)
return new int[] { i, j };
}
}
return new int[] { -1, -1 };
}
// Finding coords for the tile in current state
public int[] findTile(int tileNr) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state[i][j] == tileNr)
return new int[] { i, j };
}
}
return new int[] { -1, -1 };
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:44:16.753",
"Id": "77936",
"Score": "0",
"body": "You don't care about the other pieces being in a different position before and after do you ?"
}
] | [
{
"body": "<h2>Concerns</h2>\n\n<p>This logic is complicated and long winded... so much so, that you cut a huge portion of it, or otherwise there is a big bug... You have the condition inside the while-loop:</p>\n\n<blockquote>\n<pre><code> // If the tile needs to be moved upwards (row coord is smaller in\n // goal)\n if (goal[0] < current[0]) {\n</code></pre>\n</blockquote>\n\n<p>But there is no 'else' condition for that. Did you 'trim' that out?</p>\n\n<p>What if the row is in the other direction? What if it is already in the correct row?</p>\n\n<h2>Incremental Suggestion</h2>\n\n<p>Generally, when presented with problems like this it often helps to generalize the problem....</p>\n\n<p>For example, if you create a concept called a 'direction', which is a two-value pair, say an <code>int[2]</code> (keeping it consistent with your code). If the target is at coordinate <code>[0,0]</code> and the current position of the tile is at <code>[2,2]</code> then the direction is <code>[-1,-1]</code> (you need to be reducing the row/column coordinates by 1 to get to your target.</p>\n\n<p>Then, your while loop can become:</p>\n\n<pre><code>int[] goal = findGoal(tileNr);\nint[] current = findTile(tileNr);\nint[] empty = findTile(0);\nfor (int[] direction = getDirection(current, goal);\n direction[0] != 0 || direction[1] != 0;\n direction = getDirection(current, goal)) {\n\n if (direction[0] != 0) {\n // find a way to move things in the row axis\n // do this by getting the empty space where we need to move to....\n ......\n // swap our tile with the empty space.\n empty[0] -= direction[0];\n current[0] += direction[0]; // update the current position.\n } else { // direction[1] must be != 0\n // find a way to move things in the column axis\n // do this by getting the empty space where we need to move to....\n ......\n // swap our tile with the empty space.\n empty[1] -= direction[1];\n current[1] += direction[1]; // update the current position.\n }\n}\n// to exit the loop, direction == [0, 0] ... i.e. we are at our target.\n</code></pre>\n\n<h2>Bigger suggestion</h2>\n\n<p>In this case I would consider a significantly different data structure.... :</p>\n\n<ol>\n<li>Create a Tile Object for each Tile.</li>\n<li>The <code>GameState</code> instance will then just become a loose collection of Tiles.</li>\n<li>Keep the tile location embedded in the Tile instance.</li>\n<li>Treat the empty space as a tile, and the 'rule' is that the Empty tile is the only tile that can swap positions with it's neighbour.</li>\n<li>You can embed the logic in to methods on the Tile to identify the tile position and directions.</li>\n</ol>\n\n<p>Doing the above can reverse a lot of your game logic, but the benefit will be that you move the logic out of the main methods in to the object orientation....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T00:02:16.143",
"Id": "44815",
"ParentId": "44783",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "44815",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:22:01.930",
"Id": "44783",
"Score": "5",
"Tags": [
"java",
"matrix"
],
"Title": "In 8-puzzle finding nr of steps moving a tile to the right place"
} | 44783 |
<p>This is the first time that I have played around with AsyncTask in Android and I wanted to make sure I'm using it correctly. The idea is I'm grabbing all the rows from a table in the database using <code>dao</code> and putting them into an Arraylist based off my Item class. Once finished, I added it to a custom Adapter and add it to my ListView. I wasn't sure if the placement to the AsyncTask class inside the ListFragment is correct or if I used <code>getActivity()</code> correctly ( would it have been better to pass it as a variable?). Any other constructive criticism is welcome as well.</p>
<pre><code>package com.domain.myapp;
import java.util.ArrayList;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.domain.myapp.adapters.ItemsListAdapter;
import com.domain.myapp.database.DAO;
import com.domain.myapp.models.Item;
public class ItemsListFragment extends ListFragment {
private ItemsListAdapter falAdp;
private OnFragmentInteractionListener mListener;
public ItemsListFragment() {
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.item_list_view_menu, menu);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getItemLists gfl = new getItemLists();
gfl.execute();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
mListener.onFragmentInteraction(item.getItemId(), 0);
return true;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (null != mListener) {
mListener.onFragmentInteraction(R.id.ViewItemDetails, falAdp
.getItem(position).getId());
}
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(int mnuId, int Id);
}
private class getItemLists extends
AsyncTask<Void, String, ArrayList<Item>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected ArrayList<Item> doInBackground(Void... params) {
DAO dao = new DAO();
ArrayList<Item> fal = dao.ItemsGetList(getActivity());
return fal;
}
@Override
protected void onPostExecute(ArrayList<Item> result) {
super.onPostExecute(result);
falAdp = new ItemsListAdapter(getActivity(),
R.layout.fragment_list_item_text_view, result);
setListAdapter(falAdp);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T14:08:02.653",
"Id": "83630",
"Score": "0",
"body": "Why don't you use the [Loader API](http://developer.android.com/guide/components/loaders.html)?"
}
] | [
{
"body": "<p>All in all, this code is great. I don't see much in the way of problems. There are a few nit-picks:</p>\n\n<blockquote>\n<pre><code> } catch (ClassCastException e) {\n throw new ClassCastException(activity.toString()\n + \" must implement OnFragmentInteractionListener\");\n }\n</code></pre>\n</blockquote>\n\n<p>The above code takes one ClassCastException and swaps it with another. Is it necessary? If it is necessary (because the current message does not give details on the current activity), then I recommend initializing the cause of the thrown CCE:</p>\n\n<pre><code> } catch (ClassCastException e) {\n ClassCastException tothrow = new ClassCastException(activity.toString()\n + \" must implement OnFragmentInteractionListener\");\n tothrow.initCause(e);\n throw tothrow;\n }\n</code></pre>\n\n<p>it is a pain, but you benefit from getting all the information in the stack trace. Currently you are losing some.</p>\n\n<p>The only other issue I see is the extension of the AsyncTask. You have re-implemented the methods:</p>\n\n<blockquote>\n<pre><code> @Override\n protected void onPreExecute() {\n super.onPreExecute();\n }\n\n @Override\n protected void onProgressUpdate(String... values) {\n super.onProgressUpdate(values);\n }\n</code></pre>\n</blockquote>\n\n<p>This is completely unnecessary and you can delete that code. Just let the ancestor code be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:58:58.393",
"Id": "78061",
"Score": "1",
"body": "Cool, thank you for your input. I will make the changes to my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T00:22:56.740",
"Id": "44816",
"ParentId": "44789",
"Score": "8"
}
},
{
"body": "<p>Few minor things;</p>\n\n<p>I would consider renaming your member variables to something like the following; </p>\n\n<pre><code>private ItemsListAdapter falAdp; => mItemsAdapter;\nprivate OnFragmentInteractionListener mListener; => mInteractionListener;\n</code></pre>\n\n<p>Follows the android m prefix, and makes it slightly more readable.</p>\n\n<p>Also your getItemLists async task, should be renamed to something like the following; </p>\n\n<pre><code>getItemLists = > RetrieveItemListTask\n</code></pre>\n\n<p>Should begin with an uppercase letter and the class name should reflect what it actually is.</p>\n\n<p>You could also consider moving your task execute into onResume, this is called just after onCreate. This would then update your\nlist when your fragment is being resumed and not only on creating the initial instance.</p>\n\n<pre><code>@Override\npublic void onResume() {\n super.onResume();\n mRetrieveItemListTask.execute();\n}\n</code></pre>\n\n<p>Finally you do not need to recreate your adapter every time your async task runs, you can just reset the data and call notifydatasetchanged.</p>\n\n<p>For example, create your adapter in onCreate:</p>\n\n<pre><code>@Override\npublic void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n mItemsAdapter = new ItemsListAdapter(getActivity(), R.layout.fragment_list_item_text_view);\n setListAdapter(mItemsAdapter);\n}\n</code></pre>\n\n<p>then;</p>\n\n<pre><code>@Override\nprotected void onPostExecute(ArrayList<Item> result) {\n super.onPostExecute(result);\n\n mItemsAdapter.clearAll();\n mItemsAdapter.addAll(result); //which will call notifydatasetchanged\n}\n</code></pre>\n\n<p>Nothing wrong with your listener implementation. But might be worth having a look at an EventBus like otto, make it much cleaner :D</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T12:20:54.593",
"Id": "45490",
"ParentId": "44789",
"Score": "0"
}
},
{
"body": "<p>A minor point about your Java code. For the parameter types for getItemLists and onPostExecute(), you should use the interface List rather than the class ArrayList. Similarly, </p>\n\n<pre><code>ArrayList<Item> fal = dao.ItemsGetList(getActivity());\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>List<Item> fal = dao.ItemsGetList(getActivity());\n</code></pre>\n\n<p>This will make your code more flexible in case the type of list later needs to be changed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-16T21:10:28.800",
"Id": "93789",
"ParentId": "44789",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44816",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:15:29.713",
"Id": "44789",
"Score": "11",
"Tags": [
"java",
"multithreading",
"android",
"sqlite"
],
"Title": "Using an AsyncTask to populate a ListView in a Fragment From a SQLite table"
} | 44789 |
<p>I'm wondering if I am doing this in the most efficient way. </p>
<p>So I'm declaring my function <code>el</code> which is equal to a macro (Google Tag Manager), then I reassign or overwrite that previously-defined var which grabs the innerText/textContent of the element. It then converts the string to lowerCase and then capitalizes the first letter of the string, before finally returning the 'cleaned-up' element.</p>
<pre><code> function() {
var el = {{element}}
el = (el.innerText || el.textContent);
el = el.toLowerCase();
el = el.charAt(0).toUpperCase() + el.slice(1);
return el;
}
</code></pre>
| [] | [
{
"body": "<p>You can using chaining, move the <code>toLowerCase()</code> to simplify a little and return the last statement directly:</p>\n\n<pre><code>function() {\n var el = {{element}};\n el = (el.innerText || el.textContent);\n return el.charAt(0).toUpperCase() + el.slice(1).toLowerCase();\n}\n</code></pre>\n\n<p>I'm personally not a fan of using a single variable for many purposes (I think it interferes with readability and maintainability) so I would probably do this:</p>\n\n<pre><code>function() {\n var el = {{element}};\n var text = (el.innerText || el.textContent);\n return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T05:39:51.757",
"Id": "78018",
"Score": "0",
"body": "Simplified a bit further by returning the last statement directly (one less line and assignment) and moved `.toLowerCase()` to operate on the final result."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:23:05.470",
"Id": "44792",
"ParentId": "44790",
"Score": "7"
}
},
{
"body": "<p>I think you have a valid concern about the repeated reassignment.</p>\n\n<p>Based on the Single-Responsibility Principle, I would split this function into two: one that interfaces with the DOM, and another that transforms a string.</p>\n\n<pre><code>function content(element) {\n var el = {{ element }};\n return el.innerText || el.textContent;\n}\n\nfunction titleCase(str) {\n return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();\n}\n\n// The original function in question\nfunction() {\n return titleCase(content(element));\n}\n</code></pre>\n\n<p>Decomposing the problem that way addresses the code smell at the root cause.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:58:36.943",
"Id": "77940",
"Score": "0",
"body": "Splitting functionality into 1 liners that you use only once usually fails code review. -1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:40:37.003",
"Id": "77950",
"Score": "4",
"body": "@konijn Big assumption with \"you'll only use once\". `titleCase` and `content` look like they could be reused a lot assuming this application has more than one DOM element. Besides, these methods are now testable and composable which can be a big win."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:43:07.183",
"Id": "77951",
"Score": "0",
"body": "Save possible upper-to-lower-to-upper conversion of the first character with `str.substr(1).toLowerCase()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T05:42:02.957",
"Id": "78019",
"Score": "1",
"body": "@DavidHarkness The order of operations will make a negligible difference in performance, but I think that the parallelism of putting `toUpperCase()`/`toLowerCase()` last is appealing. I've incorporated the change into Rev 2."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:38:22.143",
"Id": "44795",
"ParentId": "44790",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44792",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:17:44.030",
"Id": "44790",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Declaring JavaScript variable and then overwriting it multiple times"
} | 44790 |
<p>I've written JavaScript for a while, but lately I've been writing a lot of C#. I wanted to write a method that could take the column name of a <code>DataTable</code> and return an average for those values. Having never written closures in C#, but being comfortable with them in JavaScript, I came up with this:</p>
<pre><code>public static double GetColumnAverage(DataTable dt,string columnName)
{
Func<DataTable, double> getAverage = (t) => t.AsEnumerable().Where(x => x[columnName] != DBNull.Value)
.Average(x => x.Field<dynamic>(columnName));
bool isNumeric = true;
foreach (DataRow row in dt.Rows)
{
var type = row[columnName].GetType();
//not all numeric data types, but close enough for this
isNumeric = type == typeof(int) || type == typeof(double) || type == typeof(float) || type == typeof(uint)
|| type == typeof(byte);
if (isNumeric ==false)
{
throw new Exception();
}
}
return getAverage(dt);
}
</code></pre>
<p>From this I learned that the parameters passed to an inner delegate are matched to the outer delegate, so Intellisense picked up the <code>t</code> parameter as a DataTable (not sure about implications, but neat). Cool. My initial thought was to create a private helper method <code>IsNumeric</code> that would return a bool if the value in the DataRow was something we could average.</p>
<p>I know that I could probably improve this a little, but I'm wondering if there's any practical reason to using a closure here, or if there are any potential pitfalls that might make it a bad idea?</p>
| [] | [
{
"body": "<p>I would recommend reading <a href=\"http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/\" rel=\"nofollow noreferrer\">this article</a> by Eric Lippert </p>\n\n<p>You'll definitally want an extension method for this... let me hit the google real quick.... Using some inspired code from this <a href=\"https://stackoverflow.com/questions/1749966/c-sharp-how-to-determine-whether-a-type-is-a-number/1750093\">SO post</a> I wrote this.</p>\n\n<pre><code>static class Extensions\n{\n private const HashSet<Type> NumericTypes = new HashSet<Type> \n {typeof(decimal), typeof(byte), typeof(sbyte), typeof(short), typeof(ushort),\n typeof(int),typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double)};\n\n /// <summary>Determines whether the specified object is numeric.</summary>\n public static bool IsNumeric(this object obj) { return NumericTypes.Contains(obj.GetType()); }\n}\n</code></pre>\n\n<p>Now in your code you can just say</p>\n\n<pre><code>if(!row[columnName].IsNumeric())\n throw new Exception();\n</code></pre>\n\n<p>However, now I will review your code in general.</p>\n\n<ol>\n<li><p>You should not throw <code>Exception</code>, you should always be specific with your exception throwing. In this case I probably would throw an <code>ArgumentException</code>, but really this seems like a specific case where you should define your own.</p></li>\n<li><p>I'm a bit confused by your declaring <code>isNumeric</code> outside the loop, when you don't use it outside that scope.</p></li>\n<li><p>instead of saying <code>if (isNumeric == false)</code> just say <code>if(!isNumeric)</code></p></li>\n<li><p>I don't see why you nested this function inside your loop. its not taking full advantage of the fact that it is nested, and could just aswell be a function outside. Plus why declare it if you might be throwing an exception.. might as well wait. And while you're waiting, lets just take this one liner and make it a statement instead. (My thoughts jumped around there a bit)</p></li>\n</ol>\n\n<p>In the end your code could just look like.</p>\n\n<pre><code>public static double GetColumnAverage(DataTable dt, string columnName)\n{\n foreach (DataRow row in dt.Rows)\n if (!row[columnName].IsNumeric())\n throw new ArgumentException(\"-Something meaningful here-\");\n return dt.AsEnumerable().Where(x => x[columnName] != DBNull.Value).Average(x => x.Field<dynamic>(columnName));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:56:04.157",
"Id": "77957",
"Score": "0",
"body": "Thanks for the contribution. The reason why I declared the lambda at the top of the method is simply because that's what JavaScript does: it hoist the inner function to the top of the containing function. Secondly (again, this is coming from more of a JS background) I feel that letting someone else who might be reading your code that there's a closure as soon as possible helps readability. Personally, I don't think having an IsNumeric extension method is the best bet, but I was exploring some new ground and wanted to test the waters a bit :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:06:12.227",
"Id": "77958",
"Score": "0",
"body": "@wootscootinboogie you could make it a normal method too if you wanted to (isNumeric), but Extension methods are awesome, so why not :D.\nyou can declare the lambda outside your function, or inside. But in your case there is no reason to even have a lambda. Might as well just run the code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:12:36.677",
"Id": "77960",
"Score": "0",
"body": "agreed, I don't think the lambda here serves any real useful function, and probably makes the code less readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T00:08:57.173",
"Id": "77981",
"Score": "0",
"body": "1. How is closing over the loop variable relevant? The posted code doesn't close over `row`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T00:09:32.927",
"Id": "77982",
"Score": "0",
"body": "2. You can't have `const` fields with complex values, I think you meant `readonly`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T00:11:35.050",
"Id": "77983",
"Score": "0",
"body": "3. Using `All()` instead of the loop would make the code even simpler."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:29:41.943",
"Id": "44801",
"ParentId": "44796",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44801",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:52:28.710",
"Id": "44796",
"Score": "6",
"Tags": [
"c#",
"closure"
],
"Title": "Closures in C#, necessary or not?"
} | 44796 |
<p>I have recently answered a <a href="https://stackoverflow.com/questions/22441747/c-winapi-creating-treeview-with-nodes-and-checkboxes/22443388#22443388">question on Stack Overflow</a> where OP wanted to programmatically determine if <code>TreeView</code>'s node is checked or not, among other things. My answer got accepted since everything seems to work fine.</p>
<p>Still, after reading MSDN documentation for <a href="https://stackoverflow.com/questions/22445851/proper-return-value-for-tvn-keydown?lq=1"><code>TVN_KEYDOWN</code></a>, I found the part in the "Return value" section that mentioned incremental search. Therefore I have decided to ask <a href="https://stackoverflow.com/questions/22445851/proper-return-value-for-tvn-keydown?lq=1">what is a proper return value for my usage of that notification</a> and have concluded that I should return a nonzero value.</p>
<p><strong>Question:</strong></p>
<p>My concern is if my code is <strong>the best way for testing</strong> if the tree's node is checked or not. That is why I came here to ask for review of that code, and for possible suggestions for improving it.</p>
<p>Here is the tree's creation in <code>WM_CREATE</code> handler:</p>
<pre><code>case WM_CREATE:
{
// this is your treeview
TreeView = CreateWindowEx(0, WC_TREEVIEW,
TEXT("Tree View"), WS_VISIBLE | WS_CHILD,
0, 0, 200, 500,
hwnd, (HMENU)ID_TREE_VIEW, GetModuleHandle(NULL), NULL);
/************ enable checkboxes **************/
DWORD dwStyle = GetWindowLong( TreeView , GWL_STYLE);
dwStyle |= TVS_CHECKBOXES;
SetWindowLongPtr( TreeView , GWL_STYLE, dwStyle );
/************ add items and subitems **********/
// add root item
TVINSERTSTRUCT tvis = {0};
tvis.item.mask = TVIF_TEXT;
tvis.item.pszText = L"This is root item";
tvis.hInsertAfter = TVI_LAST;
tvis.hParent = TVI_ROOT;
HTREEITEM hRootItem = reinterpret_cast<HTREEITEM>( SendMessage( TreeView ,
TVM_INSERTITEM, 0, reinterpret_cast<LPARAM>( &tvis ) ) );
// add firts subitem for the hTreeItem
memset( &tvis, 0, sizeof(TVINSERTSTRUCT) );
tvis.item.mask = TVIF_TEXT;
tvis.item.pszText = L"This is first subitem";
tvis.hInsertAfter = TVI_LAST;
tvis.hParent = hRootItem;
HTREEITEM hTreeSubItem1 = reinterpret_cast<HTREEITEM>( SendMessage( TreeView ,
TVM_INSERTITEM, 0, reinterpret_cast<LPARAM>( &tvis ) ) );
// now we insert second subitem for hRootItem
memset( &tvis, 0, sizeof(TVINSERTSTRUCT) );
tvis.item.mask = TVIF_TEXT | TVIF_STATE; // added extra flag
tvis.item.pszText = L"This is second subitem";
tvis.hInsertAfter = TVI_LAST;
tvis.hParent = hRootItem;
// for demonstration purposes let us check this node;
// to do that add the following code, and add the extra flag for
// mask member like above
tvis.item.stateMask = TVIS_STATEIMAGEMASK;
tvis.item.state = 2 << 12;
HTREEITEM hTreeSubItem2 = reinterpret_cast<HTREEITEM>( SendMessage( TreeView ,
TVM_INSERTITEM, 0, reinterpret_cast<LPARAM>( &tvis ) ) );
// let us expand the root node so we can see if checked state is really set
TreeView_Expand( TreeView, hRootItem, TVE_EXPAND );
}
return 0L;
</code></pre>
<p>Here is the <code>WM_NOTIFY</code> handler that determines if tree is checked or not:</p>
<pre><code>case WM_NOTIFY:
{
LPNMHDR lpnmh = (LPNMHDR) lParam;
if( lpnmh->idFrom == ID_TREE_VIEW ) // if this is our treeview control
{
switch( lpnmh->code ) // let us filter notifications
{
case TVN_KEYDOWN: // tree has keyboard focus and user pressed a key
{
LPNMTVKEYDOWN ptvkd = (LPNMTVKEYDOWN)lParam;
if( ptvkd->wVKey == VK_SPACE ) // if user pressed spacebar
{
// get the currently selected item
HTREEITEM ht = TreeView_GetSelection( ptvkd->hdr.hwndFrom );
// Prepare to test items state
TVITEM tvItem;
tvItem.mask = TVIF_HANDLE | TVIF_STATE;
tvItem.hItem = (HTREEITEM)ht;
tvItem.stateMask = TVIS_STATEIMAGEMASK;
// Request the information.
TreeView_GetItem( ptvkd->hdr.hwndFrom, &tvItem );
// Return zero if it's not checked, or nonzero otherwise.
if( (BOOL)(tvItem.state >> 12) - 1 )
MessageBox( hwnd, L"Not checked!", L"", MB_OK );
else
MessageBox( hwnd, L"Checked!", L"", MB_OK );
}
}
return 0L; // see the documentation for TVN_KEYDOWN
case NM_CLICK: // user clicked on a tree
{
TVHITTESTINFO ht = {0};
DWORD dwpos = GetMessagePos();
// include <windowsx.h> and <windows.h> header files
ht.pt.x = GET_X_LPARAM(dwpos);
ht.pt.y = GET_Y_LPARAM(dwpos);
MapWindowPoints( HWND_DESKTOP, lpnmh->hwndFrom, &ht.pt, 1 );
TreeView_HitTest(lpnmh->hwndFrom, &ht);
if(TVHT_ONITEMSTATEICON & ht.flags)
{
// Prepare to receive the desired information.
TVITEM tvItem;
tvItem.mask = TVIF_HANDLE | TVIF_STATE;
tvItem.hItem = (HTREEITEM)ht.hItem;
tvItem.stateMask = TVIS_STATEIMAGEMASK;
// Request the information.
TreeView_GetItem( lpnmh->hwndFrom, &tvItem );
// Return zero if it's not checked, or nonzero otherwise.
if( (BOOL)(tvItem.state >> 12) - 1 )
MessageBox( hwnd, L"Not checked!", L"", MB_OK );
else
MessageBox( hwnd, L"Checked!", L"", MB_OK );
}
}
default:
break;
}
}
}
break;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:09:28.547",
"Id": "77942",
"Score": "2",
"body": "Could you post the code here instead of linking to it on another Stack Exchange site? It makes the reviewing process easier for the reviewers, so they don't have to jump back and forth between sites."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:13:19.343",
"Id": "77944",
"Score": "1",
"body": "you can still post that here as a question for review.will remove my downvote when you edit in your code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:19:55.557",
"Id": "77945",
"Score": "0",
"body": "@syb0rg: Done. Thank you for your suggestions. I apologize, but this is my first post. Please reconsider removing the downvote. Best regards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:20:20.667",
"Id": "77946",
"Score": "1",
"body": "@Malachi: Done. Thank you for your suggestions. I apologize, but this is my first post. Please reconsider removing the downvote. Best regards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:25:02.027",
"Id": "77948",
"Score": "0",
"body": "@AlwaysLearningNewStuff I didn't downvote in the first place. I thought it was too extreme for your case ;)"
}
] | [
{
"body": "<p>I have learned more about tree view check-boxes than I wanted to ;)</p>\n\n<p>From a first glance I only have 2 observations:</p>\n\n<ul>\n<li>You have 10 lines of copy pasted code in there, you should have a function for that</li>\n<li><p>This looks terrible:</p>\n\n<pre><code>// Return zero if it's not checked, or nonzero otherwise.\nif( (BOOL)(tvItem.state >> 12) - 1 )\n</code></pre>\n\n<ul>\n<li>Why 12 -> Magic constant ?</li>\n</ul></li>\n</ul>\n\n<p>But then, from reading <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb773456%28v=vs.85%29.aspx\" rel=\"nofollow\">this</a> and <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/hh270424%28v=vs.85%29.aspx\" rel=\"nofollow\">that</a>, it seems that is the right way of doing it. For the sanity of whoever would maintain this, you need a lengthy comment block there because it just looks wrong. The comment should mention why you need to shift 12 positions, and that the index can be 1 or 2 ( so that is why you subtract 1 ).</p>\n\n<p>I find it funny that there is a <code>#define INDEXTOSTATEIMAGEMASK(i) ((i) << 12)</code> provided but no <code>#define STATEIMAGEMASKTOINDEX(i) ((i) >> 12)</code>, perhaps you could create this macro yourself and make the code more readable by employing that macro.</p>\n\n<p>As an aside, there is a 'cleaner' way of getting the state, but that works only as of Vista, so I would stick to your approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T20:37:06.030",
"Id": "78827",
"Score": "0",
"body": "Thank you for your detailed review. Upvoted. I will wait 3 more days to see if anything else pops up before accepting your answer officially. Best regards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T09:44:48.387",
"Id": "79128",
"Score": "1",
"body": "I doubt my code can be improved beyond your suggestions, so I am officially accepting your answer. I have already upvoted, and I have awarded the bounty points as well. Thank you for your time and useful suggestions. Best regards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T13:26:27.627",
"Id": "45210",
"ParentId": "44798",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45210",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:03:32.647",
"Id": "44798",
"Score": "7",
"Tags": [
"c++",
"performance",
"winapi"
],
"Title": "Testing if TreeView's node is checked"
} | 44798 |
<p>This is my first "useful" Haskell program. It's invoked with filenames as arguments where the last filename is the destination to which the content of all other files will be concatenated. As far as I can tell it's working but I don't like the two returns in the main function and would like to know how I can get rid of the do in the concatFiles function.</p>
<pre><code>import System.Environment (getArgs)
import System.IO (hClose, hPutStr, openFile, IOMode(WriteMode))
concatFiles :: FilePath -> [FilePath] -> IO ()
concatFiles destination files = do
writeHandle <- openFile destination WriteMode
mapM (writeToDestination writeHandle) files
hClose writeHandle
where
writeToDestination writeHandle file =
hPutStr writeHandle =<< readFile file
main = do
args <- getArgs
argc <- return $ length args
destination <- return $ last args
concatFiles destination $ take (argc-1) args
</code></pre>
| [] | [
{
"body": "<p>For your <code>argc <- return $ length args</code> , the reason the compiler is telling you to use the return is because in <code>do</code> notation, monadic binding lines must be the form:</p>\n\n<pre><code>binding <- value wrapped in whatever monad you're using\n</code></pre>\n\n<p>So <code>length args</code> just returns an <code>Int</code>, but Haskell wants an <code>IO Int</code>. By doing <code>return $ length args</code>, you lift the value returned by <code>length args</code> into the <code>IO</code> monad. </p>\n\n<p>You are correct in smelling something funny here. Haskell provides a much cleaner way of assigning non-monadic values to be used inside of <code>do</code> notation with the <code>let</code> keyword.</p>\n\n<p>You can replace those two lines with:</p>\n\n<pre><code>let argc = length args\n destination = last args\n</code></pre>\n\n<p>Note that bindings must have the same indentation level within a <code>let</code> assignment block.</p>\n\n<p>But really, there is more to improve! In Haskell, the four most common list partitions are:</p>\n\n<ol>\n<li>First element (<code>head</code>)</li>\n<li>Last element (<code>last</code>)</li>\n<li>Everything but the first (<code>tail</code>)</li>\n<li>Everything but the last (<code>init</code>)</li>\n</ol>\n\n<p>So with <code>init</code> we can eliminate the need for argc, changing your <code>main</code> to</p>\n\n<pre><code>main = do\n args <- getArgs\n let destination = last args\n concatFiles destination $ init args\n</code></pre>\n\n<p>But really, the word <code>destination</code> is longer than the function call <code>last args</code>, and doesn't really add much clarity, so we can change that, too, removing the need for the <code>let</code> entirely!</p>\n\n<pre><code>main = do\n args <- getArgs\n concatFiles (last args) (init args)\n</code></pre>\n\n<p>And if you <em>really</em> wanted to become more intimately familiar with how <code>do</code> notations and monads in general work, we can actually remove the <code>do</code> notation and replace it with a <code>>>=</code> operator by doing</p>\n\n<pre><code>main = getArgs >>= \\args -> concatFiles (last args) (init args)\n</code></pre>\n\n<p>So as a quick recap of what is happening here, we are calling <code>getArgs</code>, which returns a list of arguments wrapped in the <code>IO</code> monad. The <code>>>=</code> (bind) operator takes that <code>IO</code> value, extracts the value inside, and sends it into the function on the right side of the <code>>>=</code> operator, where it gets bound to the argument <code>args</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T06:57:41.123",
"Id": "78024",
"Score": "3",
"body": "If you're going to get fancy by using `>>=`, you may as well get rid of the lambda as well! `main = getArgs >>= concatFiles <$> last <*> init`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:46:20.527",
"Id": "84874",
"Score": "0",
"body": "@amalloy exactly what I was thinking"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:37:20.280",
"Id": "44803",
"ParentId": "44799",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "44803",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:03:39.723",
"Id": "44799",
"Score": "10",
"Tags": [
"haskell",
"monads"
],
"Title": "Probably unneeded returns"
} | 44799 |
<p>I have to implement a simple program in SSE, and I don't know if I have done it in the right way (it's my first program in SSE).</p>
<p>This is the C++ program:</p>
<pre><code>double distance (int x1, int x2, int y1, int y2)
{
double x = abs(x2 - x1);
double y = abs(y2 - y1);
double dist = sqrt(x*x + y*y);
return dist;
}
</code></pre>
<p>And this is the program in SSE instructions:</p>
<pre><code>__m128d vx1 _mm_load_pd(x1); // load x1 and x2
__m128d vx2 = _mm_load_pd(x2);
__m128d vdiff = _mm_sub_pd(vx2, vx1); // x2 - x1
__m128d vnegdiff = mm_sub_pd(_mm_set1_pd(0.0), vdiff); // 0.0 - diff
__m128d vabsX = _mm_max_pd(vdiff, vnegdiff); // abs = max(diff, - diff)
__m128d vy1 = _mm_load_pd(y1);
__m128d vy2 = _mm_load_pd(y2);
__m128d vdiff2 = _mm_sub_pd(vy2, vy1);
__m128d vnegdiff2 = mm_sub_pd(_mm_set1_pd(0.0), vdiff2);
__m128d vabsY = _mm_max_pd(vdiff2, vnegdiff2);
__m128d absX = _mm_mul_pd(vabsX,vabsX); //x*x
__m128d absY = _mm_mul_pd(vabsY,vabsY); //y*y
__m128d suma = _mm_add_pd(absX, absY); // x^2 + y^2
__m128d square = _mm_sqrt_pd(suma); // square root x^2 + y^2
return square;
</code></pre>
| [] | [
{
"body": "<p>Your SSE code looks like a reasonably accurate translation of your original C, <em>but</em> that C code doesn't immediately jump out as the best way to do things. In particular, I don't see where you gain anything by taking the absolute value before you do your multiplication. Given that your're squaring the value immediately afterwards anyway, it would appear simpler to just leave it negative if that's what it happens to be. Lacking a specific reason to do otherwise, I'd start with something simpler, like this:</p>\n\n<pre><code>double x = x1 - x2;\ndouble y = y1 - y2;\n\ndouble dist = sqrt(x * x + y * y);\n</code></pre>\n\n<p>Then I'd convert that to SSE instructions.</p>\n\n<p>Especially if you're concerned with speed, you might want to consider using an alternative to the Pythagorean theorem to compute the hypotenuse though. I posted some C for one possibility in a <a href=\"https://stackoverflow.com/a/3506633/179910\">previous answer</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T04:27:09.440",
"Id": "45126",
"ParentId": "44802",
"Score": "1"
}
},
{
"body": "<h2>Without SSE</h2>\n\n<ul>\n<li>There is no need to take the absolute value. If X is real, then X^2 is always positive.</li>\n<li>Consider using hypot(x,y) rather than sqrt(x*x+y*y). It is simpler and more accurate.</li>\n</ul>\n\n<p>My suggestions:</p>\n\n<pre><code>double distanceSqrt(int x1, int x2, int y1, int y2)\n{\n double dx = x2 - x1;\n double dy = y2 - y1;\n return sqrt(dx*dx + dy*dy);\n}\n\ndouble distanceHypot(int x1, int x2, int y1, int y2)\n{\n return hypot(x2 - x1, y2 - y1);\n}\n</code></pre>\n\n<h2>SSE</h2>\n\n<ul>\n<li>What version of SSE are you targeting?</li>\n</ul>\n\n<p>Rather than trying to correct your SSE version, I will build a new version. First I want to point out a few errors to try and clear up some misconceptions. Lets look at your first line of code:</p>\n\n<pre><code>__m128d vx1 = _mm_load_pd(x1);\n</code></pre>\n\n<p>A double is 64-bits. A __m128d is 128-bits. A __m128d holds two doubles. _mm_load_pd() takes a pointer to an array of doubles and loads the first two into a __m128d. You defined x1 to be of type int in your distance() function. The pointer passed to _mm_load_pd() must be 16 byte aligned or your program will crash. Another snippet:</p>\n\n<pre><code>__m128d absX = _mm_mul_pd(vabsX,vabsX);\n__m128d absY = _mm_mul_pd(vabsY,vabsY);\n</code></pre>\n\n<p>You only need to call _mm_mul_pd() once. A __m128 holds two doubles so _mm_mul_pd() actually performs two multiplications.</p>\n\n<pre><code>//a={a1,a2}\n//b={b1,b2}\n//{a1*b1,a2*b2}=_mm_mul_pd(a,b)\n\ndouble distance(int x1, int x2, int y1, int y2)\n{\n __declspec(align(16)) double diff[2] = {x2 - x1, y2 - y1};\n __m128d temp = _mm_load_pd(diff);\n temp = _mm_mul_pd(temp, temp);\n //...\n}\n</code></pre>\n\n<p>In this example the variable temp holds diff[0]*diff[0] in the low 8 bytes and diff[1]*diff[1] in the high 8 bytes.</p>\n\n<p>Lets build a working SSE version of the distance() function.</p>\n\n<pre><code>double distanceSSE(int x1, int x2, int y1, int y2)\n{\n</code></pre>\n\n<p>The first thing we need to do load the integers into SSE variables. A _m128i can hold four 32-bit integers, but we only need two.</p>\n\n<pre><code> __m128i point1 = _mm_set_epi32(0,0,x1,y1);\n __m128i point2 = _mm_set_epi32(0,0,x2,y2);\n</code></pre>\n\n<p>We eventually need to convert these integers to doubles. We will wait because integer math is easier than double math. Also, the next operation is subtraction and there is no loss of information by sticking with integers. Find the distance on each plane.</p>\n\n<pre><code> __m128i diff = _mm_sub_epi32(point2,point1);\n</code></pre>\n\n<p>Next is multiplication which we can do with _mm_mul_epi32() without loss of information, but that creates two 64-bit integers. Converting 64-bit integers to doubles is harder than 32-bit integers to doubles so we will convert them now.</p>\n\n<pre><code> __m128d temp = _mm_cvtepi32_pd(diff);\n</code></pre>\n\n<p>The variable temp now contains two doubles {y2-y1,x2-x1}. Lets square them.</p>\n\n<pre><code> temp = _mm_mul_pd(temp,temp);\n</code></pre>\n\n<p>Now we need to add the two doubles in temp together before we take the square root. This time we use a horizontal add. We need a second argument so we just add a dummy.</p>\n\n<pre><code> temp = _mm_hadd_pd(temp,_mm_setzero_pd());\n</code></pre>\n\n<p>The square root.</p>\n\n<pre><code> temp = _mm_sqrt_pd(temp);\n</code></pre>\n\n<p>Finally, we copy the low double from temp into a double.</p>\n\n<pre><code> double ret;\n _mm_storel_pd(&ret,temp);\n return ret;\n}\n</code></pre>\n\n<p>Put it all together:</p>\n\n<pre><code>double distanceSSE(int x1, int x2, int y1, int y2)\n{\n __m128i point1 = _mm_set_epi32(0, 0, x1, y1);\n __m128i point2 = _mm_set_epi32(0, 0, x2, y2);\n __m128i diff = _mm_sub_epi32(point2, point1);\n __m128d temp = _mm_cvtepi32_pd(diff);\n temp = _mm_mul_pd(temp, temp);\n temp = _mm_hadd_pd(temp, _mm_setzero_pd());\n temp = _mm_sqrt_pd(temp);\n double ret;\n _mm_storel_pd(&ret, temp);\n return ret;\n}\n</code></pre>\n\n<p>This is a simple method to find the distance but not necessarily the best. For more information on the drawbacks of this method see <a href=\"http://en.wikipedia.org/wiki/Hypot\" rel=\"nofollow\">Hypot</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T11:19:33.987",
"Id": "45135",
"ParentId": "44802",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:31:30.113",
"Id": "44802",
"Score": "4",
"Tags": [
"c++",
"assembly",
"sse"
],
"Title": "Is this C++ program correctly implemented in SSE?"
} | 44802 |
<p>I have a class that I call "Icons"</p>
<p>Icons.h</p>
<pre><code>#import <Foundation/Foundation.h>
@interface Icons : NSObject
+ (UIImage *) someIcon;
+ (UIImage *) someOtherIcon;
+ (NSString *)imageToNSString:(UIImage *)image;
+ (UIImage *)stringToUIImage:(NSString *)string;
@end
</code></pre>
<p>Icons.m</p>
<pre><code>#import "Icons.h"
@implementation Icons
+ (UIImage *) someIcon {
return [self stringToUIImage:[self someIconStr]];
}
+ (UIImage *) menuLines {
return [self stringToUIImage:[self someOtherIconStr]];
}
+ (NSString *)imageToNSString:(UIImage *)image {
NSData *data = UIImagePNGRepresentation(image);
return [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}
+ (UIImage *)stringToUIImage:(NSString *)string {
NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
+ (NSString *) someIconStr {
return @"iVBORw0KGgoAAAANSUhEUgAAABYAAAAoCAYAAAD6xArmAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAHGlET1QAAAACAAAAAAAAABQAAAAoAAAAFAAAABQAAAB5EsHiAAAAAEVJREFUSA1iYKAimDhxYjwIU9FIBgaQgZMmTfoPwlOmTJGniuHIhlLNxaOGwiNqNEypkwlGk9RokoIUfaM5ijo5Clh9AAAAAP//ksWFvgAAAEFJREFUY5g4cWL8pEmT/oMwiM1ATTBqONbQHA2W0WDBGgJYBUdTy2iwYA0BrILDI7VMmTJFHqv3yBUEBQsIg/QDAJNpcv6v+k1ZAAAAAElFTkSuQmCC";
}
+ (NSString *) someOtherIconStr {
return @"iVBORw0KGgoAAAANSUhEUgAAADIAAAAKCAYAAAD2Fg1xAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAHGlET1QAAAACAAAAAAAAAAUAAAAoAAAABQAAAAUAAACZxAe6RgAAAGVJREFUOBFiYACCmTNn8k+ePLl+0qRJ74H4PxS/B4mB5EkFA2Ye0MHnkTwA8wiYBsmR6pEBMQ8U6rg8ARMHqSHWMwNmHtCxyMkJJTZgHgGpIdYjA2YekmNxeQIsToxHQHljoMwDAAAA//+psxowAAAAWUlEQVRjmDRp0n9iMAMRYObMmfzEmAVSQ4RxDCSZBzT0PRGWvyfGYpCaATNv8uTJ9YQ8AlJDrEcG1Dyg5edxeQYkR6wnYOoG1DxoSCIns/cgMZjjSKXpbR4A1NvIaZrhxd8AAAAASUVORK5CYII=";
}
</code></pre>
<p>This way, whenever I need to add an icon to a button or whatever, it's</p>
<pre><code>UIButton * btn;
[btn setImage:[Icons someIcon] forControlState:UIControlStateNormal];
</code></pre>
<p>It doesn't seem like a big fix, but here's the main reasons I do it.</p>
<ol>
<li>Easy To Use Same Icon Library Across Projects</li>
<li>No misspelled image errors</li>
<li>No need to create image file keys</li>
<li>Changing an icon quickly updates all iterations across project</li>
</ol>
<h3> Questions </h3>
<ol>
<li>Anyone else using something similar to this?</li>
<li>Should I store the image strings statically as opposed to returning them via method as is now?</li>
<li>Any other thoughts?</li>
</ol>
| [] | [
{
"body": "<p>I do something similar, except rather than creating my own class, I create a <code>UIImage</code> class category.</p>\n\n<p>File names are called <code>UIImage+Icon.h</code> and <code>UIImage+Icon.m</code>.</p>\n\n<p>In the <code>.h</code>, we have this:</p>\n\n<pre><code>@import UIKit.UIImage;\n\n@interface UIImage (Icon)\n\n+ (UIImage*)someIcon;\n+ (UIImage*)someOtherIcon;\n\n@end\n</code></pre>\n\n<p>And then put your code in the <code>.m</code> as normal.</p>\n\n<p>Be sure to note <code>@import UIKit.UIImage;</code> versus the <code>#import</code>. You don't need to import the entire UIKit. <code>@import</code> is new in Xcode 5 and vastly speeds up compile time as it only imports the required modules.</p>\n\n<p>Anyway, the advantage to this versus what you're doing is that we call our methods as such:</p>\n\n<pre><code>[UIImage someIcon];\n</code></pre>\n\n<p>It's clear as day that we're definitely returning a <code>UIImage</code> object, because we're calling a <code>UIImage</code> class method.</p>\n\n<p>EDIT: Having just noticed that your class also includes a method which returns <code>NSString</code>, I still recommend the class category. In this case, the <code>imageToNSString</code> method would look like this:</p>\n\n<pre><code>- (NSString*)toEncodedString;\n</code></pre>\n\n<p>The method doesn't take an argument because it is an instance method. Because this is a <code>UIImage</code> class category, you can refer to <code>self</code>, which gives you the <code>UIImage</code> instance on which this method was called.</p>\n\n<hr>\n\n<p>I personally like the <code>UIImage</code> class category, but another option that is still potentially better than what you're doing would be to create C-style functions.</p>\n\n<p>So you'll have a <code>.h</code> file that would include this function declaration:</p>\n\n<pre><code>UIImage * imageFromString(NSString *str);\n</code></pre>\n\n<p>As well as a list of <code>NSString * const</code> objects that you send as arguments. Then your <code>.m</code>, you've just got the logic for returning an image from a string.</p>\n\n<hr>\n\n<p>The main point here is that there are two options here that don't involve a class called <code>Icon</code>. The problem is, if there's a class called <code>Icon</code>, I kind of expect to be working with <code>Icon</code> objects in some way. And I might even try to instantiate an <code>Icon</code> object, which makes no sense...</p>\n\n<p>Ultimately though, if you're NOT going to create a <code>UIImage</code> class category OR use C-style functions and still work with the <code>Icon</code> class, since you only have class methods and your class certainly shouldn't be instantiated, I highly recommend adding this to your <code>.h</code> file:</p>\n\n<pre><code>+ (id)alloc __attribute__((unavailable(\"Icon class can not be instantiated\")));\n- (id)init __attribute__((unavailable(\"Icon class can not be instantiated\")));\n</code></pre>\n\n<p>This will throw red errors and prevent compilation if anyone tries to instantiate the <code>Icon</code> class. This is the worst option of the three I purposed in this situation, but it can be acceptable in some cases perhaps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:18:05.997",
"Id": "77961",
"Score": "0",
"body": "I like the alloc blockers, I'll add those in. I originally had it as a UIImage category, but I prefer it as an Icons class only for my own mental organization. What is the benefit of using a function over a method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:26:41.583",
"Id": "77964",
"Score": "0",
"body": "Technically, the function performs slightly better, but you'd never notice it. Even if you're trying to measure the difference, it's hard to detect. The main advantage is readability though. To me, an `Icon` class means there are `Icon` objects--there's a method out there SOMEWHERE that will return an `Icon` object type. If we instead use functions, we're making it more clear that these are simply helper methods for instantiating existing object types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:28:55.027",
"Id": "77966",
"Score": "0",
"body": "Consider Apple's own code. There's not a single Foundation class that can't be instantiated. When there's a method that, for whatever reason, Apple doesn't want to include within the relevant class, they provide a function. For example: https://developer.apple.com/library/ios/documentation/uikit/reference/UIKitFunctionReference/Reference/reference.html"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:08:38.127",
"Id": "44807",
"ParentId": "44806",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44807",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T21:49:43.497",
"Id": "44806",
"Score": "7",
"Tags": [
"objective-c",
"ios"
],
"Title": "Storing icons statically as strings in custom class"
} | 44806 |
<p><strong>Task:</strong> </p>
<p>Create an interactive slider that allows the user to view a given image gallery. </p>
<p><strong>Slider controls:</strong> </p>
<ul>
<li>See previous slide </li>
<li>See next slide </li>
<li>Quick navigation through the images / Paging - transition to an arbitrary slide </li>
</ul>
<p><strong>Properties of the object slide:</strong> </p>
<ul>
<li>image</li>
<li>title </li>
<li>description </li>
<li>link</li>
</ul>
<p><strong>Settings slider:</strong> </p>
<ul>
<li>Container - DOM-element slider </li>
<li>An array of images, links, titles and descriptions </li>
<li>Current slide </li>
<li>The time delay between turning </li>
<li>Speed of turning </li>
<li>Width slider </li>
<li>Height slider </li>
<li>Flag to show / hide title </li>
<li>Flag to show / hide description </li>
<li>Flag on / off auto rotate slide </li>
<li>Flag to show / hide button next / previous slide </li>
<li>Flag to show / hide the navigation bar slider / paging </li>
<li>Complete revolutions counter</li>
</ul>
<p><strong>Methods slider:</strong></p>
<ul>
<li>Generate a slider</li>
<li>Start Auto Play</li>
<li>Go to the slide №x</li>
<li>Next slide</li>
<li>Previous slide</li>
</ul>
<p><strong>Requirements:</strong></p>
<ul>
<li>Create a file default.css styles with the general settings page style</li>
<li>Create a file with parameters slider.css styles specifically slider</li>
<li>Create a file for the most slider.js slider</li>
<li>Width and height of the slider should not be described in a style file, and should be taken from the object parameters slider</li>
<li>Initialization command occurs slider var slider1 = slider (parameters), resulting in slider1 - will be subject to the above properties and methods.</li>
<li>Animation slider should take place by means of CSS3: transition: left / margin</li>
<li>Use only pure JavaScript</li>
</ul>
<p><strong>P.s. I'm a young programmer so I want to hear real reviews for further development.</strong> </p>
<p><strong>HTML:</strong></p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link href="css/default.css" rel="stylesheet" type="text/css">
<link href="css/slider.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/slider.js"></script>
<script type="text/javascript">
window.onload = function () {
var arrImgs = ["images/bigImg1.jpg", "images/bigImg2.jpg", "images/bigImg3.jpg", "images/bigImg4.jpg", "images/bigImg5.jpg", "images/bigImg6.jpg"];
var arrTitles = ["Title1", "Title2", "Title3", "Title4", "Title5", "Title6"];
var arrDescriptions = ["Description1", "Description2", "Description3", "Description4", "Description5", "Description6"];
var arrLinks = ["#", "#", "#", "#", "#", "#"];
var arrSlideProperties = [arrImgs, arrTitles, arrDescriptions, arrLinks];
var sliderOptions={
containerForSlider: ".container",
widthSlider:790,
heightSlider:450,
slideProperties:arrSlideProperties,
showTitles: true,
showDescriptions: true,
showNextPrevButtons: true,
showNavigationPanel: true,
delayTime: 3000,
speedTime: 2,
autoRotate: false,
fullCounter:0
}
var slider = Slider(sliderOptions);
}
</script>
</head>
<body>
<div class="container"><div>
</body>
</html>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code>function Slider(sliderOpt) {
var inteval = 0;
var numSlide = 1;
this.fullCounter = sliderOpt.fullCounter;
(this.createSlider = function() {
if (sliderOpt.containerForSlider.charAt(0) == ".") {
var container = document.getElementsByClassName(sliderOpt.containerForSlider.substring(1, sliderOpt.containerForSlider.length))[0];
}
if (sliderOpt.containerForSlider.charAt(0) == "#") {
var container = document.getElementById(sliderOpt.containerForSlider.substring(1, sliderOpt.containerForSlider.length));
}
container.style.width = sliderOpt.widthSlider + "px";
container.style.height = sliderOpt.heightSlider + "px";
container.style.border = "2px solid #808080";
var innerContainer = document.createElement("ul");
container.appendChild(innerContainer);
innerContainer.className = "innerContainer";
innerContainer.style.width = sliderOpt.widthSlider * sliderOpt.slideProperties[0].length + "px";
innerContainer.style.height = sliderOpt.heightSlider + "px";
for (var i = 0; i < sliderOpt.slideProperties[0].length; i++) {
var li = document.createElement("li");
innerContainer.appendChild(li);
li.className = "slide";
li.style.width = sliderOpt.widthSlider + "px";
li.style.height = sliderOpt.heightSlider + "px";
var a = document.createElement('a');
li.appendChild(a);
a.style.background = "url(" + sliderOpt.slideProperties[0][i] + ") no-repeat";
(function(e) {
a.onclick = function() {
location.href = sliderOpt.slideProperties[3][e];
}
})(i);
if (sliderOpt.showTitles == true) {
var title = document.createElement("div");
a.appendChild(title);
title.className = "title";
title.style.width = sliderOpt.widthSlider + "px";
title.innerHTML = sliderOpt.slideProperties[1][i];
}
if (sliderOpt.showDescriptions == true) {
var title = document.createElement("div");
a.appendChild(title);
title.className = "description";
title.style.width = sliderOpt.widthSlider + "px";
title.style.marginTop = sliderOpt.heightSlider - 50 + "px";
title.innerHTML = sliderOpt.slideProperties[2][i];
}
}
if (sliderOpt.showNextPrevButtons == true) {
var leftButton = document.createElement('a');
container.appendChild(leftButton);
leftButton.className = "leftButton";
var rightButton = document.createElement('a');
container.appendChild(rightButton);
rightButton.className = "rightButton";
}
var navigationPanel = document.createElement('div');
container.appendChild(navigationPanel);
navigationPanel.className = "navigationPanel";
for (var i = 0; i < sliderOpt.slideProperties[0].length; i++) {
var navigationPanelButton = document.createElement('a');
navigationPanel.appendChild(navigationPanelButton);
navigationPanelButton.className = "navigationPanelButton";
if (i == 0) navigationPanelButton.style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
}
})();
(this.runAutoRotate = function() {
if (sliderOpt.autoRotate == true) {
var innerContainer = document.getElementsByClassName("innerContainer")[0];
var navigationPanelButton = document.getElementsByClassName("navigationPanelButton");
interval = setInterval(function() {
if (numSlide == sliderOpt.slideProperties[0].length) {
innerContainer.style.MozTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.webkitTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.marginLeft = -40 + "px";
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 97% 55%";
numSlide = 1;
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
this.fullCounter++;
console.log(this.fullCounter); // counter full rotate(show console)
} else {
innerContainer.style.MozTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.webkitTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.marginLeft = -40 - sliderOpt.widthSlider * numSlide + "px";
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 97% 55%";
numSlide++;
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
}
}, sliderOpt.delayTime);
}
})();
(this.prevSlideRotate = function() {
var leftButton = document.getElementsByClassName("leftButton")[0];
var innerContainer = document.getElementsByClassName("innerContainer")[0];
var navigationPanelButton = document.getElementsByClassName("navigationPanelButton");
leftButton.addEventListener("click", function() {
if (sliderOpt.autoRotate == true) {
clearInterval(interval);
}
if (numSlide == 1) {
innerContainer.style.MozTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.webkitTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.marginLeft = -40 - sliderOpt.widthSlider * (sliderOpt.slideProperties[0].length - 1) + "px";
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 97% 55%";
numSlide = sliderOpt.slideProperties[0].length;
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
} else {
innerContainer.style.MozTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.webkitTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.marginLeft = -40 - sliderOpt.widthSlider * (numSlide - 2) + "px";
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 97% 55%";
numSlide--;
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
}
}, false);
})();
(this.nextSlideRotate = function() {
var rightButton = document.getElementsByClassName("rightButton")[0];
var innerContainer = document.getElementsByClassName("innerContainer")[0];
var navigationPanelButton = document.getElementsByClassName("navigationPanelButton");
rightButton.addEventListener("click", function() {
if (sliderOpt.autoRotate == true) {
clearInterval(interval);
}
if (numSlide == sliderOpt.slideProperties[0].length) {
innerContainer.style.MozTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.webkitTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.marginLeft = -40 + "px";
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 97% 55%";
numSlide = 1;
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
} else {
innerContainer.style.MozTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.webkitTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.marginLeft = -40 - sliderOpt.widthSlider * (numSlide) + "px";
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 97% 55%";
numSlide++;
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
}
}, false);
})();
(this.jumpToSlideRotate = function() {
var innerContainer = document.getElementsByClassName("innerContainer")[0];
var navigationPanelButton = document.getElementsByClassName("navigationPanelButton");
for (var i = 0; i < sliderOpt.slideProperties[0].length; i++) {
(function(e) {
navigationPanelButton[i].addEventListener("click", function() {
if (sliderOpt.autoRotate == true) {
clearInterval(interval);
}
innerContainer.style.MozTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.webkitTransition = "margin-left " + sliderOpt.speedTime + "s ease";
innerContainer.style.marginLeft = -40 - sliderOpt.widthSlider * (e) + "px";
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 97% 55%";
numSlide = e + 1;
navigationPanelButton[numSlide - 1].style.background = "url(images/buttonNavigation.jpg) no-repeat 1% 55%";
}, false);
})(i);
}
})();
}
</code></pre>
<p><strong>defaul.css:</strong></p>
<pre><code>html, body {
width: 100%;
height: 100%;
margin: 0;
background-color:#000;
}
.container {
margin: 20px auto;
border-radius: 7px;
overflow: hidden;
}
</code></pre>
<p><strong>slider.css:</strong></p>
<pre><code>.innerContainer {
position: relative;
background-color: #fff;
display: block;
margin: 0 0 0 -40px;
list-style: none;
}
.slide {
display: block;
float: left;
}
.slide a {
display: block;
width: 100%;
height: 100%;
}
.title {
width: 100%;
height: 50px;
position: absolute;
font-size: 34px;
font-weight: bold;
text-align: center;
}
.description {
width: 100%;
height: 50px;
position: absolute;
font-size: 34px;
font-weight: bold;
padding-left: 20px;
}
.leftButton {
display: block;
width: 40px;
height: 40px;
float: left;
margin: -245px 0 0 20px;
border-radius: 20px;
background: url(../images/button.jpg) no-repeat 5% 90%;
opacity: 0.5;
cursor: pointer;
}
.rightButton {
display: block;
width: 40px;
height: 40px;
float: right;
margin: -245px 20px 0 0;
border-radius: 20px;
background: url(../images/button.jpg) no-repeat 88% 90%;
opacity: 0.5;
cursor: pointer;
}
.leftButton:hover, .rightButton:hover {
opacity: 0.6;
}
.navigationPanel {
width: 210px;
height: 20px;
float: right;
margin: -40px 15px 0 0;
position: relative;
}
.navigationPanelButton {
display: block;
width: 14px;
height: 14px;
border-radius: 6px;
float: left;
margin-left: 12px;
cursor: pointer;
background: url(../images/buttonNavigation.jpg) no-repeat 97% 55%
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:57:33.470",
"Id": "77971",
"Score": "0",
"body": "Just to be clear, when you say \"slider\", you mean \"slideshow\", correct? Not like a slider you'd use to control e.g. volume."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:59:53.467",
"Id": "77972",
"Score": "0",
"body": "meant image rotator)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:01:29.937",
"Id": "77973",
"Score": "0",
"body": "such task I had at the interview!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T05:19:11.047",
"Id": "78017",
"Score": "0",
"body": "what do you advise?)"
}
] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>Do not use <code>window.onload = function () {</code> use <code>window.addEventListener(\"load\",</code></li>\n<li>In <code>arrImgs</code>, if all your images have the same folder as a prefix, then you should add support for an image folder</li>\n<li>Avoid Hungarian notation, <code>arrImgs</code> should <code>images</code>, drop that <code>arr</code>, it's important</li>\n<li>Prefer spelling out variables <code>inteval</code> -> <code>interval</code></li>\n<li>For you slider.js -> use JSHint.com, there are a lot of style problems</li>\n<li>You are setting a lot of things in your JavaScript that should be kept in .css files</li>\n<li><code>innerContainer.style.MozTransition = \"margin-left \" + sliderOpt.speedTime + \"s ease\";</code> and the surrounding statements appear 7(!) times in your code, I strongly suggest a common helper function.</li>\n</ul>\n\n<p>I think you need to use JsHint.com, check for copy pasted code, and fix that, and then come back with your fixed code in a new question.\n* </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T18:30:28.883",
"Id": "45874",
"ParentId": "44810",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45874",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T22:48:27.063",
"Id": "44810",
"Score": "6",
"Tags": [
"javascript",
"object-oriented",
"html",
"dom",
"user-interface"
],
"Title": "Interactive slider"
} | 44810 |
<p>I am parsing excel data and need to create object based on StartDate-EndDate difference.</p>
<p>Is there a better way to have only one linq perform this task and return two different result sets ? Only difference in both linq is just the variable on which its applied.</p>
<pre><code>private Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] ParseData(ExcelFile file, Dictionary<string, string>[] ConfigMap)
{
// Extract the information from the excel file
var excelData = file.GetWorksheetData(sheet: 0, rowStart: 2);
var monthlyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days > 1);
var dailyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days == 1);
var monthlyData = monthlyRows.Where(r => r[KeyCol] != null && ConfigMap[0].ContainsKey((string)r[KeyCol]))
.GroupBy(r => (string)r[KeyCol])
.ToDictionary(g => g.Key,
g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
.ToDictionary(c => c.Key,
c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
.ToList()));
var dailyData = dailyRows.Where(r => r[KeyCol] != null && ConfigMap[1].ContainsKey((string)r[KeyCol]))
.GroupBy(r => (string)r[KeyCol])
.ToDictionary(g => g.Key,
g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
.ToDictionary(c => c.Key,
c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
.ToList()));
return new Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] { monthlyData, dailyData };
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:12:28.300",
"Id": "77974",
"Score": "0",
"body": "I love `var` with a passion, but in this specific context it's not clear what type `monthlyRows` and `dailyRows` are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:19:02.347",
"Id": "77976",
"Score": "0",
"body": "where enumerable ExcelDataRows"
}
] | [
{
"body": "<p>Assuming <code>monthlyRows</code> and <code>dailyRows</code> are both <code>IEnumerable<ExcelDataRow></code>, a first step could be to <em>extract a method</em> (assuming return type here, I only skimmed through your code):</p>\n\n<pre><code>private Dictionary<DateTime, List<DataPoint>> GetDataDictionary(IEnumerable<ExcelDataRow> data)\n{\n var result = data.Where(r => r[KeyCol] != null && ConfigMap[0].ContainsKey((string)r[KeyCol]))\n .GroupBy(r => (string)r[KeyCol])\n .ToDictionary(g => g.Key,\n g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))\n .ToDictionary(c => c.Key,\n c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))\n .ToList())); \n return result;\n}\n</code></pre>\n\n<p>Your <code>ParseData</code> method's body could then look like this:</p>\n\n<pre><code> // Extract the information from the excel file\n var excelData = file.GetWorksheetData(sheet: 0, rowStart: 2);\n\n var monthlyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days > 1);\n var monthlyData = GetDataDictionary(monthlyRows);\n\n var dailyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days == 1);\n var dailyData = GetDataDictionary(dailyRows);\n\n return new Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] { monthlyData, dailyData };\n</code></pre>\n\n<hr>\n\n<p>That solves <em>one</em> issue.</p>\n\n<p>Next step would be to break down the LINQ query and make the code self-explanatory as far as <em>why</em> you need to have a dictionary of dictionaries of lists.. and then make that simpler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:34:27.067",
"Id": "77977",
"Score": "0",
"body": "That dict of dict is required with some other reasons. Was wondering if I can slice the data based on Date difference and apply the linq to prepare result all in one linq only and get two different results for different conditions. Guess its too much to ask for :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:46:24.977",
"Id": "77979",
"Score": "0",
"body": "@buffer_overflow make sure you check out our [help/on-topic] to see what CR is all about - it's possible you get answers with alternative implementations, but the answers you should be expecting are answers that identify weak spots in your coding style and in your implementation. But yes, it's possible. Take a look at what type that the `Where()` method is expecting - that's the type you could take as a parameter to the extracted method if you wanted to supply a condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:50:35.527",
"Id": "77980",
"Score": "0",
"body": "Thanks. Just wondering. As I haven't seen linq implementation which works on two different conditions in same statement and returns two different results say a list or array of size = number of conditions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T00:18:32.783",
"Id": "77984",
"Score": "0",
"body": "Why have the `result` variable at all? Instead, you could simply `return data.Where(…`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T00:19:51.950",
"Id": "77985",
"Score": "0",
"body": "@svick true, ..I systematically assign those to something, just to I have a chance to break and inspect when debugging, there's no other reason - actually now that I think of it, that's not even a good reason... I should stop doing that?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:22:43.330",
"Id": "44813",
"ParentId": "44811",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44813",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T23:03:54.153",
"Id": "44811",
"Score": "5",
"Tags": [
"c#",
"linq"
],
"Title": "Identical linq for different index"
} | 44811 |
<p>I am trying to learn C++ by myself. I looked up a sample question after going through some text. Though I would like someone to review my code. I'm basically asking you to break it to show some flaws or some thing I missed. As a beginner I tried exhaustively to improve it and now hit a wall to analyse robustness of the code.</p>
<p>Problem statement:</p>
<blockquote>
<p>In this challenge, write a program that takes in three arguments, a
start temperature (in Celsius), an end temperature (in Celsius) and a
step size. Print out a table that goes from the start temperature to
the end temperature, in steps of the step size; you do not actually
need to print the final end temperature if the step size does not
exactly match. You should perform input validation: do not accept
start temperatures less than a lower limit (which your code should
specify as a constant) or higher than an upper limit (which your code
should also specify). You should not allow a step size greater than
the difference in temperatures.</p>
</blockquote>
<pre><code>#include <iostream>
#include <cstdlib>
#include <string>
#define LOWER_LIMIT 23.3
#define UPPER_LIMIT 256.3
using namespace std;
bool isnum(string s)
{
//check if the string is a number
//48 & 57
int len = s.length();
for(int i = 0; i < len; i++)
{
//cout << s[i] << "\t" << int(s[i])<< endl;
if(int(s[i])>=48 && int(s[i])<=57)
return true;
else
{
return false;
break;
}
}
}
int main(int argc, char** argv)
//The int argc holds the argument count and the argv is a 2-D array4
// of characters
{
double start,end,step_size;
if(argc!=4)
{
cout<<"Please enter three intigers"<<endl;
cout<<"celcius <start_temprature> <end_temprature> <step_size>"<<endl;
cout<<"Last step may not be printed"<<endl;
}
else
{
//check if all the arguments are intigers
if(isnum(argv[1]) && isnum(argv[2]) && isnum(argv[3]))
{
cout<<argv[1]<<endl;
cout<<argv[2]<<endl;
cout<<argv[2]<<endl;
start = atof(argv[1]);
end = atof(argv[2]);
step_size = atof(argv[3]);
//calculate the table and print.
if(start < LOWER_LIMIT || start >UPPER_LIMIT)
{
cout<<"The <start_temprature> does not meet the limit requirement ("<<LOWER_LIMIT<<"\u00B0"<<"C - "<<UPPER_LIMIT<<"\u00B0"<<"C)"<<endl;
// The degree symbol to be printed on command line requires UTF-8 characters which has the degree symbol and the location is \u00B0
return -1;
}
if(end >UPPER_LIMIT || end <LOWER_LIMIT)
{
cout<<"The <end_temprature> does not meet the requirement ("<<LOWER_LIMIT<<"\u00B0"<<"C - "<<UPPER_LIMIT<<"\u00B0"<<"C)" <endl;
return -1;
}
if (step_size <1 || step_size >=(UPPER_LIMIT - LOWER_LIMIT))
{ //zero or negetive stepsize checking
cout<<"The step_size cannot be negetive, zero or greater than or equal to step_size"<<endl;
return -1;
}
if(end<start) //swapping variables if start is greater than end
{
cout <<"Swapped! end and start values for simplicity" <<endl;
double tmp = start;
start = end;
end = tmp;
}
cout << "start "<<start<<endl;
cout << "end "<<end<<endl;
cout << "step_size "<<step_size<<endl;
int nend = (int)((end-start)/step_size);
cout << nend <<"number of iterations"<<endl;
for(int i = 0; i < nend ;i++)
{
cout << start << "\u00B0"<<"C = " << ((start*(9/5))+32) << "\u00B0"<<"F" <<endl;
start += (double)step_size;
}
}
else
cout <<"All three input arguments must be positive numbers!" <<endl;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:29:59.063",
"Id": "78012",
"Score": "4",
"body": "Gentlemen && / || Ladies! This has been the most enlightening code review ever. A first for me :) . I am learning from the best."
}
] | [
{
"body": "<p>I won't review it all: just one comment as follows.</p>\n\n<p>Have you tested it and verified whether the output is correct?</p>\n\n<p>Some known-good test results (which you can assert your code should produce) are: 0C is 32F; -40C is -40F; and 100C is 212F.</p>\n\n<p>I think this is a bug:</p>\n\n<pre><code>((start*(9/5))+32)\n</code></pre>\n\n<p>The value of <code>(9/5)</code> is <code>1</code> (integer division rounding error). Instead you want</p>\n\n<pre><code>(((start*9)/5)+32) // less rounding error: a good approximation\n</code></pre>\n\n<p>or</p>\n\n<pre><code>((start*(9.0/5))+32) // floating point arithmetic: will have decimal places\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:06:23.693",
"Id": "77996",
"Score": "0",
"body": "You are right! the code was giving wrong output values. TY.. still looking for something that can break the code though. Applied the last fix to get correct output :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T02:58:23.827",
"Id": "44825",
"ParentId": "44821",
"Score": "11"
}
},
{
"body": "<h1>Things you could improve:</h1>\n\n<h3>Bugs</h3>\n\n<ul>\n<li><p>Your initial printing of the input command line arguments looks buggy.</p>\n\n<blockquote>\n<pre><code>cout<<argv[1]<<endl;\ncout<<argv[2]<<endl;\ncout<<argv[2]<<endl;\n</code></pre>\n</blockquote>\n\n<p>It looks like you meant to print <code>argv[3]</code> here, but accidentally put a <code>2</code>.</p></li>\n</ul>\n\n<h3>Syntax/Styling</h3>\n\n<ul>\n<li><p>Please don't use <code>using namespace std;</code>. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">It's considered a bad practice</a>, and is a bad habit to form.</p></li>\n<li><p>Use <a href=\"http://en.cppreference.com/w/cpp/string/byte/isdigit\" rel=\"nofollow noreferrer\"><code>std::isdigit()</code></a> instead of your <code>isnum()</code> function.</p></li>\n<li><p>You don't need to include the <code><cstdlib></code> or <code><string></code> headers (you will have to include <code><string></code> if you implement <code>std::isdigit()</code>).</p></li>\n<li><p>Put the variable declarations to separate lines. </p>\n\n<blockquote>\n<pre><code>double start,end,step_size;\n</code></pre>\n</blockquote>\n\n<p>From <em>Code Complete, 2d Edition</em>, p. 759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom,\n instead of top to bottom and left to right. When you’re looking for a\n specific line of code, your eye should be able to follow the left\n margin of the code. It shouldn’t have to dip into each and every line\n just because a single line might contain two statements.</p>\n</blockquote></li>\n</ul>\n\n<h3>Loops</h3>\n\n<ul>\n<li><p>You could use more loops throughout your program.</p>\n\n<blockquote>\n<pre><code>if(isnum(argv[1]) && isnum(argv[2]) && isnum(argv[3]))\n{ \n cout<<argv[1]<<endl;\n cout<<argv[2]<<endl;\n cout<<argv[2]<<endl;\n ...\n</code></pre>\n</blockquote>\n\n<p>Using a simple <code>for</code> loop here to reduce the code down a bit.</p>\n\n<pre><code>for (int i = 0; i < 3; i++)\n{\n if (std::isdigit(*argv[i])) std::cout << argv[i] << std::endl;\n else return -1; // or re-ask for user input\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:16:11.937",
"Id": "77997",
"Score": "1",
"body": "WoW! that is some good insight on the best way to do this :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:04:44.517",
"Id": "44826",
"ParentId": "44821",
"Score": "12"
}
},
{
"body": "<ul>\n<li><p><code>#define</code> macros are more common in C than in C++, and you should instead use constants:</p>\n\n<pre><code>const float LOWER_LIMIT = 23.3;\nconst float UPPER_LIMIT = 256.3;\n</code></pre></li>\n<li><p><code>main()</code> is doing too much. Ideally, you should have it handle input/output and function calls. For everything else, put them into separate functions with descriptive names. This will help make your code look cleaner and easier to follow.</p></li>\n<li><p>You're doing a C-style cast here:</p>\n\n<pre><code>int nend = (int)((end-start)/step_size);\n</code></pre>\n\n<p>This can be problematic in C++ and is generally unneeded.</p>\n\n<p>In cases such as these, you would use <code>static_cast<></code>:</p>\n\n<pre><code>int nend = static_cast<int>((end-start)/step_size);\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1609163/what-is-the-difference-between-static-cast-and-c-style-casting\">here</a> for more information.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:21:44.483",
"Id": "77999",
"Score": "0",
"body": "This is really good stuff. I have a long list of things to keep in mind while coding c. You caught me :) i use \"C\" a lot :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:23:20.227",
"Id": "78000",
"Score": "1",
"body": "Why should any `int` be involved at all? Just say what you mean, and use `while (start <= end)` as the termination condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:25:40.000",
"Id": "78002",
"Score": "0",
"body": "@200_success: Where, exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:26:55.433",
"Id": "78004",
"Score": "0",
"body": "I'm saying that `nend` is pointless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:28:47.393",
"Id": "78007",
"Score": "0",
"body": "@200_success: I know. I was pointing out the casting and used that as an example."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:16:24.647",
"Id": "44827",
"ParentId": "44821",
"Score": "11"
}
},
{
"body": "<h3>Automatically detectable bugs</h3>\n\n<p>First, let the compiler do some reviewing:</p>\n\n<pre><code>$ clang++ -Wall -c cr44821.cpp\ncr44821.cpp:26:1: warning: control may reach end of non-void function\n [-Wreturn-type]\n}\n^\n1 warning generated.\n</code></pre>\n\n<h3>User experience</h3>\n\n<p>I found your program to be infuriating to use. My first few attempts to run the program all failed; I would have expected all of them to produce reasonable output.</p>\n\n<pre><code>$ ./cr44821 -40 +40 0.5\nAll three input arguments must be positive numbers!\n$ ./cr44821 0 +40 0.5\nAll three input arguments must be positive numbers!\n$ ./cr44821 0 40 0.5\n0\n40\n40\nThe <start_temprature> does not meet the limit requirement (23.3°C - 256.3°C)\n$ ./cr44821 23.3 +40 0.5\nAll three input arguments must be positive numbers!\n$ ./cr44821 23.3 40 0.5\n23.3\n40\n40\nThe step_size cannot be negetive, zero or greater than or equal to step_size\n</code></pre>\n\n<p>I finally succeeded in getting an incomplete response. What happened to 24.3°C?</p>\n\n<pre><code>$ ./cr44821 23.3 25 1\n23.3\n25\n25\nstart 23.3\nend 25\nstep_size 1\n1number of iterations\n23.3°C = 55.3°F\n</code></pre>\n\n<p>My frustration appears to be partly a consequence of poor number parsing, and partly a consequence of artificial temperature limits. Reasonable limits, I think, are −273.15°C (absolute zero) for the lower bound, and 1.4e32°C (<a href=\"http://en.wikipedia.org/wiki/Absolute_hot\">absolute hot</a>) for the upper bound. (<code>std::numeric_limits<double>::max()</code> is 9.9e307, which is too large.)</p>\n\n<h3>Problem decomposition</h3>\n\n<p>There is plenty of action going on in <code>main()</code>. The temperature conversion calculation itself does not belong there. This problem cries out for a function</p>\n\n<pre><code>double c_to_f(double celsius) {\n return celsius / 5 * 9 + 32;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:27:27.800",
"Id": "78006",
"Score": "0",
"body": "I would actually like to see you do this code, you sound like a pro :) also i would have a great example to start with for learning c++. I am a newbie so i would like to know how would i parse the negetive numbers/arguments ? You have a great approach to the problem , i thing you will be able to generate the most robust and complete code :P Do you accept the challenge? :P :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T05:00:10.133",
"Id": "78013",
"Score": "1",
"body": "Asking for code to be written is normally off-topic on Code Review, but [I've taken the bait](http://codereview.stackexchange.com/q/44836/9357)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T05:15:47.310",
"Id": "78016",
"Score": "0",
"body": "Thankyou for taking the bait :P This is gonna help me soooooooooooo much. As for the input validation it looks PERFECT! based on just executing the code by passing the arguments you supplied in your comments above. The code is huge might take a while before i can digest it whole (because i am a noob) :). I appreciate you helping me out, you are AWESOME!I cannot reply on the code link you provided because apparently i dont have 50 reputation on CR."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T15:05:13.203",
"Id": "78117",
"Score": "1",
"body": "@Dexobox 200_success's answer uses the standard strtod function. Choosing and using the right standard function is very probably the right/correct/best way to do it. In contrast I [posted another topic](http://codereview.stackexchange.com/q/44869/34757) on how to parse it yourself; IMO it shows that doing it yourself (instead of reusing a standard function) not trivial, and takes a while to get it right. (It would have been simpler if had been integers instead of double-precision numbers: double-precision numbers have a more complicated syntax, because of the `.` and `E` characters)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:17:57.290",
"Id": "44829",
"ParentId": "44821",
"Score": "14"
}
},
{
"body": "<p>This question has been covered very thoroughly, but I have a bit more to add.</p>\n\n<hr>\n\n<p>Use spacing consistently. Sometimes you do <code>if(x>y)</code> sometimes you do <code>if(x > y)</code> and sometimes you do <code>if (x >y)</code>. Pick one (that's not <code>if(x >y)</code> and stick with it. Personally, I prefer <code>if (x > y)</code> as the spacing makes the operator easy to find.</p>\n\n<hr>\n\n<p>Declare variables as close to use as possible. For example, <code>start</code>, <code>end</code>, and <code>step_size</code> could all be declared and defined at the same time. This makes it clear where the variables are used and gives a better context.</p>\n\n<hr>\n\n<p>You have a typo that actually shouldn't compile (seems only the newest version of clang catches it):</p>\n\n<pre><code>cout<<\"The <end_temprature> does not meet the requirement (\"<<LOWER_LIMIT<<\"\\u00B0\"<<\"C - \"<<UPPER_LIMIT<<\"\\u00B0\"<<\"C)\" <endl;\n</code></pre>\n\n<p>There's a missing <code><</code> before the <code>endl</code>.</p>\n\n<hr>\n\n<p>Just like with your <code>if</code> statements, it's much easier to read <code>cout</code> statements if they have more space in them:</p>\n\n<pre><code>std::cout << \"...\" << x << \"...\" << ...\n</code></pre>\n\n<hr>\n\n<p>Prefer <code>std::swap</code> over manual swapping. It's both clearer and cleaner.</p>\n\n<hr>\n\n<p>Instead of <code>-1</code>, I would probably return <code>EXIT_FAILURE</code>. <code>-1</code> does not have particularly well defined meaning as a return value on most systems. In fact, on linux, it will a rather large positive number.</p>\n\n<hr>\n\n<p>Preferably (<em>in my opinion</em>) use braces for all blocks (meaning for <code>if</code>, <code>else</code>, <code>while</code>, etc). At a very minimum though, make sure to indent. It makes it clear that a piece of code belongs to the control flow above it.</p>\n\n<hr>\n\n<p>Once again, be consistent:</p>\n\n<pre><code>for(int i = 0; i < nend ;i++)\n</code></pre>\n\n<p>Should be</p>\n\n<pre><code>for(int i = 0; i < nend; i++)\n</code></pre>\n\n<hr>\n\n<p>Generally standard out (typically accessed through <code>cout</code> in C++) should be reserved for output and standard error (<code>cerr</code>) should be used for error messages or debugging. This allows for easier output handling for programs or users using your program.</p>\n\n<hr>\n\n<p><code>isnum</code> is not guaranteed to have a return value if <code>s</code> is empty.</p>\n\n<hr>\n\n<p>Returning and then breaking is redundant. The return will kill the loop already.</p>\n\n<hr>\n\n<p>Since <code>s</code> isn't modified, it should be passed by <code>const reference</code>. As <code>isnum</code> is now, it will copy the string passed to it.</p>\n\n<hr>\n\n<p>The magic numbers <code>48</code> and <code>57</code> are confusing and can be avoided by doing <code>s[i] >= '0' && s[i] <= '9'</code>. There's also no need to cast to an int since this will be comparing a char to a char.</p>\n\n<p>Note that the standard does not mandate the ASCII charset or something compatible be used. This means that in theory a charset with non contiguous characters could be in use. For this reason (and because it's cleaner/clearer), you should use <code>std::isdigit</code> instead of a range check.</p>\n\n<hr>\n\n<p>Your loop in <code>isnum</code> is broken. You return true if the first character is a digit and return false if the first character is not a digit. Otherwise, the return is undefined. This is not the behavior you desire, and you need to restructure your loop. In psuedo-code:</p>\n\n<pre><code>for each character:\n if character is not a digit:\n return false\n return true\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:20:11.837",
"Id": "78010",
"Score": "0",
"body": "Kudos ... great code review mate. I am learning so much in my very first program :). I will keep in mind the spacing of everything from now. I love this website and the creative criticism :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:57:10.593",
"Id": "44831",
"ParentId": "44821",
"Score": "13"
}
},
{
"body": "<p>The program calls for upper and lower bounds, but these:</p>\n\n<pre><code>#define LOWER_LIMIT 23.3\n#define UPPER_LIMIT 256.3\n</code></pre>\n\n<p>...strike me as rather strange choices. </p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>I doubt I'm the first one to mention it, but this is generally considered a poor idea, and better avoided.</p>\n\n<pre><code>bool isnum(string s)\n{\n //check if the string is a number\n //48 & 57\n int len = s.length();\n for(int i = 0; i < len; i++) \n {\n //cout << s[i] << \"\\t\" << int(s[i])<< endl;\n if(int(s[i])>=48 && int(s[i])<=57)\n return true;\n else\n {\n return false;\n break;\n }\n }\n}\n</code></pre>\n\n<p>There are a number of ways to do this more cleanly. For one example, you could use something like:</p>\n\n<pre><code>static const char digits[] = \"0123456789\";\n\nreturn s.find_first_not_of(digits) == std::string::npos;\n</code></pre>\n\n<p>Another possibility would be to use <code>std::isdigit</code> from <code><cctype></code> (or <code><ctype.h></code>). I would also (strongly) consider supporting negative numbers, as negative temperatures are fairly common on the Celsius scale.</p>\n\n<pre><code>int main(int argc, char** argv)\n//The int argc holds the argument count and the argv is a 2-D array4\n// of characters\n</code></pre>\n\n<p>Sort of a technicality, but <code>argv</code> isn't really a 2D array--it's an array of pointers, each holding the address of a string. Though they can be used in some of the say ways, there are other ways of using one that don't apply to the other. They can be easy to confuse, but doing so can lead to problems later.</p>\n\n<pre><code>{\n double start,end,step_size;\n if(argc!=4)\n {\n cout<<\"Please enter three intigers\"<<endl;\n cout<<\"celcius <start_temprature> <end_temprature> <step_size>\"<<endl;\n cout<<\"Last step may not be printed\"<<endl;\n</code></pre>\n\n<p>Nit-picky perhaps, but it's worth putting some effort into getting the spelling in your strings correct. </p>\n\n<pre><code> //check if all the arguments are intigers\n</code></pre>\n\n<p>Spelling in comments counts too. :-) The compiler may not care, but you should normally plan on writing primarily for human readers, and only secondarily for a compiler.</p>\n\n<pre><code> if(end<start) //swapping variables if start is greater than end\n {\n cout <<\"Swapped! end and start values for simplicity\" <<endl;\n</code></pre>\n\n<p>For \"errors\" like this that don't really effect the normal operation of the program, I consider it better (at least as a rule) to not print out an error message at all.</p>\n\n<pre><code> double tmp = start;\n start = end;\n end = tmp;\n</code></pre>\n\n<p>You might want to use <code>std::swap</code> to do the swapping though.</p>\n\n<pre><code>cout << start << \"\\u00B0\"<<\"C = \" << ((start*(9/5))+32) << \"\\u00B0\"<<\"F\" <<endl;\n</code></pre>\n\n<p>I'd try to separate the <code>\"\\u00B0\"</code> out and give it a meaningful name:</p>\n\n<pre><code>static char const *degree_symbol = \"\\u00B0\";\n\ncout << start << degree_symbol << \"C = \" // ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:27:31.723",
"Id": "78011",
"Score": "0",
"body": "I was really confused at the temperature ranges as the problem statement did not specify any values for the limits. I just wanted to see if the code would run on some limits. Interesting insight on error handling, and the unicode format tip. Thank You Very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:12:13.290",
"Id": "44833",
"ParentId": "44821",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "44829",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T02:21:09.590",
"Id": "44821",
"Score": "25",
"Tags": [
"c++",
"beginner"
],
"Title": "Print out table with start/end temperatures and step size"
} | 44821 |
<p>I am a beginner and I have made Colorful Lights using check-boxes in HTML. I'm pretty sure it will look horrible to any developer out there, but hey, that's why I've posted it.</p>
<p>I'd like a general review of this. I'm especially concerned about the quality and enhancements of this form.</p>
<pre><code><html>
<head>
<title>
Javascript
</title>
</head>
<body topmargin=15><p align=center>
<script>
var time = 0
for (var num1 = 0; num1 <= 32; num1+=2)
{
for (var num2 = 0; num2 <= num1; num2++)
{
// if (num1 >= 26 && num2 == (10 || 11) ; else
randomnumber=Math.floor(Math.random()*2323232)
document.write('<INPUT type="checkbox" onmouseover="document.bgColor='+"'"+randomnumber
+"'"+'">')
}
num2 = 0
document.write("<br>")
}
for (var num5 = 30; num5 >= 0; num5-=2)
{
for (var num6 = 0; num6 <= num5; num6++)
{
randomnumber=Math.floor(Math.random()*2323232)
document.write('<INPUT type="checkbox" onmouseover="document.bgColor='+"'"+randomnumber
+"'"+'">')
}
num6 = 0
document.write("<br>")
}
</script>
</p>
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T06:02:01.917",
"Id": "78020",
"Score": "0",
"body": "Why do you use checkboxes for this? Any element can have mouseover events, and using checkboxes when you don't seem to use them as, well, checkboxes seems odd"
}
] | [
{
"body": "<p>1) I'd start with a better HTML template, you forgot the DOCTYPE and meta tags:</p>\n\n<pre><code><!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title></title>\n</head>\n<body>\n\n</body>\n</html>\n</code></pre>\n\n<p>2) Don't use <code>topalign</code> and <code>align</code> HTML attributes. Keep the styles and layout separate, use CSS:</p>\n\n<pre><code>body {\n margin: 15px 0;\n text-align: center;\n}\n</code></pre>\n\n<p>3) In JavaScript it is ussually preferred to put braces on the same line, because the ASI (automatic semicolon insertion) feature can be problematic, consider this buggy example:</p>\n\n<pre><code>return\n{\n foo: 'foo'\n}\n</code></pre>\n\n<p>JavaScript will do this:</p>\n\n<pre><code>return; //<--!!!!\n{\n foo: 'foo'\n}\n</code></pre>\n\n<p>See the semicolon it added? Now you return <code>undefined</code>, and not an object.</p>\n\n<p>Now, you forgot a bunch of semicolons. Again, ASI can fill them up for you, but I don't recommend you rely on it if you're a beginner, so my advice is always put the semicolons.</p>\n\n<p>5) Check your code in <a href=\"http://jshint.com\" rel=\"nofollow noreferrer\">JSHint</a>, this is what I got:</p>\n\n<pre><code>13 warnings\n1 Missing semicolon.\n5 Missing semicolon.\n6 document.write can be a form of eval.\n6 Missing semicolon.\n8 Missing semicolon.\n9 document.write can be a form of eval.\n9 Missing semicolon.\n13 Missing semicolon.\n14 document.write can be a form of eval.\n14 Missing semicolon.\n16 Missing semicolon.\n17 document.write can be a form of eval.\n17 Missing semicolon.\nOne undefined variable\n5 randomnumber\n6 randomnumber\n13 randomnumber\n14 randomnumber\nOne unused variable\n1 time\n</code></pre>\n\n<p>Go one by one, try to fix all those warnings.</p>\n\n<p>6) Avoid <code>document.write</code>, see <a href=\"https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice\">Why is document.write considered bad practice</a>. In other words, use the DOM.</p>\n\n<p>7) Inline events are bad practice, again, use the DOM, with <code>addEventListener</code>.</p>\n\n<p>8) Using the DOM can be expensive. Try to always add elements all at once. Document fragments help you improve performance, because you don't mess with the DOM on every iteration of the loop.</p>\n\n<p>9) Finally, separate concerns; the single responsibility idea. This is how I would write it taking all those points into consideration:</p>\n\n<pre><code>// Use the DOM to create elements\nfunction makeInput() {\n var input = document.createElement('input');\n input.type = 'checkbox';\n return input;\n}\n\nfunction append(ele, parent) { \n (parent||document.body).appendChild(ele);\n}\n\nfunction makeLights() {\n var i, j;\n var br = document.createElement('br');\n\n // Use a document frag to improve performance\n var frag = document.createDocumentFragment();\n\n // No need to reset \"j\" on every iteration\n for (i=0; i<=32; i+=2) {\n for (j=0; j<=i; j++) append(makeInput(), frag);\n append(br.cloneNode(), frag);\n }\n\n for (i=30; i>=0; i-=2) {\n for (j=0; j<=i; j++) append(makeInput(), frag);\n append(br.cloneNode(), frag);\n }\n\n // Append to document all at once\n append(frag); \n}\n\nfunction randomColor() {\n return Math.floor(Math.random() * 2323232);\n}\n\n// Use event delegation for best performance\ndocument.body.addEventListener('mouseover', function(e) {\n if (e.target.tagName == 'INPUT') {\n document.bgColor = randomColor();\n }\n});\n\nmakeLights(); // init\n</code></pre>\n\n<p><strong>Demo:</strong> <a href=\"http://jsbin.com/yiyic/1\" rel=\"nofollow noreferrer\">http://jsbin.com/yiyic/1</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T06:09:54.987",
"Id": "78021",
"Score": "2",
"body": "Nice answer. But why the `j = 0;` after each loop? They're not necessary"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T06:11:24.057",
"Id": "78022",
"Score": "0",
"body": "Good point, I edited the answer, I just copy/pasted from OPs code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T03:17:43.253",
"Id": "44828",
"ParentId": "44822",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "44828",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T02:28:41.400",
"Id": "44822",
"Score": "10",
"Tags": [
"javascript",
"beginner",
"html"
],
"Title": "Colorful Lights in HTML"
} | 44822 |
<p>It's harder to do than <a href="https://codereview.stackexchange.com/a/44829/9357">criticize</a>. Here's my attempt to implement a Celsius-to-Fahrenheit conversion table in C++.</p>
<pre><code>#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#define DEGREE_SIGN "\u00B0"
class Fahrenheit;
class Celsius {
public:
explicit Celsius(double c) : c(c) {
if (c < MIN_VALUE) {
throw "Temperature below minimum";
} else if (c > MAX_VALUE) {
throw "Temperature above maximum";
}
}
Celsius(Fahrenheit f);
operator double() const { return c; }
Celsius operator +(Celsius incr) const { return Celsius(c + incr.c); }
Celsius &operator +=(Celsius incr) { c += incr.c; return *this; }
friend std::ostream &operator<<(std::ostream &os, Celsius c) {
return os << (double)c << DEGREE_SIGN << 'C';
}
static const Celsius MIN; // Absolute zero
static const Celsius MAX; // Absolute hot (approx.)
private:
double c;
static const double MIN_VALUE;
static const double MAX_VALUE;
};
class Fahrenheit {
public:
explicit Fahrenheit(double f) : f(f) {
if (f < MIN_VALUE) {
throw "Temperature below minimum";
} else if (f > MAX_VALUE) {
throw "Temperature above maximum";
}
}
Fahrenheit(Celsius c);
operator double() const { return f; }
Fahrenheit operator +(Fahrenheit incr) const { return Fahrenheit(f + incr.f); }
Fahrenheit &operator +=(Fahrenheit incr) { f += incr.f; return *this; }
friend std::ostream &operator<<(std::ostream &os, Fahrenheit f) {
return os << (double)f << DEGREE_SIGN << 'F';
}
static const Fahrenheit MIN; // Absolute zero
static const Fahrenheit MAX; // Absolute hot (approx.)
private:
double f;
static const double MIN_VALUE;
static const double MAX_VALUE;
};
Celsius::Celsius(Fahrenheit f) : c((f - 32) / 9 * 5) {}
const double Celsius::MIN_VALUE = -273.15;
const double Celsius::MAX_VALUE = 1.4e32;
const Celsius Celsius::MIN = Celsius(Celsius::MIN_VALUE);
const Celsius Celsius::MAX = Celsius(Celsius::MAX_VALUE);
Fahrenheit::Fahrenheit(Celsius c) : f(c / 5 * 9 + 32) {}
const double Fahrenheit::MIN_VALUE = -459.67;
const double Fahrenheit::MAX_VALUE = 2.5e32;
const Fahrenheit Fahrenheit::MIN = Fahrenheit(Fahrenheit::MIN_VALUE);
const Fahrenheit Fahrenheit::MAX = Fahrenheit(Fahrenheit::MAX_VALUE);
#ifdef _WIN32
const char PATH_SEPARATOR = '\\';
#else
const char PATH_SEPARATOR = '/';
#endif
const char *basename(const char *path) {
const char * sep = strrchr(path, PATH_SEPARATOR);
return sep ? sep + 1 : path;
}
int main(int argc, char *argv[]) {
if (argc != 4) {
std::cout << "Usage: " << basename(argv[0]) << " MIN MAX STEP" << std:: endl;
return 1;
}
try {
char *minEnd, *maxEnd, *stepEnd;
Celsius min(strtod(argv[1], &minEnd)),
max(strtod(argv[2], &maxEnd)),
step(strtod(argv[3], &stepEnd));
if (*minEnd != '\0') {
std::cerr << "Invalid minimum temperature" << std::endl;
return 1;
} else if (*maxEnd != '\0') {
std::cerr << "Invalid maximum temperature" << std::endl;
return 1;
} else if (*stepEnd != '\0') {
std::cerr << "Invalid temperature step" << std::endl;
return 1;
}
if (step <= 0.0) {
std::cerr << "Step must be positive" << std::endl;
return 1;
} else if (step > max - min) {
std::cerr << "Step exceeds temperature range" << std::endl;
return 1;
} else if (max < min) {
std::cerr << "Minimum temperature exceeds maximum temperature" << std::endl;
return 1;
}
for (Celsius c = min; c <= max; c += step) {
std::cout << std::setw(8) << c
<< std::setw(8) << Fahrenheit(c)
<< std::endl;
}
} catch (const char *msg) {
std::cerr << msg << std::endl;
return 1;
}
return 0;
}
</code></pre>
<p>Some concerns I have:</p>
<ul>
<li>What do you think of the input validation?</li>
<li>Is the code repetition justified? Much of the <code>Fahrenheit</code> class is not strictly necessary for the problem, and is included for completeness. Still, does the repetition enhance clarity, or is it harmful?</li>
</ul>
| [] | [
{
"body": "<p>I would have gone (and actually have gone in production code) for a <code>Temperature</code> class providing methods to obtain the values in the different units. This makes the streaming output slightly trickier but avoids the code repetition and makes it easier to lets say add Kelvin to it.</p>\n\n<p>I'd also prefer to use <a href=\"http://www.stroustrup.com/C++11FAQ.html#member-init\">C++11 in class member initializers</a> for the min and max limits rather than initializing them outside (unavoidable though if you don't have a C++11 compiler at hand).</p>\n\n<p>Also I don't like errors which say \"This value is outside of the valid range\" without telling me what the valid range actually is (which is not necessarily obvious if I don't have the source to check)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T07:27:06.900",
"Id": "44837",
"ParentId": "44836",
"Score": "13"
}
},
{
"body": "<p>My first reaction was the same as ChrisWue's: consider using a single Temperature class instead. For example <a href=\"https://codereview.stackexchange.com/a/39371/34757\">here is an example</a> of a (C#) class handle angle units (i.e. radians and degrees).</p>\n\n<p>Alternatively, the repetition/duplication between the two classes could perhaps be avoided with a common base class or by using templates.</p>\n\n<blockquote>\n <p>Still, does the repetition enhance clarity, or is it harmful?</p>\n</blockquote>\n\n<p>I had a few concerns:</p>\n\n<ul>\n<li><p>What a wall of text for such a simple problem! It reminded me of <a href=\"http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html\" rel=\"nofollow noreferrer\">this joke</a>.</p></li>\n<li><p>I had to inspect the core of it twice, for example:</p>\n\n<pre><code>f(c / 5 * 9 + 32)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>c((f - 32) / 9 * 5)\n</code></pre>\n\n<p>No way around that; it's because you implemented functionality (bi-directional conversion) that wasn't required in the original problem (which only needed uni-directional conversion).</p></li>\n<li><p>Checking that you didn't have the same bug as the original solution required me to check two lines instead of just one, i.e.:</p>\n\n<pre><code>f(c / 5 * 9 + 32)\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>operator double() const { return c; }\n</code></pre></li>\n<li><p>I was puzzled to find PATH_SEPARATOR in this code (\"Why are you handling paths? Oh, I see.\") If you have it, you needn't have defined it at global scope (it could have been inside basename which could have been inside main, or it could have been inside its own class.</p></li>\n<li><p>You have explicit construction from double, which is good. Perhaps it would be clearer to have explicit conversion to double too.</p></li>\n<li><p>operator+ can be defined using operator+= <a href=\"https://codereview.stackexchange.com/questions/44505/type-safe-date-class-with-total-encapsulation/44507#comment77279_44507\">as discussed elsewhere</a>.</p></li>\n</ul>\n\n<blockquote>\n <p>What do you think of the input validation?</p>\n</blockquote>\n\n<p>You throw a string instead of some exception class. Your main knows that it needs to catch a string, but if the classes were reused elsewhere it might be better to throw something else.</p>\n\n<p>If you throw it might be helpful to the user to print not only the error message, but also the error value and which temperature (high or low) which failed to intialize.</p>\n\n<p>Maybe you'd like to be able to count downwards (negative step).</p>\n\n<p>I doubt that step should be of type Celcius and subject to the same min/max range validation as Celcius: by analogy, the difference (i.e. step) between two dates is not a date, but a time-span (e.g. a number of days or seconds).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T11:30:34.923",
"Id": "44843",
"ParentId": "44836",
"Score": "9"
}
},
{
"body": "<ol>\n<li>Don't throw string literals directly. Instead throw an instance of <code>std::exception</code> or (even better) a subclass thereof (in this case, I would choose either <code>std::domain_error</code> or <code>std::out_of_range</code>). It makes it easier for people to catch using <code>catch (std::exception&)</code>.</li>\n<li>The <code>Celsius(Fahrenheit)</code> constructor should probably take its argument by const reference.</li>\n<li>I don't like the <code>operator double</code> conversion operator; it seems too easy to accidentally invoke. I think it's better to have a member function that you have to explicitly call to get its numeric value.</li>\n<li><p><code>operator+</code> is usually better to be a free function. That way, you can use the standard implementation:</p>\n\n<pre><code>Celsius operator+(Celsius lhs, Celsius const& rhs) {\n return lhs += rhs;\n}\n</code></pre>\n\n<p>noting that <code>lhs</code> is passed by value. There are other reasons for having <code>operator+</code> be a free function, such as being able to use other types for the LHS, other types for the RHS, etc., but here, the main advantage is that you can take the LHS by value.</p></li>\n<li><code>operator+=</code> should take its argument by const reference.</li>\n<li>I would actually embed the degree sign straight into the string literal(s), rather than using a <code>#define</code> (the use of which is discouraged in C++). We live in a UTF-8 world.</li>\n<li>Do not use C-style casts (<code>(double)c</code> as you had it). Here, it's much clearer to just write <code>c.value()</code> (if you added that member function as I suggested above; this has the added benefit of not requiring <code>friend</code> access) or <code>c.c</code>. In the general case of casting, it'd be better to use (in this case) a <code>static_cast</code>.</li>\n<li><code>Fahrenheit::MIN_VALUE</code> and <code>Fahrenheit::MAX_VALUE</code> should be calculated off the value of <code>Celsius::MIN_VALUE</code> and <code>Celsius::MAX_VALUE</code>.</li>\n<li>All the comments about <code>Celsius</code> above apply to <code>Fahrenheit</code> too.</li>\n<li>Use <code>std::cerr</code> to print out the usage message, not <code>std::cout</code>.</li>\n<li>Use <code>'\\n'</code> instead of <code>std::endl</code>. See <a href=\"http://www.aristeia.com/Papers/C++ReportColumns/novdec95.pdf\" rel=\"noreferrer\"><em>The little <code>endl</code> that couldn't</em></a> for rationale.</li>\n<li>It's much more robust to parse numbers using <code>boost::lexical_cast</code> instead of <code>strtod</code> and then checking the end pointers. In particular, your code doesn't handle the case of empty strings correctly, and will treat them as valid.</li>\n<li>The <code>else</code>s in your error checks are superfluous since all of the preceding <code>if</code> branches are exiting conditions.</li>\n<li>Use <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> for the exit codes instead of 0 and 1. Also, the bottom successful <code>return</code> is superfluous and should be removed.</li>\n</ol>\n\n<p>To answer your bottom question, by YAGNI principles, much of your <code>Fahrenheit</code> class should be omitted. But if you want to be general, you could have written a templated <code>TemperatureConverter</code>, of which <code>Celsius</code> and <code>Fahrenheit</code> could both be specialised typedefs.</p>\n\n<p>I also agree with the other two answers (also by Chrises, hah), and have upvoted them both.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:42:09.563",
"Id": "81215",
"Score": "1",
"body": "+1 lots of good stuff. Related to #14, you should mention that a return isn't needed at the end of `main()`. The compiler will do this automatically as successful termination is implied."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T20:35:52.073",
"Id": "46495",
"ParentId": "44836",
"Score": "14"
}
},
{
"body": "<p>For a strictly C++ effort, your use of objects could be considered commendable, from a certain perspective. However, your program is very long for a table. In fact, I wrote a similar program a few days ago that uses only 14 lines of code. To implement the degree sign would be 15, and most of it is just a simple for-loop. You would do well to avoid overcomplicating with objects if you want to do a task that requires some text output. </p>\n\n<p>Instead of using a class, make a namespace that includes a <code>double</code> function that returns the calculated number. Take a look at lines <strong>17</strong> to <strong>31</strong> <a href=\"https://github.com/Nnmjywg/F2C/blob/master/f2c_getopts.cc\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>You should also consider implementing <code>getopt</code> from <code>unistd.h</code> so that you don't have to write your own <code>argv[]</code> parser.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-12T12:54:13.600",
"Id": "172782",
"ParentId": "44836",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T04:57:23.067",
"Id": "44836",
"Score": "23",
"Tags": [
"c++",
"validation",
"floating-point",
"unit-conversion"
],
"Title": "Celsius → Fahrenheit conversion table"
} | 44836 |
<p>I'm new with Angular promise and I would like to know how to improve my code.</p>
<p>I have a service which preload media or data by calling an API.
The media API return an array of urls to preload.</p>
<pre><code>'use strict';
angular.module('myApp').service('PreloaderService', ['$http', '$q', 'localStorageService', function PreloaderService($http, $q, localStorageService) {
this.preload = function(key){
var current = 0;
var deferred = $q.defer();
switch (key) {
case 'media':
// Simplified, in fact it call a config service to get baseUrl
var url = 'http://myapi/media';
$http.get(url, {cache: true}).then(function(data) {
var data = data.data;
preloadImage(data, localStorageService.get('cachetoken'));
}, function(data) {
deferred.reject(data);
});
break;
case 'data':
var url = 'http://myapi/data';
$http.get(url, {cache: true}).then(function(data) {
var data = data.data;
localStorageService.add('data', data);
deferred.resolve(data);
}, function(data) {
deferred.reject(data);
});
break;
}
function preloadImage(arrayOfImages, cachetoken) {
var promises = [];
var totalImg = arrayOfImages.length;
for (var i = 0; i < totalImg; i++) {
(function(url, promise) {
var img = new Image();
img.onload = function() {
var currentStatus = {
currentImg: ++current,
totalImg: totalImg
};
deferred.notify(currentStatus);
promise.resolve();
};
img.src = url + '&tok=' + cachetoken;
})(arrayOfImages[i], promises[i] = $.Deferred());
}
$.when.apply($, promises).done(function() {
deferred.resolve('RESOLVED');
}).fail(function(data) {
deferred.reject(data);
});
}
return deferred.promise;
};
}]);
</code></pre>
<p>And I call it with</p>
<pre><code> var promise = Preloader.preload('media');
promise.then(
function(){
$rootScope.preload.imagesLoaded = true;
},
function(){},
function(currentStatus){
$rootScope.preload.currentImg = currentStatus.currentImg;
$rootScope.preload.totalImg = currentStatus.totalImg;
}
);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T11:11:53.297",
"Id": "78045",
"Score": "2",
"body": "I'm really trying hard not to be \"that guy\", but I can't help myself: \"data\" and \"media\" are plural forms already, so \"datas\" and \"medias\" isn't quite right. (The singular forms are \"datum\" and \"medium\", by the way.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T17:28:47.097",
"Id": "78163",
"Score": "1",
"body": "Too late, you're that guy ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T21:01:32.180",
"Id": "78200",
"Score": "0",
"body": "Ahah you are totally right, I updated my question :)"
}
] | [
{
"body": "<p>This took a while to parse, it's probably me, I found few flaws with the code, except for a distinct lack of comments.</p>\n\n<ul>\n<li><p>I would have made <code>url</code> in <code>preload</code> an optional, 2nd parameter, I would probably want to call preload a few times with different URL's ( for 'data' )</p></li>\n<li><p>I think using a <code>switch</code> for <code>media</code> and <code>data</code> is overkill, I would have done a simple <code>if</code> statement.</p></li>\n<li><p>Since you have a number of times <code>function(data) {deferred.reject(data);});</code>, I would have assigned this to an actual function.</p></li>\n<li><p><code>{cache: true}</code>, for <code>data</code> seem unfortunately hardcoded, consider this as well as optional parameter ?</p></li>\n<li><p>You define <code>current</code> on top, but <code>totalImg</code> in <code>preloadImage</code>, pick one spot and put both vars there</p></li>\n<li><p>Sometimes you postfix with <code>Img</code>, sometimes with <code>Images</code>. I would stick everywhere to <code>Images</code>, it is so much more readable</p></li>\n<li><p>Except for the <code>angular.module('myApp').service(</code> line, you have succinct lines of code, nice to read</p></li>\n<li><p>No need to store a shortcut to <code>data.data</code> in <code>var data = data.data;preloadImage(data, localStorageService.get('cachetoken'));</code></p></li>\n<li><p>I would not have gone down the road of managing an array of promises, I probably would have done a simple <code>if (current===totalImg) deferred.resolve('RESOLVED');</code></p></li>\n<li><p><code>'RESOLVED'</code> seems kind of pointless to provide as a parameter to <code>resolve</code>, we know it's resolved ;) Perhaps <code>totalImg + ' images loaded'</code> ?</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T20:23:19.730",
"Id": "46215",
"ParentId": "44840",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46215",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T09:53:19.563",
"Id": "44840",
"Score": "5",
"Tags": [
"javascript",
"angular.js",
"promise"
],
"Title": "Angular promise in service"
} | 44840 |
<p>I have a small Coldfusion section of our site that all uses similar JavaScript and CSS files and page design. The code is currently repeated for each file, and I'd like to factor it out and set something up using a master page and templates.</p>
<p>Master.cfm page:</p>
<pre><code><!--- Master template, includes all necessary js and css files.
Expects following variables to be defined:
- pageName - name of the file to be loaded as the body of the page
- title - text to be used as the title of the page and as the header text in the header bar --->
<cfinclude template="_lockedPage.cfm" />
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>#title#</title>
... all script and css links here ...
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.3.2.js"></script>
... etc ...
</head>
<body>
<div data-role="page">
<div class="headerDiv" data-role="header" data-theme="b" data-position="fixed">
<a id="backButton" data-role="button" data-direction="reverse" data-rel="back" data-icon="arrow-l" data-iconpos="left" data-theme="a">Back</a>
<h1><cfoutput>#title#</cfoutput></h1>
<a href="index.cfm" data-role="button" data-icon="home" data-iconpos="left" data-theme="a">Home</a>
</div>
<div data-role="content" class="container">
<cfinclude template="#pageName#.cfm" />
</div>
</div>
</body>
</html>
</code></pre>
<p>Then a page example would be something like this. CustomerSearch.cfm:</p>
<pre><code><cfscript>
title = "Customer Search";
pageName = "_customer-search";
include "Master.cfm";
</cfscript>
</code></pre>
<p>And then I would need a _customer-search.cfm page that would include all the body content for the page.</p>
<p>This means that I would need 2 files for every page that we currently have - the outer page that defines the variable and includes the master page, and the template page that has the individual page content.</p>
<p>Is this a good logical design? Is there anyway to improve it?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-05T18:12:24.447",
"Id": "92076",
"Score": "0",
"body": "The `#pageName#` concerns me. What will be setting that? Are you sure that you aren't subjecting the site for a url inject attack"
}
] | [
{
"body": "<p>My ColdFusion is a little rusty, but why would you not have the setting of the master dependent variables and the call to the master page both contained within the same page? Other than that, sure, you're implementing this the same way everyone does unless it's specifically built into the language.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T17:52:50.603",
"Id": "51636",
"ParentId": "44841",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T10:05:35.840",
"Id": "44841",
"Score": "10",
"Tags": [
"html",
"template",
"coldfusion"
],
"Title": "Structuring a master page"
} | 44841 |
<p>Method:</p>
<ul>
<li>Input: a string which represents an integer or a non-integer value.</li>
<li>Output: a string which represents the same value multiplied by 100.</li>
</ul>
<p>Requirements:</p>
<ul>
<li>No floating-point unless needed.</li>
<li>No leading 0s in the part left of the floating-point.</li>
<li>No trailing 0s in the part right of the floating-point.</li>
</ul>
<p>I cannot use the <code>Double.parseDouble</code> method, because it sometimes yields an "ugly" result.</p>
<p>For example:</p>
<pre><code>String.valueOf(Double.parseDouble("0.0071")*100)); // yields 0.7100000000000001
String.valueOf(Double.parseDouble("0.072" )*100)); // yields 7.199999999999999
</code></pre>
<p>Here is my code, and I would like to know if there are any cavities in it:</p>
<pre><code>String MultiplyBy100(String number)
{
StringBuilder sb = new StringBuilder();
String[] parts = number.split("\\.");
if (parts.length == 1)
sb.append(parts[0]+"00");
else if (parts[1].length() == 1)
sb.append(parts[0]+parts[1]+"0");
else if (parts[1].length() == 2)
sb.append(parts[0]+parts[1]);
else
sb.append(parts[0]+parts[1].substring(0,2)+"."+parts[1].substring(2));
if (sb.charAt(0) == '-')
{
while (sb.length() > 2 && sb.charAt(1) == '0' && sb.charAt(2) != '.')
sb.deleteCharAt(1);
}
else
{
while (sb.length() > 1 && sb.charAt(0) == '0' && sb.charAt(1) != '.')
sb.deleteCharAt(0);
}
return sb.toString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T12:23:17.560",
"Id": "78262",
"Score": "0",
"body": "@palacsint already answered this, but in a nutshell the issue is simply that floating point data types are imprecise and math operations on floats produce rounding errors at the edge of the precision of the data type (turning 0.0071 into 0.007100000000000001 for instance). That is *totally fine* as long as the error falls outside the precision you require. Decimal data types (scaled integers) on the other hand are not subject to those rounding errors. Math results from decimal types will be as precise as the inputs. **Caveat: decimal operations are extremely slow compared to floats**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T12:33:54.057",
"Id": "78271",
"Score": "0",
"body": "Also, my comment that \"Math results from decimal types will be as precise as the inputs\" was on the simplistic side, but these comment fields are short. The results will be as precise as the least precise of the inputs, and still not always perfect mathematically, and quite slow because the operations are 100% software with no help from specialized hardware. The decimal data type is fundamentally the same thing whether you're dealing with Java, C#, C++, MySQL or SQL Server. [This post is informative](http://stackoverflow.com/a/20482699/618649)"
}
] | [
{
"body": "<ol>\n<li><p>It would be much easier with <a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html\" rel=\"nofollow noreferrer\"><code>BigDecimal</code></a>s:</p>\n\n<pre><code>String input = \"00007.880000\";\nBigDecimal hundred = BigDecimal.valueOf(100);\nBigDecimal result = new BigDecimal(input).multiply(hundred).stripTrailingZeros();\n\nSystem.out.println(result.toString()); // prints \"788\"\n</code></pre>\n\n<p>It works with big numbers well:</p>\n\n<pre><code>String input = \"0000123456789123456789.123456789123456789123456789123456789880000\";\nBigDecimal hundred = BigDecimal.valueOf(100);\nBigDecimal result = new BigDecimal(input).multiply(hundred).stripTrailingZeros();\n\n// prints \"12345678912345678912.345678912345678912345678912345678988\"\nSystem.out.println(result.toString()); \n</code></pre>\n\n<p>Two readings:</p>\n\n<ul>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n<li><a href=\"https://stackoverflow.com/q/3730019/843804\">Why not use Double or Float to represent currency?</a></li>\n</ul></li>\n<li><p>The original code returns <code>788.0000</code> for <code>00007.880000</code> which I guess does not fulfill the specification.</p></li>\n<li><p>Java developers usually start method names with lowercase letters.</p>\n\n<blockquote>\n <p>Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">Code Conventions for the Java TM Programming Language, 9 - Naming Conventions</a></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:29:33.773",
"Id": "78050",
"Score": "1",
"body": "So much for the answer I was half way through"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:31:11.923",
"Id": "78051",
"Score": "0",
"body": "What about 1.234? Will `BigDecimal` yield 123.4?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:32:45.400",
"Id": "78052",
"Score": "1",
"body": "@barakmanos you should read the documentation and try this. It will help you learn. But, yes, it will."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:33:36.410",
"Id": "78053",
"Score": "0",
"body": "Oh... was probably thinking of `BigInteger`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:53:23.393",
"Id": "78058",
"Score": "0",
"body": "And this does not have the same problem as with `Double.parseDouble`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:59:38.280",
"Id": "78062",
"Score": "0",
"body": "@barakmanos: It handles those cases properly. (Answer updated.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T15:22:25.300",
"Id": "78122",
"Score": "1",
"body": "Thanks. Regarding your second comment: I assume that the input is already \"aligned\" with the requirements of the output, so `00007.880000` is not a viable input in my program (though, I should have probably mentioned that in the question). Regarding your third comment: I know, it's just a typo (happened when I copied the code I wanted to be reviewed into a separate method). Thanks again for the detailed answer."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:29:13.547",
"Id": "44850",
"ParentId": "44848",
"Score": "11"
}
},
{
"body": "<p>Aside from palacsint's great suggestions:</p>\n\n<ul>\n<li><p>You are using a StringBuilder, yet you still are doing string concatenations.</p></li>\n<li><p>Your code for removing the leading zeros duplicates the <s><code>for</code></s> <code>while</code> loop.</p></li>\n</ul>\n\n<p>Also: Why is your original input a string? This doesn't feel right. I've got the feeling there is something wrong with the bigger picture of your code.</p>\n\n<p>EDIT: I meant the <code>while</code> loops. Better would be something like:</p>\n\n<pre><code>int startAt = sb.charAt(0) == '-' ? 1 : 0;\n\nwhile (sb.length() > startAt + 1 && sb.charAt(startAt) == '0' && sb.charAt(startAt + 1) != '.')\n sb.deleteCharAt(startAt);\n</code></pre>\n\n<p>EDIT 2: Better readable?</p>\n\n<pre><code>boolean negative = sb.charAt(0) == '-';\nif (negative) sb.deleteCharAt(0);\n\nwhile (sb.length() > 1 && sb.charAt(0) == '0' && sb.charAt(1) != '.')\n sb.deleteCharAt(0);\n\nif (negative) sb.insert(0, '-');\n</code></pre>\n\n<p>(Add brackets to taste)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:11:43.420",
"Id": "44857",
"ParentId": "44848",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44850",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:16:48.873",
"Id": "44848",
"Score": "10",
"Tags": [
"java",
"strings"
],
"Title": "Converting a numerical string to the equivalent multipled by 100"
} | 44848 |
<p>I want to have a continuous date sequence like ['2014-01-01','2014-01-02', ...]</p>
<p>Then I define a stream to do that.</p>
<pre><code>def daySeq(start: Date): Stream[Date] = Stream.cons(start, daySeq(plusDays(start, 1)))
</code></pre>
<p>I get the sequence within range [start, end) by calling </p>
<pre><code>daySeq(from).takeWhile(_.getTime < to.getTime)
</code></pre>
<p>Any better/simple solution to do this ?</p>
| [] | [
{
"body": "<p>I suggest using Joda-Time's <code>LocalDate</code> instead of Java's <code>Date</code> to represent dates without a time zone.</p>\n\n<p>Assuming you only need to traverse the days once, use an <code>Iterator</code> instead of a <code>Stream</code>.</p>\n\n<pre><code>def dayIterator(start: LocalDate, end: LocalDate) = Iterator.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)\n</code></pre>\n\n<p>Example usage: </p>\n\n<pre><code>dayIterator(new LocalDate(\"2013-10-01\"), new LocalDate(\"2014-01-30\")).foreach(println)\n</code></pre>\n\n<p>If you do need a lazily-evaluated list, then <code>Stream</code> is appropriate. I suggest using <code>iterate</code> instead of <code>cons</code> in that case.</p>\n\n<pre><code>def dayStream(start: LocalDate, end: LocalDate) = Stream.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T01:22:17.987",
"Id": "78683",
"Score": "0",
"body": "iterate looks better and simpler"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:02:12.533",
"Id": "448167",
"Score": "1",
"body": "FYI: The [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), its creator, [Stephen Colebourne](https://stackoverflow.com/users/38896/jodastephen), having gone on to lead [JSR 310](https://jcp.org/en/jsr/detail?id=310) defining the [*java.time*](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html) classes built into Java 8+. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:17:50.977",
"Id": "459761",
"Score": "0",
"body": "This works with the java.time classes if you replace `new LocalDate` with `LocalDate.parse`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T03:32:08.633",
"Id": "45124",
"ParentId": "44849",
"Score": "7"
}
},
{
"body": "<blockquote>\n <p>Any better/simple solution to do this ?</p>\n</blockquote>\n\n<p>Yes. Functionality now built into Java 9 and later. </p>\n\n<h1><code>java.time.LocalDate::datesUntil</code> ➙ Stream of <code>LocalDate</code> objects</h1>\n\n<p>The modern approach uses <em>java.time</em> classes. </p>\n\n<p>The <code>java.time.LocalDate</code> has built-in support for generating a stream of dates. Call <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html#datesUntil(java.time.LocalDate)\" rel=\"nofollow noreferrer\"><code>LocalDate::datesUntil</code></a>. </p>\n\n<p>I do not know Scala, so here is Java syntax.</p>\n\n<pre><code>LocalDate today = LocalDate.now ( ZoneId.of ( \"Africa/Tunis\" ) );\nLocalDate later = today.plusDays ( 3 );\nList < LocalDate > dates = today.datesUntil ( later ).collect ( Collectors.toUnmodifiableList () );\n</code></pre>\n\n<blockquote>\n <p>[2019-10-04, 2019-10-05, 2019-10-06]</p>\n</blockquote>\n\n<hr>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html\" rel=\"nofollow noreferrer\"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"nofollow noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html\" rel=\"nofollow noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html\" rel=\"nofollow noreferrer\"><code>Calendar</code></a>, & <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"nofollow noreferrer\">JSR 310</a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow noreferrer\"><em>Joda-Time</em></a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"nofollow noreferrer\">maintenance mode</a>, advises migration to the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes.</p>\n\n<p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href=\"https://en.wikipedia.org/wiki/JDBC_driver\" rel=\"nofollow noreferrer\">JDBC driver</a> compliant with <a href=\"http://openjdk.java.net/jeps/170\" rel=\"nofollow noreferrer\">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"nofollow noreferrer\"><strong>Java SE 9</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10\" rel=\"nofollow noreferrer\"><strong>Java SE 10</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11\" rel=\"nofollow noreferrer\"><strong>Java SE 11</strong></a>, and later - Part of the standard Java API with a bundled implementation.\n\n<ul>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"nofollow noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Most of the <em>java.time</em> functionality is back-ported to Java 6 & 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"nofollow noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the <em>java.time</em> classes.</li>\n<li>For earlier Android (<26), the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"nofollow noreferrer\"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"nofollow noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"nofollow noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"nofollow noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"nofollow noreferrer\">more</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T14:04:43.443",
"Id": "459759",
"Score": "1",
"body": "It's worth noting that the LocalDate::datesUntil method was one of the \"minor features\" added in Java 9. This means that it's not available if you're using an environment that is running on Java 8, which many things are since it's an LTS release."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:01:43.313",
"Id": "230190",
"ParentId": "44849",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:27:15.123",
"Id": "44849",
"Score": "6",
"Tags": [
"scala",
"datetime",
"stream"
],
"Title": "Construct date sequence in Scala"
} | 44849 |
<p>I'm writing a JavaScript library, and I am using this function for type detection:</p>
<pre><code>function type(obj){
return Object.prototype.toString.call(obj).replace(/([\[\]]|object|\s)/gi, "");
}
</code></pre>
<p>Their works ok, but compared to jQuery and MooTools it stinks.</p>
<p><a href="http://jsperf.com/code-type-test-a-test" rel="nofollow noreferrer">http://jsperf.com/code-type-test-a-test</a></p>
<p><img src="https://i.stack.imgur.com/19xuZ.png" alt="Speed Test"></p>
<p>How can I improve its performance?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:40:11.573",
"Id": "78054",
"Score": "0",
"body": "This is micro-optimization, don't worry about it. 7,767,355 ops/sec in FF is more than enough. How often do you check the type of something anyway?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:41:13.430",
"Id": "78055",
"Score": "0",
"body": "Your test case seems completely wrong, basically you are measuring the speed of creating the function, not executing it.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:41:51.083",
"Id": "78056",
"Score": "0",
"body": "@elclanrs You are right. But if I have functions in my library that are slower than functions in other libraries, then wouldn't you use the faster library?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:43:35.457",
"Id": "78057",
"Score": "0",
"body": "@konijn I am pretty sure that jsperf.com puts inputs into the functions. I'll change my test just in case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:53:40.610",
"Id": "78059",
"Score": "0",
"body": "@konijn I think I have a more accurate test now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T16:50:05.283",
"Id": "78154",
"Score": "0",
"body": "I would not run a performance test if I don't see a difference! You need to be really more slower than other libraries IMO."
}
] | [
{
"body": "<p>Interesting question, since there is only 1 line to review and a limited amount of ways to get the 'type` of an object</p>\n\n<p>I will say that </p>\n\n<pre><code>function type(obj){\n return Object.prototype.toString.call(obj).replace(/([\\[\\]]|object|\\s)/gi, \"\");\n}\nvar o = new (function Name(){})();\nconsole.log( type(o) );\n</code></pre>\n\n<p>returns \"\"</p>\n\n<p>whereas</p>\n\n<pre><code>function type(o){\n return o !== undefined && o.constructor ? o.constructor.name : \"Undefined\";\n}\nvar o = new (function Name(){})();\nconsole.log( type(o) );\n</code></pre>\n\n<p>returns \"Name\" which is more correct.</p>\n\n<p>It seems ( though I fudged it a little, a re-test is required ) that the second approach can be faster on IE and Safari ). All in all, I would copy the jQuery source, it takes care of all corner cases and is sufficiently fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T20:36:16.753",
"Id": "78192",
"Score": "0",
"body": "Shouldn't the type of \"o\" be \"object\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T21:17:12.727",
"Id": "78202",
"Score": "0",
"body": "Is this quicker that other jQuery/MooTools/My original function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T22:16:03.887",
"Id": "78214",
"Score": "0",
"body": "Progo, that's how it looks like for IE/Safari, it is slowest on Chrome though. @Kevindra, no, the name of the constructor is the name of the type."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T17:25:02.620",
"Id": "44886",
"ParentId": "44851",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T12:34:02.397",
"Id": "44851",
"Score": "4",
"Tags": [
"javascript",
"performance"
],
"Title": "Improving the performance of my \"type\" function"
} | 44851 |
<p>Basically, I have two separate tables, Campaign and CampaignDetails. They relate via CampaignID. I want a service that can handle both at the same time, as they're closely related and when one gets updated- so will the other.</p>
<p>At the moment I'm combining the two but it's starting to get a bit hard to look at</p>
<pre><code>public interface ICampaignService
{
//INSERT
void InsertCampaign(Campaign campaign);
void InsertCampaignDetails(CampaignDetails campaign);
//UPDATE
void UpdateCampaign(Campaign campaign);
void UpdateCampaignDetails(CampaignDetails campaign);
//DELETE
void DeleteCampaign(Campaign campaign);
void DeleteCampaign(object id);
void DeleteCampaignDetails(CampaignDetails campaign);
void DeleteCampaignDetails(object id);
//ALL
IList<Campaign> AllCampaigns();
//FIND
Campaign FindCampaignBy(Expression<Func<Campaign, bool>> expression);
CampaignDetails FindCampaignDetailsBy(Expression<Func<CampaignDetails, bool>> expression);
//FILTER
IList<Campaign> FilterCampaignBy(Expression<Func<Campaign, bool>> expression);
IList<CampaignDetails> FilterCampaignDetailsBy(Expression<Func<CampaignDetails, bool>> expression);
//GET
Campaign GetCampaignByID(object id);
CampaignDetails GetCampaignDetailsByID(object id);
Campaign GetLatestCampaign();
Campaign GetMostRecentSentCampaign();
//SAVE
void Save();
}
</code></pre>
<p>This is just my interface, so the implementation is obviously a lot more.. And it seems a lot of similar code.</p>
<p>I came across this article <a href="http://bobcravens.com/2010/09/the-repository-pattern-part-2/" rel="nofollow">http://bobcravens.com/2010/09/the-repository-pattern-part-2/</a> and I quite like the DataService that wraps all the individual services. But is it bad practise to say have one variable <code>DataService mainService = new DataService(repo1, repo2, repo3, repo4)</code> that can the access every service?</p>
<p>So I should I split it into CampaignService and CampaignDetailsService or keep it as one?</p>
<p><strong>EDIT</strong></p>
<p>Example of update method</p>
<pre><code> public void UpdateCampaign(Campaign campaignToUpdate)
{
_campaignRepository.Update(campaignToUpdate);
}
public void UpdateCampaignDetails(CampaignDetails campaignToUpdate)
{
_campaignDetailsRepository.Update(campaignToUpdate);
}
</code></pre>
<p>Doing the same thing basically but with different entities.</p>
<p>Example of using method above:</p>
<pre><code> [HttpPost]
public ActionResult Create(Campaign campaign)
{
if (ModelState.IsValid)
{
try
{
_campaignService.InsertCampaign(campaign);
var campaignDetails = new CampaignDetails()
{
CampaignId = campaign.CampaignId
};
_campaignService.InsertCampaignDetails(campaignDetails);
_campaignService.Save();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Something went wrong. Message: " + ex.Message);
}
}
return View(campaign);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:24:32.007",
"Id": "78073",
"Score": "0",
"body": "You have a design issue. Your `ICampaignService` is too low level. Post an example method that uses `UpdateCampaignDetails(CampaignDetails)` and we will have a better idea what can be done to clean up the interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:29:10.733",
"Id": "78075",
"Score": "0",
"body": "I can't help but wondering whether this \"service\" actually provides any additional value to the Entity Framework context? At best it's a leaky abstraction, at worst it's no abstraction at all, just a middle man."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:33:03.383",
"Id": "78076",
"Score": "0",
"body": "also you probably should not use an object as id. I'd guess you actually have a long or BigInteger as Id, why not pass one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T14:02:26.550",
"Id": "78084",
"Score": "0",
"body": "@abuzittingillifirca what do you mean low-level? And please see edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T14:06:33.930",
"Id": "78091",
"Score": "0",
"body": "@MattDavey I have the same thoughts as you.. it's pretty much a pointless abstraction between the controller and the repository... But I was thinking if I want to create services that actually provide a useful service (i.e. sending out mailing campaigns) then I may as well have services that perform the CRUD operations too.. Or should I just have CRUD operations as Controller -> Repository. What if I need to perform a lot of logic before I create a new `Campaign` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T14:07:38.860",
"Id": "78092",
"Score": "0",
"body": "I was asking *an example method that uses `UpdateCampaignDetails`* that is the (controller) method that **calls** `UpdateCampaignDetails`. I was expecting the implementations to be such, that is just a very thing layer over EF, what Matt calls a leaky abstraction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T14:15:17.910",
"Id": "78099",
"Score": "0",
"body": "@abuzittingillifirca my bad, please see edit again. It is a very thin layer indeed. The only reason I created it is so I could have a platform of managing Campaign and CampaignDetails. Should I instead just refer to the two separate repositories within the controller?"
}
] | [
{
"body": "<p>Overview of your service looks like this. I've put T-SQL commands that execute in each methods comment.</p>\n\n<pre><code>interface ICampaignService\n{\n //INSERT = INSERT INTO CAMPAIGN....\n void InsertX( ... );\n\n //UPDATE = UPDATE CAMPAIGN....\n void UpdateX( ... );\n\n //DELETE = DELETE FROM CAMPAIGN\n void DeleteX( ... );\n\n //ALL = SELECT * FROM CAMPAIGN\n IList<Campaign> AllCampaigns();\n\n //FIND = SELECT * FROM CAMPAIGN WHERE ...\n //FILTER\n //GET\n Campaign FindX( ... );\n Campaign GetCampaignByID(object id);\n\n //SAVE = COMMIT TRANSACTION;\n void Save();\n}\n</code></pre>\n\n<p>And you yourself say:</p>\n\n<blockquote>\n <p>I have two separate tables, Campaign and CampaignDetails. They relate via CampaignID.</p>\n</blockquote>\n\n<p>The problem is your service is not just a thin layer over Entity Framework it still is a thin layer over SQL. In fact even your action names mirror database commands.</p>\n\n<p>The service interface must be a must be the interface to your business logic layer. \nAnd repositories be your gateway to the data access layer.</p>\n\n<p>Let's look at the <code>Create(Campaign campaign)</code> action for a second:</p>\n\n<pre><code>Create(Campaign campaign)\n{\n// BOILER PLATE IGNORED\n _campaignService.InsertCampaign(campaign);\n var campaignDetails = new CampaignDetails()\n {\n CampaignId = campaign.CampaignId\n };\n\n _campaignService.InsertCampaignDetails(campaignDetails);\n _campaignService.Save();\n// BOILER PLATE IGNORED\n}\n</code></pre>\n\n<p>When your user pressed the submit button <strong>one time</strong>, did he intend <strong>4 different things</strong>?</p>\n\n<pre><code>Create(Campaign campaign)\n{\n// BOILER PLATE IGNORED\n _campaignService.CreateCampaign(campaign);\n// BOILER PLATE IGNORED\n}\n</code></pre>\n\n<p>It is clear that this more closely captures user's intent.</p>\n\n<pre><code>void CreateCampaign(Campaign campaign)\n{\n _campaignRepository.InsertCampaign(campaign);\n var campaignDetails = new CampaignDetails()\n {\n CampaignId = campaign.CampaignId\n };\n\n _campaignRepository.InsertCampaignDetails(campaignDetails);\n _campaignRepository.Save();\n}\n</code></pre>\n\n<p>As you do the above transformation -in other words above refactoring- for each action there will be unused methods on the service interface. Remove them and your service interface will be cleaner. </p>\n\n<blockquote>\n <p>I want a service that can handle both at the same time, as they're closely related and when one gets updated- so will the other.</p>\n</blockquote>\n\n<p>This means that <code>Campaign</code> and <code>CampaignDetails</code> form an <strong>aggregate</strong>. And <code>Campaign</code> is the <strong>aggregate root</strong>. (I'm just giving you the standard terminology, so you can more easily look up the situation on the Internet.)</p>\n\n<p>In situation where you have <em>closely related [entities] and [such that] when one gets updated- so will the other</em>, or in database-speak a master table and one ore more detail tables, you service should not contain direct references to the detail entities, or in other words you service should only deal with the aggregate root, in this particular case <code>Campaign</code>. It only makes sense that <code>ICampaignService</code> only deals with <code>Campaign</code>s directly.</p>\n\n<p>I had asked for the <code>UpdateCampaignDetails</code> example usage so that I can give a more concrete example of this but we will have to make do with the made up example below:</p>\n\n<p>Suppose we are talking about sales campaigns here and one thing that is stored in <code>CampaignDetails</code> is a discount rate for the <code>Campaign</code>. After the above refactoring to your service and controller instead of <code>UpdateCampaignDetails</code> your service will have methods like below:</p>\n\n<pre><code>void ChangeDiscountRate(Campaign campaign, decimal newDiscountRate)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>void ChangeDiscountRate(Guid CampaignId, decimal newDiscountRate)\n</code></pre>\n\n<p>whose implementation would be something like:</p>\n\n<pre><code>var campaignDetailsToUpdate = _campaignDetailsRepository.GetById(CampaignId);\ncampaignDetailsToUpdate.DiscountRate = newDiscountRate;\n_campaignDetailsRepository.Update(campaignDetailsToUpdate);\n_campaignDetailsRepository.Save();\n</code></pre>\n\n<p>You need not stop there. Ideally after a next round of refactorings (Including defining One-to-One and one-to-many relations where necessary) your service methods will read like below:</p>\n\n<pre><code>var campaignToUpdate = _campaignRepository.GetById(CampaignId);\ncampaignToUpdate.ChangeDiscountRate(newDiscountRate);\n_campaignRepository.Update(campaignToUpdate );\n</code></pre>\n\n<p>or more generally:</p>\n\n<pre><code>var aggregateRoot = repository.GetById(id);\naggregateRoot.ModifyThisEntityAndItsDetails(...);\nrepository.Update(aggregateRoot);\n</code></pre>\n\n<p>The other thing to do would be separate the methods that update campaigns (hint those methods that return <code>void</code>, who are also the methods that are called from <code>[HttpPost]</code> controller methods from search methods (hint they are the method that return SomeCollection and take <code>Expression<Func<Campaign, bool>> expression</code> as parameters) that are called from elsewhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T16:52:23.707",
"Id": "78155",
"Score": "1",
"body": "+1 for *\"This means that `Campaign` and `CampaignDetails` form an aggregate. And `Campaign` is the aggregate root.\"*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T17:31:39.590",
"Id": "78164",
"Score": "0",
"body": "Thank you very much you've made a lot of sense. I see now, instead of having `UpdateCampaign` in the service layer repeat the repository, you tailor it with logic, and then call the repository. This will be good for my `EmailRecipient` entity, because there will be different ways of adding an email (through .xls, .csv etc.) so the service will have different methods but end up calling a simple update query in the repository/DAL."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T15:41:50.133",
"Id": "44876",
"ParentId": "44854",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44876",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T13:05:06.813",
"Id": "44854",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Should I create two seperate Services and then combine them or have one large?"
} | 44854 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.