body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I just want to know if this is reasonably good implementation of including local/remote JavaScript files. </p>
<p>The function takes a dictionary with (string) <code>.src</code> whitespace-separated list of urls to include/execute in global context, and (func) <code>.done/.error/.load</code> callbacks to run in corresponding cases, resolves URLs to absolute, temporarily inserts <code><script></code> blocks in page header, caches loaded addresses, and attaches few static properties: (object) <code>.defaults</code> and (func) <code>.ls/.reload</code> to main <code>includejs()</code> function. </p>
<pre><code>// #includejs
;((function (name, def) {
this[name] = def(document);
}).call(
this, "includejs", function (doc) {
// will be used to reference private includejs() version
var _include;
// holds cached script urls
var imported = {};
// no-op callback default
var pass = function () {};
// helpers
var _ = {
// <a> helper element to resolve urls to absolute
anchor: doc.createElement("a"),
// calculates difference of two arrays
// used by includejs() to filter new urls to load
arrdiff: function (a1, a2) {
return a1.filter(_.cbuniq).filter(_.cbdiff, a2);
},
// calculates intersection of two arrays
// used by includejs.reload() to filter cached urls
arrinters: function (a1, a2) {
return a1.filter(_.cbuniq).filter(_.cbinters, a2);
},
cbdiff: function (node) {
//this: a2[]
return this.indexOf(node) == -1;
},
cbinters: function (node) {
//this: a2[]
return this.indexOf(node) != -1;
},
cbpropcp: function (name) {
//this: {src{}, target{}}
this.target[name] = this.src[name];
},
cbrmprop: function (name) {
//this: target{}
try {
delete this[name];
} catch (e) {}
},
cbuniq: function (node, idx, arr) {
return idx <= arr.indexOf(node);
},
// shallow copies an (object) node
// used by includejs.ls() to list cached urls
cp: function (node) {
var nodecp = {};
_.keys(node).forEach(_.cbpropcp, {src: node, target: nodecp});
return nodecp;
},
// default settup
defs: {
src : "",
done : pass,
error : pass,
load : pass
},
// removes passed properties from (object) node
// used in includejs.reload() to filter cached urls
del: function (node) { //, ...props
_.arrinters(_.keys(imported), _.slc(arguments, 1))
.forEach(_.cbrmprop, node);
return node;
},
// helper for wssplit() for filter out empty strings
fnid: function (node) {
return node;
},
// <head> reference for temporarily injecting <script>-s
h: doc.getElementsByTagName("head")[0],
// attaches properties of (object) items to (object) target
// used in few places to assign object properties
init: function (target, items) {
for (var name in items) {
if (items.hasOwnProperty(name)) {
target[name] = items[name];
}
}
return target;
},
isfn: function (node) {
return "function" == typeof node;
},
isplainobj: function (node) {
return "[object Object]" == Object.prototype.toString.call(node);
},
isstr: function (node) {
return "[object String]" == Object.prototype.toString.call(node);
},
keys: function (node) {
return Object.keys(Object(node));
},
now: Date.now,
// calculates absolute url coresponding to given (string) url
// not sure if this works on old ies
path2abs: function (url) {
_.anchor.href = ""+ url;
return _.anchor.href;
},
// matches whitespace globaly
// copy-pasted from es5-shim.js
// https://github.com/es-shims/es5-shim.git
rews: /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/g,
// used for converting dynamic arguments object to static array
slc: function () {
return Array.prototype.slice.apply(Array.prototype.shift.call(arguments), arguments);
},
// empties an object
// used in includejs.reload() to empty private url cache
// forcing reload
vacate: function (node) {
for (var name in node) {
if (!Object.prototype.hasOwnProperty(name)) {
delete node[name];
}
}
return node;
},
// splits whitespace-separated string to it's components
// returns array of uniqe (string) urls
// used by includejs() to turn (string) .src urls to array
wssplit: function (str) {
return (""+ str).split(_.rews).filter(_.cbuniq).filter(_.fnid);
}
};
// main function
_include = function (settup) {
var opts = {};
_.isplainobj(settup) || (settup = {});
// take only uncached absolute script urls
opts.src =
_.arrdiff(
_.wssplit(_.isstr(settup.src) ? settup.src : "").map(_.path2abs),
_.keys(imported)
);
opts.done = _.isfn(settup.done) ? settup.done : _.defs.done;
opts.error = _.isfn(settup.error) ? settup.error : _.defs.error;
opts.load = _.isfn(settup.load) ? settup.load : _.defs.load;
// acts as counter to track download progress
opts.i = 0;
// holds <script> nodes for caching, and for callback clean-up afterward
opts.s = [];
// for tracking download progress, when opts.i == opts.len download is done
opts.len = opts.src.length;
if (opts.len) {
opts.src.forEach(_requireloadcb, opts);
} else {
// asyncs _requireloadcompletecb()
setTimeout(function () {
_requireloadcompletecb(opts);
});
}
return opts.src.slice(0);
};
// export
// adds 'includejs' function identifier to global scope
return _.init(_include, {
defaults: _.defs,
// query cached urls
ls: function () {
return _.cp(imported);
},
// reloads cached .src urls
// takes same-format-object as includejs()
reload: function (settup) {
if (_.isstr(settup))
settup = {src: settup};
_.isplainobj(settup) || (settup = {});
if (!settup.hasOwnProperty("src")) {
settup.src = _.keys(imported).join(" ");
_.vacate(imported);
} else {
_.del.apply(null,
[imported]
.concat(_.wssplit(_.isstr(settup.src) ? settup.src : "").map(_.path2abs))
);
}
_include(settup);
}
});
// helpers
// nulls .onload/.onerror handlers
// detaches loaded <script> node
// used by _requireloadcompletecb() to perform cleanup
function _requiregcloadcb (nodescript) {
nodescript.onload = null;
nodescript.onerror = null;
_.h.removeChild(nodescript);
}
// generates new <script> and appends it to <head>
// executing <script>.src file in global context
// used by includejs() to download/execute script files
function _requireloadcb (fileurl) {
//this: {src, done, error, load, i, len, s}
var opts = this;
var nodescript = _.init(doc.createElement("script"), {
onerror : function () { // ...e
//this: <script>
opts.i += 1;
opts.error.apply(this, arguments);
_requireloadcompletecb(opts);
},
onload : function () { // ...e
//this: <script>
opts.i += 1;
imported[fileurl] = _.now();
opts.load.apply(this, arguments);
_requireloadcompletecb(opts);
},
defer : false,
src : fileurl,
type : "application/javascript"
});
//opts.s.push(_.h.removeChild(_.h.appendChild(nodescript)));
opts.s.push(_.h.appendChild(nodescript));
}
// cleans up after scripts load/fail-to-load
// nulls .onload/.onerror handlers
// empties settup (object) opts
function _requireloadcompletecb (opts) {
if (opts.i == opts.len) {
opts.done.apply(doc, opts.src);
opts.s.forEach(_requiregcloadcb);
// opts.s.splice(0, 1/0);
opts.s.splice(0);
_.vacate(opts);
}
}
}
));
//
// use:
//
// includejs({
// src: "lib/_.js //cdnjs.cloudflare.com/ajax/libs/modernizr/2.7.1/modernizr.min.js",
// done: function (scripturls) {
// // _doStuff(scripturls);
// console.log("done", this, arguments);
// },
// load: function (e) {
// // _srcLoaded(this);
// console.log(e, this);
// },
// error: function (e) {
// // _srcFailed(this);
// console.log(e, this);
// }
// });
//
// // console:
// load <script src="http://localhost/sites/xsite/lib/_.js" type="application/javascript">
// load <script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.7.1/modernizr.min.js" type="application/javascript">
// done Document index.htm ["http://localhost/sites/xsite/lib/_.js", "http://cdnjs.cloudflare.../2.7.1/modernizr.min.js"]
//
// console.log(includejs.ls());
// // console:
// Object {
// http://localhost/sites/xsite/lib/_.js = 1394306633258,
// http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.7.1/modernizr.min.js = 1394306633369
// }
//
// includejs.reload({
// done: function (urls) {
// // _doStuffOnReload(urls);
// console.log("reloaded", this, arguments);
// }
// });
//
// // console:
// reloaded Document index.htm ["http://localhost/sites/xsite/lib/_.js", "http://cdnjs.cloudflare.../2.7.1/modernizr.min.js"]
//
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:19:36.837",
"Id": "75810",
"Score": "0",
"body": "There are many script loader libraries out there, some extremely small and simple. What new functionality are you offering over all these other offerings. Or put another way, what benefit do you have to reinventing a solution that has been offered in many tried/true libraries? Here's one for comparison: http://labjs.com/."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:53:24.593",
"Id": "75814",
"Score": "0",
"body": "Yes, there are dozens of tested solutions out there, there's nothing new and extraordinary revolutionary in this peace of code I've posted. I was hoping to get/implement critics for this implementation because it is critical in javascript utility library I'm working on..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:57:19.417",
"Id": "75815",
"Score": "0",
"body": "I'd suggest that maybe you write up a list of features it has. As your question is now, we're left to try to discern from the code what it is supposed to do and then try to evaluate how well it does that. I rather doubt you will get much feedback without providing a lot more info. And, why can't you use an existing, tested, supported open source library that already exists in your own utility library? Why rewrite from scratch?"
}
] | [
{
"body": "<p>Your code is interesting,</p>\n\n<p>you are clearly smart and know JavaScript, but this is a maintenance nightmare. I am assuming you will not take my advice to heart but here goes:</p>\n\n<ul>\n<li>Do not abbreviate: <code>isfn</code> -> <code>isFunction</code>, <code>isstr</code> -> <code>isString</code>, <code>cbpropcp</code> -> ? ,<code>slc</code> -> <code>slice</code>, <code>_requiregcloadcb</code> -> ? etc. etc. etc. etc.</li>\n<li>Also, use lowerCamelCase </li>\n<li>Also, avoid <code>_xx</code> for private variables, as per Crockford</li>\n<li><p>Name functions for what they do, not how they are used:</p>\n\n<pre><code>fnid: function (node) {\n return node;\n}, \n</code></pre>\n\n<p><code>fnid</code> is a terrible name, if possible I would refactor the code so that I would not need this function. A better name might be <code>value</code> ?</p></li>\n<li>JSHint could not find anything wrong, except that your event handlers do not use <code>e</code>, so you do not need to declare <code>e</code> as a parameter</li>\n<li>You use <code>cbrmprop</code> and similar functions only once, consider in-lining them</li>\n<li><code>settup</code> -> <code>setup</code> ;)</li>\n<li><code>opts.s.splice(0, 1/0);</code> -> <code>opts.s.splice();</code></li>\n<li><code>defer : false,</code> -> I think this should have been an option</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T07:05:19.620",
"Id": "76204",
"Score": "0",
"body": "Fully private variables as per Crockford: http://javascript.crockford.com/private.html -- I see that as problematic though because each time you create a new object, a new set of functions and variables are created when really only the variables should be duplicated. Not having such private variables means lighter code... right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:22:08.023",
"Id": "76237",
"Score": "0",
"body": "It's more that `_` does not do anything in the language, and it's one more version of Hungarian notation in a way. Trying to find a link.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:57:36.650",
"Id": "43939",
"ParentId": "43803",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43939",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:52:40.770",
"Id": "43803",
"Score": "5",
"Tags": [
"javascript",
"reinventing-the-wheel"
],
"Title": "Am I including these JavaScript files correctly?"
} | 43803 |
<p>I want to divide the screen in two halves. The layout is locked on portrait mode. The top half will have one button and the bottom half will have many buttons. That's why I choose this division, since the top half can be potentially scrollable. </p>
<p>This is my layout xml:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/play_button" />
</LinearLayout>
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button_1" />
<Button
android:id="@+id/button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button_2" />
<Button
android:id="@+id/button_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button_3" />
</LinearLayout>
</LinearLayout>
</code></pre>
<p>And this is how it looks like:</p>
<p><img src="https://i.stack.imgur.com/vb0qd.png" alt="Layout"></p>
<p>It looks as expected, but I was wondering if I'm doing it correctly. Is there a better, easier, more common, different, (etc) way to achieve this? Are there any mistakes or anti-patterns or bad things in there?</p>
| [] | [
{
"body": "<p>Your layout looks very good. <code>android:layout_weight</code> is the correct way to solve this.</p>\n<h3>A couple of other notes regarding your XML layout:</h3>\n<ul>\n<li><p>As your outermost LinearLayout has match_parent for both width and height, there is no need for <code>android:gravity="center"</code>.</p>\n</li>\n<li><p>I would write <code>0dp</code> instead of <code>0dip</code> (even though it is the exact same thing). Using <code>dp</code> just seems more common to me. This is a very minor nitpick though :)</p>\n</li>\n<li><p>Don't hardcode strings in your XML. Use the <code>strings.xml</code> resource file and use <code>android:text="@string/button3text"</code></p>\n</li>\n<li><p>You might know about this but either way you (and any future readers of this post) should also be aware that there exists <code>android:layout_gravity</code>. Although they sound similar, they are not the same thing. Read more about the differences between them in <a href=\"https://stackoverflow.com/questions/3482742/android-gravity-and-layout-gravity\">Android - gravity and layout_gravity</a></p>\n</li>\n<li><p>If, in the future you want to play around a bit more with layout_weights, you should take a look at <a href=\"https://stackoverflow.com/questions/7452741/what-is-androidweightsum-in-android-and-how-does-it-work\">What is android:weightSum in android, and how does it work?</a>, especially <a href=\"https://stackoverflow.com/questions/7452741/what-is-androidweightsum-in-android-and-how-does-it-work/12776742#12776742\">this answer</a></p>\n</li>\n<li><p>If you would like to support landscape mode as well, I suggest learning how to use <a href=\"http://developer.android.com/guide/components/fragments.html\" rel=\"nofollow noreferrer\">Android Fragments</a>. If you would like to support older devices, there's a <a href=\"http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html\" rel=\"nofollow noreferrer\">support package</a> that can help with that. A <code>Fragment</code> has one <code>onCreate</code> method and one <code>onCreateView</code> method, which makes it easy to persist data between screen orientation changes (or other changes) while creating a new view for the data.</p>\n</li>\n</ul>\n<h3>Summary:</h3>\n<p>Your layout looks excellent. At least in my eyes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:37:30.597",
"Id": "43807",
"ParentId": "43806",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43807",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:19:40.253",
"Id": "43806",
"Score": "6",
"Tags": [
"android",
"xml",
"layout"
],
"Title": "Dividing the screen in two halves using LinearLayout"
} | 43806 |
<p>This one review will be a little bit tricky: I was trying to implement a template <code>Vector</code> struct in C11. Of course, templates don't really exist in C11, so I used <em>a few</em> macros to get the desired interface. Here is the implementation of the core features, trying to mimick those of the c++ <code>std::vector</code>. Some are still missing though. First, the macro <code>define_Vector</code>:</p>
<pre><code>#define define_Vector(T) \
\
struct _vector_##T; \
\
typedef struct \
{ \
void (*delete)(struct _vector_##T*); \
T (*at)(const struct _vector_##T*, size_t); \
T (*front)(const struct _vector_##T*); \
T (*back)(const struct _vector_##T*); \
T* (*data)(const struct _vector_##T*); \
T* (*begin)(struct _vector_##T*); \
const T* (*cbegin)(const struct _vector_##T*); \
T* (*end)(struct _vector_##T*); \
const T* (*cend)(const struct _vector_##T*); \
bool (*is_empty)(const struct _vector_##T*); \
size_t (*size)(const struct _vector_##T*); \
size_t (*max_size)(void); \
void (*reserve)(struct _vector_##T*, size_t); \
size_t (*capacity)(const struct _vector_##T*); \
void (*shrink_to_fit)(struct _vector_##T*); \
void (*clear)(struct _vector_##T*); \
void (*erase1)(struct _vector_##T*, const T*); \
void (*erase2)(struct _vector_##T*, const T*, const T*); \
void (*push_back)(struct _vector_##T*, T); \
void (*pop_back)(struct _vector_##T*); \
void (*resize1)(struct _vector_##T*, size_t); \
void (*resize2)(struct _vector_##T*, size_t, T); \
} _vector_functions_##T; \
\
typedef struct _vector_##T \
{ \
T* _data; \
size_t _size; \
size_t _capacity; \
const _vector_functions_##T* _functions; \
} Vector_##T; \
\
Vector_##T* new_Vector_##T(); \
void vector_delete_##T(Vector_##T*); \
T vector_at_##T(const Vector_##T*, size_t); \
T vector_front_##T(const Vector_##T*); \
T vector_back_##T(const Vector_##T*); \
T* vector_data_##T(const Vector_##T*); \
T* vector_begin_##T(Vector_##T*); \
const T* vector_cbegin_##T(const Vector_##T*); \
T* vector_end_##T(Vector_##T*); \
const T* vector_cend_##T(const Vector_##T*); \
bool vector_is_empty_##T(const Vector_##T*); \
size_t vector_size_##T(const Vector_##T*); \
size_t vector_max_size_##T(void); \
void vector_reserve_##T(Vector_##T*, size_t); \
size_t vector_capacity_##T(const Vector_##T*); \
void vector_shrink_to_fit_##T(Vector_##T*); \
void vector_clear_##T(Vector_##T*); \
void vector_erase1_##T(Vector_##T*, const T*); \
void vector_erase2_##T(Vector_##T*, const T*, const T*); \
void vector_push_back_##T(Vector_##T*, T); \
void vector_pop_back_##T(Vector_##T*); \
void vector_resize1_##T(Vector_##T*, size_t); \
void vector_resize2_##T(Vector_##T*, size_t, T); \
\
void vector_delete_##T(Vector_##T* vector) \
{ \
free(vector->_data); \
free(vector); \
} \
\
T vector_at_##T(const Vector_##T* vector, size_t index) \
{ \
return vector->_data[index]; \
} \
\
T vector_front_##T(const Vector_##T* vector) \
{ \
return vector->_data[0]; \
} \
\
T vector_back_##T(const Vector_##T* vector) \
{ \
return vector->_data[size(vector)-1]; \
} \
\
T* vector_data_##T(const Vector_##T* vector) \
{ \
return vector->_data; \
} \
\
T* vector_begin_##T(Vector_##T* vector) \
{ \
return data(vector); \
} \
\
const T* vector_cbegin_##T(const Vector_##T* vector) \
{ \
return data(vector); \
} \
\
T* vector_end_##T(Vector_##T* vector) \
{ \
return data(vector) + size(vector); \
} \
\
const T* vector_cend_##T(const Vector_##T* vector) \
{ \
return data(vector) + size(vector); \
} \
\
bool vector_is_empty_##T(const Vector_##T* vector) \
{ \
return size(vector) == 0; \
} \
\
size_t vector_size_##T(const Vector_##T* vector) \
{ \
return vector->_size; \
} \
\
size_t vector_max_size_##T(void) \
{ \
return SIZE_MAX; \
} \
\
void vector_reserve_##T(Vector_##T* vector, size_t new_cap) \
{ \
if (new_cap > capacity(vector)) \
{ \
vector->_capacity = new_cap; \
vector->_data = realloc(vector->_data, \
new_cap * sizeof(T)); \
} \
} \
\
size_t vector_capacity_##T(const Vector_##T* vector) \
{ \
return vector->_capacity; \
} \
\
void vector_shrink_to_fit_##T(Vector_##T* vector) \
{ \
vector->_capacity = size(vector); \
vector->_data = realloc(vector->_data, \
size(vector) * sizeof(T)); \
} \
\
void vector_clear_##T(Vector_##T* vector) \
{ \
vector->_size = 0; \
} \
\
void vector_erase1_##T(Vector_##T* vector, const T* pos) \
{ \
T* it = (T*) pos; \
while (it != end(vector)-1) \
{ \
*it = it[1]; \
++it; \
} \
--vector->_size; \
} \
\
void vector_erase2_##T(Vector_##T* vector, const T* first, const T* last) \
{ \
T* it1 = (T*) first; \
T* it2 = (T*) last; \
while (it2 != end(vector)) \
{ \
*it1 = *it2; \
++it1; \
++it2; \
} \
vector->_size -= last-first; \
} \
\
void vector_push_back_##T(Vector_##T* vector, T value) \
{ \
vector->_size += 1; \
if (capacity(vector) < size(vector)) \
{ \
reserve(vector, capacity(vector)+40); \
} \
last(vector) = value; \
} \
\
void vector_pop_back_##T(Vector_##T* vector) \
{ \
if (size(vector) > 0) \
{ \
vector->_size -= 1; \
} \
} \
\
void vector_resize1_##T(Vector_##T* vector, size_t count) \
{ \
if (count < size(vector)) \
{ \
while (size(vector) > count) \
{ \
pop_back(vector); \
} \
} \
else \
{ \
reserve(vector, count); \
vector->_size = count; \
} \
} \
\
void vector_resize2_##T(Vector_##T* vector, size_t count, T value) \
{ \
if (count < size(vector)) \
{ \
while (size(vector) > count) \
{ \
pop_back(vector); \
} \
} \
else \
{ \
while (size(vector) < count) \
{ \
push_back(vector, value); \
} \
} \
} \
\
const _vector_functions_##T _vector_funcs_##T = { \
&vector_delete_##T, \
&vector_at_##T, \
&vector_front_##T, \
&vector_back_##T, \
&vector_data_##T, \
&vector_begin_##T, \
&vector_cbegin_##T, \
&vector_end_##T, \
&vector_cend_##T, \
&vector_is_empty_##T, \
&vector_size_##T, \
&vector_max_size_##T, \
&vector_reserve_##T, \
&vector_capacity_##T, \
&vector_shrink_to_fit_##T, \
&vector_clear_##T, \
&vector_erase1_##T, \
&vector_erase2_##T, \
&vector_push_back_##T, \
&vector_pop_back_##T, \
&vector_resize1_##T, \
&vector_resize2_##T, \
}; \
\
Vector_##T* new_Vector_##T() \
{ \
Vector_##T* res = malloc(sizeof(Vector_##T)); \
res->_functions = &_vector_funcs_##T; \
res->_capacity = 40; \
res->_size = 0; \
res->_data = malloc(40*sizeof(T)); \
return res; \
}
</code></pre>
<p>To access the functions contained in the global struct, I use the following macros (some also provide extra features):</p>
<pre><code>////////////////////////////////////////////////////////////
// Element access
#define at(collection, index) \
collection->_functions->at(collection, index)
#define front(collection) \
collection->_functions->front(collection)
#define back(collection) \
collection->_functions->back(collection)
#define data(collection) \
collection->_functions->data(collection)
////////////////////////////////////////////////////////////
// Iterators
#define begin(collection) \
collection->_functions->begin(collection)
#define cbegin(collection) \
collection->_functions->cbegin(collection)
#define end(collection) \
collection->_functions->end(collection)
#define cend(collection) \
collection->_functions->cend(collection)
////////////////////////////////////////////////////////////
// Capacity
#define is_empty(collection) \
collection->_functions->is_empty(collection)
#define size(collection) \
collection->_functions->size(collection)
#define max_size(collection) \
collection->_functions->max_size()
#define reserve(collection, new_cap) \
collection->_functions->reserve(collection, new_cap)
#define capacity(collection) \
collection->_functions->capacity(collection)
#define shrink_to_fit(collection) \
collection->_functions->shrink_to_fit(collection)
////////////////////////////////////////////////////////////
// Modifiers
#define clear(collection) \
collection->_functions->clear(collection)
#define erase(collection, ...) \
DISPATCH(erase, __VA_ARGS__)(collection, __VA_ARGS__)
#define erase1(collection, pos) \
collection->_functions->erase1(collection, pos)
#define erase2(collection, first, last) \
collection->_functions->erase2(collection, first, last)
#define push_back(collection, elem) \
collection->_functions->push_back(collection, elem)
#define pop_back(collection) \
collection->_functions->pop_back(collection)
#define resize(collection, ...) \
DISPATCH(resize, __VA_ARGS__)(collection, __VA_ARGS__)
#define resize1(collection, count) \
collection->_functions->resize1(collection, count)
#define resize2(collection, count, value) \
collection->_functions->resize2(collection, count, value)
////////////////////////////////////////////////////////////
// Macros to improve usability
/**
* @def define(type)
* Defines all the functions for the given type.
*/
#define define(type) \
define_##type
/**
* @def new(type)
* Creates a new instance of the given type and
* returns a pointer to it.
*/
#define new(type) \
new_##type
/**
* @def delete(collection)
* Calls the class "destructor" to free what has
* to be freed.
*/
#define delete(collection) \
collection->_functions->delete(collection)
/**
* @def elem(collection, index)
* Returns the given element of a contiguous collection.
*/
#define elem(collection, index) \
data(collection)[index]
/**
* @def first(collection)
* Returns the first element of a contiguous collection.
*/
#define first(collection) \
data(collection)[0]
/**
* @def last(collection)
* Returns the last element of a contiguous collection.
*/
#define last(collection) \
data(collection)[size(collection)-1]
</code></pre>
<p>And here are the macros - only well-known macros - used to implement the interface macros:</p>
<pre><code>// Some compilers need one more level of indirection
// than GCC, hence PASTE_3.
#define PASTE_3(x, y) \
x ## y
#define PASTE_2(x, y) \
PASTE_3(x, y)
#define PASTE_1(x, y) \
PASTE_2(x, y)
// DISPATCH cannot use VA_NARGS because of the
// sizeof check. Therefore, it uses the version
// which cannot handle the 0.
#define VA_NARGS_2(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, N, ...) \
N
// Note: the last dummy parameter sole purpose is
// to avoid a warning
#define VA_NARGS_1(...) \
VA_NARGS_2(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, /* dummy */)
/**
* @def PASTE(x, y)
* Pastes two macros tokens together to create
* a new name.
*/
#define PASTE(x, y) \
PASTE_1(x, y)
/**
* @def VA_NARGS(...)
* Counts the number of arguments of the given
* macro parameter pack.
*/
#define VA_NARGS(...) \
sizeof(#__VA_ARGS__) == sizeof("") ? 0 : \
VA_NARGS_1(__VA_ARGS__)
/**
* @def DISPATCH(func, ...)
* Calls different functions in function of the
* number of parameters in the parameter pack.
* Therefore, it allows to overload macros based
* on the number of arguments passed to it.
*
* @warning Can not handle 0-sized parameter packs.
*/
#define DISPATCH(func, ...) \
PASTE(func, VA_NARGS_1(__VA_ARGS__))
</code></pre>
<p>And finally, here is an example of how to use all the code above:</p>
<pre><code>define(Vector(float))
define(Vector(int))
define(Vector(double))
int main()
{
Vector(int)* vec_i = new(Vector(int));
Vector(double)* vec_d = new(Vector(double));
printf("is_empty: %d\n", is_empty(vec_i));
printf("size: %u\n", size(vec_i));
printf("max_size: %u\n", max_size(vec_i));
printf("capacity: %u\n", capacity(vec_i));
printf("front: %d == %d\n", front(vec_i), at(vec_i, 0));
printf("back: %d == %d\n", back(vec_i), at(vec_i, 2));
reserve(vec_d, 56);
printf("capacity: %d\n", capacity(vec_d)); // 56
reserve(vec_d, 30);
printf("capacity: %d\n", capacity(vec_d)); // 56
for (int i = 0 ; i < 3 ; ++i)
{
push_back(vec_d, 0.0);
}
first(vec_d) = 5.6;
elem(vec_d, 1) = 1.0;
elem(vec_d, 2) = 2.0;
for (size_t i = 0 ; i < 3 ; ++i)
{
printf("%f ", at(vec_d, i));
}
printf("\n");
shrink_to_fit(vec_d);
printf("capacity: %d\n", capacity(vec_d)); // 3
assert(data(vec_d) == vec_d->_data);
assert(last(vec_d) == elem(vec_d, 2));
for (int i = 5 ; i > 0 ; --i)
{
push_back(vec_i, i);
}
printf("size: %u\n", size(vec_i)); // 5
printf("capacity: %d\n", capacity(vec_i)); // 40
pop_back(vec_i);
pop_back(vec_i);
shrink_to_fit(vec_i);
printf("size: %u\n", size(vec_i)); // 3
printf("capacity: %d\n", capacity(vec_i)); // 3
int foo = 8;
push_back(vec_i, foo);
printf("size: %u\n", size(vec_i)); // 4
printf("capacity: %d\n", capacity(vec_i)); // 43
delete(vec_i);
delete(vec_d);
// erase methods
Vector(int)* vi = new(Vector(int));
for (int i = 0 ; i < 10 ; ++i)
{
push_back(vi, i);
}
printf("\n");
for (int* it = begin(vi) ; it != end(vi) ; ++it)
{
// 0 1 2 3 4 5 6 7 8 9
printf("%d ", *it);
}
printf("\n");
erase(vi, begin(vi));
for (size_t i = 0 ; i < size(vi) ; ++i)
{
// 1 2 3 4 5 6 7 8 9
printf("%d ", at(vi, i));
}
printf("\n");
erase(vi, begin(vi)+2, begin(vi)+5);
for (size_t i = 0 ; i < size(vi) ; ++i)
{
// 1 2 6 7 8 9
printf("%d ", at(vi, i));
}
delete(vi);
}
</code></pre>
<p>Of course, none of this is meant to be used with a C++ compiler and all this code is merely done for fun; I would never use that as production code. Also, I already know that all those macros pollute everything, but I don't care - all of this is just a proof of concept. So, would there be any way to improve the interface even further? Moreover, are there ovious errors in the <code>Vector</code> implementation?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T06:31:24.977",
"Id": "76874",
"Score": "0",
"body": "Interesting, however the implementation is by force of nature of cpp not so appealing as it should. I think somebody should develop more powerful and elegant macro/templating language which to use to write this kind of stuff, and then compile that hand-edited file to C and to object code. This is easily to automated if you use `make` or a similar tool. Omitting desire for syntactic sugar, `eperl`, `eruby` would be easy grounds of experimentation about what this thing would like to look like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T16:18:56.223",
"Id": "78969",
"Score": "0",
"body": "What C11 features are you actually using? It seems to compile just fine as C99."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T16:22:03.670",
"Id": "78972",
"Score": "1",
"body": "@200_success It indeed does compile in C99. But I would be glad to know whether it could be improved with C11; I don't want to limit myself to C99."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-30T12:01:59.287",
"Id": "153828",
"Score": "0",
"body": "I suggest to use generic list implementation of Rusty Russels (used in Linux kernel). It does not need all this preprocessor code. See http://ccodearchive.net/info/list.html."
}
] | [
{
"body": "<p>There is a rather large amount of code here and a lot of macro trickery, so I shall refrain from attempting to comment on it all.</p>\n\n<p>There are, however, a few things that immediately jumped out at me.</p>\n\n<hr>\n\n<p>Don't use <code>new</code> as your allocating macro. That's extremely confusing, and it's going to make compiling it as C++ rather difficult. (Not that having C be compilable as C++ is exactly a noble goal -- it's just not worth throwing away over one word).</p>\n\n<hr>\n\n<p>Your macros should be namespaced. <code>size</code>? <code>at</code>? You don't think anyone else might try to use those names?</p>\n\n<p>Rather than <code>define_Vector</code> have <code>vector_define</code> and then <code>vector_at</code>, <code>vector_size</code>, etc. Not only does this make it immediately clearer that things like <code>size</code> aren't some kind of magic, it should hopefully help avoid potential collisions if someone were to use this with other code.</p>\n\n<hr>\n\n<p><code>realloc</code> can fail. You need to consider that in <code>vector_reserve</code>, <code>vector_shrink_to_fit</code> and so on.</p>\n\n<hr>\n\n<p>Are you sure your accessors (<code>vector_at</code>, <code>vector_front</code>, etc) should return a <code>T</code> and not a <code>T*</code>? Imagine if you're storing a large struct. You would probably rather be able to mutate the struct inside of the vector rather than having to copy it, modify it, and then put it back. (Yes, you can get direct access like this with your 'iterators', but eh...).</p>\n\n<hr>\n\n<p>This feels a bit incomplete if you're trying to mimic C++. Where are constructors? Destructors? Copiers? What if I have a vector of 10 structs that have FILE* pointers? It would be nice to be able to assign a destructor to those so that calls like <code>vector_clear</code> would not leave a dangling file handle.</p>\n\n<hr>\n\n<p>I actually might consider going with <code>T</code> here like you've done, but it's fairly customary in C to use an automatic form of <code>sizeof</code> rather than explicit. Like:</p>\n\n<pre><code>res->_data = malloc(40*sizeof(*(res->data)));\n</code></pre>\n\n<hr>\n\n<p>Accepting constant pointers rather than values in a few places would allow you to avoid potential copies. Unfortunately that makes the calling semantics a bit grosser, but welcome to C :).</p>\n\n<hr>\n\n<p>40 is a rather large default capacity. (Also, you <em>have</em> to handle malloc/realloc failures for a library like this.)</p>\n\n<p>It would be nice to be able to avoid a malloc until something is actually stored in the vector. It could avoid a rather costly allocation in certain cases where a vector is created and then not pushed into.</p>\n\n<hr>\n\n<p>I might try to pull the default capacity into a constant or something, but either way, it shouldn't be repeated:</p>\n\n<pre><code>res->_capacity = 40; \\\nres->_size = 0; \\\nres->_data = malloc(40*sizeof(T)); \n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>res->_capacity = 40; \\\nres->_size = 0; \\\nres->_data = malloc(res->_capacity*sizeof(T)); \n</code></pre>\n\n<p>This is just to avoid a mismatch if at some point 40 is changed on one line and not the other.</p>\n\n<hr>\n\n<p><em>Unsolicited, blatant opinion incoming :)</em></p>\n\n<p>Though this is elegant and clever, overall I'm not sure how I feel about it. </p>\n\n<p>As you almost certainly know, data structures in C typically revolve around <code>void*</code> with a complete lack of type safety. Your vector give type safety at a relatively minor cost (binary size), so that's rather nice and a very real benefit.</p>\n\n<p>I can't help but feel though that at the end of the day, you've just recreated templates in a language not meant to support them. In almost all situations where this would be used, I think the proper option would be to just use C++. Then again, I'm <strong>very</strong> biased towards C++, and my sentiment is almost always \"if you <em>can</em> use C++, then you <strong>should</strong> use C++.\"</p>\n\n<p>In situations where you're stuck using C, this could be very valuable if type safety is very important. I do believe though that it would require a bit more polishing in terms of the items mentioned above, and it would need to be tested very thoroughly in both functional and performance senses.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:01:34.003",
"Id": "79937",
"Score": "0",
"body": "The goal was indeed to \"recreate templates in C\" (as said in the introduction), and also to create a basic set of features meant to be built upon later. It was not meant to be integrated to any actual project. Using unnamespaced names was part of the design (using c++ keywords was also part of it); also, the \"interface\" macros can match any other collections with the required functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:05:13.417",
"Id": "79938",
"Score": "0",
"body": "@Morwenn Ah :). I would still highly suggest against un-namespaced names or C++ keywords though. Just go with something more general like `container_` and something with a similar meaning but a non-keyword like `create` or `delete`. I guess if you're determined to mimic C++ as closely as possible, I can see where you're coming from, but unless this is purely academic, mimicking a language for the sake of mimicking a language is dubious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:05:53.420",
"Id": "79939",
"Score": "0",
"body": "I generally use C++ (ok, always use it actually). This was nothing but an exercise to see how far I could push a plain *new* C. Concerning the constructor and destructor, those are `vector_delete_##T` and `new_Vector_##T`. I totally do lack a copier and a mean to compare the vectors though..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:08:21.407",
"Id": "79940",
"Score": "0",
"body": "Overall, your comments are valuable though. And you're right, having `container_*` or `collection_*` is not that heavy and still quite generic :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:09:41.290",
"Id": "79941",
"Score": "0",
"body": "@Morwenn I meant a ctor/dtor for the elements, not the container. It would of course be a bit awkward though since the constructor/destructor would be attached to the container rather than the stored `struct`. A case could certainly be made for the \"you're expected to clean stuff up manually before disposing of a vector or any elements\" route."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:17:44.643",
"Id": "79942",
"Score": "0",
"body": "Oh, I see what you mean. I totally overlooked that. If meant to be built upon, I could require users to have destructors (`mytype_delete`) and call `delete` in `vector_delete_mytype`. Since there isn't such a thing for built-in types, I could probably `_Generic` away those types in the implementation of `delete`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T08:25:37.867",
"Id": "79944",
"Score": "0",
"body": "@Morwenn Yeah. I would be tempted to implement it as just a simple function pointer stored in the vector instance. That would allow the consumer to theoretically customize it to be whatever they wanted to be named, but in the case that a dtor wasn't provided to the vector constructor it could default to either no constructor, or you could use compiler specific tricks to look for an optional `type_delete`. That might get very gross though, and the flexibility would probably go unused. Probably better to do as you said and just require `delete_*` unless rather interesting use were expected."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T06:01:22.820",
"Id": "45805",
"ParentId": "43809",
"Score": "13"
}
},
{
"body": "<p>I did manage to improve some things since the question was posted. So here is what I discovered, that could somehow improve the implementation and the usability of the <code>Vector(T)</code>:</p>\n\n<ul>\n<li><p>First of all, there was an error in the code. <em>Shame on me</em>. I shared a piece of code that could not be compiled. I must have posted a version that was not up-to-date. The macro <code>new</code> does not work for two reasons: the token pasting is not well done <strong><em>and</em></strong> I forgot to add the parenthesis for the function call. The first solution to fix that error is to have <code>new(Vector(int))</code> call <code>new_Vector_int()</code>:</p>\n\n<pre><code>#define new(type) \\\n PASTE(new_, type)()\n</code></pre>\n\n<p>The second solution is to have <code>new(Vector(int))</code> resolve to <code>new_Vector_int</code> and add the call by hand on the calling site. This would allow to \"overload constructors\":</p>\n\n<pre><code>#define new(type) \\\n PASTE(new_, type)\n\nVector(int)* vec_i = new(Vector(int))(/* maybe more paremeters later */);\n</code></pre></li>\n<li><p>The <code>define_vector_##T</code> macro introduces names that begin with an underscore in the global scope. Such names are reserved to the implementation; they should either use another prefix or be put somewhere else (for example, the function table could be a <code>static</code> variable in a function. Not that this is a good idea either, but you get it...).</p></li>\n<li><p>The <code>typedef</code> between <code>struct _vector_##T</code> and <code>Vector_##T</code> is done quite late. I could have used the \"forward <code>typedef</code>\":</p>\n\n<pre><code>typedef struct _vector_##T Vector_##T;\n</code></pre>\n\n<p>This would have allowed me use <code>Vector_##T</code> instead of <code>struct _vector_##T</code> in the function declarations.</p></li>\n<li><p>Actually, I can also use <code>Vector(T)</code> directly instead of <code>Vector_##T</code> in the body of <code>define_Vector</code>. Thanks to that, I can drop many <code>##</code> operators and the code ends up being easier to read.</p></li>\n<li><p>The macros parameters are not always correctly guarded with parenthesis. If I have a stack-allocated vector and try to give its address to a function (<em>e.g.</em> <code>begin(&vec_i)</code>), it fails miserably. More parenthesis are needed:</p>\n\n<pre><code>#define begin(collection) \\\n (collection)->_functions->begin(collection)\n</code></pre></li>\n<li><p>Last but not least, I kind of failed (at first) to mimic the C++ functions returning lvalues (non-<code>const</code> references). I can still work around that by having the functions return pointers and having the interface macros dereference those functions returns. Take the example of <code>front</code>. The declaration becomes:</p>\n\n<pre><code>T* vector_front_##T(const Vector(T)*);\n</code></pre>\n\n<p>The definition becomes:</p>\n\n<pre><code>T* vector_front_##T(const Vector(T)* vector)\n{\n return vector->_data;\n}\n</code></pre>\n\n<p>And the macro <code>front</code> becomes:</p>\n\n<pre><code>#define front(collection) \\\n (*((collection)->_functions->front(collection)))\n</code></pre>\n\n<p>This new trick allows us to get rid of the workaround macros <code>elem</code>, <code>first</code> and <code>last</code> since <code>at</code>, <code>front</code> and <code>back</code> can now somehow return lvalues instead of simple values, and not only for data structures with contiguous storage. Of all the points, this is the only one that allows to increase the usability of the code.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:54:03.390",
"Id": "46191",
"ParentId": "43809",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "45805",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T20:10:14.730",
"Id": "43809",
"Score": "16",
"Tags": [
"c",
"template",
"vectors",
"macros",
"c11"
],
"Title": "Template vector struct in C11"
} | 43809 |
<p>As usual, please be <em>brutally</em> honest with your opinion of my code, and how you would judge it if I were to code this at a top-tier tech company for an interview(think Google, MSFT, Facebook, etc). My algorithm is has a worst time complexity of O(n).</p>
<p>Question:
Given an unsorted integer array, find the first missing positive integer.
For example,</p>
<pre><code>Given [1,2,0] return 3,
and [3,4,-1,1] return 2.*
</code></pre>
<p>My code(coded in 22 minutes, with all test cases passed, devised initial algorithm in 2-5 minutes)</p>
<pre><code> public int firstMissingPositive(int[] A) {
int minVal=0;
if(A.length==0){
return 1;
}
Hashtable<Integer, Integer> myTable = new Hashtable<Integer, Integer>();
for(int i : A){
if(i<minVal && i>0){
minVal = i;
}
myTable.put(i, i);
}
for(int i=0; i<=A.length; i++){
if( (!myTable.containsKey(minVal-1)) && minVal-1>0){
return minVal-1;
}
else if(!myTable.containsKey(minVal+1)){
return minVal+1;
}
minVal++;
}
return minVal;
}
</code></pre>
| [] | [
{
"body": "<p>I guess it's quite good in 22 minutes.</p>\n\n<ol>\n<li><blockquote>\n<pre><code>Hashtable<Integer, Integer> myTable = new Hashtable<Integer, Integer>();\n</code></pre>\n</blockquote>\n\n<p>Instead of the <code>Hashtable</code> use <code>HashMap</code>, but you use it like a <code>Set</code> (same key and value, so value is unused), so use a <code>HashSet</code> instead. See: <a href=\"https://stackoverflow.com/q/40471/843804\">Differences between HashMap and Hashtable?</a></p></li>\n<li><p>I would use a longer variable names than <code>A</code>. Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses. Furthermore, usual Java variable names are camelCase, with lowercase first letter. (See: <em>Effective Java, 2nd edition</em>, <em>Item 56: Adhere to generally accepted naming conventions</em>)</p></li>\n<li><p><code>myTable</code> could have a more descriptive name.</p></li>\n<li><p>I've removed everything which does not change <code>minVal</code>'s value:</p>\n\n<blockquote>\n<pre><code>int minVal=0;\n...\nfor(int i : A){\n if(i<minVal && i>0){\n minVal = i;\n }\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>If I'm right the condition of the <code>if</code> statement is always <code>false</code>. If you substitute <code>minVal</code>'s initial value, you get this:</p>\n\n<p>i < 0 && i > 0</p>\n\n<p>which is <code>false</code>, so <code>minVal</code>'s value never can be changed.</p></li>\n<li><p>I'd put a <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause</a> inside the for to get rid of the negative values and save some memory in the set:</p>\n\n<pre><code>for (int i: A) {\n if (i < 0) {\n continue;\n }\n set.add(i);\n}\n</code></pre></li>\n<li><p>If you want to save some memory with big, non-repetitive input arrays you could use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html\" rel=\"nofollow noreferrer\"><code>new BitSet(A.length)</code></a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:30:23.887",
"Id": "43817",
"ParentId": "43813",
"Score": "5"
}
},
{
"body": "<p>I have to disagree with palacsint about using <code>HashMap</code>, if anything, I think that you should use a <code>Set</code> implementation such as <code>HashSet</code>. You're never using the value that is stored in the map, and you have no reason to use it either. Therefore, I would go with a <code>Set</code>. (The fact that a HashSet internally uses a HashMap is an entirely different subject) Palacsint is correct though that HashMap is a better alternative than Hashtable.</p>\n\n<hr>\n\n<p>Reading lines like this makes me sea-sick:</p>\n\n<pre><code>if( (!myTable.containsKey(minVal-1)) && minVal-1>0){\n</code></pre>\n\n<p>Use spacing properly and remove unnecessary parameters and it becomes:</p>\n\n<pre><code>if(!myTable.containsKey(minVal - 1) && minVal - 1 > 0) {\n</code></pre>\n\n<hr>\n\n<p>Overall, I think that you shouldn't need to use Objects for this (except an array of course, which technically is an object). I would <a href=\"https://codereview.stackexchange.com/questions/43818/first-missing-positive-with-only-primitives\">only use primitives and use more self-documenting variable names</a>.</p>\n\n<p>An unnecessary operation in your code is that on each iteration you check <code>containsKey</code> twice. Once to see if <code>value - 1</code> is set and once to see if <code>value + 1</code> is set. <strong>Why not just check if value itself is set?</strong></p>\n\n<p>Your code can be rewritten and optimized into this: (This is a fixed version of ChrisW's approach, I had started the approach when he posted his answer and then I did some modifications to make sure it matched your code).</p>\n\n<pre><code>public int firstMissingPositive(int[] array) {\n boolean[] foundValues = new boolean[array.length];\n for (int i : array) {\n if (i > 0 && i <= foundValues.length)\n foundValues[i - 1] = true;\n }\n\n for (int i = 0; i < foundValues.length; i++) {\n if (!foundValues[i]) {\n return i + 1;\n }\n }\n return foundValues.length + 1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:43:25.630",
"Id": "75828",
"Score": "0",
"body": "So would you hire me, considering I just graduated from college, with such code? I want to see what more experienced folks like yourself think of what I have written."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:47:58.470",
"Id": "75829",
"Score": "2",
"body": "@bazang I've never been at a real interview where I've had to write any code so honestly, I don't know. I'm not an employer. Even though I think that you haven't written the most optimal code performance-wise, just the fact that you managed to solve the problem is a good start."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:41:58.667",
"Id": "43819",
"ParentId": "43813",
"Score": "8"
}
},
{
"body": "<p>Re. the question, I take it that 0 isn't a positive integer? In an interview you might look for holes/ambiguities in the specification, and ask about them (double-check that you understand the requirements before coding).</p>\n\n<p>Re. your code, on the plus side, well done for using a hash? Because a hash tends to be O(1) per lookup therefore O(n) overall.</p>\n\n<p>I don't see how you can do better than O(n) because you need to look at every item.</p>\n\n<p>On the minus side I think I see a simpler implementation, as follows (in pseudocode because I don't know Java):</p>\n\n<pre><code>public int firstMissingPositive(int[] A) {\n{\n int length = A.Length;\n // create a vector of length 'length'\n Vector<bool> vector = new Vector<bool>(length);\n // this loop isn't necessary if Vector's elements are default-initialized (to false)\n for (int i = 0; i < length; ++i)\n vector[i] = false;\n // remember what the interesting input integers are\n foreach (a in A)\n {\n if (a > 0) && (a <= length)\n vector[a-1] = true;\n // else a is not a candidate\n }\n for (int i = 0; i < length; ++i)\n {\n if (!vector[i])\n // i+1 was not in the input array\n return i+1;\n }\n return length+1;\n}\n</code></pre>\n\n<p>I think my solution is easier to read; and is probably faster and uses less memory (because I guess that <code>Vector<boolean></code> is simpler and uses less space than <code>HashSet<int></code>).</p>\n\n<hr>\n\n<blockquote>\n <p>how you would judge it if I were to code this at a top-tier tech company for an interview</p>\n</blockquote>\n\n<p>Assuming that one of the reasons for writing code in an interview is in order to give us something to talk about, to see how you respond to criticism, whether you can be guided to a better answer, whether you deeply understand the tools you choose to use, I might ask you whether you should specify the initialCapacity and loadFactor when you construct a HashSet, and what the effect of that would be; and drop some hints about whatever the best solution is (which as an interview I might already know 'unfairly' because I was looked it up in advance) to see whether you can get it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:15:59.253",
"Id": "75832",
"Score": "0",
"body": "`(a < length)`, cool :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:17:56.997",
"Id": "75833",
"Score": "0",
"body": "`Vector<bool>` should be `boolean[]` here. (Although there is a `Vector` class in Java, it shouldn't be used because it's totally synchronized, `ArrayList` should be used instead, but is not needed here as it's enough with a boolean array)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:25:14.137",
"Id": "75834",
"Score": "0",
"body": "@SimonAndréForsberg In C++, std::vector<bool> has a special optimization using bits instead of bytes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:30:38.130",
"Id": "75836",
"Score": "0",
"body": "In Java, that would be a `BitSet` I believe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:38:37.217",
"Id": "75837",
"Score": "0",
"body": "Your code has two unexpected results, for input `[1, 2, 3]` you returned 3 but OP's code returns 4. For input `[]` (empty array) you returned 0 but OP's code returns 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:42:09.087",
"Id": "75838",
"Score": "0",
"body": "As Simon found, you can't depend on the values starting from zero. For `[3, 4, 5]` your code produces `1` because it doesn't store any of the numbers due to `(a < length)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:43:17.980",
"Id": "75839",
"Score": "2",
"body": "@DavidHarkness That's not clear from the specs: it's possible that for 3,4,5 the first missing positive integer is 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:45:11.913",
"Id": "75840",
"Score": "0",
"body": "@DavidHarkness For [3, 4, 5] the OP's code also returns 1. [While in my other question, I would return 6](http://codereview.stackexchange.com/questions/43818/first-missing-positive-with-only-primitives)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:46:28.620",
"Id": "75841",
"Score": "0",
"body": "@ChrisW LOL, yes it pays to read the spec better. :) `1` is indeed correct in that case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T02:42:36.550",
"Id": "75864",
"Score": "0",
"body": "@ChrisW can you tell me how the load factor or initial capacity would make a difference? The initial capacity would specify the size of the HashSet right, and the load factory would be number of occupied buckets over the size? I'm confused with that question but I feel like you are asking me a question that I would stumble on so please tell me what you would like to hear and why that helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T10:37:48.240",
"Id": "75878",
"Score": "0",
"body": "@bazang https://www.google.com/search?q=initialCapacity+and+loadFactor"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:04:49.627",
"Id": "43820",
"ParentId": "43813",
"Score": "4"
}
},
{
"body": "<p>One more implementation that I can think off using treeSet. Code is a bit easy to read and putting in some edge case checks to improve performance. This might not give a O(N) performance but would give O(Nlog N) as treeSet inserts are O(log N) for each insert. But the advantage is the retrieving of elements from treeSet.</p>\n\n<pre><code>public static int firstMissingPositive(int[] ip) {\n\n if (ip == null || ip.length == 0) {\n return 1;\n }\n\n TreeSet<Integer> postiveElements = new TreeSet<Integer>();\n\n for (int e : ip) {\n if (e > 0) {\n postiveElements.add(e);\n }\n }\n\n int tsSize = postiveElements.size();\n\n if (tsSize == 0 || postiveElements.first() > 1) {\n return 1;\n }\n\n if (tsSize == postiveElements.last()) {\n return tsSize+1;\n }\n\n\n int incElement = 1;\n\n for(; incElement <= tsSize; incElement++) {\n if (incElement != postiveElements.pollFirst()) {\n break;\n }\n }\n\n return incElement;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-05T14:23:46.693",
"Id": "52513",
"ParentId": "43813",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "43819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:09:53.513",
"Id": "43813",
"Score": "7",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "First missing positive"
} | 43813 |
<p>I'm trying to implement a <code>TaskScheduler</code> that runs all tasks in the order they are submitted, on a single dedicated thread. Here's my implementation, using a <code>BlockingCollection</code>:</p>
<pre><code>class SequentialScheduler : TaskScheduler, IDisposable {
readonly BlockingCollection<Task> m_taskQueue = new BlockingCollection<Task>();
readonly Thread m_thread;
bool m_disposed;
public SequentialScheduler() {
m_thread = new Thread(Run);
m_thread.Start();
}
public void Dispose() {
m_disposed = true;
}
void Run() {
while (!m_disposed) {
var task = m_taskQueue.Take();
Debug.Assert(TryExecuteTask(task));
}
}
protected override IEnumerable<Task> GetScheduledTasks() {
return m_taskQueue;
}
protected override void QueueTask(Task task) {
m_taskQueue.Add(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) {
if (Thread.CurrentThread == m_thread) {
return TryExecuteTask(task);
}
return false;
}
}
</code></pre>
<p>I've played with it a bit and it seems to work well. I have some lingering questions however:</p>
<ul>
<li>As you can tell by the Debug.Assert, I'm not sure how <code>TryExecuteTask</code> could return false and I'm just assuming that given my current implementation, it won't. Can that actually happen and what I should I do if it does?</li>
<li>I'm not sure my implementation of <code>TryExecuteTaskInline</code> makes sense as it doesn't get called in my tests. If I understand correctly, this method should run the task synchronously if possible; hence why I'm checking if the current thread is the scheduler's dedicated thread.</li>
<li>Also, my implementation of <code>Dispose</code> doesn't wait for the current task to complete, and will cause the rest of the tasks in the queue to just wait there forever, but short of making it blocking and wait for the queue to empty, I don't see how to do that any differently. I just need a way to release the thread.</li>
</ul>
| [] | [
{
"body": "<p><code>TryExecuteTaskInline</code> is used in what is called \"task inlining\": basically, when you call <code>Wait()</code> on a <code>Task</code> that didn't start executing yet, it might be executed on the current thread. A simple way to test that is:</p>\n\n<pre><code>var factory = new TaskFactory(new SequentialScheduler());\n\nfactory.StartNew(\n () =>\n {\n factory.StartNew(() => { }).Wait();\n });\n</code></pre>\n\n<p>For more information, see <a href=\"https://devblogs.microsoft.com/pfxteam/task-wait-and-inlining/\" rel=\"nofollow noreferrer\">Stephen Toub's article <em>Task.Wait and “Inlining”</em></a>.</p>\n\n<p>But this all means that a <code>Task</code> might be executed outside of your <code>Run()</code> loop, so the call to <code>TryExecuteTask()</code> there might return <code>false</code>. Because of that, you should simply ignore the return value there (<a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler\" rel=\"nofollow noreferrer\">just like the official example scheduler does</a>, in its <code>NotifyThreadPoolOfPendingWork()</code>).</p>\n\n<p>Another option would be to remove inlined <code>Task</code>s from the queue, but there is no simple way to do that for <code>BlockingCollection</code>.</p>\n\n<hr>\n\n<p>I think that <code>m_disposed</code> should be <code>volatile</code>, otherwise, the <code>Run()</code> loop can be optimized into an infinite loop that checks the value of <code>m_disposed</code> only once, at the start.</p>\n\n<hr>\n\n<p>For disposal, you might want to use <a href=\"http://msdn.microsoft.com/en-us/library/dd287086\" rel=\"nofollow noreferrer\">the completion capability of <code>BlockingQueue</code></a>. That way, trying to schedule a new <code>Task</code> after the scheduler has been disposed will throw, which I think is the correct behavior.</p>\n\n<p>If you do this, you can also rewrite <code>Run()</code> to use <code>GetConsumingEnumerable()</code>, and remove <code>m_disposed</code> altogether.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T02:20:38.243",
"Id": "78437",
"Score": "0",
"body": "Thanks a lot. Does this mean that my implementation of TryExecuteInline is correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T02:28:29.493",
"Id": "78439",
"Score": "0",
"body": "I have difficulty seeing under what circumstances a task might be executed outside the Run() loop yet on the same thread, so perhaps my check there is unnecessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-18T20:04:01.330",
"Id": "44697",
"ParentId": "43814",
"Score": "5"
}
},
{
"body": "<h2>Dispose the scheduler gracefully</h2>\n\n<p>As you mentioned, you lack proper disposal functionality.</p>\n\n<blockquote>\n<pre><code>void Run() {\n while (!m_disposed) {\n var task = m_taskQueue.Take();\n Debug.Assert(TryExecuteTask(task));\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The first issue is that <code>bool m_disposed</code> is not marked as <em><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile\" rel=\"nofollow noreferrer\">volatile</a></em>. This means that this variable is subject to optimisations that could render its usage invalid for your scenario. If optimized, the value will be cached once, and never re-read in the same ongoing method call, causing an infinite loop.</p>\n\n<p>The second issue is that you can't abort waiting a new task using <code>Take()</code>. But there is a simple alternative <code>Take(CancellationToken ct)</code>; Keep track of a <code>CancellationTokenSource</code> in your task scheduler, pass its <code>Token</code> to <code>Take(token)</code>; on disposal of the instance, flag it by calling <code>Cancel()</code>.</p>\n\n<p>I would also verify how <code>Debug.Assert(TryExecuteTask(task))</code> gets optimized in production code. And whether this could introduce unwanted side effects.</p>\n\n<h3>Revised</h3>\n\n<pre><code>class SequentialScheduler : TaskScheduler, IDisposable {\n readonly BlockingCollection<Task> m_taskQueue = new BlockingCollection<Task>();\n readonly Thread m_thread;\n readonly CancellationTokenSource m_cancellation; // CR comment: field added\n volatile bool m_disposed; // CR comment: volatile added\n\n public SequentialScheduler() {\n m_cancellation = new CancellationTokenSource();\n m_thread = new Thread(Run);\n m_thread.Start();\n }\n\n public void Dispose() {\n m_disposed = true;\n m_cancellation.Cancel(); // CR comment: cancellation added\n }\n\n void Run() {\n while (!m_disposed) {\n // CR comment: dispose gracefully\n try\n {\n var task = m_taskQueue.Take(m_cancellation.Token);\n // Debug.Assert(TryExecuteTask(task));\n TryExecuteTask(task); // CR comment: not sure about the Debug.Assert here\n }\n catch (OperationCanceledException)\n { \n Debug.Assert(m_disposed);\n }\n }\n }\n\n protected override IEnumerable<Task> GetScheduledTasks() {\n return m_taskQueue;\n }\n\n protected override void QueueTask(Task task) {\n m_taskQueue.Add(task);\n }\n\n protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) {\n if (Thread.CurrentThread == m_thread) {\n return TryExecuteTask(task);\n }\n return false;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T17:30:11.160",
"Id": "224916",
"ParentId": "43814",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-08T21:11:26.753",
"Id": "43814",
"Score": "10",
"Tags": [
"c#",
"task-parallel-library",
"concurrency"
],
"Title": "TaskScheduler that uses a dedicated thread"
} | 43814 |
<p>As soon as I saw the <a href="https://codereview.stackexchange.com/questions/43813/first-missing-positive">First missing positive</a> question, I decided to write my own method for this before writing my review on the question.</p>
<p>Judge me by the same standards as bazang wants to be judged, i.e. As if this was written for a big company such as Google for an interview.</p>
<p>I wasn't sure how the input 7, 8, 9 should be treated so to make it a bit harder for myself I gave myself the requirement that it should return 10.</p>
<pre><code>@Test
public void test() {
Assert.assertEquals(3, missingInt(new int[]{ 1, 2, 0 }));
Assert.assertEquals(4, missingInt(new int[]{ 1, 2, 3 }));
Assert.assertEquals(2, missingInt(new int[]{ 3, 4, -1, 1 }));
Assert.assertEquals(10, missingInt(new int[]{ 7, 8, 9 }));
Assert.assertEquals(5, missingInt(new int[]{ 3, 4, 2, 7, 6, 1 }));
Assert.assertEquals(5, missingInt(new int[]{ 3, 4, 2, 7, 6, 1, -4 }));
}
public int missingInt(int[] array) {
boolean[] foundIntegers = new boolean[array.length];
int smallestPositive = Integer.MAX_VALUE;
for (int i : array) {
if (i > 0 && i < smallestPositive)
smallestPositive = i;
}
for (int i : array) {
if (i < smallestPositive)
continue;
int index = i - smallestPositive;
if (index < foundIntegers.length)
foundIntegers[index] = true;
}
for (int i = 0; i < foundIntegers.length; i++) {
if (!foundIntegers[i])
return i + smallestPositive;
}
return foundIntegers.length + smallestPositive;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:41:18.677",
"Id": "75826",
"Score": "2",
"body": "You should use `import static ` for all your asserts. So you could do `assertEquals(3, missingInt(new int[]{ 1, 2, 0 }));`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:43:05.333",
"Id": "75827",
"Score": "1",
"body": "@Marc-Andre True. I do that normally, just forgot about that this time :)"
}
] | [
{
"body": "<p>That solution is the algorithm I would have chosen.</p>\n\n<p>I like the data you chose for your list of test cases; you could have added at least one more test case, i.e. an input array with zero elements.</p>\n\n<p>In fact IMO your code will fail when the input is a zero-length array.</p>\n\n<p>You code will also fail when all the input integers are <code><= 0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:42:19.060",
"Id": "75848",
"Score": "0",
"body": "@SimonAndréForsberg The code (or problem specification) will also fail if the input is a contiguous range of positive integers whose largest value is Integer.MaxValue"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:05:30.180",
"Id": "75851",
"Score": "0",
"body": "Oh, of course. Silly me. Yes, that would cause overflow and return `Integer.MIN_VALUE`. Not so much to do about that though :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:07:07.977",
"Id": "75852",
"Score": "0",
"body": "You could throw."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:10:01.950",
"Id": "75855",
"Score": "0",
"body": "yes, if there's any case that is exceptional, it's that one."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:05:04.010",
"Id": "43822",
"ParentId": "43818",
"Score": "8"
}
},
{
"body": "<h1>Stupid edge-cases!</h1>\n<p>While doing some testing for coming up with a better version for the <a href=\"https://codereview.stackexchange.com/questions/43813/first-missing-positive\">First missing positive</a> question, I added a bunch of more test cases and compared several different methods with each other. Then I found the following problems:</p>\n<pre><code>Input [-5] returned 2147483647 but expected 1\nInput [-5, -4, -3] returned 2147483647 but expected 1\nInput [0, 0, 0, 0] returned 2147483647 but expected 1\nInput [] returned 2147483647 but expected 1\n</code></pre>\n<p>To correct these problems, I added some edge-case checking; to check for array where there are no positive integers. As these really are edge-cases, I haven't decided how to handle these. As there technically isn't a clear "first missing positive number". If I would have handled <code>7 8 9</code> as <code>return 1</code> then I would have returned <code>1</code> for these edge cases also, but I feel that wouldn't be expected behavior from this algorithm so therefore I decided to throw an exception.</p>\n<p>The new code is:</p>\n<pre><code>public int simonNew(int[] array) {\n boolean[] foundIntegers = new boolean[array.length];\n int smallestPositive = Integer.MAX_VALUE;\n\n for (int i : array) {\n if (i > 0 && i < smallestPositive)\n smallestPositive = i;\n }\n if (smallestPositive == Integer.MAX_VALUE)\n throw new IllegalArgumentException("Array must not be null and must contain at least one positive integer");\n\n for (int i : array) {\n if (i < smallestPositive)\n continue;\n\n int index = i - smallestPositive;\n if (index < foundIntegers.length)\n foundIntegers[index] = true;\n }\n\n for (int i = 0; i < foundIntegers.length; i++) {\n if (!foundIntegers[i])\n return i + smallestPositive;\n }\n return foundIntegers.length + smallestPositive;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:34:03.940",
"Id": "75846",
"Score": "0",
"body": "Maybe 1 is a reasonable return value for a zero-length array. Maybe you should change the type to `unsigned int` instead of throwing if the input is negative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:37:11.520",
"Id": "75847",
"Score": "1",
"body": "@ChrisW Java... unsigned int.... wait, what? :) [There's no such thing](http://stackoverflow.com/questions/430346/why-doesnt-java-support-unsigned-ints)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:24:33.877",
"Id": "43824",
"ParentId": "43818",
"Score": "10"
}
},
{
"body": "<ol>\n<li><blockquote>\n<pre><code>if (i > 0 && i < smallestPositive)\n smallestPositive = i;\n</code></pre>\n</blockquote>\n\n<p>could be</p>\n\n<pre><code>if (i > 0)\n smallestPositive = Math.min(smallestPositive, i);\n</code></pre>\n\n<p>I think it's a little bit easier to read.</p></li>\n<li><p>At work I'd use <a href=\"https://codereview.stackexchange.com/a/7602/7076\">parametrized tests</a> which help <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow noreferrer\">defect localization</a>. Anyway, you could extract out a verifier method to remove some duplication:</p>\n\n<pre><code>@Test\npublic void test() {\n verifyMissingInt(3, 1, 2, 0);\n verifyMissingInt(4, 1, 2, 3);\n verifyMissingInt(2, 3, 4, -1, 1);\n verifyMissingInt(10, 7, 8, 9);\n verifyMissingInt(5, 3, 4, 2, 7, 6, 1);\n verifyMissingInt(5, 3, 4, 2, 7, 6, 1, -4);\n}\n\nprivate void verifyMissingInt(int expected, int... data) {\n assertEquals(expected, missingInt(data));\n}\n</code></pre>\n\n<p>Unfortunately, every parameter is integer, so it's not easy to separate expected output from input data. Two other ways:</p>\n\n<pre><code>verifyMissingInt(3, new int[] { 1, 2, 0 });\n</code></pre>\n\n<p>and</p>\n\n<pre><code> verifyMissingInt(3, array(1, 2, 0));\n</code></pre>\n\n<p>with</p>\n\n<pre><code>private int[] array(int... data) {\n return data;\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:22:57.030",
"Id": "75912",
"Score": "1",
"body": "Never knew that `varargs` can be changed into an `array`. +1 for so cool testing technique."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:35:53.063",
"Id": "43825",
"ParentId": "43818",
"Score": "8"
}
},
{
"body": "<p>It <em>might</em> be possible to solve this problem without using a bitfield or boolean array at all. In an interview, it's important to ask questions to clarify the requirements.</p>\n\n<p>Assuming that the positive inputs always consist of a consecutive range of numbers with no duplicates and exactly one missing number, the answer can be obtained by arithmetic in a single pass. The following solution passes all of the tests in the question.</p>\n\n<pre><code>public static int missingInt(int[] array) {\n int min = Integer.MAX_VALUE, max = 0, count = 0;\n long sum = 0;\n\n for (int i : array) {\n if (i <= 0) continue;\n count++;\n sum += i;\n if (i < min) min = i;\n if (i > max) max = i;\n }\n\n int range = max - min;\n if (count == 0) {\n // No positive inputs\n assert sum == 0;\n return 1;\n } else if (range == count) {\n // Probably one missing element between min and max.\n // Calculate expected sum of all integers from min to max, inclusive.\n long rangeSum = ((long)max + min) * (max - min + 1) / 2;\n return (int)(rangeSum - sum);\n } else if (range == count - 1) {\n // Probably all consecutive numbers. As defined in the\n // question, we want max + 1.\n assert sum == ((long)max + min) * (max - min + 1) / 2;\n return max + 1;\n } else {\n throw new IllegalArgumentException();\n }\n}\n</code></pre>\n\n<p>The caveat is that if the input array contains duplicate entries, or if it is missing multiple entries between the smallest and largest positive number, then the behaviour is undefined. It is sometimes possible to detect such unexpected inputs, but not always.</p>\n\n<p>As indicated by the assertions, there is some redundancy in the statistics. If you don't want to perform the consistency check (which is pretty weak anyway), you could eliminate <code>count</code>.</p>\n\n<p>Since there are multiple ways to solve this problem, and you don't know which solution your interviewer prefers to see, it's important to ask and clarify what the requirements are.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:16:12.227",
"Id": "43963",
"ParentId": "43818",
"Score": "5"
}
},
{
"body": "<p><strong>Tests</strong></p>\n\n<p>As I said in my comment, you should use <code>import static Assert.*</code> as it help improve the readability of the code. This is very minor, but it could help you demonstrate that you know this features of the language. (I know that you're using it, but for future readers it could help)</p>\n\n<p>You could have more than one method for your tests. In modern IDE, having single method/test case with a meaningful case would help to know at first glance what is working, from what is not. This is minor, but it could show to an interviewer that you're as organize in your test than in your code. If the major company that you're applying works with TDD, it could really help.</p>\n\n<p><strong>Coding Style</strong></p>\n\n<p>I was wondering why you were not using brackets for all your <code>if</code> :</p>\n\n<blockquote>\n<pre><code>if (i > 0 && i < smallestPositive)\n smallestPositive = i;\n</code></pre>\n</blockquote>\n\n<p>In the same time, you're not doing the same thing for <code>for</code> loops : </p>\n\n<blockquote>\n<pre><code>for (int i = 0; i < foundIntegers.length; i++) {\n if (!foundIntegers[i])\n return i + smallestPositive;\n}\n</code></pre>\n</blockquote>\n\n<p>I don't know if this would come up in an interview, but this struck me. Why the difference ? If the reason is readability, I would : Why is it good for <code>for</code> but not for <code>if</code> ? </p>\n\n<p>Anyway, I would recommend to always use brackets.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>This is just consideration about the style of your code, and nothing that would mark you as a bad or good candidate. Your code in general is really impressively good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T21:26:43.820",
"Id": "44403",
"ParentId": "43818",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43822",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:38:44.930",
"Id": "43818",
"Score": "11",
"Tags": [
"java",
"algorithm"
],
"Title": "First missing positive with only primitives"
} | 43818 |
<p>After spending a few ages writing out every combination of triggers, bindings and storyboards, I finally managed to get my program working. First time working with WPF, so I made a big mess. Now it's time to put on my refactoring hat and make the code neat and proper again!</p>
<p>That is, if I knew how. Could anyone experienced with WPF or XAML files help me out here and explain how to unmess this code? Suggesting a change of design is fine too, though like I said, this is the only way that I managed to actually get it working.</p>
<p>What the code is supposed to do, is dynamically be able to change sprite animations (by binding a .gif source to an Image), and dynamically "move around" the sprite on a preset animation, different animations depending on what happens in the rest of the code. Like, up and down, or in a circle, or to the corner of the screen and back. Etcetera.</p>
<p>I only copied three storyboards with small changes each per sprite in here for brevity, I suppose you can see what happens when I extend them even further..</p>
<pre><code><Window x:Class="Simplively.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gif="clr-namespace:WpfAnimatedGif"
gif:ImageBehavior.AnimateInDesignMode="True"
Title="MainWindow"
Background="Cyan" Margin="0" SizeToContent="WidthAndHeight">
<Grid Width="1280" Height="720">
<Image Source="Overlay.png" Stretch="Fill" Width="1280" Height="720"/>
<Image Name="p1Sprite" gif:ImageBehavior.AnimatedSource="{Binding PlayerOneSprite}" gif:ImageBehavior.RepeatBehavior="Forever" HorizontalAlignment="Left" Height="47" Margin="239,191,0,0" VerticalAlignment="Top" Width="47" Source="Sprites/Bard.gif" RenderTransformOrigin="1,1">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="p1Scale" ScaleY="1" ScaleX="1"/>
<SkewTransform x:Name="p1Skew" AngleY="0" AngleX="0"/>
<RotateTransform x:Name="p1Rotate" Angle="0"/>
<TranslateTransform x:Name="p1Translate" X="0" Y="0"/>
</TransformGroup>
</Image.RenderTransform>
<Image.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding StartAnimation}" Value="p1leftright">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p1updown">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p1ToCorner">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<Image Name="p2Sprite" gif:ImageBehavior.AnimatedSource="{Binding PlayerTwoSprite}" gif:ImageBehavior.RepeatBehavior="Forever" HorizontalAlignment="Left" Height="47" Margin="239,344,0,0" VerticalAlignment="Top" Width="47" Source="Sprites/Bard.gif">
<Image.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding StartAnimation}" Value="p2leftright">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p2updown">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-64"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p2ToCorner">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-64"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<Image Name="p3Sprite" gif:ImageBehavior.AnimatedSource="{Binding PlayerThreeSprite}" gif:ImageBehavior.RepeatBehavior="Forever" HorizontalAlignment="Left" Height="47" Margin="239,396,0,0" VerticalAlignment="Top" Width="47" Source="Sprites/Bard.gif">
<Image.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding StartAnimation}" Value="p3leftright">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p3updown">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-96"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p3ToCorner">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-96"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<Image Name="p4Sprite" gif:ImageBehavior.AnimatedSource="{Binding PlayerFourSprite}" gif:ImageBehavior.RepeatBehavior="Forever" HorizontalAlignment="Left" Height="47" Margin="239,448,0,0" VerticalAlignment="Top" Width="47" Source="Sprites/Bard.gif">
<Image.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding StartAnimation}" Value="p4leftright">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p4updown">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-128"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding StartAnimation}" Value="p4ToCorner">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
From="0"
To="-32"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
From="0"
To="-128"
Duration="0:0:0.2"
RepeatBehavior="1x"
AutoReverse="True"
/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<Image HorizontalAlignment="Left" Height="152" Margin="10,10,0,0" VerticalAlignment="Top" Width="152" Source="Ffiigreendragon_psp.png"/>
<TextBlock HorizontalAlignment="Left" Height="47" Margin="26,191,0,0" TextWrapping="Wrap" Text="{Binding PlayerOneName}" VerticalAlignment="Top" Width="175"/>
</Grid>
</code></pre>
<p></p>
| [] | [
{
"body": "<p>Your markup is inlining the styles, which has the effect of producing extremely redundant markup - as you've noticed.</p>\n\n<p>You can define the resources of a window in its <code>Resources</code> property - step one would be to extract your inline styles into the <code>Window</code> tag:</p>\n\n<pre><code><Window.Resources>\n <Style x:Key=\"MyStyle1\" TargetType=\"{x:Type Image}\">\n ...\n </Style>\n <Style x:Key=\"MyStyle2\" TargetType=\"{x:Type Image}\">\n ...\n </Style>\n</Window.Resources>\n</code></pre>\n\n<p>Then, you can refer to these styles with a <code>StaticResource</code> markup extension:</p>\n\n<pre><code><Image Style=\"{StaticResource MyStyle1}\">\n ...\n</Image>\n</code></pre>\n\n<p>Depending on exactly what the \"small value changes\" are, you'll want to create a new <code>Style</code>, or put a <code>BasedOn</code> attribute to specify a <code>Style</code> to \"derive\" from another. An individual element can always override any value determined by its <code>Style</code>.</p>\n\n<p>Once you've extracted the styles into the window's resources, you might want to move them to a <code>ResourceDictionary</code> so you can reuse the same styles in other windows, without having to redefine them over again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:27:36.477",
"Id": "75858",
"Score": "0",
"body": "Hmn, I think the biggest issue is that decide which of the four sprite's animation to activate, I need all kinds of variables like 'p1transform', 'p2transform', 'p3transform' etc.etc. for all the different things there are to animate. Is there a way to group the styles and still call on them with different names? Like.. only define \"transform\" once, and then do something like \"p1.transform\", \"p2.transform\", etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:30:23.693",
"Id": "75859",
"Score": "1",
"body": "that could have been clearer if you had included the entire markup."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:36:46.357",
"Id": "75860",
"Score": "0",
"body": "Ah, I apologize. Edited with the full thing in."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:12:30.210",
"Id": "43828",
"ParentId": "43821",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "43828",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T22:56:18.807",
"Id": "43821",
"Score": "11",
"Tags": [
"c#",
"wpf",
"xaml"
],
"Title": "Lots of Storyboards in XAML, huge file"
} | 43821 |
<p>I've done a library that can parse strings to different java types and to <code>List<...></code>, <code>Set<...></code>, <code>Map<...></code> and <code>arrays</code> of such types. Below are some usage examples, to get a better understanding where to start reviewing:</p>
<pre><code>StringToTypeParser parser = StringToTypeParser.newBuilder().build();
Integer i = parser.parse("1", Integer.class);
Set<Integer> setOfIntegers = parser.parse("1,2,3,4", new GenericType<Set<Integer>>(){});
float[] arrayOfFloats = parser.parse("1.3, .4, 3.56", float[].class);
</code></pre>
<p>This review is a follow up to the following <a href="https://codereview.stackexchange.com/questions/38145/parse-strings-and-convert-the-value-to-java-types">review</a>.</p>
<p>The library is called type-parser and it's main purpose is to be used together with reflection. For example invoking a <code>java.lang.reflect.Method</code>, where argument <em>values</em> are read from an external source (xml file for example) and the argument <em>types</em> are read via reflection. type-parser can then parse the values to correct java types before invoking the <code>Method</code>. </p>
<ul>
<li>The code contains a generic way to create a List<..> of any of the supported java types (See: <code>TypeParsers#forLists()</code>), but the type <code>T</code> is never defined in code. Is this ok, or is there a better solution for this?</li>
<li>Is there a way to get rid of these <code>@SuppressWarnings("unchecked")</code> in <code>TypeParsers.java</code> ?</li>
<li>Is there a more user friendly way to represent a generic type than the <code>GenericType</code> class (from guava <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html" rel="nofollow noreferrer">TypeToken</a>).</li>
<li>Any other comments?</li>
</ul>
<p>.</p>
<pre><code>import static com.github.drapostolos.typeparser.TypeParserUtility.*;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
public final class StringToTypeParser {
private final Map<Type, TypeParser<?>> typeParsers;
final Splitter splitter;
final Splitter keyValuePairSplitter;
final InputPreprocessor inputPreprocessor;;
public static StringToTypeParserBuilder newBuilder() {
return new StringToTypeParserBuilder();
}
StringToTypeParser(StringToTypeParserBuilder builder) {
this.typeParsers = Collections.unmodifiableMap(new HashMap<Type, TypeParser<?>>(builder.typeParsers));
this.splitter = builder.splitter;
this.keyValuePairSplitter = builder.keyValuePairSplitter;
this.inputPreprocessor = builder.inputPreprocessor;
}
public <T> T parse(String input, Class<T> targetType) {
if (input == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("input"));
}
if (targetType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("targetType"));
}
@SuppressWarnings("unchecked")
T temp = (T) parseType2(input, targetType);
return temp;
}
public <T> T parse(String input, GenericType<T> genericType) {
if (input == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("input"));
}
if (genericType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("genericType"));
}
@SuppressWarnings("unchecked")
T temp = (T) parseType2(input, genericType.getType());
return temp;
}
public Object parseType(String input, Type targetType) {
if (input == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("input"));
}
if (targetType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("targetType"));
}
return parseType2(input, targetType);
}
private Object parseType2(final String input, Type targetType) {
String preprocessedInput = preProcessInputString(input, targetType);
if(preprocessedInput == null){
if (isPrimitive(targetType)) {
String message = "'%s' primitive can not be set to null. Input: \"%s\"; Preprocessed input: '%s'";
throw new IllegalArgumentException(String.format(message, targetType, input, preprocessedInput));
}
return null;
}
if(typeParsers.containsKey(targetType)){
return invokeTypeParser(preprocessedInput, targetType, targetType);
}
if(targetType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) targetType;
Class<?> rawType = (Class<?>) type.getRawType();
if(List.class.isAssignableFrom(rawType)){
return invokeTypeParser(preprocessedInput, TypeParsers.ANY_LIST, targetType);
}
if(Set.class.isAssignableFrom(rawType)){
return invokeTypeParser(preprocessedInput, TypeParsers.ANY_SET, targetType);
}
if(Map.class.isAssignableFrom(rawType)){
return invokeTypeParser(preprocessedInput, TypeParsers.ANY_MAP, targetType);
}
}
if(targetType instanceof Class){
Class<?> cls = (Class<?>) targetType;
if(cls.isArray()){
return invokeTypeParser(preprocessedInput, TypeParsers.ANY_ARRAY, targetType);
}
if(containsStaticMethodNamedValueOf(cls)){
return invokeTypeParser(preprocessedInput, TypeParsers.ANY_CLASS_WITH_STATIC_VALUEOF_METHOD, targetType);
}
}
if(targetType instanceof GenericArrayType){
return invokeTypeParser(preprocessedInput, TypeParsers.ANY_ARRAY, targetType);
}
String message = "There is either no registered 'TypeParser' for that type, or that "
+ "type does not contain the following static factory method: '%s.%s(String)'.";
message = String.format(message, targetType, STATIC_FACTORY_METHOD_NAME);
message = makeParseErrorMsg(preprocessedInput, message, targetType);
throw new IllegalArgumentException(message);
}
private String preProcessInputString(String input, Type targetType) {
try {
return inputPreprocessor.prepare(input, new InputPreprocessorHelper(targetType));
} catch (Exception e) {
String message = "Exception thrown from InputPreprocessor: %s [%s] with message: "
+ "%s. See underlying exception for more information.";
message = String.format(message,
inputPreprocessor, inputPreprocessor.getClass(), e.getMessage());
message = makeParseErrorMsg(input, message, targetType);
throw new IllegalArgumentException(message, e);
}
}
private Object invokeTypeParser(String input, Type key, Type targetType) {
try {
TypeParser<?> typeParser = typeParsers.get(key);
ParseHelper parseHelper = new ParseHelper(this, targetType);
return typeParser.parse(input, parseHelper);
} catch (NumberFormatException e) {
String message = String.format("Number format exception %s.", e.getMessage());
message = makeParseErrorMsg(input, message, targetType);
throw new IllegalArgumentException(message, e);
} catch (RuntimeException e) {
String message = makeParseErrorMsg(input, e.getMessage(),targetType);
throw new IllegalArgumentException(message, e);
}
}
private boolean isPrimitive(Type targetType) {
if(targetType instanceof Class){
Class<?> c = (Class<?>) targetType;
return c.isPrimitive();
}
return false;
}
}
</code></pre>
<p>.</p>
<pre><code>import static com.github.drapostolos.typeparser.TypeParserUtility.*;
import java.lang.reflect.Type;
import java.util.*;
public final class StringToTypeParserBuilder {
Map<Type, TypeParser<?>> typeParsers;
Splitter splitter = defaultSplitter();
Splitter keyValuePairSplitter = defaultKeyValuePairSplitter();
InputPreprocessor inputPreprocessor = defaultInputPreprocessor();
StringToTypeParserBuilder() {
typeParsers = TypeParsers.copyDefault();
}
public StringToTypeParserBuilder unregisterTypeParser(Class<?> targetType){
if(targetType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("targetType"));
}
typeParsers.remove(targetType);
return this;
}
public <T> StringToTypeParserBuilder unregisterTypeParser(GenericType<T> targetType){
if(targetType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("targetType"));
}
typeParsers.remove(targetType.getType());
return this;
}
public <T> StringToTypeParserBuilder registerTypeParser(Class<? super T> targetType, TypeParser<T> typeParser){
if(typeParser == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("typeParser"));
}
if(targetType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("targetType"));
}
typeParsers.put(targetType, typeParser);
return this;
}
public <T> StringToTypeParserBuilder registerTypeParser(GenericType<T> targetType, TypeParser<T> typeParser){
if(typeParser == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("typeParser"));
}
if(targetType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("targetType"));
}
typeParsers.put(targetType.getType(), typeParser);
return this;
}
public StringToTypeParserBuilder setSplitter(Splitter splitter){
if(splitter == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("splitter"));
}
this.splitter = splitter;
return this;
}
public StringToTypeParserBuilder setKeyValuePairSplitter(Splitter splitter){
if(splitter == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("splitter"));
}
this.keyValuePairSplitter = splitter;
return this;
}
public StringToTypeParserBuilder setInputPreprocessor(InputPreprocessor inputPreprocessor) {
if(inputPreprocessor == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("inputPreprocessor"));
}
this.inputPreprocessor = inputPreprocessor;
return this;
}
public StringToTypeParser build(){
return new StringToTypeParser(this);
}
}
</code></pre>
<p>.</p>
<pre><code>public interface TypeParser<T>{
T parse(String input, ParseHelper helper);
}
</code></pre>
<p>.</p>
<pre><code>import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
final class TypeParsers {
static final Type ANY_LIST = new GenericType<List<?>>() {}.getType();
static final Type ANY_SET = new GenericType<Set<?>>() {}.getType();
static final Type ANY_MAP = new GenericType<Map<?, ?>>() {}.getType();
static final Type ANY_CLASS_WITH_STATIC_VALUEOF_METHOD = ValueOfTypeParser.class;
static final Type ANY_ARRAY = Array.class;
static final Type CLASS_TYPE = new GenericType<Class<?>>(){}.getType();
private static final Type ARRAY_OF_CLASS = new GenericType<Class<?>[]>(){}.getType();
private static final String BOOLEAN_ERROR_MESSAGE = "\"%s\" is not parsable to a Boolean.";
private static final String CLASS_ERROR_MESSAGE = "\"%s\" is not parsable to a Class object.";
private static final String CHARACTER_ERROR_MESSAGE = "\"%s\" must only contain a single character.";
private static final Map<Type, TypeParser<?>> DEFAULT_TYPE_PARSERS = new HashMap<Type, TypeParser<?>>();
private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE = new HashMap<Class<?>, Class<?>>();
private TypeParsers() { throw new AssertionError("Not meant for instantiation"); }
static Map<Type, TypeParser<?>> copyDefault() {
return new HashMap<Type, TypeParser<?>>(DEFAULT_TYPE_PARSERS);
}
static{
WRAPPER_TO_PRIMITIVE.put(Boolean.class, boolean.class);
WRAPPER_TO_PRIMITIVE.put(Byte.class, byte.class);
WRAPPER_TO_PRIMITIVE.put(Short.class, short.class);
WRAPPER_TO_PRIMITIVE.put(Character.class, char.class);
WRAPPER_TO_PRIMITIVE.put(Integer.class, int.class);
WRAPPER_TO_PRIMITIVE.put(Long.class, long.class);
WRAPPER_TO_PRIMITIVE.put(Float.class, float.class);
WRAPPER_TO_PRIMITIVE.put(Double.class, double.class);
}
static{
registerTypeParser(ANY_LIST, TypeParsers.forLists());
registerTypeParser(ANY_SET, TypeParsers.forSets());
registerTypeParser(ANY_MAP, TypeParsers.forMaps());
registerTypeParser(ANY_ARRAY, TypeParsers.forArrays());
registerTypeParser(ANY_CLASS_WITH_STATIC_VALUEOF_METHOD, new ValueOfTypeParser());
registerTypeParser(Boolean.class, new TypeParser<Boolean>(){
@Override
public Boolean parse(final String value0, ParseHelper helper) {
String value = value0.trim().toLowerCase();
if(value.equals("true")){
return Boolean.TRUE;
} else if(value.equals("false")){
return Boolean.FALSE;
}
throw new IllegalArgumentException(String.format(BOOLEAN_ERROR_MESSAGE, value0));
}
});
registerTypeParser(Character.class, new TypeParser<Character>() {
@Override
public Character parse(String value, ParseHelper helper) {
if(value.length() == 1){
return Character.valueOf(value.charAt(0));
}
throw new IllegalArgumentException(String.format(CHARACTER_ERROR_MESSAGE, value));
}
});
registerTypeParser(BigDecimal.class, new TypeParser<BigDecimal>() {
@Override
public BigDecimal parse(String value, ParseHelper helper) {
try {
return new BigDecimal(value.trim());
} catch (NumberFormatException e){
String message = String.format("For input string: \"%s\"", value.trim());
throw new NumberFormatException(message);
}
}
});
registerTypeParser(Byte.class, new TypeParser<Byte>() {
@Override
public Byte parse(String value, ParseHelper helper) {
return Byte.valueOf(value.trim());
}
});
registerTypeParser(Integer.class, new TypeParser<Integer>() {
@Override
public Integer parse(String value, ParseHelper helper) {
return Integer.valueOf(value.trim());
}
});
registerTypeParser(Long.class, new TypeParser<Long>() {
@Override
public Long parse(String value, ParseHelper helper) {
return Long.valueOf(value.trim());
}
});
registerTypeParser(Short.class, new TypeParser<Short>() {
@Override
public Short parse(String value, ParseHelper helper) {
return Short.valueOf(value.trim());
}
});
registerTypeParser(Float.class, new TypeParser<Float>() {
@Override
public Float parse(String value, ParseHelper helper) {
return Float.valueOf(value);
}
});
registerTypeParser(Double.class, new TypeParser<Double>() {
@Override
public Double parse(String value, ParseHelper helper) {
return Double.valueOf(value);
}
});
registerTypeParser(File.class, new TypeParser<File>() {
@Override
public File parse(String value, ParseHelper helper) {
return new File(value.trim());
}
});
registerTypeParser(String.class, new TypeParser<String>() {
@Override
public String parse(String value, ParseHelper helper) {
return value;
}
});
registerTypeParser(Class.class, new TypeParser<Class<?>>() {
@Override
public Class<?> parse(String input, ParseHelper helper) {
try {
return Class.forName(input.trim());
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(String.format(CLASS_ERROR_MESSAGE, input));
}
}
});
registerTypeParser(ARRAY_OF_CLASS, new TypeParser<Class<?>[]>() {
@Override
public Class<?>[] parse(String input, ParseHelper helper) {
List<String> strList = helper.split(input);
Class<?>[] array = new Class<?>[strList.size()];
for(int i = 0; i < strList.size(); i++){
Class<?> element = helper.parse(strList.get(i), Class.class);
array[i] = element;
}
return array;
}
});
}
private static void registerTypeParser(Type type, TypeParser<?> typeParser) {
DEFAULT_TYPE_PARSERS.put(type, typeParser);
if(WRAPPER_TO_PRIMITIVE.containsKey(type)){
Class<?> primitiveType = WRAPPER_TO_PRIMITIVE.get(type);
DEFAULT_TYPE_PARSERS.put(primitiveType, typeParser);
}
if(type.equals(Class.class)){
DEFAULT_TYPE_PARSERS.put(CLASS_TYPE, typeParser);
}
}
private static <T> TypeParser<T> forArrays(){
return new TypeParser<T>() {
@Override
public T parse(String input, ParseHelper helper) {
List<String> strList = helper.split(input);
Class<?> componentType = helper.getComponentClass();
Object array = Array.newInstance(componentType, strList.size());
for(int i = 0; i < strList.size(); i++){
Object element = helper.parse(strList.get(i), componentType);
Array.set(array, i, element);
}
@SuppressWarnings("unchecked")
T temp = (T) array;
return temp;
}
};
}
private static <T> TypeParser<List<T>> forLists() {
return new TypeParser<List<T>>() {
public List<T> parse(String input, ParseHelper helper) {
Class<T> targetType = getParameterizedTypeArgument(helper);
List<T> list = new ArrayList<T>();
for(String value : helper.split(input)){
list.add(helper.parse(value, targetType));
}
return list;
}
};
}
private static <T> TypeParser<Set<T>> forSets() {
return new TypeParser<Set<T>>() {
public Set<T> parse(String input, ParseHelper helper) {
Class<T> targetType = getParameterizedTypeArgument(helper);
Set<T> set = new LinkedHashSet<T>();
for(String value : helper.split(input)){
set.add(helper.parse(value, targetType));
}
return set;
}
};
}
private static <K,V> TypeParser<Map<K, V>> forMaps() {
return new TypeParser<Map<K, V>>() {
private static final int KEY = 0;
private static final int VALUE = 1;
public Map<K, V> parse(String input, ParseHelper helper) {
Class<K> keyType = getParameterizedTypeArgument(helper, KEY);
Class<V> valueType = getParameterizedTypeArgument(helper, VALUE);
Map<K, V> map = new HashMap<K, V>();
for(String entryString : helper.split(input)){
List<String> entry = helper.splitKeyValuePair(entryString);
map.put(helper.parse(entry.get(KEY), keyType), helper.parse(entry.get(VALUE), valueType));
}
return map;
}
};
}
private static <T> Class<T> getParameterizedTypeArgument(ParseHelper helper) {
return getParameterizedTypeArgument(helper, 0);
}
private static <T> Class<T> getParameterizedTypeArgument(ParseHelper helper, int index) {
Class<?> type = helper.getParameterizedTypeArguments().get(index);
@SuppressWarnings("unchecked")
Class<T> temp = (Class<T>) type;
return temp;
}
}
</code></pre>
<p>.</p>
<pre><code>import static com.github.drapostolos.typeparser.TypeParserUtility.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
final class ValueOfTypeParser implements TypeParser<Object>{
private static final Object STATIC_METHOD = null;
public Object parse(String input, ParseHelper helper) {
Class<?> targetType = (Class<?>) helper.getTargetType();
Method method = getMethodNamedValueOf(targetType);
try {
if(targetType.isEnum()){
input = input.trim();
}
method.setAccessible(true);
return method.invoke(STATIC_METHOD, input);
} catch (InvocationTargetException e) {
// filter out the InvocationTargetException stacktrace/message.
throw new IllegalArgumentException(makeErrorMsg(input, targetType), e.getCause());
} catch (Throwable t) {
throw new IllegalArgumentException(makeErrorMsg(input, targetType), t);
}
}
private String makeErrorMsg(String input, Class<?> targetType) {
String methodSignature = String.format("%s.%s('%s')", targetType.getName(), STATIC_FACTORY_METHOD_NAME, input);
String message = " Exception thrown in static factory method '%s'. "
+ "See underlying exception for additional information.";
message = String.format(message, methodSignature);
return makeParseErrorMsg(input, message, targetType);
}
}
</code></pre>
<p>.</p>
<pre><code>import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
final class TypeParserUtility {
static final String STATIC_FACTORY_METHOD_NAME = "valueOf";
private static final Splitter DEFAULT_SPLITTER = new DefaultSplitter();
private static final Splitter DEFAULT_KEY_VALUE_PAIR_SPLITTER = new KeyValuePairSplitter();
private static final InputPreprocessor DEFAULT_INPUT_PREPROCESSOR = new NullInputPreprocessor();
private TypeParserUtility() { throw new AssertionError("Not meant for instantiation"); }
static InputPreprocessor defaultInputPreprocessor(){
return DEFAULT_INPUT_PREPROCESSOR;
}
static Splitter defaultSplitter(){
return DEFAULT_SPLITTER;
}
static Splitter defaultKeyValuePairSplitter(){
return DEFAULT_KEY_VALUE_PAIR_SPLITTER;
}
static String makeNullArgumentErrorMsg(String argName) {
return String.format("Argument named '%s' is illegally set to null!", argName);
}
static String makeParseErrorMsg(String input, String message, Type targetType) {
return String.format("Can not parse \"%s\" to type \"%s\" [instance of: %s] due to: %s",
input, targetType, targetType.getClass().getName(), message);
}
static boolean containsStaticMethodNamedValueOf(Class<?> type){
Method method = getMethodNamedValueOf(type);
if(method == null){
return false;
}
if (!Modifier.isStatic(method.getModifiers())) {
return false;
}
return true;
}
static Method getMethodNamedValueOf(Class<?> targetType){
try {
return targetType.getDeclaredMethod(STATIC_FACTORY_METHOD_NAME, String.class);
} catch (Exception e) {
return null;
}
}
}
</code></pre>
<p>.</p>
<pre><code>public interface Splitter {
List<String> split(String input, SplitHelper helper);
}
</code></pre>
<p>.</p>
<pre><code>final class DefaultSplitter implements Splitter{
@Override
public List<String> split(String input, SplitHelper helper) {
if(input.trim().isEmpty()){
return new ArrayList<String>();
}
return Arrays.asList(input.split(","));
}
}
</code></pre>
<p>.</p>
<pre><code>final class KeyValuePairSplitter implements Splitter{
@Override
public List<String> split(String input, SplitHelper helper) {
return Arrays.asList(input.split("="));
}
}
</code></pre>
<p>.</p>
<pre><code>import java.lang.reflect.Type;
import java.util.List;
public final class SplitHelper {
private static final SplitHelper IGNORED = null;
private final Type targetType;
SplitHelper(Type targetType) {
this.targetType = targetType;
}
public List<String> splitWithDefaultSplitter(String input){
return TypeParserUtility.defaultSplitter().split(input, IGNORED);
}
public Type getTargetType() {
return targetType;
}
}
</code></pre>
<p>.</p>
<pre><code>import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public abstract class GenericType<T> {
private final Type type;
public GenericType() {
if(GenericType.class != getClass().getSuperclass()){
String errorMsg = "'%s' must be a direct subclass of '%s'";
errorMsg = String.format(errorMsg, getClass().getName(), GenericType.class.getName());
throw new IllegalArgumentException(errorMsg);
}
Type t = getClass().getGenericSuperclass();
if(t instanceof ParameterizedType){
ParameterizedType superClass = (ParameterizedType) t;
type = superClass.getActualTypeArguments()[0];
} else {
String message = "'%s' must be parameterized (for example \"new GenericType<List<Integer>>(){}\"), "
+ "it can not be of raw type \"new GenericType(){}\".";
throw new IllegalStateException(String.format(message, getClass().getName()));
}
}
final Type getType(){
return type;
}
@Override
final public String toString() {
return type.toString();
}
}
</code></pre>
<p>.</p>
<pre><code>public interface InputPreprocessor {
String prepare(String input, InputPreprocessorHelper helper);
}
</code></pre>
<p>.</p>
<pre><code>import java.lang.reflect.Type;
public final class InputPreprocessorHelper {
private final Type targetType;
InputPreprocessorHelper(Type targetType) {
this.targetType = targetType;
}
public Type getTargetType(){
return targetType;
}
public String prepareWithDefaultInputPreprocessor(String input) {
return TypeParserUtility.defaultInputPreprocessor().prepare(input, this);
}
}
</code></pre>
<p>.</p>
<pre><code>final class NullInputPreprocessor implements InputPreprocessor{
@Override
public String prepare(String input, InputPreprocessorHelper helper) {
if (input.trim().equalsIgnoreCase("null")) {
return null;
}
return input;
}
}
</code></pre>
<p>Javadoc has been removed for brevity. The full code (w/ javadoc/unit tests) can be found here: <a href="https://github.com/drapostolos/type-parser" rel="nofollow noreferrer">https://github.com/drapostolos/type-parser</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:33:16.357",
"Id": "76002",
"Score": "0",
"body": "There is a fair amount to go through here... it is on my radar.... but will probably be a day before I get to it."
}
] | [
{
"body": "<p>There is a lot of detail in your code, and there is no way to just scan it, and look for problems/patterns, etc.</p>\n<p>Still, here are some observations for the moment, and, depending on time availablility, I may come back with some additional comments (maybe posted as a different answer, we will see).</p>\n<h2>General:</h2>\n<p>As a general note, you are reinventing some (really big) wheels here... there are a number of formats/transformations available to communicate/save Java objects: XML (multiple systems), SQL(multiple systems), JSON(multiple systems), plain text(Multiple systems), Beans, Serialization, Externalizable, Parcels, etc. Many of these mechanisms have Annotation-style markup to make the process easier (hibernate, etc.). There are a lot of lessons you can learn from other implementations, and one of those lessons may just be: <em>"Oh, this works for me, I don't need to build my own..."</em></p>\n<p>I am somewhat surprised that you feel there is a need for another mechanism....</p>\n<h2>Conventions:</h2>\n<ul>\n<li><p><code>StringToTypeParser.newBuilder()</code> is the entry point to your library.... but, why does it return <code>StringToTypeParserBuilder</code> and not <code>StringToTypeParser</code> ? Your <code>newBuilder()</code> method is on the wrong class... it should be on <code>StringToTypeParserBuilder.newBuilder()</code>. This makes the builder your 'core' class.</p>\n<p>I am not sure if that is what you want, but, as it stands at the moment, it is inconsistent with standards.</p>\n</li>\n<li><p>The <code>public interface TypeParser</code> class does not need to be public. I believe all the implementations of it are package-private, and this interface can be as well.</p>\n</li>\n<li><p>When de-serializing a Set, you use a LinkedHashSet for the actual implementation. I can understand why you may want to preserve the set 'order'. But, on the Map side, you use a regular HashMap.... why not a LinkedHashMap?</p>\n</li>\n</ul>\n<h2>Potential bugs.</h2>\n<ul>\n<li><p>Your DefaultSplitter does not do any form of <code>,</code> (comma) escaping on the split. If an input String has a comma in the value, the split will fail.</p>\n</li>\n<li><p>The KeyValue splitter should use a split-limit of 2 so that the value can contain an <code>=</code> (equals) character: <code>return Arrays.asList(input.split("=", 2));</code></p>\n</li>\n<li><p>In your <code>getMethodNamedValueOf()</code> method you use the Java reflection method <code>return targetType.getDeclaredMethod(STATIC_FACTORY_METHOD_NAME, String.class);</code>. This will nly work if the actual class declares the <code>valueOf()</code> method. If the class has an inheritance chain, and an ancestor in the chain actually declares the method, then this call will return <code>null</code>, even though the class <em>has</em> the method.</p>\n<p>It is a tricky thing to get reflection right.... you probably want to be using <code>getMethod(...)</code>, because that will walk the inheritance for you, but, unfortunately, the methods all need to be public for that.... ;-)</p>\n</li>\n</ul>\n<h2>Generics <code>unchecked</code> warnings</h2>\n<p>As far as I can tell, the generics are mostly OK. You can reduce the number of unchecked annotations you have by declaring it for the whole class ;-) But, you only have two, and, for a reflective system, that is not too bad.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:44:31.980",
"Id": "76357",
"Score": "0",
"body": "Thanks for your comments! I know there are other libraries that do similar things, but they also do A LOT of other things too, where the parsing mechanism is just a small fraction of the offered features. I'm trying to avoid adding a 500K size dependencies, just for parsing/converting a string to a java type. I usually end up with writing a long if/switch statement (+ more code if generic types are to be parsed too). I want to avoid copy/paste code between libraries by making a lightweight library doing only the parsing stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:59:06.100",
"Id": "76360",
"Score": "0",
"body": "I don't think the \"newBuilder()\" method goes against any standard. It is very similar to how \"Effective Java, 2nd edition\" describes the builder pattern: \"new StringToTypeParser.Builder()\", but with the Builder class separated from the Built class (and no use of public constructors).\n\nThe TypeParser interface needs to be public, as the user can register his/her own TypeParser implementations. Example:\n\n`StringToTypeParser parser = StringToTypeParser.newBuilder().registerTypeParser(MyClass.class, new MyTypeParser()).setSplitter(new MySplitter()).setInputPreprocessor(...).build();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:01:24.447",
"Id": "76361",
"Score": "0",
"body": "@drapostolos - OK with the public TypeParser interface then. About the `newBuilder()`. I am not worried about the concept of the method, but I am concerned as to why it is on the class `StringToTypeParser` instead of `StringToTypeParserBuilder`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:04:20.453",
"Id": "76363",
"Score": "0",
"body": "Will change to LinkedHashSet, and add a limit to 2 in the KeyValue splitter. I missed that :) Will also look into the geetDeclaredMethod vs. getMethod, I was not aware of the differences! You're also right about the \"no escaping\" of \",\", will look into that as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:12:14.040",
"Id": "76364",
"Score": "0",
"body": "Regarding the `newBuilder()`. One more reason to place it in the `StringToTypeParser` class is that the user only needs to care about one class, due to the chaining possibility. Only one entry class :) `StringToTypeParserBuilder.newBuilder()` would imply to return a class to build the Builder class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:19:08.763",
"Id": "76365",
"Score": "0",
"body": "Should also mention that this library is not meant for parsing advanced strings. More likely simple strings from command line, or values in a property file etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:23:32.297",
"Id": "76366",
"Score": "0",
"body": "About the getDeclaredMethod... consider this [code I put on ideone](http://ideone.com/uMbSWI)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T02:44:27.030",
"Id": "76400",
"Score": "0",
"body": "@drapostolos I'm with rolfl on `newBuilder`'s location, but I'd probably call it `create` since it obviously creates a builder at that point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:41:43.667",
"Id": "85441",
"Score": "0",
"body": "First version of the type-parser library is now available in maven central and github here: https://github.com/drapostolos/type-parser"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T02:23:14.190",
"Id": "44020",
"ParentId": "43823",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44020",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T23:21:47.787",
"Id": "43823",
"Score": "4",
"Tags": [
"java",
"parsing",
"generics",
"library"
],
"Title": "Library for parsing strings to java types, generic types and collections/arrays"
} | 43823 |
<p>I'm a F# newbie, and would like to share my implementation of the <a href="http://codingdojo.org/cgi-bin/index.pl?KataPokerHands">Poker Hands Kata problem</a> to get some feedback.</p>
<pre><code>module PokerHands
open System.Text.RegularExpressions
type Figure =
| Two | Three | Four | Five
| Six | Seven | Eight | Nine
| Ten | Jack | Queen | King | Ace
type Suit = Diamonds | Spades | Hearts | Clubs
type Card = Figure * Suit
type Rank =
| HighCard of Figure * Rank option
| Pair of Figure * Rank
| TwoPair of Figure * Figure * Rank
| ThreeOfKind of Figure
| Straight of Figure
| Flush of Rank
| FullHouse of Figure
| FourOfKind of Figure
| StraightFlush of Rank
type Player = {
Name: string;
Cards: Card list;
Hand: Rank;
}
let SortDesc sequence = sequence |> Seq.toList |> List.sortWith (fun x y -> compare y x)
let SortDescBy f sequence = sequence |> List.sortWith (fun x y -> compare (f y) (f x))
let rec BuildHighCard (figures : Figure list) =
match SortDesc figures with
| [h] -> HighCard(h, None)
| h :: t -> HighCard(h, Some(BuildHighCard(t)))
| _ -> failwith "empty"
let isFlush (cards : Card list) =
cards |> Seq.distinctBy snd |> Seq.length = 1
let isStraight (cards : Card list) =
let figs = cards |> List.map fst |> List.sort
let flag = ref true
for i in {1 .. List.length figs - 1} do
if (compare figs.[i-1] figs.[i]) <> -1 then flag.Value <- false
flag.Value
let (|IsStraightFlush|_|) cards =
if isFlush cards && isStraight cards then Some(StraightFlush(BuildHighCard(cards |> List.map fst))) else None
let (|IsFlush|_|) cards =
if isFlush cards then Some(Flush(BuildHighCard(cards |> List.map fst))) else None
let (|IsStraight|_|) cards =
if isStraight cards then Some(Straight(cards |> List.minBy fst |> fst)) else None
let (|IsGrouped|_|) (counts : int list) cards =
let groups = cards |> Seq.countBy fst |> Seq.toList |> SortDescBy snd
if groups |> List.map snd = counts then Some(groups |> List.map fst) else None
let DetermineRank (cards : Card list) =
match cards with
| IsStraightFlush straightFlush -> straightFlush
| IsGrouped [4;1] [f;_] -> FourOfKind(f)
| IsGrouped [3;2] [f;_] -> FullHouse(f)
| IsFlush flush -> flush
| IsStraight straight -> straight
| IsGrouped [3;1;1] [f;_;_] -> ThreeOfKind(f)
| IsGrouped [2;2;1] [f1;f2;rest]-> TwoPair(List.max [f1;f2], List.min [f1;f2], BuildHighCard([rest]))
| IsGrouped [2;1;1;1] (h :: t) -> Pair(h, BuildHighCard(t))
| _ -> BuildHighCard(cards |> List.map fst)
let ParsePlayers input =
let r = Regex("(\w+):( [2-9,T,J,Q,K,A][H,C,D,S]){5}")
let matches = input |> r.Matches
let parseCard (capture : Capture) =
let literal = capture.Value.Trim()
let figure =
match literal.[0] with
| '2' -> Two
| '3' -> Three
| '4' -> Four
| '5' -> Five
| '6' -> Six
| '7' -> Seven
| '8' -> Eight
| '9' -> Nine
| 'T' -> Ten
| 'J' -> Jack
| 'Q' -> Queen
| 'K' -> King
| 'A' -> Ace
| _ -> failwith "unrecognized figure"
let suit =
match literal.[1] with
| 'D' -> Diamonds
| 'S' -> Spades
| 'H' -> Hearts
| 'C' -> Clubs
| _ -> failwith "unrecognized suit"
(figure, suit)
let parsePlayer (input : Match) =
let name = input.Groups.[1].Value
let cards =
input.Groups.[2].Captures
|> Seq.cast
|> Seq.map parseCard
|> Seq.toList
{Name = name; Cards = cards; Hand = DetermineRank cards}
matches
|> Seq.cast
|> Seq.map parsePlayer
|> Seq.toArray
type Score =
| Win of string * string
| Tie
let rec Rationale wonHand lostHand =
let (|RanksEq|_|) (wonHand,lostHand) =
match wonHand, lostHand with
| StraightFlush(w), StraightFlush(l) -> Some (Rationale w l)
| Flush(w), Flush(l) -> Some (Rationale w l)
| TwoPair(w1,w2,r1), TwoPair(l1,l2,r2) when w1 = l1 && w2 = l2 -> Some (Rationale r1 r2)
| Pair(f1,r1), Pair(f2,r2) when f1 = f2 -> Some (Rationale r1 r2)
| HighCard(w,r1), HighCard(l,r2) when w = l -> Some (Rationale (Option.get r1) (Option.get r2))
| _ -> None
match wonHand, lostHand with
| RanksEq(res) -> res
| StraightFlush(_), _ -> "straight flush"
| FourOfKind(f), _ -> sprintf "four of kind: %A" f
| FullHouse(f), _ -> "full house"
| Flush(_), _ -> "flush"
| Straight(f), _ -> "straight"
| ThreeOfKind(f), _ -> sprintf "three of kind: %A" f
| TwoPair(f1,f2,_), _ -> sprintf "two pairs: %A + %A" f1 f2
| Pair(f,_), _ -> sprintf "pair of: %A" f
| HighCard(w,_), _ -> sprintf "high card: %A" w
| _ -> failwith "unhandled rationale"
let DetermineScore (players : Player array) =
let c = compare (players.[0].Hand) (players.[1].Hand)
if c = 0
then Tie
else
let winner = players |> Array.maxBy (fun p -> p.Hand)
let looser = players |> Array.minBy (fun p -> p.Hand)
Win(winner.Name, Rationale winner.Hand looser.Hand)
let FormatScore score =
match score with
| Win(winner, rationale) -> sprintf "%s wins - %s" winner rationale
| Tie -> "Tie"
let CompareHands input =
input
|> ParsePlayers
|> DetermineScore
|> FormatScore
</code></pre>
<p>At the first glance, what could look strange is the <code>Rank</code> discriminated union. I decided to implement it this way so that I have the comparing of <code>Rank</code>s out of the box.</p>
<p>Another thing that should require explanation is the Rationale function: It resolves a string rationale for the winning rank, and the inner <code>RanksEq</code> active pattern solves cases such as where both ranks are Pairs - here the rationale should return "high card".</p>
<p>Here's a list of my concerns:</p>
<ol>
<li><code>isStraight</code> function - how to achieve a pure functional-looking function that would check if all elements in sequence are consecutive (in regards to a discriminated union type)?</li>
<li><code>IsStraight</code>, <code>IsFlush</code>, <code>IsStraightFlush</code> active patterns, these three feel like they have something in common - could they be somehow merged into one active pattern?</li>
<li><code>DetermineScore</code> function - I don't like usage of <code>Array.min</code> and max for getting a lower and higher value from a pair of values - is there a one-liner for this? i.e something returning a tuple <code>Player</code> * <code>Player</code>?</li>
</ol>
<p>Any other comments about the code will be more than welcome.</p>
| [] | [
{
"body": "<p>I like this! Your use of discriminated unions and active patterns is quite elegant, I think. (Although exploiting that <code>compare</code> on discriminated unions does what it does seems a bit of a hack–although I have a hard time justifying that sentiment.)</p>\n\n<p>As to your concerns:</p>\n\n<ol>\n<li><p>Here is a manual way to do it functionally (replace the <code>let flag ... flag.Value</code> with this):</p>\n\n<pre><code>let rec check = function \n | x :: y :: zs -> compare x y <> -1 && check (y :: zs) \n | [x] -> true\n | _ -> false\ncheck figs\n</code></pre>\n\n<p>For more on this style, see <a href=\"http://en.wikibooks.org/wiki/F_Sharp_Programming/Pattern_Matching_Basics\" rel=\"nofollow\">here</a>. Alternatively, you could try to use combinators. If you're willing to compare only sequences of five cards, then maybe like this?</p>\n\n<pre><code>List.toSeq cards |> Seq.distinct |> Seq.toList \n |> function\n | [x;_;_;_;y] -> compare x y = -4\n | _ -> false\n</code></pre></li>\n<li><p>I think these are fine. I don't think you should try to factor out the redundant looking <code>BuildHighCard(cards |> List.map fst)</code>. I think if you did, you'd clutter your program rather than make it more readable. As it is, it's perfectly clear what's going on, yes?</p></li>\n<li><p>Yes:</p>\n\n<pre><code>let winner, loser = Array.max players, Array.min players\n</code></pre></li>\n</ol>\n\n<p>But maybe already <code>ParsePlayers</code> return a tuple instead of an array?</p>\n\n<p>Minor suggestion: You could implement <code>SortDesc</code> and <code>SortDescBy</code> as:</p>\n\n<pre><code>let SortDescBy f = List.sortWith (fun x y -> compare (f y) (f x)) \n</code></pre>\n\n<p>In general, when you write <code>x |> f</code> it means just <code>f x</code>. So when you define</p>\n\n<pre><code>let f x = x |> g ...\n</code></pre>\n\n<p>you can cut out the middle man and just do</p>\n\n<pre><code>let f = g ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:21:05.340",
"Id": "77668",
"Score": "1",
"body": "I think that your recursive `check` is wrong. It compares first with second and third with fourth, but not second with third. To fix it, you could change the recursive call to `check (y :: zs)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:50:11.160",
"Id": "77681",
"Score": "0",
"body": "Quite! I updated the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T22:32:08.707",
"Id": "44411",
"ParentId": "43831",
"Score": "6"
}
},
{
"body": "<p>The way I would implement <code>isStraight</code> in a functional way would be to take all pairs of i-th and (i+1)-th cards using <a href=\"http://msdn.microsoft.com/en-us/library/ee370261.aspx\" rel=\"nofollow\"><code>Seq.zip</code></a> and then ensure that all pairs satisfy the condition using <a href=\"http://msdn.microsoft.com/en-us/library/ee370522.aspx\" rel=\"nofollow\"><code>Seq.forall</code></a>:</p>\n\n<pre><code>let isStraight (cards : Card list) =\n let figs = cards |> Seq.map fst |> Seq.sort\n let pairs = Seq.zip figs (Seq.skip 1 figs)\n Seq.forall (fun pair -> compare (fst pair) (snd pair) = -1) pairs\n</code></pre>\n\n<p>(I use <code>Seq</code> instead of <code>List</code>, because <code>List.zip</code> behaves slightly differently and because there is no <code>List.skip</code>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T21:07:03.583",
"Id": "77683",
"Score": "0",
"body": "I like zipping the sequences. You can write the third line with combinators: `Seq.forall ((<||) compare >> (=) -1) pairs`. In this case, yours is nicer, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T20:39:22.247",
"Id": "44702",
"ParentId": "43831",
"Score": "4"
}
},
{
"body": "<p>Turns out, there is a <code>Seq.pairwise</code> function which in this case will work as <code>Seq.zip figs (Seq.skip 1 figs)</code> does. </p>\n\n<p>So follwing @svick and @soren-debois suggestions and using <code>Seq.pairwise</code> we can write the <code>isStraight</code> function like this:</p>\n\n<pre><code>let isStraight (cards : Card list) =\n cards\n |> Seq.map fst\n |> Seq.sort\n |> Seq.pairwise\n |> Seq.forall ((<||) compare >> (=) -1)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T08:05:05.820",
"Id": "44944",
"ParentId": "43831",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:42:54.550",
"Id": "43831",
"Score": "13",
"Tags": [
"beginner",
"game",
"f#",
"playing-cards"
],
"Title": "Poker Hands Kata in F#"
} | 43831 |
<p>I really do not have access to anyone, outside of professors, that is highly knowledgeable about Java so I figured I would post my stuff here to further my knowledge and improve my coding. This is homework for my Operating Systems class and it works. Here are some of my main concerns. </p>
<ol>
<li>Is this a good use of the static inner class? </li>
<li>Are my variable and class declarations properly declared?</li>
<li>Is there a better way than using Thread.sleep to make the sure that the main thread waits for certain child threads to complete before it performs some action?</li>
</ol>
<p>The object of the program is to find the max in an array using 3 steps. Each step is to perform one part of the task with its own thread. For example, step one uses n threads to initialize an array of size n with 1's. Input done via command line: Prog1.java n x0 x1 ... xn, where n is the number of elements and x0 x1 ... xn are the elements. Input is limited to about 20 elements.</p>
<p>As I am a student, I will also glady accept any critiques on any part of the code. Sorry if this seems like too much for one question and thanks in advance to anyone who contributes.</p>
<pre><code>/* User Input: 4 3 1 7 5
Number of input values = 4
Input values x = 3 1 7 5
After initialization w = 1 1 1 1
Thread T(0,1) compares x[0] = 3 and x[1] = 1, and writes 0 into w[1]
Thread T(2,3) compares x[2] = 7 and x[3] = 5, and writes 0 into w[3]
Thread T(1,3) compares x[1] = 1 and x[3] = 5, and writes 0 into w[1]
Thread T(1,2) compares x[1] = 1 and x[2] = 7, and writes 0 into w[1]
Thread T(0,3) compares x[0] = 3 and x[3] = 5, and writes 0 into w[0]
Thread T(0,2) compares x[0] = 3 and x[2] = 7, and writes 0 into w[0]
After Step 2 w = 0 0 1 0
Maximum = 7
Location = 2
*/
import java.util.Arrays;
public class Prog1 {
private static int[] w;
private static int[] x;
public static void main(String[] args) throws InterruptedException {
if (args.length == 0) { /* return if there are NO arguments */
System.out.println("No arguments!");
return;
}
int size = Integer.parseInt(args[0]); /* Get the number of args */
x = new int[size]; /* Parse string array to integer */
for (int i = 0; i < size; i++) {
try {
x[i] = Integer.parseInt(args[i + 1]);
} catch (NumberFormatException nfe) {
System.out.println("Conversion Error: " + nfe.getMessage());
return;
}}
/* Initialize all w elements to 1 with a thread for each element */
w = new int[size];
for (int i = 0; i < size; i++) {
Initialize t = new Initialize(i);
t.start();
}
System.out.printf("%-25s%d\n","Number of input values = ", size);
String input = Arrays.toString(x).replace("[", "").
replace("]", "").replace(",", "");
System.out.printf("%-21s%s\n","Input values ", "x = " + input);
String init = Arrays.toString(w).replace("[", "").
replace("]", "").replace(",", "");
System.out.printf("%-21s%s\n","After initialization ", "w = " + init);
/* Perform Comparisons with a thread for each comparison */
int inc = 1;
for (int i = 0; i < size - 1; i++) {
for (int j = inc; j < size; j++) {
FindMax t = new FindMax(i,j);
t.start();
}
inc++;
}
Thread.sleep(100); /* After Step 2 Output */
String maxFound = Arrays.toString(w).replace("[", "").
replace("]", "").replace(",", "");
System.out.printf("%-21s%s\n","After Step 2 ","w = " + maxFound);
/* Print the maximum number and its location with a thread for each element*/
for (int i = 0; i < size; i++) {
PrintMax t = new PrintMax(i);
t.start();
}
} // End main()
private static class Initialize extends Thread {
private final int value = 1;
private final int index;
public Initialize(int i) {
this.index = i;
}
@Override
public void run() {
w[index] = this.value;
}}
private static class FindMax extends Thread {
private final int indI;
private final int indJ;
public FindMax(int indI, int indJ) {
this.indI = indI;
this.indJ = indJ;
}
@Override
public void run() {
int num1 = x[indI];
int num2 = x[indJ];
int lesser;
int compare = Integer.compare(num1, num2);
if (compare < 0) {
w[indI] = 0;
lesser = indI;
} else {
w[indJ] = 0;
lesser = indJ;
}
System.out.printf("Thread T(%d,%d) compares x[%1$d] = %d and x[%2$d] = %d, "
+ "and writes 0 into w[%d]\n", indI, indJ, num1, num2, lesser);
}
}
static class PrintMax extends Thread {
private final int index;
public PrintMax(int index) {
this.index = index;
}
@Override
public void run() {
if (w[index] == 1) {
int max = x[index];
System.out.printf("%-23s%s%d\n", "Maximum", "= ", max);
System.out.printf("%-23s%s%d\n", "Location", "= ", index);
}
}
}}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T04:17:17.440",
"Id": "75868",
"Score": "3",
"body": "Sorting 20 elements using multiple threads seems overkill. Doing it in a single thread should occupy the processor for microseconds. Starting the threads probably takes longer then just running across 20 elements in a single thread. Is there a particular reason you are using threads (personally I would not even look at threads until I was sifting through billions of values)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:26:17.360",
"Id": "75915",
"Score": "0",
"body": "The assignment explicitly requires that we use threads. We need n threads to initialize each element in the array to a 1, n(n-1)/2 threads to do each of the comparisons, and n threads to check whether an index has a 0 or 1 in it. I am learning java thread programming in my O/S Concepts class. I agree that it does not seem like the best way to do this."
}
] | [
{
"body": "<p>I agree with <em>@Loki Astari</em> that this is overkill but as a homework for a course is fine. Some notes about the current code:</p>\n\n<ol>\n<li><blockquote>\n <p>Is this a good use of the static inner class? </p>\n</blockquote>\n\n<p>It's OK but I prefer putting them to separate files. I've found that switching between windows/tabs is more handy than scrolling in the same file. You can do it if you pass the <code>w</code> and/or <code>x</code> arrays to their constructor.</p></li>\n<li><blockquote>\n <p>Is there a better way than using Thread.sleep to make the sure that the main thread waits for certain child threads to complete before it performs some action?</p>\n</blockquote>\n\n<p>Yes. On low level <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28%29\" rel=\"nofollow noreferrer\"><code>Thread.join</code></a> but I suggest you using higher level structures, like <code>Executor</code>s and <code>Future</code>s for that.</p>\n\n<p>I'd <a href=\"https://stackoverflow.com/a/541506/843804\"><code>implements Runnable</code> than <code>extends Thread</code></a> and change the following loop</p>\n\n<blockquote>\n<pre><code>for (int i = 0; i < size; i++) {\n Initialize t = new Initialize(i);\n t.start();\n}\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>// creates an executor with size threads\nExecutorService executorService = Executors.newFixedThreadPool(size);\nList<Future<?>> initalizerFutures = new ArrayList<>();\nw = new int[size];\nfor (int i = 0; i < size; i++) {\n // runs the Initializer with the executor on separate threads\n final Future<?> initalizerFuture = executorService.submit(new Initialize(i));\n initalizerFutures.add(initalizerFuture);\n}\n// waits for each initializer to complete\nfor (final Future<?> future: initalizerFutures) {\n future.get();\n}\n</code></pre>\n\n<p>(At the end of the program you should shutdown the executor.)</p></li>\n<li><p>Unfortunately, the code is still not thread safe. Although <a href=\"https://stackoverflow.com/q/6060682/843804\">accessing array elements on separate threads could be safe</a> but the code in the question accesses the same array index from separate threads which should be synchronized properly.</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>Source: <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em></p>\n\n<blockquote>\n <p>Locking is not just about mutual exclusion; it is also about memory visibility.\n To ensure that all threads see the most up-to-date values of shared mutable \n variables, the reading and writing threads must synchronize on a common lock.</p>\n</blockquote>\n\n<p>Source: <em>Java Concurrency in Practice, 3.1.3. Locking and Visibility</em>.</p></li>\n<li><blockquote>\n<pre><code>Arrays.toString(a).replace(\"[\", \"\").replace(\"]\", \"\").replace(\",\", \"\");\n</code></pre>\n</blockquote>\n\n<p>This is duplicated in the code. You should move this logic into a separate method and use that to keep it <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>. Additionally, I guess the format of <code>Arrays.toString</code> won't change but it would be cleaner iterating through the array and <a href=\"https://stackoverflow.com/q/1515437/843804\">building the string with a loop or using an already existing join implementation</a>.</p></li>\n<li><p>In <code>System.out.printf</code> use <code>%n</code> instead of <code>\\n</code>. The former outputs the correct platform-specific line separator.</p></li>\n<li><blockquote>\n<pre><code>System.out.printf(\"%-21s%s\\n\", \"Input values \", \"x = \" + input);\n</code></pre>\n</blockquote>\n\n<p>could be</p>\n\n<pre><code>System.out.printf(\"%-21s%s%s%n\", \"Input values \", \"x = \", input);\n</code></pre>\n\n<p>(without the concatenation).</p></li>\n<li><p>Short variable names are hard to read, like <code>x</code> and <code>w</code>. Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses.</p></li>\n<li><p>Comments like this are rather noise:</p>\n\n<blockquote>\n<pre><code>if (args.length == 0) { /* return if there are NO arguments */\n</code></pre>\n</blockquote>\n\n<p>It's rather obvious from the code itself, so I'd remove the comment. Your professors might require these comments but keep in mind that it's not clean. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><blockquote>\n<pre><code>System.out.println(\"No arguments!\");\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<li><p><a href=\"http://docs.oracle.com/javase/specs/\" rel=\"nofollow noreferrer\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a>:</p>\n\n<blockquote>\n <p>Class and Interface Type Names</p>\n \n <p>Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed\n case with the first letter of each word capitalized.</p>\n</blockquote>\n\n<p>According to that I'd rename <code>Initialize</code> to <code>Initializer</code>, <code>FindMax</code> to <code>MaximumFinder</code>, PrintMax to <code>MaximumPrinter</code>.</p></li>\n<li><p>Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs could highlight blocks.</p>\n\n<blockquote>\n<pre><code>} // End main()\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/q/53274/36726\">“// …” comments at end of code block after } - good or bad?</a></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:40:24.770",
"Id": "76356",
"Score": "0",
"body": "In a problem such as mine is it necessary to use the `List<Future<?>> initalizerFutures = new ArrayList<>();`? I am not sure if I fully understand the way it works, but is this not needed in my case because I do not really need to return any value? @TwoThe has a similar solution, but just used the `ExecutorService`. If it is not too much trouble and there is some reason for using `Future` in this context could you explain it? I have read through a few blogs and the Javadoc for the associated classes and it is all a bit murky to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T17:27:39.420",
"Id": "76523",
"Score": "1",
"body": "@brinks: The other option is `Thread.join` (or maybe other classes from the `java.util.concurrent` package) but it's easier to work with `Future`s and `Executor`s. You can parametrize the `Future` with `Void` (uppercase `V`) if you are not interested in the return value but `Future.get` is still needed to wait the completion of the submitted task."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T17:28:17.283",
"Id": "76524",
"Score": "1",
"body": "@brinks: Usage is easy: `submit` a `Runnable` instance to an `ExecutorService`. The `ExecutorService` runs the submitted `Runnable`'s `run` method on a separate thread. If `run` finishes the `Future.get` will return. If `run` is still working the `Future.get` will wait for its completion. `Executors.newFixedThreadPool(10)` creates an executor with 10 threads, so ten `Runnable` instances could run parallel but you can queue more."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T09:55:27.887",
"Id": "43846",
"ParentId": "43834",
"Score": "5"
}
},
{
"body": "<p>Since you asked for it, I try to comment on your code in \"extra-precise review mode\". ;)</p>\n\n<h1>General</h1>\n\n<p><strong>One does not use global variables</strong></p>\n\n<p>Unless they are static and final, in which case they are called \"constants\". There are just too many ways to fail when using those.</p>\n\n<p><strong>Code Structure</strong></p>\n\n<p>It is always a good idea to properly indent and structure your code using your IDE's build-in auto-formatting. It helps you on detecting basic coding mistakes and is in general a sign that the author has a certain level of quality.</p>\n\n<p>Use functions to structure your code. Writing all what you want to do in a single function (aka spaghetti-code) will work till the moment you need to change something. And in reality you always eventually change your code. The decision of whether or not to put parts of your code in a sub-function should follow the rules of <a href=\"http://en.wikipedia.org/wiki/Database_normalization\" rel=\"nofollow\">database normalization</a> as it is about the same concept: avoid deletion, insertion and update anomalies.</p>\n\n<p><strong>protected vs private</strong></p>\n\n<p>When deciding <code>private</code> vs <code>protected</code> you should always use <code>protected</code> unless there is a specific reason not to. <code>private</code> will hide members and functions from sub-classes as well, so without a getter/setter pair they cannot be accessed. And even then: using getters/setters for internal variables is often an unnecessary burden, code bloat and degrades performance.</p>\n\n<p><strong>User communication</strong></p>\n\n<p>When communicating with the user of your program, always assume that he/she has no clue what this program is doing and be polite. Statements like <code>No arguments!</code> while being technically correct will not help the user to figure out what to do at that point. A better version would be:</p>\n\n<blockquote>\n <p>Not enough arguments. Cannot continue.<br>\n Compares a given set of integers and prints the maximum value and its location.<br>\n Usage:<br>\n Prog1 <int>, <int>, ...<br>\n Where <int> is any valid integer.<br></p>\n</blockquote>\n\n<p><strong>Variable/method names</strong></p>\n\n<p>Be expressive with the names of your variables and methods. Something like <code>x</code> is short to type, but won't help you or anyone else to understand what the purpose of this variable might be. This is for once helpful to actually understand the code, and on the other hand a good way to prevent some mistakes while coding. If you write <code>x + 1</code> this looks reasonable, unless you know that x is actually an array. This wouldn't happen if you name it <code>integers</code> or <code>inputArray</code>.</p>\n\n<p><strong>Threads vs. Runnables</strong></p>\n\n<p>In general you should always use Runnables and process them using an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"nofollow\">ExecutorService</a>. This simplifies management of code a lot and also makes it more flexible by separating the actual tasks from the system to process them. Imagine that it might be necessary to optimize performance later on, then suddenly you need to rewrite half of your code, while with Runnables you can focus completely on the actual execution part of the code, as the task definitions stay the same.</p>\n\n<h1>Code</h1>\n\n<blockquote>\n<pre><code>int size = Integer.parseInt(args[0])\n</code></pre>\n</blockquote>\n\n<p>You assume at this point that <code>args[0]</code> is an integer, otherwise the code will crash at this point. Furthermore the size is not required at all, as it is equal to the amount of parameters.</p>\n\n<p>In general parsing the arguments is a good candidate for a sub-method for several reasons:</p>\n\n<ul>\n<li>It removes clutter from the code</li>\n<li>It is easy to find</li>\n<li>It transforms the untrusted user input into a trusted work-set (or terminates) so the rest of the program can assume that the input data is valid.</li>\n</ul>\n\n<p>An example parsing function:</p>\n\n<pre><code>public static int[] parseInputParameters(final String[] args) {\n if ((args == null) || (args.length < 2)) {\n System.out.println(\"Not enough arguments. Cannot continue.\");\n return null;\n }\n\n final int[] result = new int[args.length];\n for (int i = 0; i < args.length; ++i) {\n try {\n result[i] = Integer.parseInt(args[i]);\n } catch (NumberFormatException nfe) {\n System.out.println(\"'\" + String.valueOf(args[i]) + \"' is not a valid integer. Cannot continue.\");\n return null;\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>Note that I compare <code>length < 2</code> as comparing a single integer is not possible.</p>\n\n<blockquote>\n<pre><code>w = new int[size];\nfor (int i = 0; i < size; i++)\n</code></pre>\n</blockquote>\n\n<p>You should always do array initialization using the length operator like <code>for (int i = 0; i < w.length; i++)</code> While technically they contain the same value, this is a potential update issue if size changes in between, while <code>length</code> will always be correct. </p>\n\n<blockquote>\n<pre><code>Initialize t = new Initialize(i);\nt.start();\n</code></pre>\n</blockquote>\n\n<p>While this is thread-safe because you happen to use an array, the cost to create, initialize and run a Thread massively out-weights the cost for setting the variable in a simple loop. One might as well ask how much faster 100 threads initialize an array on a 1-core system than 1 thread can do?</p>\n\n<p>A few lines later you already use the array w, even though there is no guarantee that threads are already done initializing. There is a good chance that our output will print some of the variables as 0, because the thread was not yet done initializing.</p>\n\n<p>In addition Java uses a memory model that allows threads to use local copies of variables, as long as the code stays the same from a single-threaded perspective of the thread (and the thread alone). So even if some threads are already done initializing, the array you use in your main might not yet contain these updates just because they simply have not yet been written to the array hold by the main thread. For further reading see <code>volatile</code>.</p>\n\n<blockquote>\n<pre><code>System.out.printf(\"%-25s%d\\n\", \"Number of input values = \", size);\n</code></pre>\n</blockquote>\n\n<p>Why use variables for static text? Why not:<br>\n<code>System.out.printf(\"Number of input values = %d\\n\", size);</code></p>\n\n<p>Your version forces the JVM to do more construction than actually necessary. Unless you plan to distribute your program in different languages, you should not do that.</p>\n\n<blockquote>\n<pre><code>String input = Arrays.toString(x).replace(\"[\", \"\").replace(\"]\", \"\").replace(\",\", \"\");\n</code></pre>\n</blockquote>\n\n<p>This would be a good candidate for a sub-method, as you use this transformation in various places. Beside using a StringBuilder, this can also be done using Regex in the form of <code>Arrays.toString(x).replaceAll(\"[\\\\[\\\\],]\", \"\")</code>.</p>\n\n<blockquote>\n<pre><code>int inc = 1;\nfor (int i = 0; i < size - 1; i++) {\n for (int j = inc; j < size; j++) {\n FindMax t = new FindMax(i, j);\n t.start();\n }\n inc++;\n}\n</code></pre>\n</blockquote>\n\n<p>Again performance is questionable here. In addition you transmit indexes to your threads instead of transmitting the actual values, which violates the information hiding principle and chains those threads to the existence and correctness of those global variables. You should use a data class for your case that is considered thread-local, which means that the thread can do everything it wants with it, as all thread issues are prevented since only this single thread is able to access that encapsulated data.</p>\n\n<blockquote>\n<pre><code>Thread.sleep(100);\n</code></pre>\n</blockquote>\n\n<p>Who guarantees that your threads are done after 100 millis?</p>\n\n<blockquote>\n<pre><code>if (compare < 0) {\n w[indI] = 0;\n lesser = indI;\n} else {\n w[indJ] = 0;\n lesser = indJ;\n}\n</code></pre>\n</blockquote>\n\n<p>This would in general violate threading rules as many threads write simultaneously to the same data locations. However as you use arrays and only write 0, this is thread-safe. But still this is code that can easily break with the slightest change to your code.</p>\n\n<h1>Cleaner version</h1>\n\n<p>I uploaded a modified version of your code <a href=\"http://ideone.com/r0FMW5\" rel=\"nofollow\">here</a> including most of my suggestions. This is not what I would call clean code, but given the task trying to clean everything up would be futile.</p>\n\n<p>I am using Executors with inline Runnables to emphasize how much of an overkill that is. It would be cleaner to create extra classes for those Runnables.</p>\n\n<p>However removing the Runnables and executors alltogether and turning it into a simple loop would be a much better idea. Using <code>Arrays.sort(inputValues)</code> would be infinitively faster.</p>\n\n<h1>Your Questions</h1>\n\n<blockquote>\n <p>Is this a good use of the static inner class?</p>\n</blockquote>\n\n<p>Debatable. While on the one hand it is cleaner than not using any class, it is still overkill.</p>\n\n<blockquote>\n <p>Are my variable and class declarations properly declared?</p>\n</blockquote>\n\n<p>Technically yes, but the scope (protected vs private) is not optimal and the names are not very expressive.</p>\n\n<blockquote>\n <p>Is there a better way than using Thread.sleep to make the sure that the main thread waits for certain child threads to complete before it performs some action?</p>\n</blockquote>\n\n<p>In my example I use an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"nofollow\">ExecutorService</a> in combination with <code>shutDown()</code> and <code>awaitTermination(...)</code>. An alternative would be a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html\" rel=\"nofollow\">CountDownLatch</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T14:26:36.327",
"Id": "75888",
"Score": "2",
"body": "I disagree with your `protected` vs `private` comments. Inheritance couples classes together very tightly, and is an important design decision, not to taken lightly by just making everything `protected`. Further, it's arguably better to leave variables as `private`, and have `protected` methods that subclasses can access if and when they need to. It is very, very unlikely that there will be any kind of detectable performance degradation from this approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:29:22.890",
"Id": "75901",
"Score": "1",
"body": "It depends on your view on inheritance. I've often came across classes that went the \"all private\" approach, and extending them was a pain or impossible, because the original author wasn't creative enough to think of all possible scenarios. My approach is: create a good API, but allow everything outside of that which isn't critical, because you never know what others want to do with it. And the performance reduction was about having tons of set()/get() in your code, just because you made something private for no reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T23:06:22.710",
"Id": "75941",
"Score": "0",
"body": "Something as simple as `set()/get()` is almost guaranteed to be inlined by the JVM."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T14:08:36.713",
"Id": "43857",
"ParentId": "43834",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T02:07:14.810",
"Id": "43834",
"Score": "4",
"Tags": [
"java",
"multithreading",
"classes",
"homework",
"thread-safety"
],
"Title": "Using threads to find max in array"
} | 43834 |
<p>I have some code that I'd written using this pattern with <a href="https://github.com/creationix/step" rel="nofollow noreferrer">Step.js</a>. In this case, talking to MongoDB in Node:</p>
<pre><code>Step(
function connectToDatabaseWithAuthorization() {
mongodb.connect(mongoConnectURI, this);
},
function getCommitCollection(err, conn) {
if (err) handleResErr(res, err);
conn.collection('commits', this);
},
function addCommitToCollection(err, coll) {
if (err) handleResErr(res, err);
var commit = JSON.parse(req.param('commit', null));
commit.commit_date = requestTime;
commit.commit_id = common.makeIdFromCommit(commit);
coll.insert(commit, {safe: true}, this);
},
function respondWithShowAndVerifyUrlsInJson(err, records) {
if (err) handleResErr(res, err);
res.json({
commit_date: records[0].commit_date
});
}
)
</code></pre>
<p>When I went to update my Node libraries, I noticed Step wasn't getting much attention or undergoing much development. And I wasn't happy about the error handling being spread into each function in the steps.</p>
<p>So I went to research modern alternatives, and <a href="https://github.com/caolan/async" rel="nofollow noreferrer">Async.js</a> seemed more popular. But when I asked about how to convert it, someone <a href="https://stackoverflow.com/a/22154290/211160">suggested I look into Q Promises instead</a>.</p>
<p>I came up with this transformation, which seems to work:</p>
<pre><code>Q.try(function() {
return Q.ninvoke(mongodb, 'connect', mongoConnectURI);
}).then(function (conn) {
return Q.ninvoke(conn, 'collection', 'commits');
}).then(function (coll) {
var commit = JSON.parse(req.param('commit', null));
commit.commit_date = requestTime;
commit.commit_id = common.makeIdFromCommit(commit);
return Q.ninvoke(coll, 'insert', commit, {safe: true});
}).then(function (records) {
res.json({
commit_date: records[0].commit_date
});
}).catch(function (err) {
handleResErr(res, err);
});
</code></pre>
<p>Not a large piece of code, but I could use a sanity check. I was having problems with figuring out if I should be using <code>.done()</code> in there somewhere, and also I couldn't get <code>.finally</code> to work. If I put it on the end of the chain, it ran after the first promise and not after all of them. :-/</p>
<p>While I mostly think the generality makes it an improvement, it does really obscure the method calls. <code>Q.ninvoke(mongodb, 'connect' mongoConnectURI)</code> is quite a bit uglier than <code>mongodb.connect(mongoConnectURI)</code>. Have people made some better way to do mongodb calls with promises than this?</p>
| [] | [
{
"body": "<p>Interesting that you're getting <code>.finally()</code> after your first method rather than at the end. Should I read that to mean that your code executed as: connect-->finally-->[DONE] or did control flow somewhere else in the promise chain subsequent to <code>finally</code>?</p>\n\n<p>Regarding the aesthetics - I couldn't agree with your more; <code>ninvoke</code> and its relatives are not the easiest to read. Two main options. One, you can look for a promise-enabled library for this or that. This is probably not my first choice unless the library would be giving you something more than just a promises wrapper. Two, you can get yourself some nicer looking functions by using the <code>denodeify</code> function. Consider if you wrote a module like this (you could of course inline this code as well which I often do for both initial development as well as if I find I really don't need more than a function or two):</p>\n\n<pre><code>var Q = require('q');\nvar lib = require('someNodeModule');\n\nmodule.exports = {\n connect: Q.denodeify(lib.connect),\n read: Q.denodeify(lib.read),\n write: Q.denodeify(lib.write)\n}\n</code></pre>\n\n<p>At this point, you have a new module with each of the above functions being promise-returning ones rather than callback-invoking ones. If you <code>require</code> the above as, say <code>libp</code>, you could then replace your various <code>return Q.ninvoke(...)</code> calls with much more clear calls such as a simple <code>return libp.connect(...)</code>. The signature of the function stays the same (other than the obvious loss of the final callback).</p>\n\n<p>I will try to return to this later this evening as well regarding the odd <code>.finally()</code> behavior. In the meantime, you might find <a href=\"https://stackoverflow.com/questions/19112801/node-js-using-promises-with-mongodb/19149119#19149119\">this Q&A</a> relevant to an issue you did not raise, but may encounter. More generally, the individual providing the answer, Bergi, appears to be quite expert with promises (from other answers I have seen), so you might check out some other answers or even solicit input on this. I am a journeyman, at best, with promises. I think I have a reasonable understanding of the concepts and library, but have not yet accumulated all the idioms that would be helpful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T03:10:21.830",
"Id": "75962",
"Score": "0",
"body": "Okay, it seems the .finally() issue is something with the console.log messages being out of chronological order in Nodejitsu's **jitsu logs tail** feature. That is certainly confusing for someone already out of their usual toolset already. :-/ Still confused about the .done()... some people use it, some don't. What's the point? Is it okay that my last `.then` clause returns nothing, and if so what makes that okay?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T03:28:53.843",
"Id": "75964",
"Score": "0",
"body": "Good old `console.log()` - it's great having such an easy logger always available, but it occasionally has me chasing non-errors because of the timing of messages (and the fact that it seems if I crash out on some code, the not-yet-emitted messages are lost). As for `.done()`, I tend not to use it and often see it omitted, but it appears I should, having read [the API doc](https://github.com/kriskowal/q/wiki/API-Reference#wiki-promisedoneonfulfilled-onrejected-onprogress)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T02:44:51.517",
"Id": "77315",
"Score": "0",
"body": "Things have been going along pretty well; I'd say the promise library was a good choice. Thanks for the help and the original suggestion! Feel free to test [blackhighlighter](http://blackhighlighter.org/write/), if it happens to be up and working. :-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:05:40.113",
"Id": "43864",
"ParentId": "43837",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43864",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T03:13:12.047",
"Id": "43837",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"mongodb",
"promise"
],
"Title": "Thoughts on this conversion of code from Step.js to Q promise library?"
} | 43837 |
<blockquote>
<p>Given an input string, reverse the string word by word.</p>
<p>For example: Given <code>s = "the sky is blue"</code>, return <code>"blue is sky the"</code>.</p>
<p><strong>What constitutes a word?</strong></p>
<ul>
<li>A sequence of non-space characters constitutes a word.</li>
</ul>
<p><strong>Could the input string contain leading or trailing spaces?</strong></p>
<ul>
<li>Yes. However, your reversed string should not contain leading or trailingspaces.</li>
</ul>
<p><strong>How about multiple spaces between two words?</strong></p>
<ul>
<li>Reduce them to a single space in the reversed string.</li>
</ul>
</blockquote>
<pre><code>public static String reverseWords(String s){
StringTokenizer strTok = new StringTokenizer(s, " ");
Stack<String> stack=new Stack<String>();
StringBuilder buff=new StringBuilder();
while(strTok.hasMoreElements()) {
String str = (String)strTok.nextToken();
if(!str.equals("")) stack.push(str);
}
while(!stack.isEmpty()){
buff.append(stack.pop());
if(!stack.isEmpty()) buff.append(" ");
}
return buff.toString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T12:36:20.977",
"Id": "75883",
"Score": "1",
"body": "There's a (little known) class in the Java class libraries that's meant for these problems. BreakIterator: http://docs.oracle.com/javase/7/docs/api/java/text/BreakIterator.html \n\nThe javadoc even has an example that does almost exactly what you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T13:35:15.783",
"Id": "75887",
"Score": "0",
"body": "@tom: I'd love to see an example for the problem with `BreakIterator` (as an answer:)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T22:24:51.263",
"Id": "75937",
"Score": "0",
"body": "Is their something I am missing? Use .toCharArray() or .split(String s)."
}
] | [
{
"body": "<ol>\n<li><p><code>Stack</code> seems more or less deprecated. <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html\">Javadoc says the following</a>:</p>\n\n<blockquote>\n <p>A more complete and consistent set of LIFO stack \n operations is provided by the Deque interface and its\n implementations, which should be used in preference to this class.</p>\n</blockquote>\n\n<p>I guess an <code>ArrayDeque</code> is a good choice here.</p></li>\n<li><p>It's seems that <code>StringTokenizer</code> is also deprecated. <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html\">Javadoc says the following</a>:</p>\n\n<blockquote>\n <p>StringTokenizer is a legacy class that is retained for \n compatibility reasons although its use is discouraged in new code. \n It is recommended that anyone seeking this functionality use the \n split method of String or the java.util.regex package instead. </p>\n</blockquote></li>\n<li><p>I'd rename </p>\n\n<ul>\n<li><code>buff</code> to <code>result</code> </li>\n<li><code>stack</code> to <code>words</code></li>\n<li><code>str</code> to <code>word</code></li>\n</ul>\n\n<p>to describe their purpose. It would be easier to read and help understanding code.</p></li>\n<li><p>You could move the declaration of <code>buff</code> right before the second while loop.</p>\n\n<pre><code>StringBuilder buff = new StringBuilder();\nwhile (!stack.isEmpty()) {\n buff.append(stack.pop());\n if (!stack.isEmpty())\n buff.append(\" \");\n}\n</code></pre>\n\n<p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><blockquote>\n<pre><code>if(!str.equals(\"\"))\n</code></pre>\n</blockquote>\n\n<p>You could use <code>String.isEmpty()</code> here. It's easier to read since it says in a similar language to English what does this condition do.</p></li>\n<li><blockquote>\n<pre><code>if(!str.equals(\"\")) stack.push(str);\n</code></pre>\n</blockquote>\n\n<p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-142311.html#430\">Code Conventions for the Java Programming Language</a>,</p>\n\n<blockquote>\n <p>if statements always use braces {}.</p>\n</blockquote>\n\n<p>Omitting them is error-prone. I've found the one-liner above hard to read because if you scan the code line by line it's easy to miss that at the end of the line there is a statement (push).</p></li>\n<li><p>It's good to know that there is a similar function in <a href=\"http://commons.apache.org/proper/commons-lang/\">Apache Commons Lang</a>: <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#reverseDelimited%28java.lang.String,%20char%29\"><code>StringUtils.reverseDelimited</code></a>. You can <a href=\"http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/main/java/org/apache/commons/lang3/StringUtils.java?view=markup#l6309\">check the implementation online</a> for other ideas.</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</ol>\n\n<hr>\n\n<p>Here is the modified code with the Deque and other suggestions:</p>\n\n<pre><code>public static String reverseWords(String input) {\n Deque<String> words = new ArrayDeque<>();\n for (String word: input.split(\" \")) {\n if (!word.isEmpty()) {\n words.addFirst(word);\n }\n }\n StringBuilder result = new StringBuilder();\n while (!words.isEmpty()) {\n result.append(words.removeFirst());\n if (!words.isEmpty()) {\n result.append(\" \");\n }\n }\n return result.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T02:27:40.930",
"Id": "75960",
"Score": "0",
"body": "Very minor point, but `result.append(\" \")` is more expensive than `result.append(' ')`. Compare: [append(char)](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.append%28char%29) with [append(String)](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.append%28java.lang.String%29) - if you are only appending a single char, it increments only one char. Strings you need to find their size, get the backing array, etc..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T03:27:56.173",
"Id": "76857",
"Score": "1",
"body": "good answer. i would choose to use a variable name like `wordSet` or `wordList` instead of words because its hard to distinguish words from word in the code"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T06:59:27.710",
"Id": "43840",
"ParentId": "43838",
"Score": "18"
}
},
{
"body": "<p>Using a Stack and StringTokenizer seems to be a bit of an overkill here. A more simplified version could be written like this:</p>\n\n<pre><code>public static String reverse(final String input) {\n Objects.requireNonNull(input);\n final StringBuilder stringBuilder = new StringBuilder();\n for (final String part : input.split(\"\\\\s+\")) {\n if (!part.isEmpty()) {\n if (stringBuilder.length() > 0) {\n stringBuilder.insert(0, \" \");\n }\n stringBuilder.insert(0, part);\n }\n }\n return stringBuilder.toString();\n}\n</code></pre>\n\n<p>This uses the ability of <code>split()</code> to take a String apart based on a given Regex. So the string is split based on <em>a sequence of one or more white-spaces</em>, which matches your initial requirement. Note that split will return an empty array in case input is an empty string.</p>\n\n<p>The for-each loop then works through the array and inserts the part at the beginning of the stringBuilder (except for the first time), which will effectively reverse the array. Most people would probably use a reverse <code>for(i...)</code> loop here, but because this is a code review I try to be extra correct, and this is the safer version: You cannot cause ArrayIndexOutOfBoundsExceptions with for-each.</p>\n\n<p>Any leading/trailing white-space will cause empty parts to appear in the splitted list, so there is a check for it in the loop. I use <code>isEmpty()</code> here, as this is in general safer (as in: less chance to do typos) than <code>length() > 0</code> and benefits from potential, internal optimizations of String in terms of execution speed. You could call <code>trim()</code> beforehand, but this would cause some unnecessary String operations and creations, so this version is more efficient.</p>\n\n<p>Please also note the check for <code>null</code> at the beginning. The code would otherwise throw when trying to split on <code>null</code>, but it is considered good practice to check before-hand, as theoretically (not in this code but in other) you otherwise might leave the system in an undefined state. </p>\n\n<p>I also make use of <code>final</code>, which allows some compiler optimizations and prevents you from some basic coding mistakes, which is considered good practice.</p>\n\n<p><strong>Testing</strong></p>\n\n<p>It is always a good idea to do some quick testing of the functionality including the basic edge-cases, so here it is:</p>\n\n<p>To check whether or not I do correct white-space removal, I change <code>stringBuilder.insert(0, \" \")</code> to <code>stringBuilder.insert(0, \"+\")</code> for the test, to make the white-space visible.</p>\n\n<p>When testing with <code>System.out.println(reverse(\"the sky is blue\"));</code> the result is:\n<code>blue+is+sky+the</code> The initial requirement is met.</p>\n\n<p>When testing with <code>System.out.println(reverse(\" \\t the sky is\\t blue \"));</code> the result is:\n<code>blue+is+sky+the</code> Leading, trailing and in-between white-spaces are correctly removed.</p>\n\n<p>When testing with <code>reverse(\"\")</code> the result is an empty String as expected.</p>\n\n<p>When testing with <code>reverse(null)</code> a NullPointerException is thrown at the beginning of the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T02:30:05.737",
"Id": "75961",
"Score": "0",
"body": "When doing inserts and appends with a single character, the code for [insert(int,char)](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.insert%28int%2Cchar%29) is less expensive than for [insert(int, String)](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.insert%28int%2Cjava.lang.String%29) - chars are always a single unit while Strings you need to find the size of the String, get the backing array, check for null, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:47:57.543",
"Id": "75984",
"Score": "0",
"body": "That's true and a good point. But also only relevant if the method above is run like a million times per second. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:30:39.260",
"Id": "76021",
"Score": "0",
"body": "Using the character version rather than the String version of the call, while not something that is *critical* to this application is a good thing to keep in mind and make part of one's standard \"this is how you do it\" and done that way without thinking if you should use a `\" \"` or `' '` in the future. While the performance likely isn't an issue here, following the best practices and writing the most efficient code up front begins with a single code review."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T11:32:53.950",
"Id": "43850",
"ParentId": "43838",
"Score": "8"
}
},
{
"body": "<p>I would simply use <code>split</code> and than iterate the resulting array backwards to create the result:</p>\n\n<pre><code>@Nonnull\npublic static String reverse(@Nonnull final String sentence) {\n final StringBuilder result = new StringBuilder();\n final String[] words = sentence.split(\"\\\\s+\"); \n for (int i = words.length - 1 ; 0 <= i; i--) {\n result.append(words[i]).append(' ');\n }\n return result.toString().trim();\n}\n</code></pre>\n\n<p>P.s. I think a <code>Stack</code> and a <code>StringTokenizer</code> are a bit heavy stuff for this and without them the implementation is still quite slim.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T15:56:55.260",
"Id": "75893",
"Score": "0",
"body": "`i >= 0` I think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:41:06.250",
"Id": "75921",
"Score": "0",
"body": "@tintinmj: You are right, fixed it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T11:58:49.020",
"Id": "43852",
"ParentId": "43838",
"Score": "12"
}
},
{
"body": "<p>This type of question is always interesting, because I always feel there is the easiest, and the best way to do things. Easiest often relies on using native mechanisms for the work. The best, I feel, is often to use primitives and to do as few object creations as possible.</p>\n\n<p>Here are the two candidate solutions I can suggest for the easiest/best. The Easiest uses the <code>String.split()</code> method, but unlike other solutions suggested here, it is purely 'additive'. No inderting things in the middle, and no inserting extra stuff which gets deleted. It also does some input validation. 'Trimming' the value before the split is important....</p>\n\n<p>The 'best' option is plain <em>O(n)</em> performance (<code>StringBuilder.insert(...)</code> used in some solutions is not going to produce an overall <em>O(n)</em> solution). This suggested solution does not create all the intermediate String objects that the other solutions create, and it uses O(1) extra memory space.</p>\n\n<pre><code>public static void main(String[] args) {\n String[] input = {\"\", null, \"a\", \"this is\", \"this is\", \" this is \"};\n for (String in : input) {\n System.out.println(\"Split: -> |\" + reverseString(in) + \"|\");\n System.out.println(\"Array: -> |\" + reverseStringFP(in) + \"|\");\n\n }\n}\n\n\nprivate static final String reverseString(String input) {\n if (input == null) {\n return null;\n }\n String[] parts = input.trim().split(\"\\\\s+\");\n if (parts.length == 0) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n sb.append(parts[parts.length - 1]);\n for (int i = parts.length - 2; i >= 0; i--) {\n sb.append(\" \").append(parts[i]);\n }\n return sb.toString();\n}\n\nprivate static final String reverseStringFP(final String input) {\n if (input == null) {\n return null;\n }\n if (input.isEmpty()) {\n return \"\";\n }\n final char[] inchar = input.toCharArray();\n // + 1 to allow for a temporary trailing space\n final char[] outchar = new char[inchar.length + 1];\n int outpos = 0;\n int wordend = inchar.length - 1;\n while (wordend >= 0) {\n while (wordend >= 0 && inchar[wordend] == ' ') {\n wordend--;\n }\n int wordstart = wordend;\n while (wordstart > 0 && inchar[wordstart - 1] != ' ') {\n wordstart--;\n }\n if (wordstart >= 0) {\n int len = wordend - wordstart + 1;\n System.arraycopy(inchar, wordstart, outchar, outpos, len);\n outpos += len;\n outchar[outpos++] = ' ';\n wordend = wordstart - 1;\n }\n }\n if (outpos > 0) {\n // deal with trailing space\n outpos--;\n }\n return new String(outchar, 0, outpos);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T13:33:52.760",
"Id": "75886",
"Score": "0",
"body": "+1. A minor note: I'd use a variable instead of the comment: `boolean hasTrailingSpace = outpos > 0; if (hasTrailingSpace) ...`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:02:21.223",
"Id": "75894",
"Score": "0",
"body": "What does `FP` stand for in `reverseStringFP`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:06:03.363",
"Id": "75895",
"Score": "0",
"body": "@tintinmj - First Principles - no reference to any other libraries ... how I imagine a basic implementation would do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:10:29.030",
"Id": "75897",
"Score": "0",
"body": "Hmmm but aren't you using `System` and `String`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:13:55.737",
"Id": "75898",
"Score": "0",
"body": "Where people draw the line is their choice. I am not using anything outside of the Java language specification and java.lang.* (i.e. I am not using regex, Collections, etc. which would, themselves, have to iterate character-by-character over the value)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T13:13:25.927",
"Id": "43854",
"ParentId": "43838",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43840",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T04:39:00.777",
"Id": "43838",
"Score": "22",
"Tags": [
"java",
"algorithm",
"strings",
"interview-questions"
],
"Title": "Reverse a string word by word"
} | 43838 |
<p>I have the following two vectors in C++11:</p>
<pre><code>vector<unsigned char> left = { 1, 2, 3, 4, 5, 6 }; // it is meant to represent the number: 123456
vector<unsigned char> right = { 1, 2, 3, 4 }; // meant to be number: 1234
</code></pre>
<p>After a function processes them, they become:</p>
<pre><code>left = { 6, 5, 4, 3, 2, 1 };
right = { 4, 3, 2, 1 };
</code></pre>
<p>Now, I need to complete the shorter one with zeros at the end until they are equal in <code>size()</code>. I have thefollowing method:</p>
<pre><code>void bigint::process_operands( vector<unsigned char> & left, vector<unsigned char> & right )
{
size_t left_size = left.size();
size_t right_size = right.size();
if( left_size < right_size )
{
size_t size_diff = right_size - left_size;
for( size_t i = 0; i != size_diff; ++i )
left.push_back( '0' );
} else if( right_size < left_size )
{
size_t size_diff = left_size - right_size;
for( size_t i = 0; i != size_diff; ++i )
right.push_back( '0' );
}
}
</code></pre>
<p>Is there any better implementation?</p>
| [] | [
{
"body": "<p>Firstly, given that you're using <code>vector</code> without namespace qualification (that is, not as <code>std::vector</code>), I assume you have a <code>using namespace std;</code> in this code. This is generally a bad idea, but especially so in this case. You use <code>vector<unsigned char> & right</code> (and <code>vector<unsigned char> left</code>), however, there is a <code>std::right</code> (and a <code>std::left</code>) defined in <code><ios></code>. This could potentially lead to some very confusing compiler errors. </p>\n\n<p>Using a few tricks from <code><algorithm></code>, we can shorten the above code considerably.</p>\n\n<pre><code>void bigint::process_operands(vector<unsigned char> & left_, vector<unsigned char> & right_)\n{\n auto& shorter = (left_.size() < right_.size()) ? left_ : right_;\n std::fill_n(std::back_inserter(shorter), std::abs(left_.size() - right_.size()), '0');\n}\n</code></pre>\n\n<p>This is much more terse, but I find that using the standard library actually makes this code easier to read and more clear as to exactly what it is doing. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T11:12:31.017",
"Id": "43848",
"ParentId": "43844",
"Score": "11"
}
},
{
"body": "<p>I’d just like to point out a very short version of your own code. It is certainly not as C++ish as a <code>vector::insert</code> or <code>fill_n</code> solution, but what it does is pretty obvious.</p>\n\n<pre><code>void bigint::process_operands( vector<unsigned char> & left, vector<unsigned char> & right )\n{\n while (left.size() < right.size())\n left.push_back( '0' );\n while (right.size() < left.size())\n right.push_back( '0' );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:05:01.657",
"Id": "43870",
"ParentId": "43844",
"Score": "5"
}
},
{
"body": "<p>How about something like this:</p>\n\n<pre><code>auto sz = std::max(left.size(), right.size());\nleft.resize(sz, '0');\nright.resize(sz, '0');\n</code></pre>\n\n<p><code>.resize()</code> will resize the container to the given size, and fill the new elements (if any) with the given value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T08:44:42.140",
"Id": "75978",
"Score": "0",
"body": "I am not sure abut its performance, but it compiles..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:15:03.240",
"Id": "76095",
"Score": "1",
"body": "@Victor What are you unsure about? It's at least as efficient as (probably more than) using `back_inserter` or `push_back`. If you're worried about `max`, replace it with a conditional (although it's almost guaranteed to get inlined)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T20:29:40.327",
"Id": "43884",
"ParentId": "43844",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "43884",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T09:42:22.407",
"Id": "43844",
"Score": "7",
"Tags": [
"c++",
"c++11"
],
"Title": "Better size aligning?"
} | 43844 |
<p>Please review this code:</p>
<pre><code>function toggleFullScreen() {
if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
var elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Right now you have a lot of duplicate-ish code because of the prefix checking. You can improve this by using a helper function to handle the prefix checking for you (untested, but should work):</p>\n\n<pre><code>function prefixed(name, scope) {\n var prefixes = ['', 'moz', 'webkit', 'o', 'ms'];\n var fullName = '';\n var i;\n if (scope === undefined) {\n scope = window;\n }\n for(i = 0; i < prefixes.length; i++) {\n if (prefixes[i]) {\n fullName = prefixes[i] + name.substr(0, 1).toUpperCase() + name.substr(1);\n }\n else {\n fullName = name;\n }\n if (scope[fullName] !== undefined) {\n return scope[fullName];\n }\n }\n return undefined;\n}\n</code></pre>\n\n<p>Afterwards you can reduce your code to this:</p>\n\n<pre><code>var requestFullscreen = prefixed('requestFullscreen');\nvar exitFullscreen = prefixed('exitFullscreen');\nfunction toggleFullScreen() {\n if (!requestFullscreen || !exitFullscreen) {\n return;\n }\n if (!prefixed('fullscreenElement', document)) {\n requestFullscreen();\n }\n else {\n exitFullscreen();\n }\n}\n</code></pre>\n\n<p>If necessary, just pass <code>Element.ALLOW_KEYBOARD_INPUT</code> to all calls or use a try..catch if that makes the call fail in non-webkit browsers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T17:40:02.473",
"Id": "43869",
"ParentId": "43856",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T14:08:09.080",
"Id": "43856",
"Score": "6",
"Tags": [
"javascript",
"cross-browser"
],
"Title": "Toggling Fullscreen"
} | 43856 |
<p>I solved this problem in about 11 minutes (with all 50+ test cases passed).</p>
<p>I think most of you already know me by now, and I truly appreciate your advice, but please be brutal and judge me as if I was being interviewed by you.</p>
<p>Question:</p>
<blockquote>
<p>Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.</p>
</blockquote>
<p>Code:</p>
<pre><code>public void setZeroes(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean[][] flagArr = new boolean[rows][cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(matrix[i][j]==0){
flagArr[i][j]=true;
}
}
}
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(flagArr[i][j]==true){
/*for rows*/
for(int k=0; k<rows; k++){
matrix[k][j]=0;
}
/*for cols*/
for(int z=0; z<cols; z++){
matrix[i][z]=0;
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:06:31.657",
"Id": "75896",
"Score": "3",
"body": "I see that you have been writing a lot of code involving primitives to implement some algorithms. How about writing your own more object-oriented classes? I think you could learn a lot by writing your own implementation of a [weekend / coding challenge](http://meta.codereview.stackexchange.com/questions/tagged/weekend-challenge) (it's never too late to submit an entry!)"
}
] | [
{
"body": "<p>At first when I took a look at your question I was thinking: Why do you first set values in a boolean matrix to true? I quickly realized, \"Oh. That's why.\"</p>\n\n<p>Overall, well done. I like your code. I would have solved it in the same way. Your coding style is consistent, which makes it easy to follow your code, even though I don't agree with the coding style itself.</p>\n\n<p>Two comments:</p>\n\n<ul>\n<li><p>Variable naming. <code>flagArr</code> is a matrix and not an (1 diemensional) array. But it would be more helpful to name it to what it is used for rather than what it is. How about <code>zerosFound</code>? <code>i</code> and <code>j</code> I would either name as <code>x</code> and <code>y</code> or <code>col</code> and <code>row</code>.</p></li>\n<li><p>Spacing. It's not wrong to have a bit of more space in your lines. Use spaces around <code><</code> and <code>=</code> and before <code>{</code> etc. Here's what parts of your code looks like when I press Ctrl + Shift + F in Eclipse (which is a key shortcut for auto formatting).</p>\n\n<pre><code>for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (matrix[i][j] == 0) {\n flagArr[i][j] = true;\n }\n }\n}\n</code></pre></li>\n</ul>\n\n<p>As I said. <strong>Good job.</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T15:57:56.953",
"Id": "43863",
"ParentId": "43861",
"Score": "10"
}
},
{
"body": "<p>I think your code is complete, but not the most efficient it could be.</p>\n\n<p>There are two areas where there are inefficiencies:</p>\n\n<ul>\n<li>there is no need to have a comprehensive row-column flag matrix... you only need two arrays, one for row, one for columns.</li>\n<li>you have very inefficient zeroing of the rows/columns because you will potentially do many cells many times. (for example, if two values in a row are zero, then you will zero that row twice....)</li>\n</ul>\n\n<p>Consider the following changes:</p>\n\n<pre><code>public void setZeroes(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n boolean[] rowzero = new boolean[rows];\n boolean[] colzero = new boolean[cols];\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (matrix[r][c] == 0) {\n rowzero[r] = true;\n colzero[c] = true;\n }\n }\n }\n for (int r = 0; r < rows; r++) {\n if (rowzero[r]) {\n for (int c = 0; c < cols; c++) {\n matrix[r][c] = 0;\n }\n }\n }\n for (int c = 0; c < cols; c++) {\n if (colzero[c]) {\n for (int r = 0; r < rows; r++) {\n matrix[r][c] = 0;\n }\n }\n }\n}\n</code></pre>\n\n<p>This only zeros out each affected row one time, and it uses much less memory</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:33:55.440",
"Id": "75903",
"Score": "1",
"body": "out of curiosity, how old are you? Your amazing style intimidates a 20ish year old guy like myself, and makes me want to run back to the drawing board. I appreciate your ruthless comments; it helps me improve and motivates me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:35:15.380",
"Id": "75904",
"Score": "4",
"body": "@bazang come join us in the [2nd monitor chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) ....."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:44:13.403",
"Id": "75905",
"Score": "2",
"body": "If I would have spent just a bit longer thinking about it, I probably would have thought about this solution... Well done, performance-monkey!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:26:24.450",
"Id": "43866",
"ParentId": "43861",
"Score": "18"
}
},
{
"body": "<p>11 minutes, nice :) Keep in mind that taking some time to keep the code maintainable after finish also important which could earn you some extra points too on an interview.</p>\n\n<p>A few things you could improve (in the original code):</p>\n\n<ol>\n<li><p>Rename <code>i</code> to <code>row</code> and <code>j</code> to <code>col</code>. It would be easier to read and harder to mistype.</p></li>\n<li><blockquote>\n<pre><code>if (flagArr[row][col] == true) {\n</code></pre>\n</blockquote>\n\n<p>could be simply</p>\n\n<pre><code>if (flagArr[row][col]) {\n</code></pre></li>\n<li><p>Extract out a few methods for higher abstraction level:</p>\n\n<pre><code>public void setZeroes(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n boolean[][] zeroMatrix = getZeroMatrix(matrix);\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (zeroMatrix[row][col]) {\n fillColumn(matrix, col, 0);\n fillRow(matrix, row, 0);\n }\n }\n }\n}\n\npublic boolean[][] getZeroMatrix(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n boolean[][] result = new boolean[rows][cols];\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (matrix[i][j] == 0) {\n result[i][j] = true;\n }\n }\n }\n return result;\n}\n\nprivate void fillRow(int[][] matrix, int row, int value) {\n int cols = matrix[0].length;\n for (int col = 0; col < cols; col++) {\n matrix[row][col] = value;\n }\n}\n\nprivate void fillColumn(int[][] matrix, int col, int value) {\n int rows = matrix.length;\n for (int row = 0; row < rows; row++) {\n matrix[row][col] = value;\n }\n}\n</code></pre>\n\n<p>It's easier to read, it's easier to get an overview what the method does (without the details) and you can still check them if you are interested in. Furthermore, you need to read and understand less code (not the whole original method) if you want to modify just a small part of it.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:36:49.110",
"Id": "43878",
"ParentId": "43861",
"Score": "7"
}
},
{
"body": "<p>The other answers have good advice: you can consume less memory and time by keeping track of only the information you need, your naming could be improved, you could refactor the problem into smaller methods.</p>\n\n<p>I would add to that one small performance consideration. Think about what this does:</p>\n\n<pre><code> if(matrix[i][j]==0){\n flagArr[i][j]=true;\n }\n</code></pre>\n\n<p>or in the more efficient algorithm:</p>\n\n<pre><code> if (matrix[r][c] == 0) {\n rowzero[r] = true;\n colzero[c] = true;\n }\n</code></pre>\n\n<p>I am going to propose a micro-optimization; this might not be justified because (1) your program might already be fast enough overall, (2) this optimization might be in a portion of the program that is not significantly contributing to the total performance cost, and (3) the optimization might actually make things worse; there's no substitute for measuring carefully to find out. All that said, I would be inclined to write these as:</p>\n\n<pre><code> flagArr[i][j] = (matrix[i][j] == 0);\n</code></pre>\n\n<p>or</p>\n\n<pre><code> rowzero[r] |= (matrix[r][c] == 0);\n colzero[c] |= (matrix[r][c] == 0);\n</code></pre>\n\n<p>A common belief amongst programmers is <strong>code does work, so if I can conditionally avoid the work the program will be faster</strong>. Though this is often true, it is also true that <strong>conditions are also work</strong> and <strong>any time the branch predictor on the chip predicts wrong, your potentially mess up the processor state</strong>. It can therefore be a good idea to do \"unnecessary\" work unconditionally <strong>if doing so is extremely cheap</strong>, and thereby skip both the cost of the condition and the risk of branch prediction failure. Setting bools to true or false is <strong>insanely fast</strong> on modern architecture; the work you are trying to save here is the fastest thing you can possibly do. It can therefore in many cases be completely worthwhile to simply do the work unconditionally rather than spending two nanoseconds trying to avoid work that takes one nanosecond.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:08:59.737",
"Id": "76030",
"Score": "0",
"body": "2 questions: is multiplication (for accessing a 2-d array) faster than messing up the branch predictor? Are you sure the internal work of performing a comparison and returning a boolean doesn't involve conditional branching?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:43:10.820",
"Id": "76050",
"Score": "0",
"body": "@Barmar: StackOverflow is a question-and-answer site for just such technical questions. Those sound like good questions to post on StackOverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:44:26.810",
"Id": "76051",
"Score": "1",
"body": "I intended them as questions about whether this answer really achieves the optimizations it claims to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:46:46.737",
"Id": "76054",
"Score": "0",
"body": "@Barmar: Well then, your first question can be answered by **trying it yourself**. Write the code both ways, get out a stopwatch, and benchmark it under carefully controlled conditions and then you'll know. Your second question is about an implementation detail of the Java virtual machine; that question will have to be addressed to the manufacturer of the virtual machine you plan to use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:49:06.833",
"Id": "76055",
"Score": "1",
"body": "You're the one making the claim, it seems like you should provide the data to back it up. I'm not a Javaprogrammer, I'm not going to try setting it up just to answer this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:51:19.440",
"Id": "76058",
"Score": "0",
"body": "@Barmar: You have misread my answer. I'm making no specific claim whatsoever; I'm making a suggestion for a possible area of performance improvement, and specifically calling out that such an optimization needs to be justified by (1) need, (2) relevance and (3) data. I'm not sure how you read that as me making a specific claim about a measured result."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T20:18:43.880",
"Id": "43883",
"ParentId": "43861",
"Score": "5"
}
},
{
"body": "<p>Your solution is clear, concise, and correct. So far, so good.</p>\n\n<p>The function should be <code>static</code>.</p>\n\n<p>I might fault your code for excessive use of memory, which would probably prompt a follow-up question. @rolfl has pointed out that you could use two one-dimensional arrays. You could do better, with just one <code>boolean</code> to decide whether to zero the current row, and one <code>boolean[]</code> to keep track of the columns that you will zero. (A simple exercise for you.)</p>\n\n<p>It is even possible to do it with two <code>boolean</code> variables (constant space). It's debatable whether such a solution is better than a one-1D-array solution, though, since it probably has worse cache locality.</p>\n\n<pre><code>public static void setZeroes(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n\n for (int i = (rows > cols ? rows : cols) - 1; i >= 0; i--) {\n boolean zeroRow = false, zeroCol = false;\n if (i < cols) {\n for (int r = 0; r < i; r++) {\n if (matrix[r][i] == 0) {\n zeroCol = true;\n break;\n }\n }\n }\n if (i < rows) {\n for (int c = 0; c < i; c++) {\n if (matrix[i][c] == 0) {\n zeroRow = true;\n break;\n }\n }\n }\n if (zeroRow) {\n for (int c = 0; c < cols; c++) {\n matrix[i][c] = 0;\n }\n }\n if (zeroCol) {\n for (int r = 0; r < rows; r++) {\n matrix[r][i] = 0;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T04:18:55.257",
"Id": "43900",
"ParentId": "43861",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "43866",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T15:32:32.020",
"Id": "43861",
"Score": "13",
"Tags": [
"java",
"algorithm",
"interview-questions",
"matrix"
],
"Title": "Set matrix zeros"
} | 43861 |
<p>This is a simple hello world sample project used for instruction. I'm just looking for general comments on the approach and design.</p>
<p><strong>AdvancedHelloWorldTest.java</strong></p>
<pre><code>
/**
* AdvancedHelloWorldTest.java
* 2014 GetGnosis.com
*/
package com.getgnosis.tutorials.tutorial01001;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Test;
/**
* Test Class for
* {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld}
*
* @author mhemphill
* @version 1.0.0 - Mar 9, 2014
*/
public class AdvancedHelloWorldTest {
/**
* Test method for
* {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld
* #AdvancedHelloWorld()}.
*/
@Test
public void testAdvancedHelloWorld() {
try {
new AdvancedHelloWorld();
} catch (Exception e) {
fail("Construction failed. ");
}
}
/**
* Test method for
* {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld
* #main(java.lang.String[])}.
*/
@Test
public void testMain() {
final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
AdvancedHelloWorld.main(null);
assertEquals("Hello World!" + System.getProperty("line.separator"), outContent.toString());
System.setOut(null);
}
/**
* Test method for
* {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld
* #toString()}.
*/
@Test
public void testToString() {
String helloWorldString = new AdvancedHelloWorld().toString();
assertEquals("AdvancedHelloWorld [message=Hello World!]",helloWorldString);
}
}
</code></pre>
<p><strong>AdvancedHelloWorld.java</strong></p>
<pre><code>/**
* AdvancedHelloWorld.java
* 2014 GetGnosis.com
*/
package com.getgnosis.tutorials.tutorial01001;
/**
* This is an example program that prints the {@link String} "Hello World!" to
* the system's output display.
*
* @author mhemphill
* @version 1.0.0 - Mar 9, 2014
*/
public class AdvancedHelloWorld {
static {
message = "Hello World!";
}
/**
* The {@link String} instance representing the message to be displayed.
*/
private final static String message;
/**
* The default constructor. Initializes the value of message via the
* static block.
*/
public AdvancedHelloWorld() {}
/**
* The application entry point. Creates a new instance of
* {@link AdvancedHelloWorld} and prints the value of the {@link String}
* message to the system's output display.
*
* @param args - @{link String} array representing the arguments to the
* application. Not used in this application.
*
*/
public static void main(String[] args) {
System.out.println(new AdvancedHelloWorld().getMessage());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AdvancedHelloWorld [");
if (getMessage() != null)
builder.append("message=").append(getMessage());
builder.append("]");
return builder.toString();
}
/**
* Returns {@link String} instance representing the message to be displayed.
*
* @return message - {@link String} instance representing the message to
* be displayed.
*/
private final String getMessage() {
return message;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T17:36:05.487",
"Id": "75907",
"Score": "1",
"body": "Personally I'd find this a little difficult to give much of a review on. My first reaction is that your tests a bit brittle because they depend on the exact format of the output, for example. But it's such a contrived, 'toy' application that I'd find it hard to say what good tests are. I'd suggest you build something a little larger and closer resembling a real application to get a good review. One thing I would say though is don't add pointless comments to methods. It's actually a violation of Don't Repeat Yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:44:12.367",
"Id": "76024",
"Score": "0",
"body": "Thanks for your comments. The intent of the example is to sort of bridge the typical \"hello world\" into a real world example. With that intent, I missed the mark. Comments are over done. Real world I wouldn't comment private methods or fields unless there was a need. I will corrected that."
}
] | [
{
"body": "<p>Having tests is great (I'd love to see more questions with tests), keep it up! Other parts I would keep simpler.</p>\n\n<ol>\n<li><p>You <em>might</em> want this as a tag in your <a href=\"https://en.wikipedia.org/wiki/Revision_control\" rel=\"nofollow noreferrer\">revision control system</a> instead of commenting:</p>\n\n<blockquote>\n<pre><code>* @version 1.0.0 - Mar 9, 2014\n</code></pre>\n</blockquote>\n\n<p>This is also in the revision control history, so it's <em>usually</em> unnecessary:</p>\n\n<blockquote>\n<pre><code>* @author mhemphill\n</code></pre>\n</blockquote>\n\n<p>See: <a href=\"https://stackoverflow.com/q/5584577/843804\">Pros and cons of versioning javadoc</a></p></li>\n<li><p>I would not want to maintain comments on test methods like this:</p>\n\n<blockquote>\n<pre><code>/**\n * Test method for \n * {@link com.getgnosis.tutorials.tutorial01001.AdvancedHelloWorld\n * #toString()}.\n */\n@Test\npublic void testToString() {\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>I don't see why would it be useful. I haven't seen anyone who likes reading javadoc of test classes instead of the test code directly. The name of the method is good, it contains the main point: it's a test for <code>toString</code>, keep that and remove the superfluous comment.</p></li>\n<li><blockquote>\n<pre><code>@Test\npublic void testMain() {\n final ByteArrayOutputStream outContent = new ByteArrayOutputStream();\n System.setOut(new PrintStream(outContent));\n AdvancedHelloWorld.main(null);\n assertEquals(\"Hello World!\" + System.getProperty(\"line.separator\"), outContent.toString());\n System.setOut(null);\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>System.setOut(null)</code> statements should be in an <code>@After tearDown</code> method or at least in a <code>finally</code> block. If the <code>assertEquals</code> throws an exception (or something else) <code>out</code> won't be set back.</p></li>\n<li><p>I the same <code>testMain</code> method I'd create a local variable for the expected result:</p>\n\n<pre><code>final String expected = \"Hello World!\" + System.getProperty(\"line.separator\");\nassertEquals(expected, outContent.toString());\n</code></pre>\n\n<p>It's easier to read. (<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><blockquote>\n<pre><code>@Test\npublic void testAdvancedHelloWorld() {\n try {\n new AdvancedHelloWorld();\n } catch (Exception e) {\n fail(\"Construction failed. \");\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The following is the same:</p>\n\n<pre><code>@Test\npublic void testAdvancedHelloWorld() {\n new AdvancedHelloWorld();\n}\n</code></pre>\n\n<p>If the constructor throws an exception (or anything inside a <code>@Test</code> method) JUnit will tell you.</p></li>\n<li><p>This comments does not say anything which isn't in the code already, I'd remove it:</p>\n\n<blockquote>\n<pre><code>/**\n * The default constructor. Initializes the value of message via the static\n * block.\n */\n</code></pre>\n</blockquote>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><blockquote>\n<pre><code>static {\n message = \"Hello World!\";\n}\n\n/**\n * The {@link String} instance representing the message to be displayed.\n */\nprivate final static String message;\n</code></pre>\n</blockquote>\n\n<p>The following is the same:</p>\n\n<pre><code>private final static String message = \"Hello World!\";\n</code></pre>\n\n<p>I would keep it simple.</p></li>\n<li><blockquote>\n<pre><code>@Override\npublic String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"AdvancedHelloWorld [\");\n if (getMessage() != null)\n builder.append(\"message=\").append(getMessage());\n builder.append(\"]\");\n return builder.toString();\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>if</code> condition can't be <code>false</code> (the <code>message</code> field is <code>final</code> and has a non-null value), so the following is the same:</p>\n\n<pre><code>StringBuilder builder = new StringBuilder();\nbuilder.append(\"AdvancedHelloWorld [\");\nbuilder.append(\"message=\").append(getMessage());\nbuilder.append(\"]\");\nreturn builder.toString();\n</code></pre></li>\n<li><p>I'd move the <code>main</code> method to a separate class. It's usually a good idea to separate a class from its clients.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:39:11.003",
"Id": "75920",
"Score": "1",
"body": "+1 for most things, but item 1 I disagree with.... strongly, and 6 is only half-the-problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:42:01.553",
"Id": "75923",
"Score": "1",
"body": "To add my 2 cents, I agree with 1. For 2., though, I don't think the test naming scheme would actually be good for larger applications. I prefer the style where the name is a statement, something like toStringShouldReturnMessage or just toStringReturnsMessage. 'testFoo' doesn't tell you much, and would stop working if your tests depended on, for example, parameters passed into Foo."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:42:08.147",
"Id": "75924",
"Score": "0",
"body": "@rolfl: Agree, #1 isn't a strong point, the keywords are \"might\" and \"usually\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:20:28.663",
"Id": "76018",
"Score": "1",
"body": "I'm thankful for the thought you put into this review. I have implemented many of your ideas into the sample. The intent of the example is to bridge the gap between the typical \"Hello World\" and a more \"Real World\" program. With that goal in mind I did miss the mark a bit."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:14:02.617",
"Id": "43873",
"ParentId": "43868",
"Score": "12"
}
},
{
"body": "<p>Despite my comment, I'll try to give a bit of a review. It is difficult though - a Hello World application will never need to be extended, and has such an extremely simple function that it's very hard to distinguish between a good and bad test. </p>\n\n<p><strong>Unnecessary comments</strong></p>\n\n<p>Generally, for comments within methods, I view them as a last resort. If I have to add a comment, it means the code itself isn't readable, which I treat as a code smell.</p>\n\n<p>For Javadoc comments, I'm a bit looser. It's often just plain not possible to communicate everything you need to in a message signature. Having said that, there is such a thing as too much here too. If you write something that's just a simple restatement of what's already available in the signature, you're repeating yourself. As violations of the Don't Repeat Yourself principle go, it's a relatively benign one, but it's still a waste of everyone's time, and still means that you now have two places to maintain if that signature changes, rather than one.</p>\n\n<p>So for example in your code you have:</p>\n\n<pre><code>/**\n * Returns {@link String} instance representing the message to be displayed. \n * \n * @return message - {@link String} instance representing the message to \n * be displayed.\n */\nprivate final String getMessage() {\n return message;\n}\n</code></pre>\n\n<p>Is any of this necessary? You don't need to say it's a string, it's right there in the signature. And everyone knows what a string is so linking to it is useless. The name 'getMessage' already says that you're getting a message, so writing that again in the comment is pointless. I suppose you've added the information that this is the message \"to be displayed\", but that's rather vague, coming to this code for the first time it wouldn't tell me anything unless I then went and read the rest of the class. If you really think it's important to communicate the information that the message is being displayed, you could rename the variable and the corresponding <code>get</code> method instead.</p>\n\n<p>And finally, the overall summary and the <code>@returns</code> part again say exactly the same thing.</p>\n\n<p>This is a trap I fell into a lot myself. You think \"Well, I have to write <em>something</em> for the Javadoc.\" But you really don't! If you have nothing to say there, say nothing.</p>\n\n<p><strong>Use of static</strong></p>\n\n<p>This is where we get into \"difficult to review because it's such a simple application\" territory. Because you're basically done now, you're not going to extend this or use it in a larger application or anything, there's nothing really wrong with using a static message as you have. So I'll try to talk about why, in a more general situation, it might not be a good idea.</p>\n\n<p>Essentially I don't really know why you'd make the message static and everything else instance. Why not get rid of your static message field altogether and just have:</p>\n\n<pre><code>private final String getMessage() {\n return \"Hello World!\";\n}\n</code></pre>\n\n<p>It's less code, just as readable, and no less flexible or extensible than what you have.</p>\n\n<p>If you imagine some possible extensions to this class- maybe pass a second string into the constructor which would get added onto the end of your \"Hello World!\" message, or a public <code>reverseMessage()</code>, you'll quickly realise it either makes sense for all of it to be static or none of it. If there were going to be multiple <code>AdvancedHelloWorld</code> instances, there's no reason they'd all want to be looking at the same <code>message</code> string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:19:20.113",
"Id": "76034",
"Score": "0",
"body": "Thanks again. Your spot-on with my intent. Too many \"fake\" comments, I totally agree. The use of the static tantalizer block was bad idea, although I did keep the field as a field because it better lead to the next example on java simple types."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:17:59.087",
"Id": "43876",
"ParentId": "43868",
"Score": "11"
}
},
{
"body": "<p>This must be one of the most complicated <code>Hello World!</code> implementations I have seen in a while.</p>\n<p>I object to this being called a hello-world problem at all... <a href=\"http://en.wikipedia.org/wiki/Hello_world_program\" rel=\"noreferrer\">by definition (wikipedia)</a> a hello world program is supposed to illustrate the simplest way to do it.... and is not supposed to be used to illustrate complex processes. I would call your program, and the text it outputs, as something else.... based on what you are trying to teach... but I can't figure out what that is. Are you using this as an example of:</p>\n<ul>\n<li>Code Style</li>\n<li>static initializers</li>\n<li>JUnit testing</li>\n<li>StringBuilder usage</li>\n<li>getters ...</li>\n</ul>\n<p>because I cannot figure it out.</p>\n<h2>Code Style</h2>\n<p>All <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"noreferrer\">static-final fields should have CAPITAL names</a>.</p>\n<p>The static field should be:</p>\n<pre><code> private final static String MESSAGE; \n</code></pre>\n<h2>Static initializer block</h2>\n<p>As an example of a static initializer, I don't like it...</p>\n<p>it may not make sense off-hand, but static initialize blocks should appear <em>after</em> the declaration for the variables they declare.</p>\n<p>The order of <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4\" rel=\"noreferrer\">execution of a static initializer is complicated</a>, and the best way to ensure it works is to write it out in the same order that you would expect it to run. In your case the code works, but, in more complicated cases, your code may not work.... for example, what would you expect the following code to output?</p>\n<pre><code>public class StaticBlocks {\n \n static String hello;\n static String bilbo = "junk";\n\n static {\n hello = "Hello";\n bilbo = "Bilbo";\n baggins = "Baggins";\n }\n\n static String baggins = "junk";\n\n\n public static void main(String[] args) {\n System.out.println("Output: " + hello + " " + bilbo + " " + baggins);\n }\n \n}\n</code></pre>\n<p>If you expected <code>Output: Hello Bilbo Baggins</code>, then you would be wrong..... because the output is <code>Output: Hello Bilbo junk</code>.</p>\n<p>To avoid static initializer surprises I strongly recommend:</p>\n<ul>\n<li>don't do them at all.... (there are some exceptions), instead have static methods that produce the right results if you have complicated values to initialize.</li>\n<li>always structure the code as declarations first, followed by initializer static blocks so that the static block runs after any other initialization is done.</li>\n</ul>\n<h2>Junit Testing</h2>\n<p>Testing a main method is not something I have seen before. Interesting.</p>\n<p>On the other hand, in this case, why? You should be testing the <code>toString()</code> method and the <code>getMessage()</code> method. You are not testing <code>getMessage()</code> directly at all, but relying on main to do that test work for you.</p>\n<p>also, re-assigning the System.out is a really bad idea. If the test <em>does</em> fail, you don't complete the re-assign. Also, it is not thread-safe, and leaving System.out as null is not exactly friendly..... :(</p>\n<h2>StringBuilder usage</h2>\n<p>Others have suggested there is no reason for the null-check on the get-message.</p>\n<p>I agree, there is no reason/way for the getMessage() to return null... and, why are you calling it twice? You should just kill the null-check.</p>\n<h2>getters</h2>\n<p>Why do you have an instance getter that retrieves a static field? This is broken.</p>\n<p>The method is private, and it returns a static constant field. The method should not exist at all, and all references to <code>getMessage()</code> should be replaced with <code>MESSAGE</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:14:59.940",
"Id": "76032",
"Score": "0",
"body": "Awesome, thanks for the input. I agree, the static block serves not purpose in the scope of this example, and I will remove it. Didn't test getMessage() because we generally test private methods via public interfaces. The toString and existence of the getMessage() method are leads into the next example in the series. A introduction to java simple types that will also serve as a hibernate DTO(overriding equals and hashcode correctly, using getters for access, ...)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T19:40:17.113",
"Id": "43881",
"ParentId": "43868",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "43873",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:58:10.613",
"Id": "43868",
"Score": "10",
"Tags": [
"java",
"unit-testing",
"junit"
],
"Title": "Simple Hello World with unit tests"
} | 43868 |
<p><a href="https://github.com/syb0rg/parcel">I've created a JSON parsing library in C</a>, and would like some feedback on it (feel free to submit a pull request on GitHub). Any and all suggestions are acceptable, but I would prefer if reviews were focused on making this more efficient.</p>
<p>My header file:</p>
<pre><code>#ifndef _json_H_
#define _json_H_
/**
* JSON type identifier. Basic types are:
* o Object
* o Array
* o String
* o Other primitive: number, boolean (true/false) or null
*/
typedef enum { JSON_PRIMITIVE, JSON_OBJECT, JSON_ARRAY, JSON_STRING } JsonType;
typedef enum
{
JSON_ERROR_NOMEM = -1, // Not enough tokens were provided
JSON_ERROR_INVAL = -2, // Invalid character inside JSON string
JSON_ERROR_PART = -3, // The string is not a full JSON packet, more bytes expected
JSON_SUCCESS = 0 // Everthing is fine
} JsonError;
/**
* JSON token description.
* @param type type (object, array, string etc.)
* @param start start position in JSON data string
* @param end end position in JSON data string
*/
typedef struct
{
JsonType type;
int start;
int end;
int size;
#ifdef json_PARENT_LINKS
int parent;
#endif
} JsonToken;
/**
* JSON parser. Contains an array of token blocks available. Also stores
* the string being parsed now and current position in that string
*/
typedef struct
{
unsigned int pos; /* offset in the JSON string */
unsigned int toknext; /* next token to allocate */
int toksuper; /* superior token node, e.g parent object or array */
} JsonParser;
/**
* Create JSON parser over an array of tokens
*/
void json_initJsonParser(JsonParser *parser);
/**
* Run JSON parser. It parses a JSON data string into and array of tokens, each describing
* a single JSON object.
*/
JsonError json_parseJson(JsonParser *parser, const char *js, JsonToken *tokens, unsigned int tokenNum);
#endif /* _json_H_ */
</code></pre>
<p>My C source code:</p>
<pre><code>/**
* @file json.c
* @brief JSON Parser
*/
#include <stdlib.h>
#include "json.h"
/**
* @fn static JsonToken *json_allocJsonToken(JsonParser *parser, JsonToken *tokens, size_t tokenNum)
* @brief Allocates a fresh unused token from the token pull.
* @param parser
* @param tokens
* @param tokenNum
*/
static JsonToken *json_allocJsonToken(JsonParser *parser, JsonToken *tokens, size_t tokenNum)
{
if (parser->toknext >= tokenNum) return NULL;
JsonToken *tok = &tokens[parser->toknext++];
tok->start = tok->end = -1;
tok->size = 0;
#ifdef json_PARENT_LINKS
tok->parent = -1;
#endif
return tok;
}
/**
* @fn static void json_fillToken(JsonToken *token, JsonType type, int start, int end)
* @brief Fills token type and boundaries.
* @param token
* @param type
* @param start
* @param end
*/
static void json_fillToken(JsonToken *token, JsonType type, int start, int end)
{
token->type = type;
token->start = start;
token->end = end;
token->size = 0;
}
/**
* @fn static JsonError json_parsePrimitive(JsonParser *parser, const char *js, JsonToken *tokens, size_t num_tokens)
* @brief Fills next available token with JSON primitive.
* @param parser
* @param js
* @param tokens
* @param num_tokens
*/
static JsonError json_parsePrimitive(JsonParser *parser, const char *js, JsonToken *tokens, size_t num_tokens)
{
JsonToken *token;
int start;
start = parser->pos;
for (; js[parser->pos] != '\0'; parser->pos++)
{
switch (js[parser->pos])
{
#ifndef json_STRICT
/* In strict mode primitive must be followed by "," or "}" or "]" */
case ':':
#endif
case '\t':
case '\r':
case '\n':
case ' ':
case ',':
case ']':
case '}':
goto found;
}
if (js[parser->pos] < 32 || js[parser->pos] >= 127)
{
parser->pos = start;
return JSON_ERROR_INVAL;
}
}
#ifdef json_STRICT
/* In strict mode primitive must be followed by a comma/object/array */
parser->pos = start;
return JSON_ERROR_PART;
#endif
found:
token = json_allocJsonToken(parser, tokens, num_tokens);
if (!token)
{
parser->pos = start;
return JSON_ERROR_NOMEM;
}
json_fillToken(token, JSON_PRIMITIVE, start, parser->pos);
#ifdef json_PARENT_LINKS
token->parent = parser->toksuper;
#endif
parser->pos--;
return JSON_SUCCESS;
}
/**
* @fn static JsonError json_parseString(JsonParser *parser, const char *js, JsonToken *tokens, size_t num_tokens)
* @brief Fills next token with JSON string.
* @param parser
* @param js
* @param tokens
* @param num_tokens
*/
static JsonError json_parseString(JsonParser *parser, const char *js, JsonToken *tokens, size_t num_tokens)
{
JsonToken *token;
int start = parser->pos;
parser->pos++;
/* Skip starting quote */
for (; js[parser->pos] != '\0'; parser->pos++)
{
char c = js[parser->pos];
/* Quote: end of string */
if (c == '\"')
{
token = json_allocJsonToken(parser, tokens, num_tokens);
if (!token)
{
parser->pos = start;
return JSON_ERROR_NOMEM;
}
json_fillToken(token, JSON_STRING, start+1, parser->pos);
#ifdef json_PARENT_LINKS
token->parent = parser->toksuper;
#endif
return JSON_SUCCESS;
}
/* Backslash: Quoted symbol expected */
if (c == '\\')
{
parser->pos++;
switch (js[parser->pos])
{
/* Allowed escaped symbols */
case '\"':
case '/':
case '\\':
case 'b':
case 'f':
case 'r':
case 'n':
case 't':
break;
/* Allows escaped symbol \uXXXX */
case 'u':
/// \todo handle JSON unescaped symbol \\uXXXX
break;
/* Unexpected symbol */
default:
parser->pos = start;
return JSON_ERROR_INVAL;
}
}
}
parser->pos = start;
return JSON_ERROR_PART;
}
/**
* @fn JsonError json_parseJson(JsonParser *parser, const char *js, JsonToken *tokens, unsigned int num_tokens)
* @brief Parse JSON string and fill tokens.
* @param parser
* @param js
* @param tokens
* @param num_tokens
*/
JsonError json_parseJson(JsonParser *parser, const char *js, JsonToken *tokens, unsigned int num_tokens)
{
JsonError r;
int i;
JsonToken *token;
for (; js[parser->pos] != '\0'; parser->pos++)
{
char c;
JsonType type;
c = js[parser->pos];
switch (c)
{
case '{':
case '[':
token = json_allocJsonToken(parser, tokens, num_tokens);
if (!token) return JSON_ERROR_NOMEM;
if (parser->toksuper != -1)
{
tokens[parser->toksuper].size++;
#ifdef json_PARENT_LINKS
token->parent = parser->toksuper;
#endif
}
token->type = (c == '{' ? JSON_OBJECT : JSON_ARRAY);
token->start = parser->pos;
parser->toksuper = parser->toknext - 1;
break;
case '}':
case ']':
type = (c == '}' ? JSON_OBJECT : JSON_ARRAY);
#ifdef json_PARENT_LINKS
if (parser->toknext < 1) return JSON_ERROR_INVAL;
token = &tokens[parser->toknext - 1];
for (;;)
{
if (token->start != -1 && token->end == -1)
{
if (token->type != type) return JSON_ERROR_INVAL;
token->end = parser->pos + 1;
parser->toksuper = token->parent;
break;
}
if (token->parent == -1) break;
token = &tokens[token->parent];
}
#else
for (i = parser->toknext - 1; i >= 0; i--)
{
token = &tokens[i];
if (token->start != -1 && token->end == -1)
{
if (token->type != type) return JSON_ERROR_INVAL;
parser->toksuper = -1;
token->end = parser->pos + 1;
break;
}
}
/* Error if unmatched closing bracket */
if (i == -1) return JSON_ERROR_INVAL;
for (; i >= 0; i--)
{
token = &tokens[i];
if (token->start != -1 && token->end == -1)
{
parser->toksuper = i;
break;
}
}
#endif
break;
case '\"':
r = json_parseString(parser, js, tokens, num_tokens);
if (r < 0) return r;
if (parser->toksuper != -1) tokens[parser->toksuper].size++;
break;
case '\t':
case '\r':
case '\n':
case ':':
case ',':
case ' ':
break;
#ifdef json_STRICT
/* In strict mode primitives are: numbers and booleans */
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 't':
case 'f':
case 'n':
#else
/* In non-strict mode every unquoted value is a primitive */
default:
#endif
r = json_parsePrimitive(parser, js, tokens, num_tokens);
if (r < 0) return r;
if (parser->toksuper != -1) tokens[parser->toksuper].size++;
break;
#ifdef json_STRICT
/* Unexpected char in strict mode */
default:
return JSON_ERROR_INVAL;
#endif
}
}
for (i = parser->toknext - 1; i >= 0; i--)
{
/* Unmatched opened object or array */
if (tokens[i].start != -1 && tokens[i].end == -1) return JSON_ERROR_PART;
}
return JSON_SUCCESS;
}
/**
* @fn void json_initJsonParser(JsonParser *parser)
* @brief Creates a new parser based over a given buffer with an array of tokens available.
* @param parser
*/
void json_initJsonParser(JsonParser *parser)
{
parser->pos = 0;
parser->toknext = 0;
parser->toksuper = -1;
}
</code></pre>
| [] | [
{
"body": "<p>I think the code looks pretty tidy. Not sure if you can get a huge speed up - you are effectively tokenizing a string by storing the meta data of the tokens (start/end positions and type). This alleviates the pain of having to copy the data and dealing with the associated memory allocation issue.</p>\n\n<p>A few remarks:</p>\n\n<ol>\n<li><p>You could consider changing the token to store a <code>const char * start</code> and a <code>size_t length</code> instead where <code>start</code> points to the first char of the token in the input. This way you can work on the data of the token without having to also pass around a reference to the original string.</p></li>\n<li><p>You have documentation for your methods but you don't really document the parameters - what they are for, what their invariants are etc.</p></li>\n<li><p>For general use the interface is probably too inconvenient - you pretty much need to know how many tokens to expect before parsing (or do the old <code>parse - fail - double memory - try again</code> dance) which could be hard to keep track of. As a user I might know what kind of object I want to parse but I'd be hard pressed to know exactly up front how many json tokens I'd need.</p></li>\n<li><p><code>goto</code> is generally frowned upon. While you use it in a fairly straight forward way that's easy to follow I'm almost certain that rewriting the code with a <code>gotValidToken</code> token flag to terminate the loop instead could potentially increase readability. The <code>goto</code> forces you to jump around while reading the code. </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T07:06:01.243",
"Id": "43907",
"ParentId": "43872",
"Score": "11"
}
},
{
"body": "<h3>What you did well</h3>\n\n<ol>\n<li>As far as I can tell, the code produces correct output when given correct input.</li>\n<li>The functions feel like a coherent library, with consistent function names and logical order of parameters.</li>\n<li>You use a caller-owns-everything memory management policy, which works well for C.</li>\n</ol>\n\n<h3>What you could improve on</h3>\n\n<ol>\n<li>The name <code>json_initJsonParser()</code> is a bit redundant. <code>json_initParser()</code> should suffice.</li>\n<li>I don't think that <code>#ifdef json_PARENT_LINKS</code> is a good idea. A user could easily compile the library without support for parent links, yet compile the application with <code>json_PARENT_LINKS</code> defined, leading to nasty bugs. Why not always enable support parent links? It would be pretty difficult to make sense of the parser output without it.</li>\n<li>I think that <code>#ifdef json_STRICT</code> would be better as a runtime option rather than a compile-time option. If the user wants to have both modes available, there's no reasonable way to do so.</li>\n<li>JSON primitives may be numbers, <code>true</code>, <code>false</code>, or <code>null</code>. You accept illegal primitives such as <code>truthy</code>.</li>\n<li><code>json_allocJsonToken()</code> doesn't \"allocate\" memory in the sense that I expect. Also, two of the three calls to <code>json_allocJsonToken()</code> are followed by <code>json_fillToken()</code>, so you might as well combine the two functions. Filling in dummy values first is senseless.</li>\n<li>In the <code>JsonParser</code> structure, <code>toknext</code> and <code>toksuper</code> should be the same data type. It's weird that one is unsigned and the other is signed. I recommend just using <code>int</code> for both, or possibly <a href=\"https://stackoverflow.com/q/19224655/1157100\"><code>ssize_t</code></a>.</li>\n<li><p>It is not obvious that the way to extract the results is to use a loop like</p>\n\n<pre><code>for (int i = 0; i < parser.toknext; i++) {\n // ^^^^^^^^^^^^^^\n}\n</code></pre>\n\n<p>Please feel free to add some generous comments with usage examples in the header file.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-16T18:18:23.760",
"Id": "177714",
"Score": "0",
"body": "I don't think using `ssize_t` is a good idea since that would tie the library to POSIX. It's range isn't intuitive either: the only negative value it has to be able to hold is -1 (see [this answer](http://stackoverflow.com/a/19224809/2073469) in the question you linked)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T08:55:04.533",
"Id": "43915",
"ParentId": "43872",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "43915",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:11:23.287",
"Id": "43872",
"Score": "23",
"Tags": [
"performance",
"c",
"parsing",
"json",
"library"
],
"Title": "parcel: a JSON parsing library in C"
} | 43872 |
<p>Sparkling is a new, lightweight, dynamic extension language. It combines elements from C, Lua, Python and JavaScript. The reference implementation is hosted on GitHub, at <a href="https://github.com/H2CO3/Sparkling" rel="nofollow">H2CO3/Sparkling</a>.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:15:51.123",
"Id": "43874",
"Score": "0",
"Tags": null,
"Title": null
} | 43874 |
Sparkling is a lightweight, dynamic extension language.
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:15:51.123",
"Id": "43875",
"Score": "0",
"Tags": null,
"Title": null
} | 43875 |
<p>After reading <a href="https://codereview.stackexchange.com/questions/43893/first-real-world-f-application-how-good-idiomatic-is-it-long?stw=2">this question</a>, I've realized that I can do a lot to improve the quality of my question, so I've edited this question quite a bit.</p>
<p>I've been teaching myself F# in my spare time off and on for the last 6 months. I've finally started getting comfortable enough with the language to feel that a lot of my code could be much better. The problem is, I don't know what changes to make.</p>
<p>Here's what I'm interested in:</p>
<ul>
<li>I'm using higher order functions to return functions for interacting with a specific message queue. Is this a good design. Would another F# developer feel comfortable with this?</li>
<li>Does this fit the idiomatic style of F#?</li>
<li>If you know RabbitMQ, are there any bugs which I may be creating here.</li>
</ul>
<p>Here's the context of the little block of code:</p>
<p>I'm doing a lot of experiments with messaging systems and I've been using RabbitMQ as a messaging framework. There's a .Net library for RabbitMQ but it's written in and for C#. I can use it in F# but it feels clunky. I wanted a small wrapper around the RabbitMQ library which which convert it into a more functional interface. Also, this will hopefully make it very easy to use RabbitMQ in an F# program. </p>
<p>My wrapper handles the following for RabbitMQ:</p>
<ol>
<li>Connect to a RabbitMQ server</li>
<li>Create a function which will let you read one message from a queue</li>
<li>Create a function which will write a message to a queue</li>
<li><p>For both 2 and 3, if the queue doesn't exist, the queue will be created (that's the <code>declareQueue</code>)</p>
<pre><code>module Client =
let connectToRabbitMqServerAt address =
let factory = new ConnectionFactory(HostName = address)
factory.CreateConnection()
let openChannelOn (connection:IConnection) = connection.CreateModel()
let private declareQueue (channel:IModel) queueName =
channel.QueueDeclare( queueName, false, false, false, null )
let private publishToQueue (channel:IModel) queueName (message:string) =
let body = Encoding.UTF8.GetBytes(message)
channel.BasicPublish("", queueName, null, body)
let createQueueReader channel queue =
declareQueue channel queue |> ignore
fun () ->
let ea = channel.BasicGet(queue, true)
if ea <> null then
let body = ea.Body
let message = Encoding.UTF8.GetString(body)
Some message
else
None
let createQueueWriter channel queue =
declareQueue channel queue |> ignore
publishToQueue channel queue
</code></pre></li>
</ol>
<p>An example use case would be:</p>
<pre><code>// open a connection to a RabbitMQ broker
let connection = connectToRabbitMqServerAt "localhost"
let myChannel = openChannelOn connection
// Connect to a queue for writing
let writeToHelloQueue = createQueueWriter myChannel "hello"
// write the message "Hello, World" to the queue "hello"
"Hello, World" |> writeToHelloQueue
</code></pre>
| [] | [
{
"body": "<p>Overall, this code looks very good. Just two nitpicks here:</p>\n\n<ol>\n<li>Give your function definitions lines to themselves:</li>\n</ol>\n\n<blockquote>\n<pre><code>let openChannelOn (connection:IConnection) = connection.CreateModel()\n</code></pre>\n</blockquote>\n\n<ol start=\"2\">\n<li>Use <code>match</code> statements unless you are checking a boolean value directly:</li>\n</ol>\n\n\n\n<blockquote>\n<pre><code>if ea <> null then\n let body = ea.Body\n let message = Encoding.UTF8.GetString(body)\n Some message\nelse\n None\n</code></pre>\n</blockquote>\n\n<p>Becomes:</p>\n\n<pre><code>match ea with\n| null -> None\n| _ ->\n let body = ea.Body\n let message = Encoding.UTF8.GetString(body)\n Some message\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-31T16:56:52.487",
"Id": "151354",
"ParentId": "43880",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "151354",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T19:03:14.130",
"Id": "43880",
"Score": "8",
"Tags": [
"beginner",
"f#"
],
"Title": "Simple RabbitMQ client wrapper"
} | 43880 |
<pre><code>/*
* LinkedList.h
*
* Created on: Mar 9, 2014
* Author: steven
*/
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <iostream>
using std::cout;
using std::endl;
template<class T>
class LinkedList {
template<class E>
struct Node {
Node<E> *rightNode;
E data;
Node() {
rightNode = NULL;
}
};
private:
Node<T> *startNode;
int size;
public:
LinkedList() {
startNode = NULL;
size = 0;
}
void pushFront(T data) {
if (size > 0) {
Node<T> *temp = new Node<T>();
temp->data = data;
temp->rightNode = startNode;
startNode = temp;
size++;
return;
}
pushBack(data);
}
void pushBack(T data) {
if (size > 0) {
Node<T> *temp = startNode;
for (int i = 0; i < size - 1; i++) {
temp = temp->rightNode;
}
temp->rightNode = new Node<T>();
temp->rightNode->data = data;
size++;
return;
}
startNode = new Node<T>();
startNode->data = data;
size++;
}
T get(int num) {
if (num > 0) {
Node<T> * temp = startNode; //1
for (int i = 0; i < num - 1; i++) {
temp = temp->rightNode;
}
T tempData = temp->rightNode->data;
delete temp;
return tempData;
} else {
return startNode->data;
}
}
void removeBack() {
if (size > 2) {
Node<T> *temp = startNode;
for (int i = 0; i < size - 2; i++) {
temp = temp->rightNode;
}
delete temp->rightNode;
temp->rightNode = NULL;
} else if (size == 2) {
delete startNode->rightNode;
startNode->rightNode = NULL;
} else {
delete startNode;
startNode = NULL;
}
size--;
}
void printLinkedList() {
Node<T> *temp = startNode;
cout << temp->data << endl;
for (int i = 0; i < size - 1; i++) {
temp = temp->rightNode;
cout << temp->data << endl;
}
}
int getSize() {
return size;
}
virtual ~LinkedList() {
if (size > 2) {
Node<T> *temp = startNode;
while (temp->rightNode->rightNode != NULL) {
Node<T> *currentTemp = temp;
temp = temp->rightNode;
delete currentTemp;
}
return;
}
if (size == 1) {
delete startNode;
return;
}
if (size == 2) {
delete startNode->rightNode;
delete startNode;
return;
}
}
};
#endif /* LINKEDLIST_H_ */
</code></pre>
<p>Please critique the singly linked list, specifically the working aspect of it (making sure deleting correctly, etc.).</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T22:30:21.733",
"Id": "75939",
"Score": "1",
"body": "One quick thing I've noticed: `getSize()` should be `const`. I also see that this wasn't corrected from your previous question. You should ideally be showing some improvement with each question asked."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T22:49:40.163",
"Id": "75940",
"Score": "0",
"body": "There is apparently no need for `Node` to be templated: you only use `Note<T>` everywhere."
}
] | [
{
"body": "<h3>Bugs</h3>\n\n<p>For a header-only library, <code>using std::cout</code> and <code>using std::endl</code> are unacceptable side effects.</p>\n\n<p>The <code>LinkedList<T>::Node<E></code> class should just be <code>LinkedList<T>::Node</code>, and it should be private.</p>\n\n<p><code>get(int)</code>, <code>printLinkedList()</code>, and <code>getSize()</code> should be <code>const</code> methods.</p>\n\n<p><code>get(int)</code> should not call <code>delete</code>. There's no corresponding <code>new</code>, and furthermore it should be a read-only operation.</p>\n\n<h3>Style</h3>\n\n<p>Instead of a <code>printLinkedList()</code> method, define an operator that allows the list to be sent to any <code>std::ostream</code>:</p>\n\n<pre><code>friend std::ostream &operator<<(std::ostream &out, const LinkedList<T> &list) {\n Node *temp = list.startNode;\n out << temp->data << std::endl;\n for (int i = 1; i < list.size; i++) {\n temp = temp->rightNode;\n out << temp->data << std::endl;\n }\n return out;\n}\n</code></pre>\n\n<p>You shouldn't need more than one base case in <code>removeBack()</code> and <code>~LinkedList()</code>. For example, <code>removeBack()</code> could be</p>\n\n<pre><code>void removeBack() {\n if (size == 1) {\n delete startNode;\n startNode = NULL;\n } else {\n Node *temp = startNode;\n for (int i = 2; i < size; i++) {\n temp = temp->rightNode;\n }\n delete temp->rightNode;\n temp->rightNode = NULL;\n }\n size--;\n}\n</code></pre>\n\n<p>In fact, nearly every one of your methods has a special case to handle an empty list. Not only is that tedious, it also doubles the number of tests you would have to write to get complete code coverage. It would be much more advantageous to use a \"dummy\" node as the head to eliminate all of those special cases.</p>\n\n<pre><code>#ifndef LINKEDLIST_H_\n#define LINKEDLIST_H_\n#include <iostream>\n\ntemplate<class T>\nclass LinkedList {\n\nprivate:\n struct Node {\n Node *rightNode;\n T data;\n Node() {\n rightNode = NULL;\n }\n };\n Node head;\n int size;\n\npublic:\n LinkedList() {\n size = 0;\n }\n\n void pushFront(T data) {\n Node *temp = new Node();\n temp->data = data;\n temp->rightNode = head.rightNode;\n head.rightNode = temp;\n size++;\n }\n\n void pushBack(T data) {\n Node *temp = &head;\n for (int i = 0; i < size; i++) {\n temp = temp->rightNode;\n }\n temp->rightNode = new Node();\n temp->rightNode->data = data;\n size++;\n }\n\n T get(int num) const {\n Node *temp = head.rightNode;\n for (int i = 0; i < num; i++) {\n temp = temp->rightNode;\n }\n return temp->data;\n }\n\n void removeBack() {\n Node *temp = &head;\n for (int i = 0; i < size; i++) {\n temp = temp->rightNode;\n }\n delete temp->rightNode;\n temp->rightNode = NULL;\n size--;\n }\n\n friend std::ostream &operator<<(std::ostream &out, const LinkedList<T> &list) {\n Node *temp = list.head.rightNode;\n for (int i = 0; i < list.size; i++) {\n out << temp->data << std::endl;\n temp = temp->rightNode;\n }\n return out;\n }\n\n int getSize() const {\n return size;\n }\n\n virtual ~LinkedList() {\n Node *temp = head.rightNode;\n for (int i = 0; i < size; i++) {\n Node *del = temp;\n temp = temp->rightNode;\n delete del;\n }\n }\n};\n\n#endif /* LINKEDLIST_H_ */\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:17:07.013",
"Id": "76017",
"Score": "0",
"body": "Will definitely consider dummy node."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T00:06:02.653",
"Id": "43894",
"ParentId": "43889",
"Score": "7"
}
},
{
"body": "<p>There seems to be an exception safety bug:</p>\n\n<p>If <code>T::operator=(T&)</code> throws in <code>LinkedList< T >::pushFront</code> you will leak a <code>Node< T ></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T07:33:02.783",
"Id": "43910",
"ParentId": "43889",
"Score": "3"
}
},
{
"body": "<p>When adding items to a list one of the most common operations is to add them to the back of the list. Your implementation makes that an <code>O(n)</code> operation while it should be <code>O(1)</code> - so consider keeping a tail pointer as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T07:58:14.530",
"Id": "43911",
"ParentId": "43889",
"Score": "2"
}
},
{
"body": "<p>When possible, use an initializer list:</p>\n\n<pre><code>Node() : rightNode()\n{ }\n</code></pre>\n\n<hr>\n\n<p>I don't think you're using C++11, but in case you are, use <code>nullptr</code>.</p>\n\n<hr>\n\n<p>Giving <code>Node</code> a full constructor would be very advantageous for simplifying a lot of boilerplate code.</p>\n\n<p>For example, everything like:</p>\n\n<pre><code>Node<T> *temp = new Node<T>();\ntemp->data = data;\ntemp->rightNode = startNode;\n</code></pre>\n\n<p>Could become a one liner:</p>\n\n<pre><code>Node* temp = new Node(data, startNode);\n</code></pre>\n\n<p>Also, a proper constructor avoids the exception safety problem that <code>user1703394</code> mentioned.</p>\n\n<p>Just for reference, the <code>Node</code> with a constructor would look like:</p>\n\n<pre><code>struct Node {\n T data;\n Node *rightNode;\n\n Node(const T& val, Node* rightNode) : data(val), rightNode(rightNode)\n { }\n};\n</code></pre>\n\n<p>Note that the member order was changed since it needs to match the initialization list order. Changing the order allowed the constructor to be more natural (since the constructor argument order should match the initialization list order).</p>\n\n<hr>\n\n<p>In C++, it's much more common to see <code>T* var</code> rather than <code>T *var</code>. It's just a stylistic qualm, but something to be aware of.</p>\n\n<hr>\n\n<p>You should have blank lines between your methods.</p>\n\n<hr>\n\n<p>A non-constant operator shouldn't exist on a list. If you can't provide it in constant time, don't provide it. It's very non-standard, and it's misleading to a consumer of the class. Note that the idiomatic way to expose the data is via a forward iterator.</p>\n\n<hr>\n\n<p>There's a grave lack of understanding of memory ownership in <code>get</code>. In particular, unless you want the ownership of the node to end, you should not be freeing it.</p>\n\n<p>As a general piece of advice, whenever you have doubts about memory management, consider using something like valgrind.</p>\n\n<hr>\n\n<p>Try to simplify your code down to a general case rather than having lots of special cases. As others have noted, a sentinel node can heavily simplify this. As a random note, if you do use a sentinel node, and you're concern about performance, try to not dynamically allocate it. That saves you an allocation on an empty list.</p>\n\n<hr>\n\n<p>Is <code>LinkedList</code> actually ever going to be extended (as implied by the virtual destructor)? Considering all of the properties are private and none of the methods (other than destructor) are virtual, there's not really a meaningful way that you can extend it.</p>\n\n<hr>\n\n<p>Don't use the implicit private visibility of classes. Everything should be in either a <code>public</code>, <code>private</code>, or <code>protected</code> block. (There's nothing technically wrong with it of course, it's just good to be consistent.) Note that this doesn't apply to structs. Structs are almost always only public, so there's no potential confusion.</p>\n\n<hr>\n\n<p>Be mindful of what can cause copies. In particular, <code>get</code> can cause an extra copy for no reason. <code>T tempData = temp->rightNode->data;</code> creates a copy, and then returning could, in theory--though never in practice--create a copy. If you just return directly, you can avoid a possible copy (though one will still have to happen).</p>\n\n<hr>\n\n<p>Better yet, should <code>get</code> really be returning a copy? You could be returning either a reference or const reference (depending on if either a const or non-const version of get is called) so that the caller can modify the data, or so that a needless copy can be avoided in the read-only situation.</p>\n\n<hr>\n\n<p>Your header stuff should have more spacing in it:</p>\n\n<pre><code>#ifndef LINKEDLIST_H_\n#define LINKEDLIST_H_\n\n#include <iostream>\n\nusing std::cout; // These should not be here!\nusing std::endl;\n</code></pre>\n\n<hr>\n\n<pre><code>#endif /* LINKEDLIST_H_ */\n</code></pre>\n\n<p>The comment is just useless noise unless you have a lot of nested directives. Considering you only have one, this comment is useless. Also, most modern IDEs make these types of comments useless even if there are a ton of directives since they can highlight the counterpart. (I'm of the school of thought that even without highlighting, if there's enough levels for the comments to be necessary, something is very, very wrong with the the structure of the code.)</p>\n\n<hr>\n\n<p>There's not a technical need to do so, but it's nice to try to be consistent with the standard library. This allows someone who is using your class for the first time to very intuitively pick up it's use. For example, I would expect <code>size()</code> rather than <code>getSize()</code>. I also might use <code>pop</code> instead of <code>remove</code>.</p>\n\n<hr>\n\n<p>Sometimes an <code>else</code> clause is less confusing than a hidden <code>return</code>, especially in void functions. For example, the following is much clearer to me:</p>\n\n<pre><code>void pushFront(T data) {\n if (size > 0) {\n Node<T> *temp = new Node<T>();\n temp->data = data;\n temp->rightNode = startNode;\n startNode = temp;\n size++;\n } else {\n pushBack(data);\n }\n}\n</code></pre>\n\n<p>I actually had to stop and pause for a long moment the first time I read through your code to make sure you weren't adding twice.</p>\n\n<hr>\n\n<p>There are a lot of const correctness issues in your code. Please look into it. The short explanation is that any time something is only being read, it should be accepted by const reference.</p>\n\n<hr>\n\n<p>Consider having each node own it's rightNode. This would mean that instead of a looping destructor, you could simple delete the head node and let the deletion cascade. This would work particularly well with a automatically allocated sentinel node since it would mean you could have a default destructor in the list.</p>\n\n<hr>\n\n<p>Sized based looping on a linked structure is rather rare. The standard way to do it is to loop on the pointers. In the situations you've used it though, the uses are arguably just as clear as the pointer case.</p>\n\n<hr>\n\n<p>Consider keeping a tail pointer. That lets you push and pop to/from the end in constant time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T08:29:40.047",
"Id": "43912",
"ParentId": "43889",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T22:17:04.390",
"Id": "43889",
"Score": "6",
"Tags": [
"c++",
"linked-list"
],
"Title": "Is this a proper singly linked list?"
} | 43889 |
<p>Every time I write a new PHP page, I usually need to include this at the top:</p>
<pre><code><?php
require_once(__DIR__ . '/../libraries/global.lib.php');
function load_classes($class) { // appears to get all the names of the classes that are needed in this script...
$file_name = './classes/' . $class . '.class.php';
if (file_exists($file_name)) {
require_once($file_name);
}
}
function load_interfaces($interface) {
$file_name = './classes/' . $interface . '.interface.php';
if (file_exists($file_name)) {
require_once($file_name);
}
}
spl_autoload_register('load_interfaces');
spl_autoload_register('load_classes');
?>
</code></pre>
<p>Is there any way to condense this? Would putting this in a separate PHP file work?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T01:07:42.557",
"Id": "75955",
"Score": "0",
"body": "Moving this to an include would work. You will have to be careful about paths like `__DIR__` since they apply directly to the file they are contained in."
}
] | [
{
"body": "<p>Yes, you could put that into a separate file and <code>include_once('header_file.php');</code>.</p>\n\n<p>You try something such as:</p>\n\n<pre><code>function loadFile($name, $isInterface = false) {\n $type = ($isInterface == true) ? 'interface' : 'class'\n $path = sprintf('./classes/%s.%s.php',$name,$type);\n if (file_exists($path)) {\n require_once($path);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T23:17:38.200",
"Id": "43892",
"ParentId": "43891",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "43892",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T22:59:05.067",
"Id": "43891",
"Score": "7",
"Tags": [
"php"
],
"Title": "Autoloader functions"
} | 43891 |
<p>After reading/watching various introductions and blog posts and some code here and there, doing a bit of the Try F# tutorial and starting to read "Real World Functional Programming", I felt I should be able to write a first small real-world application in F#.</p>
<p>In order to be able to concentrate on getting to grips with the language, I decided not to try and solve a new problem, but rather port an existing C# application to what I hope is tolerably idiomatic F#.</p>
<p>The "application" is a so-called "plugin" for Microsoft Dynamics CRM. (A plugin is an implementation of the <code>IPlugin</code> interface that is then registered to be called on certain platform operations, maybe best compared to a database trigger.)
For C# plugins, I have a base library for the general infrastructure stuff, while this particular plugin itself was (according to NCrunch) 613 lines of C# code. For the F# implementation, I decided not to use that other library, but rather reimplemented what I needed here in F# as well. The result was 68 lines of F# code for the plugin together with a new small F# library with 97 lines so far.</p>
<p>Porting the C# code wasn't that hard overall, because my SOLID classes pretty much map directly to functions. This would probably be much different for more "traditional" object-oriented code.</p>
<p>I have not been able to test it, but the code has become so concise and clear that I'm pretty sure it works; but that's not my main concern anyway.</p>
<p>I'm primarily interested in these things:</p>
<ul>
<li>How idiomatic is the F# code? I love the pattern matching and use any chance I can get to use it. Is that a good idea in all cases? What about naming of functions (some of those will certainly be odd, because I kept the class names from the C# version) and values? </li>
<li>For the composed functions that end up taking no parameter of their own (those were just classes with constructor injected dependencies and a read-only public property in C#), would it be more natural to get the result on the spot and pass that on rather than passing the function?</li>
<li>In my SOLID C# code, I build extensive object graphs via constructor injection, wired up using an IoC container in the application's composition root. I functional F# code, I have neither interfaces nor constructors, so I understand that constructor injection is essentially replaced by function composition, but I'm still unclear on how to do that in a real-world application in a way that is similarly maintainable and evolvable as what I have in C# with a composition root. I have posted an elaborate question on this <a href="https://stackoverflow.com/questions/22263779/application-architecture-composition-in-f">here</a> on Stack Overflow, so I won't repeat my further thoughts on that here, but I have employed what I described there as the "registry" in the <code>Composition</code> module. This is essentially a composition root using "poor man's DI" (as Mark Seemann calls it). Is this a good idea? What alternatives are there?</li>
</ul>
<p>This is the library:</p>
<pre><code>namespace Dymanix
module Mscrm =
open System
open Microsoft.Xrm.Sdk
open Microsoft.Xrm.Sdk.Messages
type CrmRecord =
| Entity of Entity
| Reference of EntityReference
type PluginMessage =
| Create
| Update
| Delete
| Other of string
type PreStage =
| PreValidation
| PreOperation
type Stage =
| Pre of PreStage
| PostOperation
type StepStage =
{ Message : PluginMessage
Stage : Stage }
type FullRecordImage = Entity
type TargetRecord = Entity
let MergeRecords (baseRecord : Entity) (toMerge : Entity) =
let mergeTarget = Microsoft.Xrm.Sdk.Entity(baseRecord.LogicalName, Id = baseRecord.Id)
toMerge.Attributes |> Seq.iter (fun att -> mergeTarget.[att.Key] <- att.Value)
mergeTarget
let GetMessage(context : IPluginExecutionContext) =
match context.MessageName with
| "Create" -> Create
| "Update" -> Update
| "Delete" -> Delete
| message -> Other(message)
let GetStage(context : IPluginExecutionContext) =
match context.Stage with
| 10 -> Pre(PreValidation)
| 20 -> Pre(PreOperation)
| 40 -> PostOperation
| _ -> failwith "Invalid plugin stage"
let GetStepStage(context : IPluginExecutionContext) =
{ Message = GetMessage context
Stage = GetStage context }
let GetTarget(context : IPluginExecutionContext) = context.InputParameters.["Target"] :?> TargetRecord
let GetFullRecordImage(context : IPluginExecutionContext) =
match GetStepStage context with
| { Message = Delete; Stage = _ } -> context.PreEntityImages.["Image"]
| { Message = Create; Stage = Pre(_) } -> GetTarget context
| { Message = Update; Stage = Pre(_) } -> MergeRecords context.PreEntityImages.["Image"] (GetTarget context)
| { Message = _; Stage = Pre(_) } -> context.PreEntityImages.["Image"]
| { Message = _; Stage = PostOperation } -> context.PostEntityImages.["Image"]
let DecomposeServiceProvider(serviceProvider : IServiceProvider) =
let organizationServiceFactory =
serviceProvider.GetService typeof<IOrganizationServiceFactory> :?> IOrganizationServiceFactory
let context = serviceProvider.GetService typeof<IPluginExecutionContext> :?> IPluginExecutionContext
let organizationService = organizationServiceFactory.CreateOrganizationService(System.Nullable(context.UserId))
let tracingService = serviceProvider.GetService typeof<ITracingService> :?> ITracingService
(context, organizationService, tracingService, organizationServiceFactory)
module Utility =
let GetPrimaryNameField (organizationService : IOrganizationService) entityName =
let request = RetrieveEntityRequest(LogicalName = entityName)
let response = organizationService.Execute(request) :?> RetrieveEntityResponse
response.EntityMetadata.PrimaryNameAttribute
let private getRecordName getPrimaryNameField (organizationService : IOrganizationService) record =
let reference =
match record with
| Entity(e) -> e.ToEntityReference()
| Reference(r) -> r
let primaryNameField = getPrimaryNameField organizationService reference.LogicalName
let entity =
match record with
| Entity(e) -> e
| Reference(r) ->
organizationService.Retrieve(r.LogicalName, r.Id, Query.ColumnSet([| primaryNameField |]))
string (entity.GetAttributeValue<string>(primaryNameField))
let GetRecordName(organizationService : IOrganizationService) =
getRecordName GetPrimaryNameField organizationService
</code></pre>
<p>And this is the plugin code - the actual "application":</p>
<pre><code>namespace SetClassificationIdentificationFields
open System
open Microsoft.Xrm.Sdk
open Microsoft.Xrm.Sdk.Messages
open System.Xml.Linq
open Dymanix.Mscrm
open Dymanix.Mscrm.Utility
module Domain =
let (!<>) name = XName.Get(name)
let NameAddedRegardingObject getRecordName (innerRegardingObject : unit -> EntityReference option) =
let reference = innerRegardingObject()
match reference with
| Some(record) ->
if Guid.Empty <> record.Id then record.Name <- getRecordName ((Reference(record)))
| _ -> ()
reference
let ListFindingRegardingObject regardingLookups (image : FullRecordImage) =
let existingLookups = regardingLookups() |> List.filter image.Contains
match existingLookups with
| [] -> None
| [ a ] -> Some(image.GetAttributeValue<EntityReference>(a))
| _ -> failwith "Only one parent lookup may contain data"
let ConfiguredRegardingLookups(configuration : XElement) =
configuration.Element(!<>"regardinglookups").Elements(!<>"lookup")
|> List.ofSeq
|> List.map (fun e -> e.Attribute(!<>"name").Value)
let AllRequiredAttributesArePresent(target : TargetRecord) =
[ "gcnm_recordid"; "gcnm_recordtype"; "gcnm_recordname" ] |> List.forall target.Contains
let SetClassificationIdentificationValues (target : TargetRecord) (reference : EntityReference option) =
match reference with
| Some(record) ->
target.["gcnm_recordname"] <- record.Name
target.["gcnm_recordtype"] <- record.LogicalName
target.["gcnm_recordid"] <- record.Id.ToString()
| None -> ()
let Main requiredAttributesArePresent getTarget regardingObject setValues =
if (not (requiredAttributesArePresent getTarget)) then setValues (regardingObject)
module Composition =
open Domain
let Compose serviceProvider configuration =
let (context, organizationService, _, _) = DecomposeServiceProvider serviceProvider
let configurationXml = XElement.Parse configuration
let getRecordName = GetRecordName organizationService
let regardingLookups() = ConfiguredRegardingLookups configurationXml
let listFindingRegardingObject() = ListFindingRegardingObject regardingLookups (GetFullRecordImage(context))
let regardingObject = NameAddedRegardingObject getRecordName listFindingRegardingObject
let setValues = SetClassificationIdentificationValues(GetTarget context)
let allAttributesPresent = AllRequiredAttributesArePresent
let main() = Main allAttributesPresent (GetTarget context) regardingObject setValues
main
module Plugin =
type Plugin(configuration) =
member this.Configuration = configuration
interface IPlugin with
member this.Execute serviceProvider =
let main = Composition.Compose serviceProvider this.Configuration
main()
</code></pre>
| [] | [
{
"body": "<p>Overall I think it's fine.</p>\n\n<p>A couple of suggestions that leap out, based on a quick scan.</p>\n\n<p>CAVEAT: This code was written in the browser and not compiled -- sorry for any errors, but you should get the idea.</p>\n\n<h3>1) The operation in <code>SetClassificationIdentificationValues</code> below seems like a common one.</h3>\n\n<p>I would encapsulate it like this:</p>\n\n<pre><code>let SetEntityReference (target:TargetRecord) (reference : EntityReference) =\n target.[\"gcnm_recordname\"] <- record.Name\n target.[\"gcnm_recordtype\"] <- record.LogicalName\n target.[\"gcnm_recordid\"] <- record.Id.ToString()\n</code></pre>\n\n<p>then you can simplify code that uses it to:</p>\n\n<pre><code>let SetClassificationIdentificationValues target reference =\n reference \n |> Option.iter (SetEntityReference target)\n</code></pre>\n\n<p>Once you have written something like <code>SetEntityReference</code> you might find other places where you can use it.</p>\n\n<h3>2) Using matching with options can generally be replaced with Option.map or Option.bind.</h3>\n\n<p>For example:</p>\n\n<pre><code>let NameAddedRegardingObject getRecordName (innerRegardingObject : unit -> EntityReference option) =\n let reference = innerRegardingObject()\n match reference with\n | Some(record) ->\n if Guid.Empty <> record.Id then record.Name <- getRecordName ((Reference(record)))\n | _ -> ()\n reference\n</code></pre>\n\n<p>Could be changed to:</p>\n\n<pre><code>/// return Some if the record has a non-empty Guid, else None\nlet filterIfValidGuid record =\n if Guid.Empty <> record.Id then Some record else None\n\nlet NameAddedRegardingObject getRecordName (innerRegardingObject : unit -> EntityReference option) =\n let updateName record =\n record.Name <- Reference(record) |> getRecordName \n\n innerRegardingObject()\n |> Option.bind filterIfValidGuid // filter\n |> Option.iter updateName // update only if filtered ok \n</code></pre>\n\n<h3>3) The code below has logic for converting a possibly multi-item list to a one-item list (a.k.a. an Option!)</h3>\n\n<pre><code> let ListFindingRegardingObject regardingLookups (image : FullRecordImage) =\n let existingLookups = regardingLookups() |> List.filter image.Contains\n match existingLookups with\n | [] -> None\n | [ a ] -> Some(image.GetAttributeValue<EntityReference>(a))\n | _ -> failwith \"Only one parent lookup may contain data\"\n</code></pre>\n\n<p>You could write that as a completely generic utility function:</p>\n\n<pre><code> let listToOption list =\n match list with\n | [] -> None\n | [ a ] -> Some(a)\n | _ -> failwith \"Expected only one item\"\n</code></pre>\n\n<p>and then the main code becomes</p>\n\n<pre><code> let ListFindingRegardingObject regardingLookups (image : FullRecordImage) =\n let existingLookups = regardingLookups() |> List.filter image.Contains\n existingLookups \n |> listToOption \n |> Option.map (fun a -> image.GetAttributeValue<EntityReference>(a))\n</code></pre>\n\n<p>But why is <code>regardingLookups()</code> even returning a list at all? Can it ever return two items? </p>\n\n<p>I don't like having exceptions except for things that should never happen, so if the two-item case is possible, one approach is to change it to return an error that has to be handled by the client.</p>\n\n<pre><code> let listToOption list =\n match list with\n | [] -> Choice1Of2 None // success\n | [ a ] -> Choice1Of2 Some(a) // success \n | _ -> Choice2Of2 \"Expected only one item\"\n</code></pre>\n\n<p>Better still would be to hide all this from the client if you can. I recommend using a simpler function, say <code>regardingLookup</code> that, given a predicate, is guaranteed to return an option only. The code then simplifies to this:</p>\n\n<pre><code> let ListFindingRegardingObject regardingLookup (image : FullRecordImage) =\n regardingLookup image.Contains\n |> Option.map (fun a -> image.GetAttributeValue<EntityReference>(a))\n</code></pre>\n\n<p>I assume the code in <code>ConfiguredRegardingLookups</code> is related?</p>\n\n<pre><code>let ConfiguredRegardingLookups(configuration : XElement) =\n configuration.Element(!<>\"regardinglookups\").Elements(!<>\"lookup\")\n |> List.ofSeq\n |> List.map (fun e -> e.Attribute(!<>\"name\").Value)\n</code></pre>\n\n<p>If you're going to be filtering this a lot to an Option, here's my version:</p>\n\n<pre><code>let ConfiguredRegardingLookups(configuration : XElement) predicate =\n configuration.Element(!<>\"regardinglookups\").Elements(!<>\"lookup\")\n |> Seq.map (fun e -> e.Attribute(!<>\"name\").Value)\n |> Seq.filter predicate\n |> Seq.tryPick Some \n</code></pre>\n\n<p>This version is guaranteed to return an option, and doesn't waste any effort converting the seq to a list, nor do you need anything like <code>listToOption</code>.</p>\n\n<p>To summarize this comment, converting a list or sequence to a option might be a code smell. But if you do have to do it, write a generic function. See also <a href=\"https://stackoverflow.com/questions/7487541/optionally-taking-the-first-item-in-a-sequence\">https://stackoverflow.com/questions/7487541/optionally-taking-the-first-item-in-a-sequence</a></p>\n\n<p>Using match too often (on options or lists) is generally a sign that you could write more generic code.</p>\n\n<p>As you can see, in general, what I'm doing is trying to use <code>map</code> and other built-in functions as much as possible, and then creating utility functions that help with this.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:38:19.417",
"Id": "76617",
"Score": "0",
"body": "Thanks Scott! That's a lot of interesting information; I especially didn't know about the `Option` functions that do make the code a bit more streamlined than matching, and I also hadn't heard of `Choice` at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T04:28:40.540",
"Id": "381847",
"Score": "0",
"body": "\"How dare you criticize the master!\" says a voice in my mind. I love sprinkling the code with very readable declarations like \"Person person\" and \"Order order\", and shadowing them on top of that, but using \"list\" and \"option\" I've tried to stay away from, since they are keywords. But now I'm thinking \"Why not? I'll follow the master! If he can do it, so can I.\" F# won't mind, unlike C#. (This is about \"listToOption list\" above.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T01:39:13.243",
"Id": "43896",
"ParentId": "43893",
"Score": "21"
}
},
{
"body": "<p>I don't really have any substantive comments about the code, just minor notes about the syntax.</p>\n\n<p>It's just an opinion, but I think the custom <code>!<></code> operator is kind of funky. An alternative approach would be to use a type extension to add methods to the <code>XElement</code> and <code>XAttribute</code> types:</p>\n\n<pre><code>type XContainer with\n member this.Element(name) = this.Element(XName.Get name)\n member this.Elements(name) = this.Elements(XName.Get name)\n\ntype XElement with\n member this.Attribute(name) = this.Attribute(XName.Get name)\n</code></pre>\n\n<p>Type extensions (also known as augmentations) allow you to extend an existing type. Sort of like extension methods in C#. Once you define these in the module, then you can call those methods with a string.</p>\n\n<p>That is just a preference, however.</p>\n\n<p>As for naming conventions, I notice that the <a href=\"http://fsharp.org/about/files/guidelines.pdf\" rel=\"nofollow\">F# Component Design Guidelines</a> mentions that let-bound values (including functions) are generally lowercase, especially internal ones.</p>\n\n<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/dd547125.aspx\" rel=\"nofollow\">MSDN</a>, record patterns do not have to include fields that are not matched, so the wildcards in the form <code>Message = _</code> are apparently not needed. However, the example given in that article is bad since it uses the wildcard.</p>\n\n<p>There are many places in this code where you could omit some parentheses, but this is opinionated. <code>Pre(PreValidation)</code> could become <code>Pre Prevalidation</code>. <code>if (not (requiredAttributesArePresent getTarget))</code> could become <code>if not (requiredAttributesArePresent getTarget)</code>. <code>getRecordName ((Reference(record)))</code> could become <code>getRecordName (Reference record)</code>, and so on. In general, dropping parentheses on F#-specific elements seems idiomatic, whereas dropping them on member declarations / invocations seems less common. I think it's actually harder to get parenthesization right in F# because parentheses are not always necessary, and it is harder to remember an exception than a rule. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T03:18:45.750",
"Id": "77201",
"Score": "2",
"body": "Thanks Luke! Yeah, the operator is a little fancy; I just wanted to try that because F# lets me do it. ;-) The type extensions do seem the least hassle for actual usage; I think those would belong in a library then. I chose the UpperCamelCased function names to keep \"primitives\" and compositions apart. Are there any other good ways to do that? As for parentheses, I already changed that habit since I wrote that code; that came just from C#, and the F# code does read better without them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T04:03:11.143",
"Id": "77202",
"Score": "0",
"body": "Putting the type extensions in a library might be appropriate if you plan on having many of these these plugins and a common codebase to support them all. Or if not, that is fine as well - type extensions are really nice for this type of ad-hoc, throwaway functionality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T04:03:49.867",
"Id": "77203",
"Score": "1",
"body": "I don't know about the naming thing. One thing to keep in mind is that a let binding, parameter, etc. will shadow any previous one (at least in the current scope), which might actually be desirable in some cases if you want to avoid accidentally referencing the original."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T00:42:51.507",
"Id": "77306",
"Score": "1",
"body": "Utilizing shadowing is an interesting point; I know a few places where that might be useful. I wonder how idiomatic it is to actually work that way, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-07T04:04:17.623",
"Id": "381846",
"Score": "0",
"body": "The technique luksan refers to is important for me not only to avoid accidentally referencing the original, but also because it makes the code so much more readable. You get less identifiers, often far less. You can easily trace the possible paths of the data, not having to keep in mind all the different names it would otherwise take on. There's no problem with any of this. As for idiomatic - I would vote it is."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T03:07:19.413",
"Id": "44489",
"ParentId": "43893",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "43896",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T23:59:07.000",
"Id": "43893",
"Score": "25",
"Tags": [
"beginner",
"f#"
],
"Title": "First real-world F# application - how \"good\"/idiomatic is it? (long!)"
} | 43893 |
<p>I am not sure what I am doing is right or not and am looking for experienced opinions.</p>
<p><img src="https://i.stack.imgur.com/t980u.jpg" alt="Soluton Explorer window"></p>
<p><strong>Entity Example</strong></p>
<pre><code>namespace Entities.Shop
{
public class Shop
{
public virtual int ShopId { get; set; }
public virtual string ShopName { get; set; }
public virtual IList<ShopScore> ShopScores { get; set; }
public virtual IList<ShopPromotion> ShopPromotions { get; set; }
public virtual IList<Entities.Menu.Menu> Menus { get; set; }
public virtual Address.Address Address { get; set; }
public virtual IList<DeliveryDistrict> DeliveryDistricts { get; set; }
public virtual IList<Payment.PaymentMethod> PaymentMethods { get; set; }
public virtual IList<WorkHour> WorkHours { get; set; }
public virtual int Status { get; set; }
public virtual int Activity { get; set; }
public virtual int Available { get; set; }
}
public class ShopScore
{
public virtual int ShopScoreId { get; set; }
public virtual int ShopScoreTypeId { get; set; }
public virtual int Score { get; set; }
}
public class ShopScoreType
{
public virtual int ShopScoreTypeId { get; set; }
public virtual string ShopScoreTypeName { get; set; }
}
public class ShopPromotion
{
public virtual int ShopPromotionId { get; set; }
public virtual int ShopPromotionTypeId { get; set; }
}
public class ShopPromotionType
{
public virtual int ShopScoreTypeId { get; set; }
public virtual string ShopScoreTypeName { get; set; }
}
public class DeliveryDistrict
{
public virtual int DeliveryDistrictId { get; set; }
public virtual Location.District District { get; set; }
public virtual int MinimumPaymentAmount { get; set; }
}
public class WorkHour
{
public virtual int WorkHourId { get; set; }
public virtual int Day { get; set; }
public virtual string OpenAt { get; set; }
public virtual string CloseAt { get; set; }
}
}
</code></pre>
<p><strong>Business Layer READ Example</strong></p>
<pre><code> namespace BL.Shop
{
public class READ
{
public static IList<Entities.Shop.Shop> All()
{
return DAL.Shop.READ.All();
}
public static IList<Entities.Shop.Shop> ShopList(int CountryId, int CityId, int DistrictId,
int MinimumTotalScore, List<Entities.Cuisine.Cuisine> Cuisines, int MinimumPaymentAmount, int PaymentMethodId)
{
return DAL.Shop.READ.ShopList(CountryId, CityId, DistrictId, MinimumTotalScore, Cuisines, MinimumPaymentAmount, PaymentMethodId);
}
}
}
</code></pre>
<p><strong>Data Access Layer (repository) READ Example</strong></p>
<pre><code>namespace DAL.Shop
{
public class READ
{
public static IList<Entities.Shop.Shop> All()
{
using (var session = NHibernateHelper.OpenSession())
{
IList<Entities.Shop.Shop> stores = session.CreateCriteria(typeof(Entities.Shop.Shop)).List<Entities.Shop.Shop>();
return stores;
}
}
public static IList<Entities.Shop.Shop> ShopList(int CountryId, int CityId, int DistrictId,
int MinimumTotalScore, List<Entities.Cuisine.Cuisine> Cuisines, int MinimumPaymentAmount, int PaymentMethodId)
{
using (var session = NHibernateHelper.OpenSession())
{
IList<Entities.Shop.Shop> stores = session.Query<Entities.Shop.Shop>()
.Where(C => C.Address.Country.CountryId == CountryId)
.Where(C => C.Address.City.CityId == CityId)
.Where(C => C.Address.District.DistrictId == DistrictId)
.Where(dd => dd.DeliveryDistricts.Any(d => d.District.DistrictId == DistrictId && d.MinimumPaymentAmount <= MinimumPaymentAmount))
.Where(p => p.PaymentMethods.Any(pm => pm.PaymentMethodId == PaymentMethodId))
//.Where(s => s.ShopScores.Sum(r => r.Score) >= MinimumTotalScore)
.ToList();
return stores;
}
}
public static Entities.Shop.Shop Shop(int ShopId)
{
using (var session = NHibernateHelper.OpenSession()) //bişey okurken transaction gerekmez.
{
return session.CreateCriteria(typeof(Entities.Shop.Shop))
.Add(Restrictions.Eq("ShopId", ShopId))
.SetMaxResults(1)
.UniqueResult<Entities.Shop.Shop>();
}
}
}
}
</code></pre>
<p><strong>Fluent NHibernate Mapping Example</strong></p>
<pre><code>namespace DAL.Shop
{
public class ShopMap : ClassMap<Entities.Shop.Shop>
{
public ShopMap()
{
Id(x => x.ShopId);
Map(x => x.ShopName);
Map(x => x.Status);
Map(x => x.Activity);
Map(x => x.Available);
References(x => x.Address);
HasMany(x => x.ShopScores);
HasMany(x => x.ShopPromotions);
HasMany(x => x.DeliveryDistricts);
HasMany(x => x.PaymentMethods);
HasMany(x => x.Menus);
HasMany(x => x.WorkHours);
}
}
public class ShopScoreMap : ClassMap<Entities.Shop.ShopScore>
{
public ShopScoreMap()
{
Id(x => x.ShopScoreId);
Map(x => x.ShopScoreTypeId);
Map(x => x.Score);
}
}
public class ShopScoreTypeMap : ClassMap<Entities.Shop.ShopScoreType>
{
public ShopScoreTypeMap()
{
Id(x => x.ShopScoreTypeId);
Map(x => x.ShopScoreTypeName);
}
}
public class ShopPromotionMap : ClassMap<Entities.Shop.ShopPromotion>
{
public ShopPromotionMap()
{
Id(x => x.ShopPromotionId);
Map(x => x.ShopPromotionTypeId);
}
}
public class ShopPromotionTypeMap : ClassMap<Entities.Shop.ShopPromotionType>
{
public ShopPromotionTypeMap()
{
Id(x => x.ShopScoreTypeId);
Map(x => x.ShopScoreTypeName);
}
}
public class DeliveryDistrictMap : ClassMap<Entities.Shop.DeliveryDistrict>
{
public DeliveryDistrictMap()
{
Id(x => x.DeliveryDistrictId);
References(x => x.District);
Map(x => x.MinimumPaymentAmount);
}
}
public class WorkHourMap : ClassMap<Entities.Shop.WorkHour>
{
public WorkHourMap()
{
Id(x => x.WorkHourId);
Map(x => x.Day);
Map(x => x.OpenAt);
Map(x => x.CloseAt);
}
}
}
</code></pre>
<p><strong>Unit Testing Example</strong></p>
<pre><code>namespace Test.Shop
{
[SetUpFixture]
public class SetUpClass
{
[SetUp]
public void RunBeforeAnyTests()
{
Entities.Shop.Shop Shop = null;
for (int i = 0; i < 1000; i++)
{
Shop = new Entities.Shop.Shop { ShopName = "Mc Donalds" };
BL.Shop.CREATE.CreateShop(Shop);
}
}
[TearDown]
public void RunAfterAnyTests()
{
// ...
}
}
[TestFixture]
public class READ
{
[Test]
public static void All()
{
IList<Entities.Shop.Shop> Shops = BL.Shop.READ.All();
Assert.AreEqual(1000, Shops.Count);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Browsing over the code one issue which jumped at me is the fact you have a tight coupling between your business layer and data access layer. Your BL is calling straight into the DAL by calling <code>DAL.Entity.CRUD.Whatever()</code>. This means that if you want to unit test your BL all of a sudden you have to set up a repository (most likely a database) while you should not have to. Testing the BL should not require to set up any other layer.</p>\n\n<p>One way to achieve that is by injecting an interface to the DAL into the BL and all your test for <code>BL.Shop.READ.All()</code> then cares about is the appropriate method on the injected DAL interface was called. Then use a mocking framework like <a href=\"http://hibernatingrhinos.com/oss/rhino-mocks\">RhinoMocks</a> or <a href=\"https://github.com/Moq/moq4\">Moq</a> to mock the DAL interface.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:59:41.427",
"Id": "75986",
"Score": "0",
"body": "this is exactly what type answers I am looking for! thank you, I will check mocking asap. apart from that everything else looks cool?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T07:24:58.273",
"Id": "43909",
"ParentId": "43898",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T02:09:40.640",
"Id": "43898",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Online food ordering application structure"
} | 43898 |
<p>One of the main problems I have with <code>JList</code> is that no component is actually <em>added</em> to it. This means that things like <code>ActionListener</code>s don't work, and you can't really have a list of interactive components. To solve this, I've tried to quickly implement an alternative.</p>
<p>I have a number of concerns.</p>
<ol>
<li><p>Speed: Will this be fast enough to display hundreds (thousands? millions?) of items?</p></li>
<li><p>Reliability: I've tried to make it reasonably solid, but no doubt there are a lot of things I should be checking that I am not.</p></li>
<li><p>Design: This is probably the most important. I tried to make a general, all-purpose design similar to that of <code>JList</code>, but it feels almost too complex to me. However, I cannot think of a better way. Any suggestions on how to improve it are most welcome.</p></li>
</ol>
<p>It has three general parts:</p>
<p>The <code>AdvancedList</code>:</p>
<pre><code>import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.util.List;
import java.util.Vector;
import javax.swing.BoxLayout;
public class AdvancedList<E> extends Container {
protected List<E> model;
protected List<AdvancedListCell<E>> listCells;
protected AdvancedCellRenderer<E> cellRenderer;
public AdvancedList(List<E> model, AdvancedCellRenderer<E> cellRenderer){
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.cellRenderer = cellRenderer;
this.model = new Vector<E>();
this.listCells = new Vector<AdvancedListCell<E>>();
for(E element: model){
this.addElement(element);
}
}
public AdvancedList(AdvancedCellRenderer<E> cellRenderer){
this(new Vector<E>(), cellRenderer);
}
public void addElement(E element){
AdvancedListCell<E> alc = cellRenderer.getAdvancedListCell(this, element, model.size());
this.add(alc.getComponent());
this.listCells.add(alc);
this.model.add(element);
}
public E removeElement(E element){
int idx = this.model.indexOf(element);
if(idx != -1) {
this.remove(idx);
this.listCells.remove(idx);
E removed = this.model.remove(idx);
this.repaint();
return removed;
}
return null;
}
public void paint(Graphics g){
AdvancedListCell<E> tmpListCell = null;
Component tmpComponent = null;
for(int i = 0; i < this.model.size(); i++){
tmpListCell = this.listCells.get(i);
tmpComponent = this.getComponent(i);
tmpListCell.updateCell(this, this.model.get(i), i, tmpComponent.hasFocus());
}
super.paint(g);
}
}
</code></pre>
<p>The <code>AdvancedCellRenderer</code>:</p>
<pre><code>public interface AdvancedCellRenderer<E> {
public AdvancedListCell<E> getAdvancedListCell(AdvancedList<? extends E> list, E value, int index);
}
</code></pre>
<p>The <code>AdvancedListCell</code>:</p>
<pre><code>import java.awt.Component;
public interface AdvancedListCell<E> {
public void updateCell(AdvancedList<? extends E> list, E value,
int index, boolean cellHasFocus);
public Component getComponent();
}
</code></pre>
<p>And finally, a simple test class:</p>
<pre><code>import java.awt.Component;
import java.awt.Container;
import java.util.Arrays;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AdvancedListTest {
public static void main(String[] args){
JFrame myFrame = new JFrame();
Vector<String> myStrings = new Vector<String>();
myStrings.addAll(Arrays.asList("TEST", "HI", "FOO", "BAR"));
AdvancedList<String> myList = new AdvancedList<String>(myStrings, new AdvancedCellRenderer<String>(){
@Override
public AdvancedListCell<String> getAdvancedListCell(
AdvancedList<? extends String> list, String value, int index) {
return new AdvancedListCell<String>(){
private JLabel myLabel = new JLabel();
@Override
public Component getComponent() {
return myLabel;
}
@Override
public void updateCell(AdvancedList<? extends String> list,
String value, int index, boolean cellHasFocus) {
myLabel.setText(value+", index: "+index+", has focus: "+cellHasFocus);
}
public String toString(){
return "Class: "+myLabel.getClass()+", text: "+myLabel.getText();
}
};
}
});
myFrame.setSize(500, 500);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(myList);
myFrame.revalidate();
myFrame.repaint();
myFrame.setVisible(true);
myList.addElement("Added a string");
myList.removeElement("HI");
}
}
</code></pre>
| [] | [
{
"body": "<p>This is a huge step to take to solve a problem which I am not sure actually exists.</p>\n\n<p>Why do you need to reimplement the way the entire component is rendered just to add the ActionListeners in a different way? I think you have missed something here.</p>\n\n<p>You can override the ListModel (<code>AbstractListModel</code>) and add all the hard effort in to that. As far as I can tell, none of your requirements need to extend beyond that. Your custom ListModel can register actionListeners with each added list member, and can broker the correct action respoinses if needed. Additionally, it can handle all the other events and eventhandling that needs to happen.....</p>\n\n<p>I think all three of your concerns are valid, and you are right to be concerned...</p>\n\n<ol>\n<li>Performance - I am not sure about this one, but I doubt your solution will be as well-refined as the native one.</li>\n<li>Reliability - This solution is likely to be buggy, and is not going to be as upgradable in terms of look/feel as other components. This is a big deal.... the native components will be more responsive to that sort of context change.</li>\n<li>Over complicated design: I think you are reinventing the wheel here. There is nothing in your design that I can't see in the native implementation.... I think the model/view differentiation is better in the native JList.</li>\n</ol>\n\n<p>All in all, I think you are getting ahead of yourself, and have not fully understood how the native implementation can be adapted to solve the problems you think you have.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:10:42.477",
"Id": "43946",
"ParentId": "43899",
"Score": "3"
}
},
{
"body": "<p>A few notes, mostly about the current code:</p>\n\n<ol>\n<li><blockquote>\n <p>Speed: Will this be fast enough to display hundreds (thousands? millions?) of items?</p>\n</blockquote>\n\n<p>If I understand correctly I'm afraid that this wouldn't be too user-friendly. If your users need to handle millions of items they might need some kind of filtering, pagination, autocomplete etc. not everything in one huge list.</p></li>\n<li><p>AFAIK and according to <a href=\"https://en.wikipedia.org/wiki/Event_dispatching_thread\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>all user interface components should be created and <strong>accessed</strong> only from the AWT event dispatch thread.</p>\n</blockquote>\n\n<p>including <code>myFrame.setSize(500, 500)</code>, etc.</p></li>\n<li><p>Calling overridable methods (like <code>setLayout</code> and <code>addElement</code>) from constructors usually is not a good practice. See <a href=\"https://stackoverflow.com/q/3404301/843804\">What's wrong with overridable method calls in constructors?</a> and <em>Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it</em></p></li>\n<li><p>I'd use a simple <code>List</code> or <code>ArrayList</code> instead of <code>Vector</code>s. <a href=\"https://stackoverflow.com/q/1386275/843804\">Vector is considered obsolete</a>.</p></li>\n<li><p><code>this.</code> is not always necessary (modern IDEs can highlight fields).</p></li>\n<li><blockquote>\n<pre><code>public E removeElement(E element) {\n int idx = this.model.indexOf(element);\n if (idx != -1) {\n this.remove(idx);\n this.listCells.remove(idx);\n E removed = this.model.remove(idx);\n this.repaint();\n return removed;\n }\n return null;\n}\n</code></pre>\n</blockquote>\n\n<p>I'd use a <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause</a> here:</p>\n\n<pre><code>public E removeElement(E element) {\n int idx = model.indexOf(element);\n if (idx == -1) {\n return null;\n }\n remove(idx);\n listCells.remove(idx);\n E removed = model.remove(idx);\n repaint();\n return removed;\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code> public void paint(Graphics g) {\n AdvancedListCell<E> tmpListCell = null;\n Component tmpComponent = null;\n for (int i = 0; i < this.model.size(); i++) {\n tmpListCell = this.listCells.get(i);\n tmpComponent = this.getComponent(i);\n tmpListCell.updateCell(this, this.model.get(i), i, tmpComponent.hasFocus());\n }\n super.paint(g);\n }\n</code></pre>\n</blockquote>\n\n<ul>\n<li><code>tmpListCell</code> and <code>component</code> could be declared inside the loop. </li>\n<li><p>The <code>tmp</code> prefix is unnecessary, I'd call them <code>listCell</code> and <code>component</code>.</p>\n\n<p>public void paint(Graphics g) {\n for (int i = 0; i < this.model.size(); i++) {\n AdvancedListCell listCell = listCells.get(i);\n Component component = getComponent(i);\n listCell.updateCell(this, model.get(i), i, component.hasFocus());\n }\n super.paint(g);\n}</p></li>\n</ul></li>\n<li><blockquote>\n<pre><code>this.model = new Vector<E>();\nthis.listCells = new Vector<AdvancedListCell<E>>();\n</code></pre>\n</blockquote>\n\n<p>could be assigned in the field declaration:</p>\n\n<pre><code>protected List<E> model = new Vector<E>();\nprotected List<AdvancedListCell<E>> listCells = new Vector<AdvancedListCell<E>>();\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:46:02.267",
"Id": "44093",
"ParentId": "43899",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T03:03:28.203",
"Id": "43899",
"Score": "10",
"Tags": [
"java",
"performance",
"swing"
],
"Title": "Component-oriented implementation of JList"
} | 43899 |
<p>As I was coding this algorithm I found that some variables that are meant to be global behave as they are intended to behave, but others do not. Specifically, my boolean arrays, e.g. <code>processed</code> and <code>discovered</code>, can be modified within any method without the need to declare them. </p>
<p>On the other hand, I had trouble with the variable <code>time</code>. Python complained about incrementing a variable without it being declared. The solution to this was to specifically declare <code>time</code> as a <code>Global</code>, and the complaints went away.</p>
<p>Can someone, in a clear way that makes sense, explain the why <code>time</code> needs to be declared <code>Global</code> and the other global variables do not? What is the difference between <code>time</code> and the other variables?</p>
<p>One other thing. Can someone check the correctness of the way I'm keeping track of time of entry and time of exit? According to The Algorithm Design Manual by Skiena, half the difference between time of entry and time of exit for a vertex equals the number of descendants. But I don't think that's what I'm seeing.</p>
<pre><code># Global variables
MAXV = 7
processed = [None]*MAXV # boolean list of which vertices have been processed
discovered = [None]*MAXV # boolean list of which vertices have been found
parent = [None]*MAXV # integer list of discovery relation
finished = False
entry_time = [None]*MAXV
exit_time = [None]*MAXV
time = 0
class Edgenode:
def __init__(self, y = None, weight = None, next = None):
"""
@param y: adjacency info
@param weight: edge weight, if any
@param next: next edge in list
"""
self.y = y
self.weight = weight
self.next = next
class Graph:
def __init__(self, edges = [], degree = [], nvertices = None, \
nedges = None, directed = None):
"""
@param edges: adjency info
@param degree: outdegree of each vertex
@param nvertices: number of vertices in graph
@param nedges: number of edges in graph
@param directed: is the graph directed? (boolean)
"""
self.edges = edges # this might be a dictionary, with key being vertex and values being edges
self.degree = degree
self.nvertices = nvertices
self.nedges = nedges
self.directed = directed
def initialize_graph(graph, directed):
"""
@param graph: Graph object
@param directed: boolean
"""
graph.nvertices = 0
graph.nedges = 0
graph.directed = directed
for i in xrange(MAXV):
graph.degree.append(0)
graph.edges.append(None)
def read_graph(graph, directed):
"""
@param graph: Graph object
@param directed: boolean
"""
initialize_graph(graph, directed)
data = graph_data()
graph.nvertices = data[0][0] # number of vertices
m = data[0][1] # number of edges
for i in xrange(1,m+1):
x = data[i][0] # vertex x
y = data[i][1] # vertex y
insert_edge(graph,x,y,directed)
def insert_edge(graph, x, y, directed):
"""
@param graph: Graph object
@param x, y: vertices in edge (x,y)
@param directed: boolean
"""
p = Edgenode()
p.y = y
p.next = graph.edges[x] #p.next point to whatever is in edges[x]
graph.edges[x] = p #edges[x], gets replaced by the new p, which points to whatever was in edges[x] before
graph.degree[x] += 1
if (directed == False):
insert_edge(graph, y, x, True)
else:
graph.nedges += 1
def graph_data():
data = [
(6,7),
(1,2),
(1,6),
(1,5),
(2,3),
(2,5),
(5,4),
(3,4)]
return data
def initialize_search(graph):
finished = False
for i in xrange(1,graph.nvertices+1):
processed[i] = discovered[i] = False
parent[i] = -1 # the parent of vertex i is parent[i]
entry_time[i] = exit_time[i] = None
def dfs(graph,v):
global time
if finished: #allow for search termination
return
discovered[v] = True
time = time + 1
entry_time[v] = time
process_vertex_early(v)
p = graph.edges[v]
while p != None:
y = p.y
if discovered[y] == False:
parent[y] = v
process_edge(v,y)
dfs(graph,y)
elif not processed[y] or graph.directed:
process_edge(v,y)
if finished:
return
p = p.next
process_vertex_late(v)
time = time + 1
exit_time[v] = time
processed[v] = True
def process_vertex_early(v):
print "Discovered vertex %d\n"%v
def process_edge(x,y):
print "Processed edge (%d,%d)\n"%(x,y)
def process_vertex_late(v):
print "Processed vertex %d\n"%v
def main():
graph = Graph()
read_graph(graph, False)
start = 1
initialize_search(graph)
dfs(graph,start)
for i in xrange(1,graph.nvertices+1):
print "Entry time for vertix %d: %d"%(i,entry_time[i])
print "Exit time for vertix %d: %d\n"%(i,exit_time[i])
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T06:07:01.340",
"Id": "75975",
"Score": "1",
"body": "Some minor points to consider\n\ntime is a stdlib module - that makes it a bad candidate for a global variable name! But as the code is written each new call to dfs() needs it. Why don't you pass the time down to each call and pass it back up as each recursion finishes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T06:13:11.350",
"Id": "75976",
"Score": "0",
"body": "I implemented it that way too, and it works, but I liked keeping time as global since it's consistent with the style of the algorithm. Plus, the Java implementation that I translated to Python treats time as global variable. I figure it's for a good reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:53:02.167",
"Id": "76080",
"Score": "0",
"body": "Note that `initialize_search` assigns a local variable `finished` while `dfs` accesses a global variable of the same name."
}
] | [
{
"body": "<blockquote>\n <p>Can someone, in a clear way that makes sense, explain the why time needs to be declared Global and the other global variables do not? What is the difference between time and the other variables?</p>\n</blockquote>\n\n<p>The <code>time</code> variable is an integer and the boolean arrays are lists. In python lists can be modified in place but integers cannot; you need to assign a new value to <code>time</code> variable to modify it. The global declaration is only needed for the assignment to the global variable to work. </p>\n\n<p>You would also need to declare the boolean arrays as global in any function or method that would need to assign a new value to them; modifying the existing lists in place as you are now doing does not require the global declaration.</p>\n\n<p>Now, on a bit deeper level, this is about Python using a thing called references when declaring variables. Each variable is a reference to the actual \"value\". Changing the reference is done with the assignment operator (=). You can freely assign a new reference to any variable that you have declared locally (i.e. inside a function). But when a variable is declared in the global scope, changing the global reference inside another scope requires the global declaration in that scope. The reason for this is to prevent accidental modification of a global variable when the intention was to declare a new local variable with the same name; you have to be explicit when you want to assign to global variables.</p>\n\n<hr>\n\n<p>As a general advice, you should avoid using global data because of the problems it tends to create when the code grows and needs to be maintained. If you intend to expand this code further, you should look into refactoring it to either a more object-oriented or more functional design. </p>\n\n<p>An object-oriented solution would encapsulate the global variables and their management inside classes. One obvious starting point would be moving dfs() inside the Graph class with all the necessary data as its members. </p>\n\n<p>A functional design would pass all the variables as parameters to the functions. A simple change to your code would be to declare the global variables inside the main() function and pass them to dfs() and other functions as needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T09:27:25.710",
"Id": "43916",
"ParentId": "43902",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T04:56:36.680",
"Id": "43902",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"depth-first-search"
],
"Title": "Depth first search, use of global variables, and correctness of time"
} | 43902 |
<p><a href="http://stackoverflow.com/tags/jms/info">Stack Overflow JMS tag wiki</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T06:37:22.453",
"Id": "43905",
"Score": "0",
"Tags": null,
"Title": null
} | 43905 |
The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T06:37:22.453",
"Id": "43906",
"Score": "0",
"Tags": null,
"Title": null
} | 43906 |
<p>I wrote this code to send any binary file from <strong>server</strong> to <strong>client</strong> (in our example, I am sending sample_file.txt); the client should recreate the file locally.
Code works fine (I tested with one or two files). Data is sent in chunks of 256 bytes.</p>
<p>I would appreciate remarks and critique, however, not that much from programming style point of view, rather if there are some major flaws in the networking part/logic or file I/O.</p>
<p>Client:</p>
<pre><code>#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(void)
{
int sockfd = 0;
int bytesReceived = 0;
char recvBuff[256];
memset(recvBuff, '0', sizeof(recvBuff));
struct sockaddr_in serv_addr;
/* Create a socket first */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
/* Initialize sockaddr_in data structure */
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000); // port
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
/* Attempt a connection */
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
/* Create file where data will be stored */
FILE *fp;
fp = fopen("sample_file.txt", "ab");
if(NULL == fp)
{
printf("Error opening file");
return 1;
}
/* Receive data in chunks of 256 bytes */
while((bytesReceived = read(sockfd, recvBuff, 256)) > 0)
{
printf("Bytes received %d\n",bytesReceived);
// recvBuff[n] = 0;
fwrite(recvBuff, 1,bytesReceived,fp);
// printf("%s \n", recvBuff);
}
if(bytesReceived < 0)
{
printf("\n Read Error \n");
}
return 0;
}
</code></pre>
<p>Server:</p>
<pre><code>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
int main(void)
{
int listenfd = 0;
int connfd = 0;
struct sockaddr_in serv_addr;
char sendBuff[1025];
int numrv;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
printf("Socket retrieve success\n");
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));
if(listen(listenfd, 10) == -1)
{
printf("Failed to listen\n");
return -1;
}
while(1)
{
connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL);
/* Open the file that we wish to transfer */
FILE *fp = fopen("sample_file.txt","rb");
if(fp==NULL)
{
printf("File opern error");
return 1;
}
/* Read data from file and send it */
while(1)
{
/* First read file in chunks of 256 bytes */
unsigned char buff[256]={0};
int nread = fread(buff,1,256,fp);
printf("Bytes read %d \n", nread);
/* If read was success, send data. */
if(nread > 0)
{
printf("Sending \n");
write(connfd, buff, nread);
}
/*
* There is something tricky going on with read ..
* Either there was error, or we reached end of file.
*/
if (nread < 256)
{
if (feof(fp))
printf("End of file\n");
if (ferror(fp))
printf("Error reading\n");
break;
}
}
close(connfd);
sleep(1);
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>I am not an expert in network so I will comment on the part that doesn't interest you that much. On top of that, your code is pretty clean, well documented and seemed to work properly when I tried it locally so there is not too much to say.</p>\n\n<p>You should try to avoid magic numbers to keep things maintainable and any other kind of hardcoded data in the middle of the code.</p>\n\n<p>You could put server and client in the same file in different methods.</p>\n\n<p>You have unused variable. An easy way to notice it is to try to put declaration as late as possible, in the smallest possible scope and as close to their first use as possible. Also, compiler warnings might help you.</p>\n\n<p>I am not sure you are cleaning ressources (files for instance) properly. This needs a lot of re-writing to do this properly so I'll leave this for you.</p>\n\n<p>After a bit of tweaking here and there, here is the code I have on my side :</p>\n\n<pre><code>// For both\n#include <sys/socket.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n\n// For server\n#include <netdb.h>\n\n// For client\n\n\n#define PORT 5000\n#define BUF_SIZE 256\n\nint client(const char* filename)\n{\n /* Create file where data will be stored */\n FILE *fp = fopen(filename, \"ab\");\n if(NULL == fp)\n {\n printf(\"Error opening file\");\n return 1;\n }\n\n /* Create a socket first */\n int sockfd = 0;\n if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)\n {\n printf(\"\\n Error : Could not create socket \\n\");\n return 1;\n }\n\n /* Initialize sockaddr_in data structure */\n struct sockaddr_in serv_addr;\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_port = htons(PORT); // port\n serv_addr.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n\n /* Attempt a connection */\n if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)\n {\n printf(\"\\n Error : Connect Failed \\n\");\n return 1;\n }\n\n /* Receive data in chunks of BUF_SIZE bytes */\n int bytesReceived = 0;\n char buff[BUF_SIZE];\n memset(buff, '0', sizeof(buff));\n while((bytesReceived = read(sockfd, buff, BUF_SIZE)) > 0)\n {\n printf(\"Bytes received %d\\n\",bytesReceived);\n fwrite(buff, 1,bytesReceived,fp);\n }\n\n if(bytesReceived < 0)\n {\n printf(\"\\n Read Error \\n\");\n }\n\n return 0;\n}\n\n\nint server(const char * filename)\n{\n int listenfd = socket(AF_INET, SOCK_STREAM, 0);\n\n printf(\"Socket retrieve success\\n\");\n\n struct sockaddr_in serv_addr;\n memset(&serv_addr, '0', sizeof(serv_addr));\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n serv_addr.sin_port = htons(PORT);\n\n bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));\n\n if(listen(listenfd, 10) == -1)\n {\n printf(\"Failed to listen\\n\");\n return -1;\n }\n\n for (;;)\n {\n int connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL);\n\n /* Open the file that we wish to transfer */\n FILE *fp = fopen(filename,\"rb\");\n if(fp==NULL)\n {\n printf(\"File opern error\");\n return 1;\n }\n\n /* Read data from file and send it */\n for (;;)\n {\n /* First read file in chunks of BUF_SIZE bytes */\n unsigned char buff[BUF_SIZE]={0};\n int nread = fread(buff,1,BUF_SIZE,fp);\n printf(\"Bytes read %d \\n\", nread);\n\n /* If read was success, send data. */\n if(nread > 0)\n {\n printf(\"Sending \\n\");\n write(connfd, buff, nread);\n }\n\n /*\n * There is something tricky going on with read ..\n * Either there was error, or we reached end of file.\n */\n if (nread < BUF_SIZE)\n {\n if (feof(fp))\n printf(\"End of file\\n\");\n if (ferror(fp))\n printf(\"Error reading\\n\");\n break;\n }\n }\n close(connfd);\n sleep(1);\n }\n\n return 0;\n}\n\nint main(int argc, char** argv)\n{\n if (argc == 3)\n {\n const char* mode = argv[1];\n const char* filename = argv[2];\n if (strcmp(mode, \"client\") == 0)\n return client(filename);\n else if (strcmp(mode, \"server\") == 0)\n return server(filename);\n else\n printf(\"Invalid mode %s - should be 'client' or 'server'\\n\",mode);\n }\n else\n {\n printf(\"Invalid number of argument, usage is %s [MODE] [FILENAME]\\n\",argv[0]);\n }\n return 1; // Something went wrong\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-05T21:35:18.193",
"Id": "181742",
"Score": "0",
"body": "you could use flags with gcc to check for unused variables as well. I always use `-Wall -Werror -Wextra` one of those displays a warning if there are unused variables, not sure which one right now"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T10:14:12.120",
"Id": "43918",
"ParentId": "43914",
"Score": "4"
}
},
{
"body": "<p><strong>ALWAYS</strong> check the return values of C functions and take appropriate action.</p>\n\n<p>Example:</p>\n\n<pre><code>::read() returns the number of characters read.\n Just because you write in chunks of 256 does not mean they\n will arrive in chunks of.\n\n::write() Same thing goes here.\n You may try and write in chunks of 256 does not mean\n that all 256 will be written.\n</code></pre>\n\n<p>Note. When they return -1 (error) the actual error is in the variable <code>errno</code> and not all errors are unrecoverable (see [EINTR]).</p>\n\n<p>How I would use write</p>\n\n<pre><code>std::size_t bytesWritten = 0;\nstd::size_t bytesToWrite = <Some Size>;\n\nwhile (bytesWritten != bytesToWrite)\n{\n std::size_t writtenThisTime;\n\n do\n {\n writtenThisTime = ::write(fd, buf + bytesWritten, (bytesToWrite - bytesWritten));\n }\n while((writtenThisTime == -1) && (errno == EINTR));\n\n if (writtenThisTime == -1)\n {\n /* Real error. Do something appropriate. */\n return;\n }\n bytesWritten += writtenThisTime;\n}\n</code></pre>\n\n<p>How I would read:</p>\n\n<pre><code>std::size_t bytesRead = 0;\nstd::size_t bytesToRead = <Some Size>;\n\nwhile (bytesToRead != bytesRead)\n{\n std::size_t readThisTime;\n\n do\n {\n readThisTime = ::read(fd, buf + bytesRead, (bytesToRead - bytesRead));\n }\n while((readThisTime == -1) && (errno == EINTR));\n\n if (readThisTime == -1)\n {\n /* Real error. Do something appropriate. */\n return;\n }\n bytesRead += readThisTime;\n}\n</code></pre>\n\n<p>other unchecked calls:</p>\n\n<pre><code>fwrite(recvBuff, 1,bytesReceived,fp);\nlistenfd = socket(AF_INET, SOCK_STREAM, 0);\nbind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));\nconnfd = accept(listenfd, (struct sockaddr*)NULL ,NULL);\nint nread = fread(buff,1,256,fp); // You may not get all 256 items.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:33:20.883",
"Id": "75983",
"Score": "0",
"body": "Thanks. I thought everywhere I use read, I check return values, isn't it the case? For write, I use it once in server, and once in client - on both places I shall compare if number of bytes written is equal to the number of bytes I requested to write, and if not - abort program or smth, that is your suggestion right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T01:21:59.270",
"Id": "76179",
"Score": "0",
"body": "@If the number of bytes written does not equal the number of bytes you requested just try again (starting from the first byte not written). Yes you do check the read count but you don't compensate for errors that are not errors. updated with how I would read/write."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T07:29:38.830",
"Id": "76206",
"Score": "0",
"body": "I will give more thought to your suggestions. But why is your write better than one I had, or just doing one write and checking error code? Basically, one could wrap your suggestion into a WRITE(buffer,size) function also, and use it instead of original write command too right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:10:34.937",
"Id": "76217",
"Score": "0",
"body": "Because write does not guarantee to write all the bytes requested. The FD may be busy. Checking the error code is not enough you need to check how much was written. Yes you can wrap that in a function (and I would encourage that). Also see the list of functions that you do not correctly validate the return code on."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:09:06.543",
"Id": "43923",
"ParentId": "43914",
"Score": "8"
}
},
{
"body": "<p>If I had to pick one word about networking it would be \"unreliable\". Networks are not bullet-proof, not even in lab scenarios; things can fail: whole machines, network adapters, cables, routers, switches or the application at the \"other\" end. Your code does little to ensure that errors are handled properly and only relies on the (limited) guarantees that TCP provides you with.</p>\n\n<p>What happens if the server crashes in the middle of a transfer? How do you know that the entire contents of the file has been transferred?</p>\n\n<p>I'd start by designing a 'mini protocol' for the app: maybe the client should be able to ask for a specific file. How would you change the request (non-existent right now) and response? I'd also add a header to inform the client of how much data I'm going to send or maybe some sort of file <a href=\"http://en.wikipedia.org/wiki/Cyclic_redundancy_check\" rel=\"noreferrer\">CRC</a>.</p>\n\n<p>Regarding your choice of buffer size. TCP packets are usually much larger than 256 bytes - while not a big issue in your case, you may want to choose a better value <a href=\"http://en.wikipedia.org/wiki/Maximum_transmission_unit\" rel=\"noreferrer\">MTU</a>.</p>\n\n<p><code>sleep</code> - some call it evil. Why did you use it?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T12:07:58.927",
"Id": "75988",
"Score": "0",
"body": "why would server send how many bytes it is going to send - to let the client verify that data transfer was success?? So you recommend sending CRC to let the client make sure it has successfully received file? Is that it? About `sleep` - some little part of this code, like basic client/server connection setup I found on internet, so it seems to be a relic from that ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:52:41.787",
"Id": "76008",
"Score": "0",
"body": "@dmcr_code knowing the file size beforehand can be useful for several things: 1. client knows when to stop/how much to read with the added benefit of being able to detect (more reliably) if something went wrong (maybe cleanup incomplete files). 2. it could allow you to 'pre-allocate' the space for the file(s) instead of trashing your hdd with 256byte long writes (not even a full old-style 512 byte disk sector) - torrent clients, for instance, usually do that to avoid being limited by HDD write speed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:57:55.163",
"Id": "76009",
"Score": "0",
"body": "@dmcr_code CRC doesn't replace file size though, in some way, it could be used like that. The main benefit CRCs provide is that they allow the client to verify that the data it received has not been corrupted or [tampered](http://en.wikipedia.org/wiki/Man-in-the-middle_attack) with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:01:03.877",
"Id": "76011",
"Score": "1",
"body": "@dmcr_code you should `fclose` the files once you're done with them"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:37:27.267",
"Id": "76023",
"Score": "0",
"body": "Yes fclose I added. I agree CRC can increase reliability because I can check if file receive was success. On sending file size not convinced yet, but thanks for your feedback."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:52:49.980",
"Id": "43926",
"ParentId": "43914",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T08:39:27.893",
"Id": "43914",
"Score": "16",
"Tags": [
"c",
"networking",
"socket"
],
"Title": "Client/server implementation in C (sending data/files)"
} | 43914 |
<p>I'm trying to write a Minecraft server in Ruby as an educational project and I've hit the point now where I need to decide on how I am going to structure the in-game objects (entities). In my mind, an Entity is an in-game thing such as a block, or a player, or a skeleton.</p>
<p>The reason this is code review, and not game design, is because I am interested in what you think of the design from a general programming perspective, as this is an open source project and I want it to be as programmer friendly as possible.</p>
<p>When I started writing the current spike, I came up with a few methods I could use for entity structure.</p>
<h2>Standard Object-Orientated Programming Inheritance</h2>
<p>In this example, I would have used the standard OOP class hierarchy to design my entities. you would have a base class <code>Entity</code> which would be extended by <code>Player</code>, <code>Sign</code>, <code>Skeleton</code>, you get the idea. The upside of this is that it's simple and fast to come up with - until you start wanting to share functionality in two derivatives. Ruby does not have multiple inheritance, so it gets messy when I want an <code>Enderdragon</code> entity to share some functionality with a <code>Sheep</code>. It also limits functionality unless you do a lot of code duplication at runtime if you want to, say, make a <code>Villager</code> controllable by a <code>Player</code>.</p>
<h2>Modules and Inheritance</h2>
<p>This approach would use modules to share functionality and have it all defined at compile-time. We would have modules such as <code>Positionable</code>, <code>Orirentable</code>, <code>Nameable</code> and a base <code>Entity</code> class would define all of these at compile time in derivatives (for want of a better word - no compiling in Ruby). The advantage of this is that it's more 'clear' to other programmers. <code>Player</code> would have <code>Positionable</code> and <code>RemoteControllable</code> whereas a <code>Sheep</code> might have <code>Positionable</code>. These subclasses are all designed at compile time.</p>
<h2>Modules and Meta-Programming</h2>
<p>Finally, this one would utilize the Factory (or Builder) pattern to have a similar approach to <code>Modules and Inheritance</code>, except this time, it would define the mixins at <strong>runtime</strong>. Instances of <code>Entity</code> would be re-opened at runtime and have the appropriate modules mixed-in in their factory. This has the benefit of <strong>huge</strong> flexibility at the cost of maybe perhaps slightly violating POLA.</p>
<p>I'm currently siding on the side of meta-programming. What do you think?</p>
<pre><code>module Entity
# The Id of the Entity
attr_accessor :id
def to_s
"Entity <ID:#{id}>"
end
end
module Positionable
attr_accessor :x, :y, :z
end
module Orientable
attr_accessor :yaw, :pitch
end
module Nameable
attr_accessor :name
end
entity = Entity.new
entity.extend(Positionable)
entity.extend(Nameable)
entity.extend(Orientable)
entity.x # => 0f
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:59:22.033",
"Id": "76029",
"Score": "0",
"body": "Forget my previous comment -- I didn't read the question carefuly and thought you wanted to build the map in OOP, that would be nonsense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:17:12.747",
"Id": "76349",
"Score": "0",
"body": "for the love all that is holy, do not take approach #1"
}
] | [
{
"body": "<p>I would prefer your second plan, with inheritence and mixin modules. I'll restate their different uses, which I am sure you know:</p>\n\n<ul>\n<li>Use inheritance to model relationships between objects (B <em>is a</em> A).</li>\n<li>Use mixins to model behavior (C <em>logs</em>, D <em>remembers its position</em>).</li>\n</ul>\n\n<p>Unless you have a need to dynamically add mixins, apply <a href=\"http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow\">YAGNI</a> and don't do it <em>yet</em>. Wait until you have a compelling need for dynamic mixins, and use them only where needed. Metaprogramming is a power tool, but it does make the code harder to follow. Use it judiciously.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T05:15:01.750",
"Id": "76405",
"Score": "1",
"body": "Well stated, Wayne. I'd add that metaprogramming can be especially hard to follow when there is an obvious simpler solution, for it evokes the IMBMS ('I must be missing something') reaction on the part of the reader."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:10:03.860",
"Id": "76485",
"Score": "1",
"body": "@CarySwoveland FYI, re IMBMS, BTDT."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:58:58.760",
"Id": "76553",
"Score": "1",
"body": "I've concluded that \"BT\" probably means \"been there\" or \"bacon tomato\", but I'm still working on \"DT\". Don't tell me--I want to work it out myself."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T12:24:25.963",
"Id": "43931",
"ParentId": "43917",
"Score": "4"
}
},
{
"body": "<p>One of my hobbies is woodworking. When I'm about to embark on a new project, I have a general idea of how I'm going to do it, just based on experience. I almost always begin by working up plans with Sketchup, which includes the materials I'll be using for each part. I then give considerable thought to which individual boards I'll use for which parts (e.g., to emphasize, downplay or match grain, and minimize waste), and the order in which I'll be performing various operations. For example, I know I'll be jointing, planing and sawing to square up stock, and want to do that efficiently, to save time. At that time I don't give much thought to the tools I'll be using, because I know the choice will generally be obvious, and when it is not, I can decide that later. One thing I <em>never</em> do, however, is ask myself whether I should be using power tools or hand tools for a project, for I know I'll be using both, whatever tool works best for each operation.</p>\n\n<p>I expect most people take a similar approach to coding, which leads me wonder whether your question can or should be answered. I am not questioning its merit; if nothing more, it is good food for thought.</p>\n\n<p>With regard to metaprogramming, although we all know what it is,.. Stop there. We don't, or at least I don't. We probably can agree that anything having to do with singleton classes probably falls under metaprogramming, but what about hooks like <code>included</code> and <code>extended</code>, <code>method_missing</code>, <code>alias_method</code>, even lowly <code>send</code>, and more? Moreover, while some uses of metaprogramming are truly mind-bending, others are dead-simple (e.g., using a class instance variable instead of a class variable). So what criteria could possibly be employed to decide whether a metaprogramming approach should be taken to a particular problem or a class of programs?</p>\n\n<p>One knock against metaprogramming is that it makes it difficult for other coders to understand what's going on, and therefore should be used sparingly. I would tend to agree when the metaprogramming is both complex and unnecessary. Only 'tend' because life is complex. Forget not our responsibility to teach. Sometimes that means doing things that cause others to struggle. Let's say you've done some metaprogramming that has been given to me to maintain. Knowing little about metaprogramming, it takes me awhile to figure out what you've done, more time that it would have taken had you used a less sophisticated (ww?) approach. But then I have an 'aha' moment and think, \"now that's cool, very cool indeed\", and realize I could apply the same approach to another project I'm working on, allowing me to save a huge amount of time, and impress my co-workers in the bargain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:51:20.540",
"Id": "44182",
"ParentId": "43917",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43931",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T09:38:26.400",
"Id": "43917",
"Score": "6",
"Tags": [
"ruby",
"minecraft"
],
"Title": "Game object structure for Minecraft server"
} | 43917 |
<p>At the innermost loop of my software is a lookup of a function value from a piecewise defined function with interpolation between the sample points.</p>
<p>Illustration:</p>
<pre><code>* *
* *
* *
|--|------|------|--------X---------|-------------|
</code></pre>
<p>There are several different interpolation methods in between the sample points.</p>
<p>My current implementation consists of two arrays, one for the interval endpoints and one for the function values. Searching is done via std::upper_bound if the array is large and find_if if the arrays are small. Based on the access patterns the speed improved tremendously by adding a cache value for the previous positions interval and checking if it is still valid for the new position</p>
<pre><code>[1%] if (x >= *cache && x < *(cache + 1)) {
outside = false;
position = cache;
} else if (x < *begin || x > *end) {
outside = true;
} else {
outside = false;
if (n_ < 64) {
[3%] position = std::find_if(begin, end, std::bind2nd(std::greater_equal<argument_type>(), x)) - 1;
} else {
position = std::upper_bound(begin, end, x) - 1;
}
cache = position ;
}
</code></pre>
<p>The lookup currently still takes about 5% of total execution time, which seems too much.
I have indicated costs of the most expensive lines which is the comparison with the cached position [1%] and the linear search [3%].</p>
<p><strong>Is there a faster way to lookup the interval which contains X?</strong></p>
<hr>
<p><strong>Edit</strong></p>
<ul>
<li>I have included the switch after profiling since <a href="https://stackoverflow.com/questions/1275665/at-which-n-does-binary-search-become-faster-than-linear-search-on-a-modern-cpu">Linear search can faster for small arrays</a> (and there are a lot of small arrays).</li>
</ul>
<hr>
<p><strong>Edit</strong>
It seems the std::find_if implemenation is actually faster than binary search after all.
I have made a test here: <a href="http://ideone.com/Fo5ZeW" rel="nofollow noreferrer">http://ideone.com/Fo5ZeW</a></p>
<pre><code>#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;
double* binary_search8(double* arr, const double& x)
{
if (x<arr[4]) {
if(x<arr[2]) {
if(x<arr[1]) {
return arr;
} else {
return arr + 1;
}
}
else { //2..3
if(x<arr[3]){
return arr + 2;
} else {
return arr + 3;
}
}
} else { // 4..7
if(x<arr[6]) {
if(x<arr[5]) {
return arr + 4;
} else {
return arr + 5;
}
} else { //6..7
if(x<arr[7]) {
return arr + 6;
} else {
return arr + 7;
}
}
}
}
double* binary_search16(double* arr, const double& x)
{
if (x<arr[8]) return binary_search8(arr, x);
else return binary_search8(arr+8, x);
}
int main() {
double test[16] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150};
vector<double> test_vals;
size_t num_elem = 10000000;
for (size_t i=0; i<num_elem; i++)
test_vals.push_back(rand()%150);
clock_t begin, end;
double elapsed_secs;
// Linear search
double linavg = 0;
begin = clock();
for (size_t i=0; i<num_elem; i++) {
linavg += *(find_if(test, test+16, bind2nd(std::greater_equal<double>(), test_vals[i]))-1);
}
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "linear secs: " <<elapsed_secs << ", testval = " << linavg << std::endl;
// Binary search
double binavg = 0;
begin = clock();
for (size_t i=0; i<num_elem; i++) {
binavg += *binary_search16(test, test_vals[i]);
}
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "binary secs: " <<elapsed_secs << ", testval = " << binavg << std::endl;
// Binary search 2
double binavg2 = 0;
begin = clock();
for (size_t i=0; i<num_elem; i++) {
binavg2 += *(std::upper_bound(test, test+16, test_vals[i])-1);
}
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "binary2 secs: " <<elapsed_secs << ", testval = " << binavg2 << std::endl;
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:25:13.527",
"Id": "76048",
"Score": "0",
"body": "Would be nice, if you post, if and how much you have improved the speed with witch attempt. maybe there are also some possible improvements in your *interpolation between the sample points*. Maybe make it part of another review question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:13:25.683",
"Id": "76352",
"Score": "0",
"body": "Have you tested if linear search is still faster for your 64 elements? Binary search would for 64 cases reduce the average number of comparisons from 32 to 6."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T05:45:50.037",
"Id": "76407",
"Score": "0",
"body": "@MrSmith42 yes, it is. Branch prediction is phenomenally effective in this case it seems."
}
] | [
{
"body": "<p>Why do you need a <strong>linear search [O(n)]</strong>? </p>\n\n<p>You can determine in which interval the value belongs by a <strong>binary search [O(log n)]</strong> (do not implement is with a recursion! use a loop or hard-code it))). </p>\n\n<p>Average number of comparisons for linear search is <strong>n/2</strong>.\nBinary search needs a constant number of comparisons of <strong>ceiling( ln(n) / ln(2) )</strong>.</p>\n\n<pre><code> \\ n| 1 | 2 | 4 | 8 | 16 | 32 | 64\n--------------+----+----+----+----+----+----+---- ...\nlinear-search | 0 | 1 | 2 | 4 | 8 | 16 | 32 \nbinary-search | 0 | 1 | 2 | 3 | 4 | 5 | 6 \n</code></pre>\n\n<p>So binary search should be faster, if comparison is the main factor, for <strong>n > 4</strong>.</p>\n\n<p>If n is constant (its seams 64 in your case) you can even hard-code the binary search to avoid the overhead of a loop. (that is also possible for linear search.)</p>\n\n<p>As an example how to hard-code a binary search: [for a array with 8 entries]\nCode will get quite long for 64 entries, but it will be fast.</p>\n\n<p>If your <em>intervallBoundary</em> array is intervals[0..7]:</p>\n\n<pre><code> if(x<intervalls[4]){\n if(x<intervalls[2]){\n if(x<intervalls[1]) \n return intervall0;\n else\n return intervall1\n }\n else{ //2..3\n if(x<intervalls[3]) \n return intervall2;\n else\n return intervall3\n }\n else{ // 4..7\n if(x<intervalls[6]){\n if(x<intervalls[4]) \n return intervall4;\n else\n return intervall5\n }\n else{ //6..7\n if(x<intervalls[7]) \n return intervall6;\n else\n return intervall7\n }\n }\n</code></pre>\n\n<hr>\n\n<p><strong>REMARK</strong> </p>\n\n<p>If there is any rule for the distribution of the intervals, you might be able to calculate the correct interval (or at least calculate a good guess and search from there).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:58:50.487",
"Id": "75985",
"Score": "0",
"body": "The constant that gets dropped in Landau notation is the reason $c$ in $O(c*log(n))$ for all arrays smaller than 64 linear search is faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:59:29.713",
"Id": "76010",
"Score": "0",
"body": "Added a hard-coded binary search example for 8 cases."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:26:58.900",
"Id": "43924",
"ParentId": "43920",
"Score": "1"
}
},
{
"body": "<p>It'll take some testing to be entirely certainly, but a few possibilities to consider:</p>\n\n<pre><code>if (x >= *cache && x < *(cache + 1)) {\n</code></pre>\n\n<p>I'd try replacing this with:</p>\n\n<pre><code>if (static_cast<unsigned>(x-*cache) < static_cast<unsigned>(*(cache+1) - *cache)) {\n</code></pre>\n\n<p>[Technically, <code>unsigned</code> is a place-holder here. It should really be something like <code>std::make_unsigned<input_type>::type</code>. That is, if the input is (say) <code>long long</code>, you want <code>unsigned long long</code>, not just <code>unsigned int</code>.]</p>\n\n<p>This basically replaces two comparisons (that must be executed serially, thanks to <code>&&</code> imposing a sequence point) with one plus a little extra math. The math can typically be done in parallel, and the branch becomes more predictable as well.</p>\n\n<pre><code>if (x < *begin || x > *end) {\n outside = true;\n} else {\n outside = false;\n</code></pre>\n\n<p>I'd at least try just assigning the result of the comparison:</p>\n\n<pre><code>outside = x < *begin || x > *end;\n</code></pre>\n\n<p>Again, you can try the same \"trick\" as above, and get something like:</p>\n\n<pre><code>outside = static_cast<unsigned>(x-*begin) <= static_cast<unsigned>(*end-*begin);\n</code></pre>\n\n<p>As before, this replaces two relatively unpredictable comparisons with one relatively predictable one.</p>\n\n<pre><code>if (n_ < 64) {\n[3%] position = std::find_if(begin, end, std::bind2nd(std::greater_equal<argument_type>(), x)) - 1;\n } else { \n position = std::upper_bound(begin, end, x) - 1;\n }\n</code></pre>\n\n<p>If you're spending significantly more time in the linear search than the binary search, I'd try reducing the cut-off between the two, perhaps to 32 instead of 64.</p>\n\n<p>As with any micro-optimization, none of these is really guaranteed to be effective. It's even possible your compiler may be incorporating one or more of them into the code it generates, so they'll do no good at all, or even that its optimizer won't recognize the resulting patterns in the code as well, so they could actually hurt performance. The only real way to find out is some testing and profiling.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:57:01.213",
"Id": "43970",
"ParentId": "43920",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T10:29:30.293",
"Id": "43920",
"Score": "6",
"Tags": [
"c++",
"optimization",
"performance",
"lookup"
],
"Title": "How to speed up interval lookup for a piecewise defined function?"
} | 43920 |
<p>After suggestions given in this <a href="https://codereview.stackexchange.com/questions/43476/simulation-of-an-ocean-containing-sharks-and-fish">question</a>, modifications to the code has been done.</p>
<p>Only thing I could not do is to decide, where to place the <code>starveTime</code> property (in <code>Shark</code> class or somewhere in a common place) because <code>starveTime</code> is not specific to <code>Shark</code>, it is common to any eating creature (other fish), currently <code>Shark</code> persist eating creature.</p>
<p>Please review from OOPS aspect/memory usage/... aspect.</p>
<p>Here is the modified code.</p>
<pre><code>/* point.java */
/**
* The Point class defines a location (x,y) in the Ocean.
*
* @author mohet01
*
*/
public class Point {
/**
* Here top-left of Windows screen is considered as origin.
* x is an x-coordinate of a location in an ocean
* y is an y-coordinate of a location in an Ocean
*/
private int x;
private int y;
/**
* Constructor creates a Point object below co-ordinates
* @param x
* is an x-coordinate of a Critter location in an Ocean
* @param y
* is an y-coordinate of a Critter location in an Ocean
*/
public Point(int x, int y){
this.x = x;
this.y = y;
}
/**
* This method returns the x-coordinate of Critter in an ocean
* @return
* x-coordinate of a Critter location in an Ocean.
*/
public int getX(){
return this.x;
}
/**
* This method returns the y-coordinate of Critter in an ocean
* @return
* y-coordinate of a Critter location in an Ocean.
*/
public int getY(){
return this.y;
}
}
</code></pre>
<hr>
<pre><code>/* Critter.java */
/**
* The abstract class Critter defines a base class for anything(which can be empty)
* that can exist at a specific location in the ocean.
* @author mohet01
*
*/
public abstract class Critter {
/**
* Below data member defines a location of a Critter in an Ocean
*/
Point location;
public Critter(int x, int y){
location = new Point(x,y);
}
public Point getLocation(){
return location;
}
/**
* This method computes the new value of location(which can be EMPTY) property of Critter.
* No operation is performed as this is a base class.
*/
public abstract Critter update(Ocean currentTimeStepSea);
}
</code></pre>
<hr>
<pre><code>/* Shark.java */
/**
* The Shark class defines behavior of a Shark in an Ocean.
* @author mohet01
*
*/
public class Shark extends Critter{
/**
* Below data member is the number of simulation time steps that a Shark
* can live through without eating.
*/
private static int starveTime;
/**
* Below data member specifies the hunger of each shark you add to the
* ocean.
*/
private int hungerLevel;
/**
* Constructor will create a new location for Shark
* @param x
* is the x-coordinate of location(which can be EMPTY) of Shark
* @param y
* is the y-coordinate of location(which can be EMPTY) of Shark
*/
public Shark(int x, int y, int starveTime, int hungerLevel){
super(x,y);
//need to remove this below line and assign it when class is loaded
starveTime = starveTime;
//Sharks are well-fed at birth
this.hungerLevel = hungerLevel;
}
/*
* This method provides the starvation time of Shark creature
*/
public static int getStarvationTime(){
return starveTime;
}
/**
* isSharkStarving() checks the hunger level of shark, if reached to starveTime level
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
* @return the boolean value
*/
private boolean isSharkStarving(){
return (this.hungerLevel == (starveTime+1));
}
/**
* This method updates the shark cell based on the behavior of it's
* nearest neighborhood
* @param currentTimeStepSea
* Ocean in the current time step
* @param nextTimeStepSea
* Ocean that has to look like in next time Step
*
*/
@Override
public Critter update(Ocean currentTimeStepSea){
boolean gotTheFish = false;
//Check all the 8 neighbors of a Shark Cell for fish
gotTheFish = Utility.checkFishAsNeighbor(this, currentTimeStepSea);
//Updating Shark Cell
if(gotTheFish){
/*
* 1) If a cell contains a shark, and any of its neighbors is a fish, then the
* shark eats during the time step, and it remains in the cell at the end of the
* time step. (We may have multiple sharks sharing the same fish. This is fine;
* they all get enough to eat.)
*/
return this; //return currentTimeStep Shark
}else{
/*
* 2) If a cell contains a shark, and none of its neighbors is a fish, it gets
* hungrier during the time step. If this time step is the (starveTime + 1)th
* time step the shark has gone through without eating, then the shark dies
* (disappears). Otherwise, it remains in the cell.
*
*/
this.hungerLevel++;
if(isSharkStarving()){
return new Empty(this.getLocation().getX(), this.getLocation().getY());
}
else{
return this; //return currentTimeStep Shark
}
}
}
}
</code></pre>
<hr>
<pre><code>/* Fish.java */
/**
* The Fish class defines the behavior of a Fish in an Ocean
* @author mohet01
*
*/
public class Fish extends Critter{
/**
* Constructor will create a new location for Fish
* @param x
* is the x-coordinate of location(which can be EMPTY) of Fish
* @param y
* is the y-coordinate of location(which can be EMPTY) of Fish
*/
public Fish(int x, int y){
super(x,y);
}
/**
* This method updates the Fish cell based on the behavior of it's
* nearest neighborhood
* @param currentTimeStepSea
* Ocean in the current time step
* @param nextTimeStepSea
* Ocean that has to look like in next time Step
*
*/
@Override
public Critter update(Ocean currentTimeStepSea){
int neighborSharkCount=0;
neighborSharkCount = Utility.countSharkAsNeighbor(this, currentTimeStepSea);
//Updating fish cell for current & next time step
if(neighborSharkCount ==1){
/*
* 4) If a cell contains a fish, and one of its neighbors is a shark, then the
* fish is eaten by a shark, and therefore disappears.
*
*/
return new Empty(this.getLocation().getX(),this.getLocation().getY());
}
else if(neighborSharkCount > 1){
/*
* 5) If a cell contains a fish, and two or more of its neighbors are sharks, then
* a new shark is born in that cell. Sharks are well-fed at birth; _after_ they
* are born, they can survive an additional starveTime time steps without eating.
*
*/
return new Shark(this.getLocation().getX(),this.getLocation().getY(),Shark.getStarvationTime(),0);
}
else {
/*
* condition is (neighborSharkCount < 1)
* 3) If a cell contains a fish, and all of its neighbors are either empty or are
* other fish, then the fish stays where it is.
*/
return this;
}
}
}
</code></pre>
<hr>
<pre><code>/* Empty.java */
/**
* The Empty class defines itself as an entity as it has some meaning/significance
* being empty in an Ocean. Check update() method for more meaning.
* @author mohet01
*
*/
public class Empty extends Critter{
/**
* Constructor will create a new location which is Empty
* @param x
* is the x-coordinate of location which is Empty.
* @param y
* is the y-coordinate of location which is empty.
*/
public Empty(int x, int y){
super(x,y);
}
/**
* This method updates the Empty cell based on the behavior of it's
* nearest neighborhood
* @param currentTimeStepSea
* Ocean in the current time step
* @param nextTimeStepSea
* Ocean that has to look like in next time Step
*
*/
@Override
public Critter update(Ocean currentTimeStepSea) {
int neighborFishCount = 0;
int neighborSharkCount = 0;
//Check all the 8 neighbors of an Empty cell to count sharks and Fish
neighborSharkCount = Utility.countSharkAsNeighbor(this, currentTimeStepSea);
neighborFishCount = Utility.countFishAsNeighbor(this,currentTimeStepSea);
//Update Empty Cell for next time step.
if((neighborFishCount >= 2) && (neighborSharkCount <=1)){
/*
* 7) If a cell is empty, at least two of its neighbors are fish, and at most one
* of its neighbors is a shark, then a new fish is born in that cell.
*
*/
return new Fish(this.getLocation().getX(),this.getLocation().getY());
}else if((neighborFishCount >= 2) && (neighborSharkCount >= 2)){
/*
* 8) If a cell is empty, at least two of its neighbors are fish, and at least two
* of its neighbors are sharks, then a new shark is born in that cell. (The new
* shark is well-fed at birth, even though it hasn’t eaten a fish yet.)
*
*/
return new Shark(this.getLocation().getX(),this.getLocation().getY(),Shark.getStarvationTime(),0);
}
else{
/*
* 6) If a cell is empty, and fewer than two of its neighbors are fish, then the
* cell remains empty.
*/
return this;
}
}
}
</code></pre>
<hr>
<pre><code>/* Ocean.java */
/**
* The Ocean class defines an object that models an ocean full of sharks and
* fish.
* @author mohet01
*
*/
public class Ocean {
/**
* Define any variables associated with an Ocean object here. These
* variables MUST be private.
*
*/
//width of an Ocean
private int width;
//height of an Ocean
private int height;
/*
* @Mat I preferred, 2d array of references to Critter objects
* rather than List. Reasons(correct me),
* 1) To display an array of ocean, it adds more logic in paint() method.
* 2) Checking 8 nearest neighbors of each Critter looks inefficient,
* For example: for an ocean of SEEFE
* FEEFE a 2x2 ocean, If i maintain
* a list of Critter for this 2x2 ocean, i need to traverse
* S->E->E->F->E->F to get my first nearest neighbor of Shark,
* In contrast, With 2d array, I would just use modulo operation as
* mentioned in update() method. Let us see what happens!!!
*
*/
private Critter[][] oceanMatrix;
/**
* Constructor that creates an empty ocean with below dimension
*
* @param width
* is the width of the ocean.
* @param height
* is the height of the ocean.
*
*/
public Ocean(int width, int height){
this.oceanMatrix = new Critter[height][width];
this.width = width;
this.height = height;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
oceanMatrix[row][col] = new Empty(row,col);
}
}
}
/**
* This method adds Critter in an ocean.
* @param object
* is the Critter object to be added in Ocean.
*/
public void addCritter(Critter object){
Point p = object.getLocation();
int x = p.getX();
int y = p.getY();
/*
* @Mat I understand that, location property make sense to be be moved
* to corresponding Critter<type> class as it's property, which i did, But
* also captured location property of a Critter Object in Ocean class(with
* above 3 lines of code) which is redundant and not relevant, But 2d array
* is more efficient than list, for checking neighbor in update() method.
* Are we Breaking SRS????
* So, Instead of List am using 2d array. Let us see what happens!!!
*/
oceanMatrix[x][y] = object;
}
/**
* This method returns either Critter Object reference
*
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
*/
public Critter cellContents(int x, int y) {
return oceanMatrix[x][y];
}
/**
* getWidth() returns the width of an ocean Object.
*
* @return
* the width of the ocean.
*
*/
public int getWidth() {
return this.width;
}
/**
* getHeight() returns the height of an Ocean object.
*
* @return
* the height of the Ocean.
*/
public int getHeight() {
return this.height;
}
/**
* timeStep() performs a simulation time step as described in README.
*
* @return
* an ocean representing the elapse of one time Step.
*/
public Ocean timeStep() {
Ocean nextTimeStepSea = new Ocean(width, height);
for (int row = 0; row < this.height; row++) {
for (int col = 0; col < this.width; col++) {
Critter creature = this.cellContents(row, col);
nextTimeStepSea.addCritter(creature.update(this));
}
}
return nextTimeStepSea;
}
}
</code></pre>
<hr>
<pre><code>/* Utility.java */
/**
* The Utility class provides some utility functions which are used
* by multiple classes like Fish, Shark etc...
* @author mohet01
*
*/
public final class Utility {
/**
* Don't let anyone instantiate this class.
*/
private Utility() {}
/**
* This method checks the existence of at-least one fish as nearest
* neighbor surrounding Creature's cell
* @param sea
* is the ocean of currentTimeStep
* @return
* returns true on at-least one fish existence otherwise false
*
*/
public static boolean checkFishAsNeighbor(Critter creature, Ocean sea){
//get Creatures location
Point p = creature.getLocation();
int x = p.getX();
int y = p.getY();
int row,col;
for(int i = x-1;i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
/*
* Problem statement says(as per link):
* http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/readme
* You can also refer to locations such as (4, 0) or (-4, 3),
* which are both the same as (0, 0) in a 4x3 ocean.
* so modulo is being performed for given i & j
*/
row = mod(i, sea.getHeight());
col = mod(i, sea.getWidth());
if(sea.cellContents(row, col) instanceof Fish)
return true;
}
}
return false;
}
/**
* This method counts number of Shark as nearest neighbor surrounding
* Creature's cell
* @param sea
* is the ocean of currentTimeStep
* @return
* returns number of Shark surrounding creature
*
*/
public static int countSharkAsNeighbor(Critter creature, Ocean sea){
int neighborSharkCount = 0;
//get Creatures location
Point p = creature.getLocation();
int x = p.getX();
int y = p.getY();
int row,col;
for(int i = x-1;i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
/*
* Problem statement says(as per link):
* http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/readme
* You can also refer to locations such as (4, 0) or (-4, 3),
* which are both the same as (0, 0) in a 4x3 ocean.
* so modulo is being performed for given i & j
*/
row = mod(i, sea.getHeight());
col = mod(i, sea.getWidth());
if(sea.cellContents(row, col) instanceof Shark)
neighborSharkCount++;
}
}
return neighborSharkCount;
}
/**
* This method counts number of Fish as nearest neighbor surrounding
* Creature's cell
* @param sea
* is the ocean of currentTimeStep
* @return
* returns number of Fish surrounding creature
*
*/
public static int countFishAsNeighbor(Critter creature, Ocean sea){
int neighborFishCount = 0;
//get Creatures location
Point p = creature.getLocation();
int x = p.getX();
int y = p.getY();
int row,col;
for(int i = x-1;i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
/*
* Problem statement says(as per link):
* http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/readme
* You can also refer to locations such as (4, 0) or (-4, 3),
* which are both the same as (0, 0) in a 4x3 ocean.
* so modulo is being performed for given i & j
*/
row = mod(i, sea.getHeight());
col = mod(i, sea.getWidth());
//if((sea.cellContents(row, col).getClass().getName()).equals(Fish.class))
if(sea.cellContents(row, col) instanceof Fish)
neighborFishCount++;
}
}
return neighborFishCount;
}
/**
* This method performs the modulo operation using euclidean divison
*
* @param n
* is the numerator
* @param d
* is the denominator
* @return
* Remainder
*/
private static int mod(int n, int d) {
if (n >= 0)
return n % d;
else
return d + ~(~n % d);
}
}
</code></pre>
<hr>
<pre><code>import java.util.Random;
/* SimText.java */
/* DO NOT CHANGE THIS FILE (except as noted). */
/* (You may wish to make temporary or insert println() statements */
/* while testing your code. when you're finished testing and debugging, */
/* though, make sure your code works with the original version of this file. */
/**
* The SimText class is a program that runs and animates a simulation of Sharks
* and Fish.
*
* The SimText program takes up to four parameters. The first two specify the
* width and height of the ocean. The third parameter specifies the value of
* starveTime. For example, if you run
*
* java SimText 25 25 1
*
* then SimText will animate a 25x25 ocean with a starveTime of 1. If you run
* "java SimText" with no parameters, by default SimText will animate a 50x25
* ocean with a starveTime of 3. With some choices of parameters, the ocean
* quickly dies out; with others, it teems forever.
* @author mohet01
*
*/
public final class SimText {
/**
* Don't let anyone instantiate this class.
*/
private SimText(){}
/**
* Default parameters. (You may change these if you wish.)
*
*/
// Default ocean width
private static int width = 50;
// Default ocean height
private static int height = 25;
// Default shark starvation time
private static int starveTime = 3;
//Default Shark hunger Level
private static int hungerLevel = 0;
/**
* The {@code MAGIC_NUMBER} is a prime number that is used in LCG
* expressions to select random location in an Ocean.
*/
private static final int MAGIC_NUMBER = 78887;
private static final int LOC_MULTIPLE_OF_NUMBER = 8;
/**
* paint() prints an Ocean.
*/
public static void paint(Ocean sea) {
if (sea != null) {
int width = sea.getWidth();
int height = sea.getHeight();
/* Draw the ocean */
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
for (int row = 0; row < height; row++) {
System.out.print("|");
for (int col = 0; col < width; col++) {
Critter creature = sea.cellContents(row, col);
System.out.print(creature.getClass().getName().substring(0, 1));
}
System.out.println("|");
}
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
}
}
/**
* main() reads the parameters and performs the simulation and animation.
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Ocean sea;
/**
* Read the input parameters.
*/
if (args.length > 0) {
try {
width = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out
.println("First argument to SimText is not an number");
}
}
if (args.length > 1) {
try {
height = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.out
.println("Second argument to SimText is not an number");
}
}
if (args.length > 2) {
try {
starveTime = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out
.println("Third argument to SimText is not an number");
}
}
/**
* Create the initial ocean.
*/
sea = new Ocean(width, height);
/**
* Visit each cell (in a roundabout order); randomly place either Fish,
* or Shark or Empty Object in each location.
*
*/
// Create a "Random" object with seed 0
Random random = new Random(0);
int x = 0;
int y = 0;
for (int row = 0; row < height; row++) {
x = (x + MAGIC_NUMBER) % height;
if ((x & LOC_MULTIPLE_OF_NUMBER) == 0) {
for (int col = 0; col < width; col++) {
y = (y + MAGIC_NUMBER) % width;
if ((y & LOC_MULTIPLE_OF_NUMBER) == 0) {
// Between -2147483648 and 2147483647
int r = random.nextInt();
if (r < 0) {
sea.addCritter(new Fish(x,y));
} else if (r > 1500000000) {
sea.addCritter(new Shark(x,y,starveTime,hungerLevel));
}
}
}
}
else{
sea.addCritter(new Empty(x,y));
}
}
/**
* Perform time steps forever.
*
*/
// Loop forever
while (true) {
paint(sea);
// For fun, you might wish to change the delay in the next line.
Thread.sleep(1000); // Wait one second (1000 milliseconds)
sea = sea.timeStep(); // Simulate a timestep
}
}/* end main() */
}
</code></pre>
<hr>
| [] | [
{
"body": "<p>Just one quick observation: There seems to be no point in the <code>Point</code> class (pun not intended). Its fields are private, so you can't ever read anything from it, and you don't actually use it anyway, except for the <code>Critter</code>s location property of which the getter <code>getLocation</code> is also never used.</p>\n\n<p>EDIT: Just realized you haven't implemented anything yet, so that's why you don't use <code>location</code> :-) But you still need to create getters for the fields of <code>Point</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:51:24.760",
"Id": "76434",
"Score": "0",
"body": "Above is the solution for part I of problem in [link](http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/readme)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:08:04.777",
"Id": "76484",
"Score": "0",
"body": "Jus edited the question, My question wrt starveTime is, starveTime cannot be a per class variable, it should be common any creature that eats like whale or shrimp. so what should be the solution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:46:39.807",
"Id": "76549",
"Score": "0",
"body": "@tintinmj As you requested for test cases, I do not have test cases to test this program, Do i need to use JUNIT to create test cases in eclipse?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T03:36:57.757",
"Id": "76644",
"Score": "0",
"body": "Can somebody respond to my query?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:37:09.270",
"Id": "43925",
"ParentId": "43921",
"Score": "5"
}
},
{
"body": "<h2>Critter</h2>\n<p>Your <code>Point</code> class is, as @RoToRa pointed out, underused. This constructor:</p>\n<pre><code>Point location;\n\npublic Critter(int x, int y){\n location = new Point(x,y);\n}\n</code></pre>\n<p>Could be simplified to this:</p>\n<pre><code>Point _location;\n\npublic Critter(Point location){\n _location = location;\n}\n</code></pre>\n<p>Also in this snippet:</p>\n<pre><code>/**\n * This method computes the new value of location(which can be EMPTY) property of Critter.\n * No operation is performed as this is a base class.\n */\npublic abstract Critter update(Ocean currentTimeStepSea);\n</code></pre>\n<p>The comment "no operation is performed as this is a base class" is redundant, because the method is <code>abstract</code> - don't bother writing comments that reword what the code already says.</p>\n<p>I'll skip the implementing classes and <s>jump</s> <em>dive</em> straight into the <code>Ocean</code>.</p>\n<hr />\n<h2>Ocean</h2>\n<p>You've replaced the lightweight integers you had in your array with objects. That's great, but you still have an array with tons of objects you don't need to care about - the <code>Empty</code> class doesn't need to exist. Let's see why.</p>\n<p><img src=\"https://i.stack.imgur.com/4tjCw.png\" alt=\"enter image description here\" /></p>\n<ul>\n<li>An ocean <em>has critters</em> and <em>updates</em> periodically.</li>\n<li>A critter <em>has a location</em> and <em>updates</em> periodically. To do so it needs to know about other critters in the sea, so the <code>Update</code> method takes in a <code>Iterable<Critter></code>. A critter can also be "dead" and need to be removed from the ocean.</li>\n</ul>\n<h3>Update</h3>\n<p>Your current implementation starts like this:</p>\n<pre><code>Ocean nextTimeStepSea = new Ocean(width, height);\n</code></pre>\n<p>So at every <em>time step</em>, you're re-creating the entire ocean?! What is it exactly that needs to happen in the Ocean's <em>update</em> method? Every critter must be updated. The easiest is to iterate the <code>_critters</code> list and call each instance's <code>update</code> method, passing in the <code>_critters</code> list as the <code>Iterable<Critter></code> parameter.</p>\n<p>After all critters have updated, the ocean's <em>update</em> method should spawn the new critters (<code>add</code> them to <code>_critters</code>) and destroy (<code>remove</code> them from <code>_critters</code>) the dead ones; you'll want to do that <em>after</em> a first iteration over all critters, for sanity's sake.</p>\n<p>Note that the <code>Ocean</code> class doesn't need to expose an <code>addCritter</code> or <code>removeCritter</code> method to do that.</p>\n<hr />\n<p>To make your code more object-oriented, you'll need to think in terms of <em>objects</em>, not just in terms of <em>solving a problem</em>. Forget about the <code>oceanMatrix[][]</code> - the ocean doesn't even need to have a size. If you want to have a maximum size, it's not really the ocean's size you're defining, but the boundaries of the virtual "box" a critter is allowed to move in. Thus, I'd probably define these as <code>private static final Point maxMove</code> fields (or whatever the Java equivalent of C# <code>private static readonly Point maxMove</code> is) in the <code>Critter</code> base class. What you <em>don't</em> want to be doing here, is declaring that <code>Point</code> on the <code>Ocean</code> class, and <em>tightly couple</em> critters with the <code>Ocean</code> class by merely referring to it: it's important that critters don't even know an ocean exists.</p>\n<p>To facilitate the implementation of your <code>paint</code> method to render the ocean and its critters on-screen, you could implement a <code>Critter getContent(Point)</code> method on the <code>Ocean</code> class that returns either <code>null</code> or the <code>Critter</code> instance that populates the specified coordinate; if the method returns <code>null</code> you draw nothing, if it returns a <code>Critter</code> that's alive (in theory the ocean's <code>update</code> method will have removed dead critters so that wouldn't need to be checked), you can draw a fish if it's a <code>Fish</code>, and you can draw a shark if it's a <code>Shark</code> - that's <em>one</em> simple, naive way of going about it, but it's a start.</p>\n<p>The bottom line, is that <code>Ocean</code> must stop being represented as an array of X-Y coordinates with a "content", and start being a <em>composition</em> of objects with their own concerns. I'm sure the <code>Utility</code> class will become useless when everything is in its place.</p>\n<hr />\n<p>As for where the <code>starveTime</code> should go... how about deriving a <code>PredatorCritter</code> class from <code>Critter</code>, putting <code>starveTime</code> in there, and deriving <code>Shark</code> from <code>PredatorCritter</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:35:38.287",
"Id": "81667",
"Score": "0",
"body": "Mat, In this simulation project, I would like to understand, What is Data Abstraction? What is Encapsulation? Can you let me know your understanding on these in my simulation project?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T04:18:28.157",
"Id": "44227",
"ParentId": "43921",
"Score": "8"
}
},
{
"body": "<h3>Classes and modelling</h3>\n\n<p>I'm going to make some recommendations, some of which are in direct contradiction to <a href=\"https://codereview.stackexchange.com/a/43477/9357\">previous advice from @MatsMug</a>. Specifically, I'd resist the urge to take the object-oriented modelling too seriously.</p>\n\n<p>This problem is just a variant of the <a href=\"/questions/tagged/game-of-life\" class=\"post-tag\" title=\"show questions tagged 'game-of-life'\" rel=\"tag\">game-of-life</a>. In most Game of Life implementations, you'll find that most of the logic is in a Board class. In this problem, I wouldn't ask the <code>Shark</code> and <code>Fish</code> classes to do too much. Each <code>Shark</code> should keep track of its own hunger level. That's about it. Each critter does not need to know its coordinates. Quite the opposite is true: the ocean needs to know what critter occupies each cell, since much of the logic is about inspecting the neighbours of each cell. Furthermore, the position is not really part of the state of each critter — once a critter comes into existence, it never moves.</p>\n\n<p>You tried to set <code>Shark.starveTime</code> as a <code>static</code> constant. I understand the instinct to make it a property of the <code>Shark</code> class, but here it's actually a property of the <code>Ocean</code> that is being simulated. It's similar to the idea that the fine structure constant is a property of our Universe, and <a href=\"http://en.wikipedia.org/wiki/Fine-structure_constant#Anthropic_explanation\" rel=\"nofollow noreferrer\">tweaking its value would lead to a different looking Universe</a>. (Imagine multiple ocean simulations running in multiple threads of the same Java process, each with a different <code>starveTime</code> setting. You don't want the <code>starveTime</code> to be a class variable of <code>Shark</code>. It could be an instance variable of <code>Shark</code>, but ultimately each shark would take on its <code>starveTime</code> value from the ocean it inhabits.)</p>\n\n<p>You currently have <code>Point</code> and <code>Utility</code> classes. As others have pointed out, <code>Point</code> is aimless. Naming a class <code>Utility</code> is a red flag. I think that the solution to both problems is to combine them into a <code>Cell</code> class. A <code>Cell</code> has an x-y coordinate, has an <code>Occupant</code> (a more generic name for what you call a <code>Critter</code>), and knows how to classify and count its neighbouring cells' occupants.</p>\n\n<p>As suggested in the instructions, a solution would rely mostly on duplicating immutable objects rather than mutating objects in place. Therefore, almost all of the instance variables should be <code>final</code> to enforce immutability.</p>\n\n<hr>\n\n<p>Based on the principles above, I would write the <code>Ocean</code> class and a few inner classes this way. The remaining <code>Fish</code> and <code>Shark</code> classes are rather trivial.</p>\n\n<pre><code>public class Ocean {\n\n //////////////////////////////////////////////////////////////////////\n\n public class Cell {\n private final int x, y;\n private Occupant occupant;\n\n public Cell(int x, int y) {\n this.x = x;\n this.y = y;\n this.occupant = EMPTY_CELL;\n }\n\n public void putOccupant(Occupant o) {\n this.occupant = o;\n }\n\n public Occupant getOccupant() {\n return this.occupant;\n }\n\n /**\n * 1) If a cell contains a shark, and any of its neighbors is a fish, then the\n * shark eats during the timestep, and it remains in the cell at the end of the\n * timestep. (We may have multiple sharks sharing the same fish. This is fine;\n * they all get enough to eat.)\n * \n * 2) If a cell contains a shark, and none of its neighbors is a fish, it gets\n * hungrier during the timestep. If this timestep is the (starveTime + 1)th\n * timestep the shark has gone through without eating, then the shark dies\n * (disappears). Otherwise, it remains in the cell. An example demonstrating\n * this rule appears below.\n * \n * 3) If a cell contains a fish, and all of its neighbors are either empty or are\n * other fish, then the fish stays where it is.\n * \n * 4) If a cell contains a fish, and one of its neighbors is a shark, then the\n * fish is eaten by a shark, and therefore disappears.\n * \n * 5) If a cell contains a fish, and two or more of its neighbors are sharks, then\n * a new shark is born in that cell. Sharks are well-fed at birth; _after_ they\n * are born, they can survive an additional starveTime timesteps without eating.\n * (But they will die at the end of starveTime + 1 consecutive timesteps without\n * eating.)\n * \n * 6) If a cell is empty, and fewer than two of its neighbors are fish, then the\n * cell remains empty.\n * \n * 7) If a cell is empty, at least two of its neighbors are fish, and at most one\n * of its neighbors is a shark, then a new fish is born in that cell.\n * \n * 8) If a cell is empty, at least two of its neighbors are fish, and at least two\n * of its neighbors are sharks, then a new shark is born in that cell. (The new\n * shark is well-fed at birth, even though it hasn't eaten a fish yet.)\n */\n public Occupant timeStep() {\n Occupant occ = getOccupant();\n switch (occ.getType()) {\n case SHARK:\n switch (countNeighbors(Fish.class)) {\n case 0:\n // 2) Shark gets hungrier and may die\n return occ.age();\n default:\n // 1) Shark eats neighboring fish\n return new Shark(Ocean.this.getStarveTime());\n }\n case FISH:\n switch (countNeighbors(Shark.class)) {\n case 0:\n // 3) Fish lives\n return occ.age();\n case 1:\n // 4) Fish gets eaten by one shark neighbor\n return EMPTY_CELL;\n default:\n // 5) Baby shark replaces this fish\n return new Shark(Ocean.this.getStarveTime());\n }\n default:\n switch (countNeighbors(Fish.class)) {\n case 0:\n case 1:\n // 6) Cell remains empty\n return occ.age();\n default:\n switch (countNeighbors(Shark.class)) {\n case 0: case 1:\n // 7) New fish born\n return new Fish();\n default:\n // 8) New shark born\n return new Shark(Ocean.this.getStarveTime());\n }\n }\n }\n }\n\n private <T extends Occupant> int countNeighbors(Class<T> type) {\n int count = 0;\n for (Cell c : getNeighbors()) {\n if (type.isInstance(c.getOccupant())) {\n count++;\n }\n }\n return count;\n }\n\n private Cell[] getNeighbors() {\n return new Cell[] {\n cell(x - 1, y - 1), cell(x - 1, y), cell(x - 1, y + 1),\n cell(x , y - 1), cell(x , y + 1),\n cell(x + 1, y - 1), cell(x + 1, y), cell(x + 1, y + 1)\n };\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n public static abstract class Occupant {\n public Occupant age() {\n return this;\n }\n\n public abstract int getType();\n }\n\n //////////////////////////////////////////////////////////////////////\n\n public static final Occupant EMPTY_CELL = new Occupant() {\n @Override\n public int getType() {\n return 0;\n }\n };\n\n public static final int SHARK = Shark.TYPE_CODE,\n FISH = Fish.TYPE_CODE;\n\n private final int starveTime;\n private final Cell[][] cells;\n\n /**\n * Constructor\n *\n * @param i width of the toroidal ocean\n * @param j height of the toroidal ocean\n * @param starveTime time steps that sharks can live without eating\n */\n public Ocean(int i, int j, int starveTime) {\n this.starveTime = starveTime;\n\n // Matrix is in column-major order!\n // (0, 0) (1, 0) ... (i, 0)\n // . . .\n // . . .\n // (0, j) (1, j) ... (i, j)\n this.cells = new Cell[i][j];\n for (int x = 0; x < i; x++) {\n for (int y = 0; y < j; y++) {\n this.cells[x][y] = new Cell(x, y);\n }\n }\n }\n\n public int getStarveTime() {\n return this.starveTime;\n }\n\n public void addFish(int x, int y) {\n this.cell(x, y).putOccupant(new Fish());\n }\n\n public void addShark(int x, int y) {\n this.cell(x, y).putOccupant(new Shark(this.getStarveTime()));\n }\n\n public int width() {\n return this.cells.length;\n }\n\n public int height() {\n return this.cells[0].length;\n }\n\n public Ocean timeStep() {\n Ocean next = new Ocean(width(), height(), getStarveTime());\n for (int x = 0; x < width(); x++) {\n for (int y = 0; y < height(); y++) {\n next.cells[x][y].putOccupant(this.cell(x, y).timeStep());\n }\n }\n return next;\n }\n\n public int cellContents(int x, int y) {\n return cell(x, y).getOccupant().getType();\n }\n\n private Cell cell(int x, int y) {\n return this.cells[((x % width()) + width()) % width()]\n [((y % height()) + height()) % height()];\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T09:26:33.133",
"Id": "76883",
"Score": "0",
"body": "Sure i will make these changes, another point is, i want to make this simulation browser based rather than taking input from stdin & displaying on stdout, Is it relevant to use applet approach or servlet program approach for the kind of application this is?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T15:30:02.347",
"Id": "76946",
"Score": "0",
"body": "Servlets are for generating dynamic content on the server side. To run an applet in the browser, all you need is a static HTML file that contains an `<applet>` or `<object>` tag that references the JAR file (sort of like how an `<img>` tag works)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T01:19:12.640",
"Id": "77195",
"Score": "0",
"body": "If i think of using servlet class, Does one servlet class would suffice for this nature of app? DO i need to use MVC? I want to understand, How to think on this. Becasue here the output is coming every second, as per simtext.java while loop"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T02:13:42.803",
"Id": "77200",
"Score": "0",
"body": "If you wish to refresh the display in the browser about once a second, you will have a miserable experience with server-side programming. You want all of the code to execute on the client. A Java applet could work, and would let you reuse come code. (Frankly, applets, along with ActiveX, Silverlight, and Flash, are a dying technology. Personally, I would choose to rewrite the whole thing as JavaScript that dynamically updates cells of an HTML table.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T07:21:57.240",
"Id": "77210",
"Score": "0",
"body": "As i previously said starveTime has to be read only once, when class is loaded. I read starveTime value from command line in simtext.java and as per above discussion, starveTime property should be part of Ocean class, so how do i set starveTime value using static{} block during class load time only?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T07:24:32.883",
"Id": "77211",
"Score": "0",
"body": "Read my recommendation again. Don't make `starveTime` a `static` property at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T07:30:21.177",
"Id": "77212",
"Score": "0",
"body": "I just saw the switchcase that you added in timeStep() method.If you are recommending this, I would ask, if i get new creature in Ocean, Do i need to modify this Ocean class again?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T07:34:47.557",
"Id": "77213",
"Score": "0",
"body": "@Mat If you take 'list<Critters>' in Ocean class, am unable to understand how to check neighbour for each critter in update() method of each creature class, because it is list datatype. and am still not clear why Empty is not need as part of that list, when i need to perform update() on this as per point 6,7,8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T07:42:37.023",
"Id": "77214",
"Score": "0",
"body": "With my design, all of the simulation rules are centralized. Whether you consider that to be an advantage or weakness is a matter of opinion. Normally, giant `switch` blocks are a [tag:code-smell] that indicates an inflexible design. However, in this case, I deliberately used a giant `switch` block because it directly represents a complex ruleset, and encoding all the rules together makes it easy to verify."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T08:45:20.677",
"Id": "77218",
"Score": "0",
"body": "let us continue dicussion in chat later"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T09:43:52.820",
"Id": "44242",
"ParentId": "43921",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "44242",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T10:29:43.163",
"Id": "43921",
"Score": "14",
"Tags": [
"java",
"game-of-life",
"simulation"
],
"Title": "Suggestions needed after modification of Simulation of an Ocean"
} | 43921 |
<p>I am working on angularjs, and I have created some directives with bunch of HTML elements within its templates. I have assigned a controller for those directives. Below is my code snippet: </p>
<pre><code>directives.directive('ngLd',function()
{
return {
restrict : "AE",
templateUrl:'partials/ld.html',
scope:{},
link : function(scope,element,attr)
{
var lbutton = element.find("span[class='lb-lk-comm']");
var dlbutton = element.find("span[class='lb-dlk-comm']");
if(lbutton && dlbutton)
{
lbutton.bind('click',function(event)
{
scope.likeAction(lbutton.hasClass("lb-voted-comm"),dlbutton.hasClass("lb-voted-comm"));
scope.$apply();
});
dlbutton.bind('click',function(event)
{
scope.dislikeAction(lbutton.hasClass("lb-voted-comm"),dlbutton.hasClass("lb-voted-comm"));
scope.$apply();
});
}
},
controller : "MyController"
};
});
</code></pre>
<p>In the above code, I have used a link function of bind the click event on required elements.<br>
Another approach I could have followed to use the <code>ngClick</code> directive directly over the elements, but that is sort of exposing method to client end.</p>
<p>My question is, am I following a good approach by binding click event ? or should I use <code>ngClick</code> ?</p>
<p>I am using <code>angular.bootstrap(document,"myApp");</code> to bootstrap the angular module to document, so I was wondering if I could have similar thing to dynamically bind those events (click, hover, change etc) to my HTML elements, without exposing them to HTML pages.</p>
| [] | [
{
"body": "<p>I think you did the right thing, if you used <code>ngClick</code> you would loose tooling: syntax highlighting, debugging, linting.</p>\n\n<p>Other than that your code looks good, some minor nitpickings:</p>\n\n<ul>\n<li><p>a single comma separate <code>var</code> statement is considered better:<br></p>\n\n<pre><code>var lbutton = element.find(\"span[class='lb-lk-comm']\"),\n dlbutton = element.find(\"span[class='lb-dlk-comm']\");\n</code></pre></li>\n<li><p>You keep repeating <code>\"lb-voted-comm\"</code>, you should use a constant for it.</p></li>\n<li>I only understood after reading <code>likeACtion</code>/<code>dislikeAction</code> that <code>lbutton/dbutton</code> stand for <code>likeButton</code>, <code>dislikeButton</code> ( I thought it was left button, double click button or something ), you should spell out those variables names.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:26:44.957",
"Id": "76037",
"Score": "0",
"body": "its lbutton for like button and dlbutton for dislike, its nothing just a span as I have mentioned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:29:19.807",
"Id": "76038",
"Score": "1",
"body": "@Aman I understand, if you actually called the variables `likeButton` and `dislikeButton`, then the code would be of higher quality/readability"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T12:24:14.760",
"Id": "43930",
"ParentId": "43922",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43930",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T10:32:26.020",
"Id": "43922",
"Score": "3",
"Tags": [
"javascript",
"angular.js",
"event-handling"
],
"Title": "Bootstrap/bind click event over ngClick"
} | 43922 |
<p>Is there a more efficient/direct way to find an arbitrary perpendicular vector of another vector?</p>
<pre><code>def perpendicular_vector(v):
r""" Finds an arbitrary perpendicular vector to *v*. """
a, b = random.random(), random.random()
if not iszero(v.z):
x, y, z = v.x, v.y, v.z
elif not iszero(v.y):
x, y, z = v.x, v.z, v.y
elif not iszero(v.x):
x, y, z = v.y, v.z, v.x
else:
raise ValueError('zero-vector')
c = (- x * a - y * b) / z
if not iszero(v.z):
return Vector(a, b, c)
elif not iszero(v.y):
return Vector(a, c, b)
elif not iszero(v.x):
return Vector(b, c, a)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T12:17:42.797",
"Id": "453411",
"Score": "1",
"body": "You better not use random. Arbitrary does not mean differrent on each call. Better use size that comes out of your algorithm. Either it be same size as input vector or 1 could be a good choice or whatever comes out of your equations. Using random to explicitly resize the output vector Is unnecesary performance drop."
}
] | [
{
"body": "<p>Hmm. The lack of comments make it slightly non-obvious what is happening. The inverted conditions <code>not iszero(…)</code> don't make it any easier to understand. The same set of these conditions occurs two times, which is a bit confusing. I also don't know where the <code>iszero(…)</code> function is from, and will replace it by <code>… == 0</code> in the following.</p>\n\n<p>Now a bit of math first. Two vectors are perpendicular if their scalar product is zero:</p>\n\n<pre><code>1st vector (x, y, z)\n2nd vector (a, b, c)\n0 = a·x + b·y + c·z\n</code></pre>\n\n<p>You are correct in avoiding the trivial solution <code>x = y = z = 0</code>. Note that you do not avoid the solution <code>a = b = c = 0</code>, because <code>random.random()</code> <em>can</em> return zero.</p>\n\n<p>If one of <code>x, y, z</code> is zero, then the above equation can be solved by choosing a non-zero value for the corresponding direction, and setting the other variables to zero. Example: given <code>(1, 0, 3)</code> as a first vector, the equation can be solved by a second vector <code>(0, 1, 0)</code>.</p>\n\n<p>The above rule can also be applied in reverse if the first vector has <em>two</em> zero fields, but it's only required to change one of the zero fields to a non-zero value.</p>\n\n<p>We can encode these simple cases in pseudocode as</p>\n\n<pre><code>match vec1 with\n| (0, 0, 0) -> ValueError('zero-vector')\n| (0, _, _) -> Vector(1, 0, 0)\n| (_, 0, _) -> Vector(0, 1, 0)\n| (_, _, 0) -> Vector(0, 0, 1)\n| (x, y, z) -> a more complex case which we'll handle in a moment\n</code></pre>\n\n<p>If all parts of the input vector are non-zero, the calculation is a bit more complex because we have three variables <code>a, b, c</code> to determine but only one equation – this means we can choose two values arbitrarily. Choosing a random value might make sense when hardening your application, but it's difficult to test, and we can make the code simpler by choosing <code>a = b = 1</code> (we cannot choose <code>a = b = 0</code>). The equation can now be used to calculate <code>c</code>:</p>\n\n<pre><code>c = -(x + y)/z\n</code></pre>\n\n<p>which you essentially have used as well.</p>\n\n<p>So to wrap it all up, I would write this code:</p>\n\n<pre><code>def perpendicular_vector(v):\n r\"\"\" Finds an arbitrary perpendicular vector to *v*.\"\"\"\n # for two vectors (x, y, z) and (a, b, c) to be perpendicular,\n # the following equation has to be fulfilled\n # 0 = ax + by + cz\n\n # x = y = z = 0 is not an acceptable solution\n if v.x == v.y == v.z == 0:\n raise ValueError('zero-vector')\n\n # If one dimension is zero, this can be solved by setting that to\n # non-zero and the others to zero. Example: (4, 2, 0) lies in the\n # x-y-Plane, so (0, 0, 1) is orthogonal to the plane.\n if v.x == 0:\n return Vector(1, 0, 0)\n if v.y == 0:\n return Vector(0, 1, 0)\n if v.z == 0:\n return Vector(0, 0, 1)\n\n # arbitrarily set a = b = 1\n # then the equation simplifies to\n # c = -(x + y)/z\n return Vector(1, 1, -1.0 * (v.x + v.y) / v.z)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:18:47.870",
"Id": "43937",
"ParentId": "43928",
"Score": "8"
}
},
{
"body": "<p>The cross product of two vectors is perpendicular to both vectors, unless both vectors are parallel. So you could simply take the cross product of your first vector with <code>(1, 0, 0)</code>, unless it is parallel to <code>(1, 0, 0)</code>, in which case you could use <code>(0, 1, 0)</code>. If you use lists rather than dedicated classes with attributes and are willing to use numpy, this gets ridiculously short:</p>\n\n<pre><code>import numpy as np\n\ndef perpendicular_vector(v):\n if v[1] == 0 and v[2] == 0:\n if v[0] == 0:\n raise ValueError('zero vector')\n else:\n return np.cross(v, [0, 1, 0]]\n return np.cross(v, [1, 0, 0])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:58:55.737",
"Id": "43940",
"ParentId": "43928",
"Score": "9"
}
},
{
"body": "<p>Jaime beat me to it!</p>\n\n<p>Anyway, here's an optimised version that uses the same idea and doesn't call numpy.cross:</p>\n\n<pre><code>def perpendicular_vector(v):\n if iszero(v.x) and iszero(v.y):\n if iszero(v.z):\n # v is Vector(0, 0, 0)\n raise ValueError('zero vector')\n\n # v is Vector(0, 0, v.z)\n return Vector(0, 1, 0)\n\n return Vector(-v.y, v.x, 0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T12:09:52.160",
"Id": "453409",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:43:24.693",
"Id": "43943",
"ParentId": "43928",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T12:00:17.233",
"Id": "43928",
"Score": "7",
"Tags": [
"python",
"algorithm",
"mathematics",
"computational-geometry"
],
"Title": "Algorithm to get an arbitrary perpendicular vector"
} | 43928 |
<p>I haven't thought of a nice way to remove <code>#, fuzzy</code> from the files. I think <code>process_babel_file</code> might possibly become its own module, but on the other hand, having all methods in one script is quite nice for the mean time. I expect there to be bugs, although it works for the languages I've tried.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setuptranslations.py
Generate and manipulate translation files for a flask app.
Assumes areas in jinja2 templates are marked with {% trans %}..{% endtrans %}
or gettext, _, or other gettext variants.
Related: flask, flask-babel, pybabel, jinja2, i18n, gobabslate
1. Run pybabel with extract option
pybabel extract -F babel.cfg -o messages.pot .
2. Run pybabel with init option for each language
pybabel init -i messages.pot -d translations -l fr
pybabel init -i messages.pot -d translations -l de
3. Pull translations from Google Translate API into babel files
4. Remove #fuzzy from message.po files.
5. Run pybabel with compile option
pybabel compile -d translations
"""
import sys
import codecs
from subprocess import Popen
from goslate import Goslate
pybabel_extract = ['pybabel', 'extract', '-F' 'babel.cfg',
'-o' 'messages.pot', '.']
pybabel_init_lang = ['pybabel', 'init', '-i', 'messages.pot',
'-d', 'translations', '-l']
pybabel_compile = ['pybabel', 'compile', '-d', 'translations']
def get_language_codes():
try:
from config import LANGUAGES, LANGUAGE_DEFAULT
return [lang for lang in LANGUAGES.keys() if lang != LANGUAGE_DEFAULT]
except:
return ['fr', 'de']
def return_code(args):
return Popen(args).communicate()[0]
def process_babel_file(lang, remove_fuzzy=False):
gs = Goslate()
filename = 'translations/' + lang + '/LC_MESSAGES/messages.po'
file_stream = codecs.open(filename, 'r', 'utf-8')
file_output = codecs.open(filename + '.tmp', 'w', 'utf-8')
finding_input, data = False, u''
for line in file_stream:
if finding_input is True and line == u'msgstr ""\n':
finding_input = False
new_text = gs.translate(data, lang).replace('"', '\\"')
file_output.write(u'msgstr "' + new_text + u'"\n')
continue
elif finding_input is True:
data += line.replace('\n', ' ').replace('\\n"', ' ').strip('"')\
.replace('\\"', '"')
elif line == u'msgid ""\n' or line[:7] == u'msgid "':
finding_input = True
data = u'' if line == u'msgid ""\n' else line[7:].strip()\
.strip('"').replace('\\"', '"')
elif line == '#, fuzzy\n' and remove_fuzzy:
continue
file_output.write(line)
file_stream.close()
file_output.close()
Popen(['cp', filename + '.tmp', filename]).communicate()
def main():
if return_code(pybabel_extract) is not None:
sys.exit('pybabel failed to extract translations')
for language_code in get_language_codes():
if return_code(pybabel_init_lang + [language_code]) is not None:
print('Failed to add language: %s', language_code)
continue
process_babel_file(language_code, remove_fuzzy=True)
if return_code(pybabel_compile) is not None:
sys.exit('pybabel was unable to compile translations')
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>Nice script! Found it very helpful to get started and test flask babel and see first translations.</p>\n\n<p>A few \"bugs\" I discovered for your consideration</p>\n\n<ul>\n<li>Any string with a ' will cause problems</li>\n<li>Same with other special characters, e.g. ()</li>\n</ul>\n\n<p>The resulting po file mixes entries later on and generates strings like:</p>\n\n<pre><code>#: dedri/templates/contact.html:29\nmsgid \"Your email\"\nmsgstr \"Aboutmsgstr \\\"about (modificado por Raimundo)\\\" #: dedri / templates / about.html: 13 msgid \\\"Aquí añadimos unas pocas palabras acerca de cada uno de nosotros.\\\" msgstr \\\"Aquí añadimos Unas Palabras Sobre CADA UNO de Nosotros here.\\\" #: Dedri / templates / contact.html: 29 msgid \\\"Your email\\\"\" \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-27T12:26:11.343",
"Id": "55448",
"ParentId": "43929",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T12:14:28.570",
"Id": "43929",
"Score": "1",
"Tags": [
"python",
"i18n"
],
"Title": "Script for initialising i18n for a Flask site using pybabel and goslate"
} | 43929 |
<p>I see that there are quite some words that are appearing double or more times in my code.</p>
<p>I'm thinking there might be a more efficient way of writing this code, only I don't have the knowledge to do so.</p>
<pre><code>function transitionData(data) {
if($("div#facebook div#notice").is(":visible")) {
$("div#facebook div#heading *").fadeOut();
$("div#facebook div#notice").animate({"opacity":"0"}, function() {
$("div#facebook div.wrapper > img:first-child").attr("src", "http://graph.facebook.com/"+data.id+"/picture?type=normal");
$("div#facebook h3").html("Facebook account of <b>"+data.name+"</b>");
$("div#facebook div#heading a").attr("href", "http://www.facebook.com/"+data.username);
$("div#facebook tr:first-child td:first-child b").text(data.id);
$("div#facebook tr:first-child+tr td:first-child b").text(data.first_name);
$("div#facebook tr:first-child+tr+tr td:first-child b").text(data.last_name);
$("div#facebook tr:first-child td:first-child+td b").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));
$("div#facebook tr:first-child+tr td:first-child+td b").text(data.locale);
$("div#facebook tr:first-child+tr+tr td:first-child+td b").text(data.username);
$("div#facebook div#notice").slideUp();
$("div#facebook div.wrapper").slideDown();
$("div#facebook div#heading *").fadeIn();
});
} else {
$("div#facebook div#heading *, div#facebook div.wrapper").fadeOut(function() {
$("div#facebook div.wrapper > img:first-child").attr("src", "http://graph.facebook.com/"+data.id+"/picture?type=normal");
$("div#facebook h3").html("Facebook account of <b>"+data.name+"</b>");
$("div#facebook div#heading a").attr("href", "http://www.facebook.com/"+data.username);
$("div#facebook tr:first-child td:first-child b").text(data.id);
$("div#facebook tr:first-child+tr td:first-child b").text(data.first_name);
$("div#facebook tr:first-child+tr+tr td:first-child b").text(data.last_name);
$("div#facebook tr:first-child td:first-child+td b").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));
$("div#facebook tr:first-child+tr td:first-child+td b").text(data.locale);
$("div#facebook tr:first-child+tr+tr td:first-child+td b").text(data.username);
$("div#facebook div#heading *, div#facebook div.wrapper").fadeIn();
});
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:08:44.663",
"Id": "75993",
"Score": "1",
"body": "you can store and use for example $(\"div#facebook\") in a variable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:11:22.770",
"Id": "75994",
"Score": "0",
"body": "and duplicate code parts in the if/else loop can be made as a function with the parameter `data`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:16:16.870",
"Id": "76097",
"Score": "0",
"body": "I've looked at this for 15 seconds and realized I would use a template engine for this"
}
] | [
{
"body": "<p>From a once over,</p>\n\n<ul>\n<li><p>You have far more than a <code>few words</code> that are copy pasted, you could extract all the common statements into a common function:</p>\n\n<pre><code>function transitionDataDone( data ){\n $(\"div#facebook div.wrapper > img:first-child\").attr(\"src\", \"http://graph.facebook.com/\"+data.id+\"/picture?type=normal\");\n $(\"div#facebook h3\").html(\"Facebook account of <b>\"+data.name+\"</b>\");\n $(\"div#facebook div#heading a\").attr(\"href\", \"http://www.facebook.com/\"+data.username);\n $(\"div#facebook tr:first-child td:first-child b\").text(data.id);\n $(\"div#facebook tr:first-child+tr td:first-child b\").text(data.first_name);\n $(\"div#facebook tr:first-child+tr+tr td:first-child b\").text(data.last_name);\n $(\"div#facebook tr:first-child td:first-child+td b\").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));\n $(\"div#facebook tr:first-child+tr td:first-child+td b\").text(data.locale);\n $(\"div#facebook tr:first-child+tr+tr td:first-child+td b\").text(data.username);\n}\n</code></pre></li>\n<li><p>Once you have done that, you will notice that you are not repeating too many jQuery selectors. The only one that stands out to me is <code>$(\"div#facebook div#notice\");</code> If you cache this selector and apply the previous code, you get something like this (not tested, but you should get the gist):</p>\n\n<pre><code>function transitionData(data) {\n var $divNotice = $(\"div#facebook div#notice\"); \n if($divNotice.is(\":visible\")) {\n $(\"div#facebook div#heading *\").fadeOut();\n $divNotice.animate({\"opacity\":\"0\"}, function() {\n transitionDataDone( data )\n $divNotice.slideUp();\n $(\"div#facebook div.wrapper\").slideDown();\n $(\"div#facebook div#heading *\").fadeIn();\n });\n } else {\n $(\"div#facebook div#heading *, div#facebook div.wrapper\").fadeOut(function() {\n transitionDataDone( data );\n $(\"div#facebook div#heading *, div#facebook div.wrapper\").fadeIn(); \n });\n }\n}\n\nfunction transitionDataDone( data ){\n $(\"div#facebook div.wrapper > img:first-child\").attr(\"src\", \"http://graph.facebook.com/\"+data.id+\"/picture?type=normal\");\n $(\"div#facebook h3\").html(\"Facebook account of <b>\"+data.name+\"</b>\");\n $(\"div#facebook div#heading a\").attr(\"href\", \"http://www.facebook.com/\"+data.username);\n $(\"div#facebook tr:first-child td:first-child b\").text(data.id);\n $(\"div#facebook tr:first-child+tr td:first-child b\").text(data.first_name);\n $(\"div#facebook tr:first-child+tr+tr td:first-child b\").text(data.last_name);\n $(\"div#facebook tr:first-child td:first-child+td b\").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));\n $(\"div#facebook tr:first-child+tr td:first-child+td b\").text(data.locale);\n $(\"div#facebook tr:first-child+tr+tr td:first-child+td b\").text(data.username);\n}\n</code></pre></li>\n<li>Finally, I must say, your approach is terrible. Your elements should have unique id's ( <code>first_name</code>, <code>username</code> etc. etc. ), the way you select elements now is a maintenance nightmare. Re-ordering the elements means re-writing the JavaScript code!</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:23:05.183",
"Id": "76070",
"Score": "1",
"body": "totally right, unique CSS IDs are much faster and better to select"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:27:54.003",
"Id": "43938",
"ParentId": "43933",
"Score": "2"
}
},
{
"body": "<p>I'll take a lead from <a href=\"https://codereview.stackexchange.com/a/43938/38383\">konijn</a>, and take it a few steps further.</p>\n\n<ul>\n<li>First, as konijn did, we break out the repeated parts into their own method.</li>\n<li>As Daniel Ruf noted, we can save a lot of characters by caching <code>div#facebook</code> node as a variable, and then using <a href=\"http://api.jquery.com/find/\" rel=\"nofollow noreferrer\"><code>.find(selector)</code></a> to look for subnodes.</li>\n<li>Also, we don't need to specify the HTML element type when looking for nodes, so we can go from <code>div#facebook</code> to just <code>#facebook</code>.</li>\n<li>The callback called on completion of methods such as <code>fadeOut()</code> is called for every element that is faded out (for example), where you probably only want this to happen once. Thus, we can replace the call back with a promise that will be called only once, after all of the animation is complete.</li>\n<li><p>I'd also give the same warning as konijn regarding the approach of using elements in a certain order:</p>\n\n<blockquote>\n <p>Finally, I must say, your approach is terrible. Your elements should have unique id's ( first_name, username etc. etc. ), the way you select elements now is a maintenance nightmare. Re-ordering the elements means re-writing the JavaScript code!</p>\n</blockquote></li>\n</ul>\n\n<p>This gives us a version of the code that looks like this:</p>\n\n<pre><code>function transitionData(data) {\n var $facebook = $(\"#facebook\");\n var $notice = $facebook.find(\"#notice\"); \n if($notice.is(\":visible\")) {\n var $headingStar = $facebook.find(\"#heading *\");\n $headingStar.fadeOut();\n $notice.animate({\"opacity\":\"0\"}, function() {\n transitionDataDone(data, $facebook)\n $notice.slideUp();\n $facebook.find(\".wrapper\").slideDown();\n $headingStar.fadeIn();\n });\n } else {\n var $elementsToFade = $facebook.find(\"#heading *, .wrapper\");\n $elementsToFade.fadeOut();\n $elementsToFade.promise().done(function() {\n transitionDataDone(data, $facebook);\n $elementsToFade.fadeIn();\n });\n }\n}\n\nfunction transitionDataDone(data, $facebook){\n $facebook.find(\".wrapper > img:first-child\").attr(\"src\", \"http://graph.facebook.com/\"+data.id+\"/picture?type=normal\");\n $facebook.find(\"h3\").html(\"Facebook account of <b>\"+data.name+\"</b>\");\n $facebook.find(\"#heading a\").attr(\"href\", \"http://www.facebook.com/\"+data.username);\n $facebook.find(\"tr:first-child td:first-child b\").text(data.id);\n $facebook.find(\"tr:first-child+tr td:first-child b\").text(data.first_name);\n $facebook.find(\"tr:first-child+tr+tr td:first-child b\").text(data.last_name);\n $facebook.find(\"tr:first-child td:first-child+td b\").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));\n $facebook.find(\"tr:first-child+tr td:first-child+td b\").text(data.locale);\n $facebook.find(\"tr:first-child+tr+tr td:first-child+td b\").text(data.username);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:13:37.653",
"Id": "43961",
"ParentId": "43933",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "43961",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T12:42:44.750",
"Id": "43933",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"dom",
"query-selector"
],
"Title": "Showing/hiding a box containing a Facebook profile"
} | 43933 |
<p>My software has multiple devices connected before starting. I must be sure these devices are working and are well connected. every device has different error ID code so we can see every component that is not working.</p>
<p>When the software will have completly test connection for every devices, we would like to show a message that will show every failing devices:</p>
<blockquote>
<p>Unable to connect on one or multiple devices [Error Code: XXXXXXX].
Please look at the user manual at www.xxxx.com/en/UserManual and if
you need further information, contact customer support or mail at
xxxxx@example.com.</p>
</blockquote>
<p>For the moment, i am using bitmask but i feel like it's not very "generic" and it kinda hard-coded.</p>
<p>We have made an ID for every class and put a base 2 number like this:</p>
<pre><code>enum eErrorCode
{
MOTORA = 0x0000001,
MOTORB = 0x0000010,
SERIAL = 0x0000100,
LAN = 0x0001000,
MAINBOARD = 0x0010000,
GENERATOR = 0x0100000,
MAX = 6
}
</code></pre>
<p>So when the Activating function fire, we can add every error:</p>
<pre><code>Int32 ConnectToEveryDevice()
{
Int32 Error = 0;
foreach(IDevices device in this.Devices)
{
Error = Error | device.Connect();
}
return Error;
}
</code></pre>
<p>For example: If <code>MotorA</code>, <code>Lan</code> and <code>Serial</code> fail, The screen will popup the Hex <strong>[Error Code: 0x00001101]</strong> so the client can easily find the error in the user manual (online) and if we need to add devices we can do it without needing to change everything. Does anyone have a better or cleaner alternative than this one?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:18:23.540",
"Id": "75998",
"Score": "0",
"body": "Why do you want to show the error code? Why not directly tell the user which devices failed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:42:44.207",
"Id": "76006",
"Score": "0",
"body": "I have a log box in the bottom of the screen for every event and it's a little bit small. We thought that it would looks weird that the client must scroll to see all the errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:36:21.910",
"Id": "76042",
"Score": "3",
"body": "I don't think making the error message incomprehensible to the user is a good solution to that."
}
] | [
{
"body": "<p>I think your enum is taking naming conventions, making a little paper ball out of it, and throwing it out the window.</p>\n\n<p>An enum is a type. As such, its name should be <code>PascalCase</code>. Enum members are, well, public members of a type. As such, their names should be <code>PascalCase</code> as well.</p>\n\n<p>Consider:</p>\n\n<pre><code>enum ErrorCode\n{\n MotorA = 0x0000001,\n MotorB = 0x0000010,\n Serial = 0x0000100,\n Lan = 0x0001000,\n MainBoard = 0x0010000,\n Generator = 0x0100000,\n Max = 6\n}\n</code></pre>\n\n<p>A number of things are not clear:</p>\n\n<ul>\n<li>Why use a hexadecimal representation of the values?</li>\n<li>Why is <code>6</code> not represented as hex, too?</li>\n<li>Is <code>Max</code> supposed to represent <em>all 6 bit flags turned on</em>?</li>\n</ul>\n\n<blockquote>\n <p><em>We have made an ID for every class and put a base 2 number...</em></p>\n</blockquote>\n\n<p>No, you haven't. Your numbers are hexadecimal numbers, they're base-16.</p>\n\n<p>Consider:</p>\n\n<pre><code>[Flags]\nenum ErrorCode\n{\n None = 0,\n MotorA = 1, // 2^0, or 1 << 0\n MotorB = 2, // 2^1, or 1 << 1\n Serial = 4, // 2^2, or 1 << 2\n Lan = 8, // 2^3, or 1 << 3\n MainBoard = 16, // 2^4, or 1 << 4\n Generator = 32, // 2^5, or 1 << 5\n Max = MotorA | MotorB | Serial | Lan | MainBoard | Generator\n}\n</code></pre>\n\n<p>Take a look at <a href=\"https://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c#comment1119528_8480\">this comment on SO</a>:</p>\n\n<blockquote>\n <p><em>Flags itself does nothing. Also, C# does not require Flags per se. But the ToString implementation of your enum uses Flags, and so does Enum.IsDefined, Enum.Parse, etc. Try to remove Flags and look at the result of MyColor.Yellow | MyColor.Red; without it you get \"5\", with Flags you get \"Yellow, Red\". Some other parts of the framework also use [Flags] (e.g., XML Serialization).</em> – Ruben Aug 17 '09 at 17:30</p>\n</blockquote>\n\n<p>This means the <code>[Flags]</code> attribute changes how <code>ToString()</code> represents an <code>ErrorCode</code> value. Your code breaks the type safety and treats the enum as an <code>int</code>, but you could do this as well:</p>\n\n<pre><code>ErrorCode ConnectToEveryDevice()\n{ \n var result = ErrorCode.None;\n foreach(IDevices device in this.Devices)\n {\n result = result | device.Connect();\n }\n return result;\n}\n</code></pre>\n\n<p>Then the return value of this method could be made meaningful to a user, simply with a <code>ToString()</code> call:</p>\n\n<pre><code>var result = ConnectToEveryDevice();\nvar resultString = result.ToString();\n</code></pre>\n\n<p>Where <code>resultString</code> holds \"MotorA, MainBoard, Generator\" if <code>MotorA</code>, <code>MainBoard</code> and <code>Generator</code> are in an error state.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:25:59.510",
"Id": "76071",
"Score": "0",
"body": "If we want to make the program in multiple language, is there any flags attribute or do we must implement our own language fonction?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:32:19.627",
"Id": "76074",
"Score": "0",
"body": "@Mr.Alexz localization is a different concern. I would have a `ErrorCodes.resx` file with a string for each enum value, and then an `ErrorCodes.fr-CA.resx` file for the same values in French (Canada); you then need to fetch the description that matches the enum value (perhaps a bit more complicated with combined flag values) and have the resources fetched from the .resx file that matches `Thread.CurrentThread.CurrentUICulture`. Take a look at [this SO question](http://stackoverflow.com/questions/17380900/enum-localization) :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:42:12.583",
"Id": "43950",
"ParentId": "43934",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43950",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T12:45:14.173",
"Id": "43934",
"Score": "4",
"Tags": [
"c#",
"error-handling"
],
"Title": "How to properly detect multiple devices failure?"
} | 43934 |
<p>I have a simple sorting algorithm that I was told is possibly unstable. I'm wondering what in the sort is unstable. I have test cases written to test all fields with no issues.</p>
<p>A secondary problem is that jQuery is not appending the rows for some reason (works fine in local and server environments).</p>
<p><a href="http://jsfiddle.net/SucGH/" rel="nofollow">http://jsfiddle.net/SucGH/</a></p>
<pre><code>var applyData = function (dataSet) {
$('#healthplans tbody').empty();
for (var i = 0; i < dataSet.length; i++) {
var itemRow = '';
for (item in dataSet[i]) {
var newItem = dataSet[i][item];
if (typeof newItem === 'number') newItem = "$" + newItem;
itemRow += '<td>' + newItem + '</td>';
}
$('#healthplans tbody').append('<tr>' + itemRow + '</tr>');
}
}
var order = '';
var sortDataByField = function (field, newOrder, test) {
if (!newOrder) order = (order == 'asc') ? 'desc' : 'asc';
else order = newOrder;
if (field) {
jsonData.sort(function (a, b) {
if (typeof b[field] === 'string') {
var bfield = b[field].toUpperCase();
var afield = a[field].toUpperCase();
if (bfield < afield) return (order == 'asc') ? -1 : 1;
if (bfield > afield) return (order == 'asc') ? 1 : -1;
return 0;
} else if (typeof b[field] === 'number') {
if (order == 'desc') return b[field] - a[field]
else if (order == 'asc') return a[field] - b[field]
return 0;
}
});
if (!test) {
applyData(jsonData);
}
} else {
return 'Field and/or order not properly defined';
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:14:19.663",
"Id": "76064",
"Score": "0",
"body": "I'm sorry but it's off-topic to ask to fix a bug or something like that (Read the FAQ for more details http://codereview.stackexchange.com/help/on-topic). The rest of the question is on-topic."
}
] | [
{
"body": "<p>You are using the built-in <code>sort</code> of <code>Array</code>, which is not guaranteed to be stable per the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow\">documentation</a>. You will have to write your own sort algorithm from scratch.</p>\n\n<p>Other than that, </p>\n\n<ul>\n<li>It is considered better form to have a single comma separated <code>var</code> statement</li>\n<li>Calling <code>append()</code> inside a loop gives poor performance, just collect everything in a string, and call <code>append()</code> once</li>\n<li>You could cache <code>$('#healthplans tbody')</code> since you call it more than once</li>\n<li>You should not skip the newline after an <code>if</code> statement</li>\n<li>You should consider using <code>hasOwnProperty</code> when using <code>for (item in dataSet[i])</code></li>\n<li>You did not declare <code>item</code> with <code>var</code></li>\n<li>You call too many things <code>item</code>, I am assuming that the property in dataSet is more of itemId ?</li>\n<li><p>All that gives this :</p>\n\n<pre><code>var applyData = function (dataSet) {\n var i,\n itemId\n item,\n itemRow, \n html = ''; \n $table = $('#healthplans tbody'),\n\n $table.empty();\n for (i = 0; i < dataSet.length; i++) {\n itemRow = '';\n for (itemId in dataSet[i]) {\n item= dataSet[i][itemId];\n if (typeof item=== 'number') \n item= '$' + item;\n itemRow += '<td>' + item+ '</td>';\n }\n html += '<tr>' + itemRow + '</tr>';\n }\n $table.append( html ); \n}\n</code></pre></li>\n</ul>\n\n<p>I did not comment on the <code>sort</code> function, since that most likely will be throw away.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:21:17.980",
"Id": "76046",
"Score": "0",
"body": "Ah, I didn't know that about sort and I've been using it all this time :) For this particular set of data, I don't think it mattered, but at least I know what they meant now. I particularly don't tend to go with the comma list, but that's just me. I totally forgot var to scope the item down, oops! The dataset is really a dataset, it's an array of objects with properties. The newline skipped accidentally when I pasted this here from jslint.\n\nThe hints for append and caching the elements are good catches.\n\nThanks, this list is really great and shows where I could improve things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:22:17.213",
"Id": "76047",
"Score": "0",
"body": "You wouldn't happen to know why append is not working in the jsfiddle example, would you? (and is working on local/server)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:37:05.410",
"Id": "76077",
"Score": "1",
"body": "I would, id is `healthPlans`, jQuery looks for `healthplans`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:25:25.963",
"Id": "76103",
"Score": "0",
"body": "Yet another reason I should have just cached the element :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:54:20.247",
"Id": "43949",
"ParentId": "43942",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43949",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:37:31.913",
"Id": "43942",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"sorting"
],
"Title": "Sorting possibly unstable and general jsfiddle/jquery problem"
} | 43942 |
<p>I have a function that iterates through a list of file updates, and for each file, if updates are needed, download the file from the server, make the updates, and upload the updated version. Each update gets marked with a string identifying the result of the update operation.</p>
<p>There are several steps in the update process where I would not want updating to continue for that file. Right now I have a lot of nested if-then statements, so that the iteration won't proceed any further for that file and will just mark the issue and go on to the next file. Code as follows:</p>
<pre><code> public void updateAllFiles()
{
foreach (string fileName in updateList.fileNameList())
{
updatesForFile = updateList.updatesForFile(fileName);
hyperlinkEntry = hyperlinkList.getHyperlinkEntry(fileName);
if (hyperlinkEntry == null)
{
updatesForFile.markResultAllRows("File not found on server");
}
else
{
hyperlink = hyperlinkEntry.hyperlink;
if (updatesForFile.updateNeeded())
{
if (!po.checkout(hyperlink))
{
updatesForFile.markResultAllRows("checked out to other user");
}
else
{
downloadPath = downloadFolder + fileName;
downloadResult = dl.download(hyperlink, downloadPath);
if (downloadResult == false)
{
updatesForFile.markResultAllRows("download failed");
}
else
{
file = new FileObject(xlApp, downloadPath, updatesForFile);
if (file == null)
{
updatesForFile.markResultAllRows("unable to open");
}
else
{
foreach (FeatureUpdate featureUpdate in updatesForFile.getFeatureUpdateList())
{
resultValue = featureUpdate.getColumnValue("result");
if (!resultValue.Contains("updated"))
{
file.update(featureUpdate, updateMethods.lowFeatureLength);
updatesForFile.markResult(featureUpdate.getIndex(), "updated");
}
}
file.close();
updateList.save();
}
}
}
}
}
}
}
</code></pre>
<p>Because it's getting harder to read the code, I'm wondering if I should use exception handling here instead, and if so, how it should be implemented here--e.g., should an exception be thrown in <code>getHyperlinkEntry()</code> and caught in <code>updateAllFiles()</code>, or should it be thrown and caught in <code>updateAllFiles()</code> like this? </p>
<pre><code>try
{
hyperlinkEntry=hyperlinkList.getHyperlinkEntry(fileName);
if (hyperlinkEntry == null)
{
throw new UpdateException("File not found on server");
}
///more function calls and exception throwing here
}
catch (UpdateException ue)
{
updatesForFile.markResultAllRows(ue.updateMessage);
}
</code></pre>
<p>Or are the existing nested if-then clauses more appropriate for this situation?</p>
| [] | [
{
"body": "<p>You can use <code>continue</code> instead:</p>\n\n<pre><code>public void updateAllFiles()\n{\n foreach (string fileName in updateList.fileNameList())\n {\n updatesForFile = updateList.updatesForFile(fileName);\n hyperlinkEntry = hyperlinkList.getHyperlinkEntry(fileName);\n if (hyperlinkEntry == null)\n {\n updatesForFile.markResultAllRows(\"File not found on server\");\n continue;\n }\n\n hyperlink = hyperlinkEntry.hyperlink;\n if (updatesForFile.updateNeeded())\n {\n if (!po.checkout(hyperlink))\n {\n updatesForFile.markResultAllRows(\"checked out to other user\");\n continue;\n }\n downloadPath = downloadFolder + fileName;\n ... etc ...\n</code></pre>\n\n<p>Alternatively you can move the code into a subroutine and <a href=\"https://stackoverflow.com/a/416521/49942\">use return when you want to exit early</a>.</p>\n\n<blockquote>\n <p>My if-then implementation allowed me to perform some cleanup tasks within the for-loop after all the if-thens were evaluated (similar to the finally of a try-catch structure); is that possible using this continue approach?</p>\n</blockquote>\n\n<p>The only 'cleanup task' which I see in the original code is the <code>file.close</code> statement:</p>\n\n<pre><code> file = new FileObject(xlApp, downloadPath, updatesForFile);\n if (file == null)\n {\n updatesForFile.markResultAllRows(\"unable to open\");\n }\n else\n {\n foreach (FeatureUpdate featureUpdate in updatesForFile.getFeatureUpdateList())\n {\n resultValue = featureUpdate.getColumnValue(\"result\");\n if (!resultValue.Contains(\"updated\"))\n {\n file.update(featureUpdate, updateMethods.lowFeatureLength);\n updatesForFile.markResult(featureUpdate.getIndex(), \"updated\");\n }\n }\n file.close();\n updateList.save();\n }\n</code></pre>\n\n<p>That part can be rewritten to use continue:</p>\n\n<pre><code> file = new FileObject(xlApp, downloadPath, updatesForFile);\n if (file == null)\n {\n updatesForFile.markResultAllRows(\"unable to open\");\n continue;\n }\n\n foreach (FeatureUpdate featureUpdate in updatesForFile.getFeatureUpdateList())\n {\n resultValue = featureUpdate.getColumnValue(\"result\");\n if (!resultValue.Contains(\"updated\"))\n {\n file.update(featureUpdate, updateMethods.lowFeatureLength);\n updatesForFile.markResult(featureUpdate.getIndex(), \"updated\");\n }\n }\n file.close();\n updateList.save();\n</code></pre>\n\n<p>If you have cleanup tasks that might be a good time to invent a subroutine:</p>\n\n<pre><code> file = new FileObject(xlApp, downloadPath, updatesForFile);\n updateFeatures(file); // <-- new subroutine call\n file.close();\n updateList.save();\n</code></pre>\n\n<p>The new subroutine can use <code>return</code> instead of <code>continue</code>, whenever it wants to stop processing:</p>\n\n<pre><code>void updateList(File file)\n{\n if (!someCondition)\n return; // <-- early return\n somethingElse();\n somethingFurther();\n}\n</code></pre>\n\n<p>When the subroutine returns, whether early or late, then your cleanup tasks run.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:20:01.400",
"Id": "76099",
"Score": "0",
"body": "My if-then implementation allowed me to perform some cleanup tasks within the for-loop after all the if-thens were evaluated (similar to the `finally` of a try-catch structure); is that possible using this `continue` approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:20:59.327",
"Id": "76100",
"Score": "0",
"body": "@sigil Yeah, you can still use `finally` for that, though I'm not completely sure it's a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:31:58.820",
"Id": "76133",
"Score": "0",
"body": "@sigil I updated my answer to try to address your comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:35:31.933",
"Id": "76136",
"Score": "0",
"body": "Thanks. In the meantime I implemented it using svick's `finally` recommendation; I'll try your subroutine approach if that doesn't work out."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:14:10.000",
"Id": "43962",
"ParentId": "43960",
"Score": "3"
}
},
{
"body": "<p>Maybe simple loop logic can serve your purposes better. If what you want is to ignore the rest of the loop body if a condition is met, the <code>continue</code> statement will follow immediately with the next iteration.</p>\n\n<pre><code>foreach (string fileName in updateList.fileNameList())\n{\n updatesForFile = updateList.updatesForFile(fileName);\n hyperlinkEntry = hyperlinkList.getHyperlinkEntry(fileName);\n if (hyperlinkEntry == null)\n {\n updatesForFile.markResultAllRows(\"File not found on server\");\n continue;\n }\n hyperlink = hyperlinkEntry.hyperlink;\n if (updatesForFile.updateNeeded())\n {\n if (!po.checkout(hyperlink))\n {\n updatesForFile.markResultAllRows(\"checked out to other user\");\n continue;\n }\n downloadPath = downloadFolder + fileName;\n downloadResult = dl.download(hyperlink, downloadPath);\n if (downloadResult == false)\n {\n updatesForFile.markResultAllRows(\"download failed\");\n continue;\n }\n file = new FileObject(xlApp, downloadPath, updatesForFile);\n if (file == null)\n {\n updatesForFile.markResultAllRows(\"unable to open\");\n continue;\n }\n foreach (FeatureUpdate featureUpdate in updatesForFile.getFeatureUpdateList())\n {\n resultValue = featureUpdate.getColumnValue(\"result\");\n if (!resultValue.Contains(\"updated\"))\n {\n file.update(featureUpdate, updateMethods.lowFeatureLength);\n updatesForFile.markResult(featureUpdate.getIndex(), \"updated\");\n }\n }\n file.close();\n updateList.save();\n }\n}\n</code></pre>\n\n<p>If what you need is to exit altogether when a condition is met, then I'd favor <code>return</code>, maintaining the same logic as the <code>continue</code> example. This would also give a lot more flexibility to refactor your code into functions and even probably use of kind of error codes, if it gets to that point.</p>\n\n<p>Exceptions are very useful, but they are <a href=\"http://blog.codinghorror.com/creating-more-exceptional-exceptions/\" rel=\"nofollow\">very expensive</a>, so unless you don't really care about the performance of this code, I'd favor a solution based in flow control any day of the week. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:29:37.923",
"Id": "76086",
"Score": "0",
"body": "Good to know about the performance cost of exception throwing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:37:47.123",
"Id": "76088",
"Score": "1",
"body": "@sigil Everyone says that exceptions are \"very expensive\"; but they are not entirely correct: see http://stackoverflow.com/a/891230/49942"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:44:00.857",
"Id": "76090",
"Score": "0",
"body": "@ChrisW Nice, I guess nothing is black or white..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:24:26.217",
"Id": "76102",
"Score": "0",
"body": "I'd word that performance note the other way around: Exceptions are somewhat expensive, but you should use them where appropriate anyway and use something else only if you really care about the performance of this code. (See also [the famous quote from Knuth on premature optimization](http://en.wikipedia.org/wiki/Program_optimization#Quotes).)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:26:24.743",
"Id": "43964",
"ParentId": "43960",
"Score": "4"
}
},
{
"body": "<p>You should really <a href=\"http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl\" rel=\"nofollow\">not use Exceptions for flow control</a>. They are inefficient, and can be their own readability headache. Exceptions should be used for exceptional events, such as an IO failure, or your app not finding a file it <strong>really should</strong> have. The use of continues, as ChrisW notes, is a great way to avoid this, and arranging them like <a href=\"http://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow\">guard clauses</a> (or guard-esque clauses) could aid readability:</p>\n\n<pre><code>public void updateAllFiles()\n{\n foreach (string fileName in updateList.fileNameList())\n {\n updatesForFile = updateList.updatesForFile(fileName);\n hyperlinkEntry = hyperlinkList.getHyperlinkEntry(fileName);\n if (hyperlinkEntry == null)\n {\n updatesForFile.markResultAllRows(\"File not found on server\");\n continue;\n }\n\n if (!updatesForFile.updateNeeded())\n {\n continue;\n }\n\n hyperlink = hyperlinkEntry.hyperlink;\n if (!po.checkout(hyperlink))\n {\n updatesForFile.markResultAllRows(\"checked out to other user\");\n continue;\n }\n\n downloadPath = downloadFolder + fileName;\n downloadResult = dl.download(hyperlink, downloadPath);\n if (downloadResult == false)\n {\n updatesForFile.markResultAllRows(\"download failed\");\n continue;\n }\n\n file = new FileObject(xlApp, downloadPath, updatesForFile);\n if (file == null)\n {\n updatesForFile.markResultAllRows(\"unable to open\");\n continue;\n }\n\n foreach (FeatureUpdate featureUpdate in updatesForFile.getFeatureUpdateList())\n {\n resultValue = featureUpdate.getColumnValue(\"result\");\n if (!resultValue.Contains(\"updated\"))\n {\n file.update(featureUpdate, updateMethods.lowFeatureLength);\n updatesForFile.markResult(featureUpdate.getIndex(), \"updated\");\n }\n }\n file.close();\n updateList.save();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:30:05.180",
"Id": "43966",
"ParentId": "43960",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43962",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:57:41.240",
"Id": "43960",
"Score": "5",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Should this be written with exception handling instead of nested if-thens?"
} | 43960 |
<p>I have isolated a little bit of code that was causing a small debate between myself and another user. I have taken some of the things that he said and meshed it with the code that was being reviewed in the first place <a href="https://codereview.stackexchange.com/q/36482/18427">here</a>.</p>
<p><strong>Original Code</strong></p>
<blockquote>
<pre><code>while (!validInput)
{
var playerChoice = -1;
Console.WriteLine("Please choose your Gesture ");
gameSetup(listOfGestures);
try
{
playerChoice = Convert.ToInt32 (Console.ReadLine());
}
catch (FormatException e)
{
validInput = false;
}
if (playerChoice > 0 && playerChoice <= listOfGestures.Count)
{
playerGesture = listOfGestures[playerChoice - 1];
validInput = true;
}
else
{
validInput = false;
}
}
</code></pre>
</blockquote>
<hr>
<p>Here is what I came up with based on our <a href="http://chat.stackexchange.com/rooms/13448/loops">conversation</a>.</p>
<p><strong>New Code</strong></p>
<pre><code>var validInput = false; //forgot this part
while (!validInput)
{
var playerChoice = -1;
Console.WriteLine("Please choose your Gesture ");
gameSetup(listOfGestures);
validInput = int.TryParse(Console.ReadLine(),out playerChoice);
if (playerChoice > 0 && playerChoice <= listOfGestures.Count)
{
playerGesture = listOfGestures[playerChoice - 1];
validInput = true;
}
}
</code></pre>
<hr>
<p>Do I need to create a new method to sort out user input and whether or not it is an integer inside the min and max bounds?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:24:03.877",
"Id": "76259",
"Score": "1",
"body": "You initialize `playerChoice` to `-1`, but that value is never used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:33:07.543",
"Id": "76265",
"Score": "0",
"body": "`validInput = int.TryParse(Console.ReadLine(),out playerChoice);` @CodesInChaos"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:34:16.213",
"Id": "76266",
"Score": "0",
"body": "That line overwrites the initial value of player choice and doesn't read it (it's an `out` parameter), so you didn't need to initialize it to `-1`. I'd instead declare it as `int playerChoice;` without initialization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:53:43.693",
"Id": "76270",
"Score": "0",
"body": "why not `var playerChoice`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:59:33.163",
"Id": "76294",
"Score": "1",
"body": "Unless you REALLY need to use an untyped variable, strongly typing generally is the better way to go, because it can help catch stupid errors down the line. It's an added line of defence against bugs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T23:52:48.657",
"Id": "76387",
"Score": "2",
"body": "This is C#, there are no untyped variables. All variables are strongly statically typed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T02:20:37.120",
"Id": "76397",
"Score": "0",
"body": "I thought that the `out` parameter takes in a variable that is already in scope into the function and returns it with the value it is given inside the function, is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:03:47.630",
"Id": "79714",
"Score": "0",
"body": "Malachi, you're right about the out parameter, but the variable it takes in doesn't need to be initialized. Initializing it in that line reduces readability a bit because it makes it look like that value will be used for something"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T01:16:39.557",
"Id": "79725",
"Score": "0",
"body": "but it is being used for something....@BenAaronson I am a little lost I think. are you saying that I don't need to create the variable ahead of time, that playerChoice can be created right there?"
}
] | [
{
"body": "<p>It would be best for the sake of modularity, and re-usability for this whole chunk of code to be placed in a separate method. If you are going to need more user input besides just what gesture they want to use you could also make it more generic to be re-used through the rest of your program for various situations.</p>\n\n<p>Your code seems to be a bit illogical as you are using the <code>playerChoice</code> variable even when you know it was not parsed correctly. you set <code>validInput</code>, but then don't check it in the if statement.</p>\n\n<p>Here is how I would re-write that chunk if you weren't going to just separate it all out into a generic method of its own.</p>\n\n<p><strong>Note</strong>: I also changed the default value of <code>playerChoice</code> to be 0 because that is obviously out of range in this case, as you say that valid input has to be over 0. This change is minor and unnecessary, but I just wanted you to be aware of it.</p>\n\n<pre><code>while (!validInput)\n{\n var playerChoice = 0;\n Console.WriteLine(\"Please choose your Gesture \");\n gameSetup(listOfGestures);\n if (validInput = int.TryParse(Console.ReadLine(), out playerChoice) && playerChoice > 0 && playerChoice <= listOfGestures.Count)\n playerGesture = listOfGestures[playerChoice - 1];\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong>: My <a href=\"https://codereview.stackexchange.com/a/43654/38054\">original response</a> to the overall structure of this program included code that gave the user specific feedback to tell the user why their input was wrong (Point # 9 in my review). If you are not looking for such feedback in a method, here is a simple Method that gets Integer User input from the console</p>\n\n<pre><code>public static int GetIntInRange(int min = int.MinValue, int max = int.MaxValue, string prompt = \"Please enter an Integer: \")\n{\n int parsedValue;\n do { Console.Write(prompt); } \n while (!(int.TryParse(Console.ReadLine(), out parsedValue) && parsedValue >= min && parsedValue <= max));\n return parsedValue;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:42:45.073",
"Id": "76089",
"Score": "0",
"body": "Good, but your code has the bug that inputting `0` or a number higher than the number of gestures will still end the loop. Which is, admittedly, a bug in the original code too, but it was more obvious there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:45:36.777",
"Id": "76091",
"Score": "0",
"body": "@Bobson I'm not sure I see the problem, if the user enters 0 it will fail `playerChoice > 0` which will set `validInput` to false, which will cause the main loop to go again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:15:41.757",
"Id": "76096",
"Score": "2",
"body": "Ooh, no, you're right. I misplaced the `()`'s when I was reading it such that `validInput` was only set to the result of `TryParse()` and not the rest of the conditions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:16:32.683",
"Id": "76098",
"Score": "0",
"body": "@Bobson it was a flaw in my code, and Ben's code would fix that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:23:27.883",
"Id": "76101",
"Score": "0",
"body": "@BenVlodgi will `playerChoice` be assigned before the rest of the comparisons in the `if` statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:26:58.753",
"Id": "76106",
"Score": "1",
"body": "@Malachi yes, everything happens sequentially, so the comparisons will only be ran if the `TryParse` didn't fail. the `TryParse`has to finish to be able to determine this, which means it has sent out the `playerChoice` before continuing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:40:32.550",
"Id": "76138",
"Score": "1",
"body": "I think it makes the code harder to read if you cram so much of the logic into the test part of the do-while block. I think it's generally better practice to put things like reading input inside the body of the loop, assuming that doing so gives you the same result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:36:45.537",
"Id": "76148",
"Score": "0",
"body": "@NateC-K There is an expanded version of the code I just edited in, but I'm a minimalist, I love making code as concise as possible, the expanded version required the declaration of another variable and was many more lines of code. In my own code, I may break the while statement into multiple lines if it got too confusing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:02:02.027",
"Id": "76157",
"Score": "0",
"body": "I agree that adding some line breaks would go a long way toward making the code clearer."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:41:18.413",
"Id": "43967",
"ParentId": "43965",
"Score": "11"
}
},
{
"body": "<h3>Random Nitpicks</h3>\n<ul>\n<li><code>validInput</code> should be named <code>isValidInput</code> to follow <code>bool</code> naming convention.</li>\n<li><code>listOfGestures</code> shouldn't convey its type in the name (assuming it's a <code>List<Gesture></code>); <code>gestures</code> would be a better name.</li>\n<li>if <code>gestures</code> were a <code>Dictionary<int,Gesture></code>, your <em>check-if-the-value-is-within-bounds</em> condition would become much simpler: <code>gestures.TryGetValue(playerChoice, out playerGesture);</code></li>\n</ul>\n<blockquote>\n<p><em>Do I need to create a new method to sort out user input and whether or not it is an integer inside the min and max bounds?</em></p>\n</blockquote>\n<p>If you went OOP-all-the-way and encapsulated that piece of logic into its own object, you could write a unit test that validates whether a valid input returns a <code>Gesture</code>:</p>\n<pre><code>interface IGestureInputValidator\n{\n Gesture ValidateInput(string userInput);\n}\n</code></pre>\n<p>The implementation of that interface could return <code>null</code> for any illegal <code>userInput</code> value, or a <code>Gesture</code> instance for any legal input. This would change your code a little:</p>\n<pre><code>Gesture playerGesture;\nwhile (playerGesture == null)\n{\n Console.WriteLine("Please choose your Gesture:");\n var input = Console.ReadLine();\n playerGesture = _validator.ValidateInput(input);\n}\n</code></pre>\n<p>Notice <code>_validator</code> is an instance field; you can probably <em>inject</em> that instance in your constructor (or <code>new</code> it up there).</p>\n<hr />\n<p>I... just noticed you have no <code>Gesture</code> object - a <code>string</code> could work just as well:</p>\n<pre><code>string playerGesture;\nwhile (playerGesture == null)\n{\n Console.WriteLine("Please choose your Gesture:");\n var input = Console.ReadLine();\n playerGesture = _validator.ValidateInput(input);\n}\n</code></pre>\n<p>Given a small change in the validator interface:</p>\n<pre><code>interface IGestureInputValidator\n{\n string ValidateInput(string userInput);\n}\n</code></pre>\n<p>However I don't like this, because the intent isn't crystal-clear anymore; a <code>string</code> could be anything, and we're looking for a <em>specific kind of string</em>. I think gestures deserve their own class, or even better, an enum. Whatever you do, extracting the validation into its own object (or method, if you consider that responsibility as part of the same class that holds the other piece of logic) allows you to change that logic, without affecting the rest of your code.</p>\n<p>I'd recommend to <em>separate the concerns</em> as much as possible, so to boldly answer your question, yes, you should separate it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:53:58.440",
"Id": "76142",
"Score": "0",
"body": "In one case, you're telling him to use a naming convention for bool that indicates the type, in another case you're advising him not to indicate in the name that his variable is a list. Isn't that inconsistent?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:56:01.880",
"Id": "76156",
"Score": "1",
"body": "@NateC-K a `bool` is a simple value type with true/false values; \"IsXxxxxx\" is an established naming convention for them. A *list*, however, is a reference type that implements an interface; by sticking \"List\" to a variable's name, you are potentially calling a cat as a dog, ...or a lion. Many types implement `IList<T>`, not just `List<T>`; calling an enumerable a xxxxList is a lie."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:09:51.713",
"Id": "76158",
"Score": "0",
"body": "The \"is...\" naming convention is part of Hungarian notation, which MS says you shouldn't bother with anymore. Anything that implements IList is necessarily an IList (not to mention a variable of this type can only be used to call methods that implement IList), so I don't see how you can say that it is \"a lie\" to call it a list. You program only cares about the typing of the variable at the current level of abstraction; you seem to suggest that I should care about the details underlying the abstraction even when they are irrelevant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:11:14.220",
"Id": "76159",
"Score": "0",
"body": "My main point, though, is that you are advocating for a naming convention in one case and against in another case. Personally I'm against any kind of type-based naming convention when we're using a language like C# that makes it unnecessary, but sometimes it's still helpful to include some type information in a name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:29:56.507",
"Id": "76161",
"Score": "2",
"body": "Variable naming is for the Developer only, the compiler will compile the code no matter what you name it. standards are for people maintaining the code. the naming schemes are there as guidelines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:18:34.647",
"Id": "76287",
"Score": "5",
"body": "@NateC-K From Microsoft's [Names of Type Members (4.5)](http://msdn.microsoft.com/en-us/library/ms229012(v=vs.110).aspx): \"1. DO name collection properties with a _plural phrase_ describing the items in the collection _instead of_ using a singular phrase followed by \"List\" or \"Collection.\" 2. DO name Boolean properties with an affirmative phrase (CanSeek instead of CantSeek). _Optionally, you can also prefix Boolean properties with \"Is,\" \"Can,\" or \"Has,\" but only where it adds value._\""
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:03:15.127",
"Id": "43971",
"ParentId": "43965",
"Score": "12"
}
},
{
"body": "<p>The second sample is definitely better. I would be inclined to continue to improve the code by <strong>separating mechanisms from policies</strong>. The <em>policy</em> is the code that actually expresses the <em>meaning</em> of the program; the <em>mechanism</em> is the code that expresses <em>what specific operations implement the policy</em>. </p>\n\n<p>This idea comes from security design; you don't want the code that computes \"is Bob allowed to open this door?\" and the code that computes \"is that really Bob's card key?\" to be the same code. The first is a policy, the second is a mechanism. But it applies generally to all code.</p>\n\n<p>By separating mechanism from policy we enable both to be understood more easily. The \"main line\" of your code should read like the specification. If you had to describe your code in English you'd probably say something like \"present the user with a choice of gestures. If the user chooses an invalid gesture, keep trying until they choose a valid gesture.\" That's the <em>meaning</em> of your program, but that's not what your code looks like. Rather, your code looks like the most important things in the world are integer and bool variables, list counts, and so on.</p>\n\n<p>Let's identify a mechanism: parsing an integer and testing whether it is in range is the <em>mechanism</em> behind the <em>policy</em> of \"the user must choose a valid gesture\". So let's isolate that mechanism into a <em>purely</em> mechanistic method, that knows <em>nothing</em> about your policy domain:</p>\n\n<pre><code>static class Extensions\n{\n public static int? BoundedParse(this string str, int lower, int upper)\n {\n if (str == null) \n return null;\n int result;\n bool success;\n success = int.TryParse(str, out result);\n if (!success) \n return null;\n if (result < lower) \n return null;\n if (result > upper) \n return null;\n return result;\n }\n}\n</code></pre>\n\n<p>Let's now rewrite your loop as a do-while instead of a while. Look how much ugly mechanism we removed, leaving your policy shining brightly through:</p>\n\n<pre><code>gameSetup(listOfGestures);\nint? choice;\ndo\n{\n Console.WriteLine(\"Please choose your Gesture \");\n choice = Console.ReadLine().BoundedParse(1, listofGestures.Count);\n}\nwhile(choice == null);\nplayerGesture = listOfGestures[choice.Value - 1];\n</code></pre>\n\n<p>And as a bonus, we now have a reusable method that we can apply to <em>any</em> task that requires that a string be parsed as a bounded integer.</p>\n\n<p>We can take this even further. Isn't that loop a mechanism? Move it into a helper method:</p>\n\n<pre><code>static int PromptForNumber(string prompt, int lower, int upper)\n{\n int? choice;\n do\n {\n Console.WriteLine(prompt);\n choice = Console.ReadLine().BoundedParse(lower, upper);\n }\n while(choice == null);\n return choice.Value;\n}\n</code></pre>\n\n<p>And now your method is:</p>\n\n<pre><code>gameSetup(listOfGestures);\nint choice = PromptForNumber(\"Please choose your gesture\", 1, listofGestures.Count);\nplayerGesture = listOfGestures[choice - 1];\n</code></pre>\n\n<p>Now the code is super clear what is going on <em>at the policy level</em> because all the stuff you don't care about is now the responsibility of some mechanism somewhere. (And again we have a great mechanism for prompting for a number that we can re-use later.)</p>\n\n<p>Even better: maybe there is a better way to display a prompt and get a number. If we decided that we wanted to write a GUI instead, we can change the mechanism code without changing the policy code. The policy code doesn't care <em>how</em> the valid gesture gets chosen, just that it does.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:39:16.007",
"Id": "76162",
"Score": "12",
"body": "Very well explained, puts the ideas of encapsulation and separation of responsibility into more concrete terms that others can more readily understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T02:41:27.807",
"Id": "76184",
"Score": "0",
"body": "I generally don't like `do while` loops I rather like `while` loops. I guess that I could still write it as a `while` loop. I will post the code to the game when I am finished with my changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:47:38.187",
"Id": "76252",
"Score": "11",
"body": "I know leaving \"+1\" and \"thanks\" comments are generally discouraged, but I want to ignore that here just to say thanks, Eric, for all of your answers across Stack Exchange. I regularly browse through the latest answers on your profile (mainly on SO), because the quality of the information that you provide is always so good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:14:57.030",
"Id": "76258",
"Score": "11",
"body": "@JohnH: That discouragement is in my opinion counterproductive. Politeness costs very little and goes a long way towards making people feel good about both asking for help and providing help to others. You're very welcome; it's my pleasure. Thanks for the kind words."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:34:45.710",
"Id": "76290",
"Score": "0",
"body": "@EricLippert, I have posted new code [Here](http://codereview.stackexchange.com/q/44034/18427) I used some of the code you provided word for word and other code that you provided I altered. would you mind looking at my code there and letting me know what you think. please keep in mind I was posting it at 1:30 A.M. (should be good if programmers do their best work in the middle of the night, we will see)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:36:32.893",
"Id": "76291",
"Score": "0",
"body": "Commentators please don't overlook the other answers, they are good answers as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:51:10.303",
"Id": "76372",
"Score": "0",
"body": "@JohnH: \"+1\" and \"thanks\" **answers** are against the policy of the network, with the instruction to leave a comment instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:54:48.887",
"Id": "76374",
"Score": "0",
"body": "@BenVoigt Clicking the `add comment` link below yours, without typing anything in the textbox, displays the following message: `Use comments to ask for more information or suggest improvements. Avoid comments like \"+1\" or \"thanks\".`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T04:30:11.630",
"Id": "86285",
"Score": "9",
"body": "@EricLippert \"Thanks — good point about _X_\" comments are fine; just \"Thanks\" would be noise. Votes are the currency of thanks that makes Stack Exchange sites work, so we prefer voting — it's the most rewarding form of thanks possible. I notice that you have only voted twice so far. Code Review would benefit greatly from having experts like you recognize good questions and answers from other members by voting."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:58:58.810",
"Id": "43989",
"ParentId": "43965",
"Score": "60"
}
}
] | {
"AcceptedAnswerId": "43989",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:27:51.700",
"Id": "43965",
"Score": "36",
"Tags": [
"c#",
"validation",
"console",
"comparative-review"
],
"Title": "Ensuring user input is an integer in a range"
} | 43965 |
<p>To avoid <code>switch</code> statements at multiple places, I wrote the following code. This was based on articles found in the Google search. <em>The object names are not real in the sample below. So please ignore that</em>.</p>
<pre><code> //somewhere in the code
foreach (IEmailAlertDt alert in EmailAlertFactory.GetEmailAlertDtType(allowedEmails))
{
if (alert.CheckEmailAlertDt(currReason))
{
SendEmail(alert.EmailSubject(patRegister.Pat.Id.ToString()), alert.EmailBody(patRegister.Pat.Id.ToString(), patRegister.Organ.Descrip));
alert.UpdateEmailAlertDt(currReason);
}
}
[Flags]
enum EmailAlertType
{
NoAlert=0,
FirstAlert=1,
SecondAlert=2,
ThirdAlert=4
};
static class EmailAlertFactory
{
private static Dictionary<EmailAlertType, Func<IList<IEmailAlertDt>>> EmailAlertMap = new Dictionary<EmailAlertType, Func<IList<IEmailAlertDt>>>
{
{EmailAlertType.FirstAlert,()=> new List<IEmailAlertDt>() {new FisrtEmailAlertDt() } },
{EmailAlertType.FirstAlert | EmailAlertType.SecondAlert ,()=> new List<IEmailAlertDt>() {new FisrtEmailAlertDt(), new SecondEmailAlertDt() } },
{EmailAlertType.FirstAlert | EmailAlertType.SecondAlert | EmailAlertType.ThirdAlert,()=> new List<IEmailAlertDt>() {new FisrtEmailAlertDt(), new SecondEmailAlertDt(), new ThirdEmailAlertDt() } }
};
public static IList<IEmailAlertDt> GetEmailAlertDtType(EmailAlertType alertType)
{
return EmailAlertMap[alertType]();
}
}
interface IEmailAlertDt
{
bool CheckEmailAlertDt(PatWaitListStatReason reason);
void UpdateEmailAlertDt(PatWaitListStatReason reason);
string EmailBody(string patID, string Organ);
string EmailSubject(string patID);
}
class FisrtEmailAlertDt : IEmailAlertDt
{
public bool CheckEmailAlertDt(PatWaitListStatReason reason)
{
if (reason.EmailAlertFirstDate == null)
return true;
else
return false;
}
public void UpdateEmailAlertDt(PatWaitListStatReason reason)
{
if (reason.EmailAlertFirstDate == null)
reason.EmailAlertFirstDate = DateTime.Today;
}
public string EmailBody(string patID, string Organ)
{
return String.Format(PatOnHoldSuspension.emailBody, PatOnHoldSuspension.FIRST_ALERT_DAYS, patID, Organ);
}
public string EmailSubject(string patID)
{
return String.Format(PatOnHoldSuspension.emailSubject, PatOnHoldSuspension.FIRST_ALERT_DAYS,patID);
}
}
class SecondEmailAlertDt : IEmailAlertDt
{
public bool CheckEmailAlertDt(PatWaitListStatReason reason)
{
if (reason.EmailAlertSecondDate == null)
return true;
else
return false;
}
public void UpdateEmailAlertDt(PatWaitListStatReason reason)
{
if (reason.EmailAlertSecondDate == null)
reason.EmailAlertSecondDate = DateTime.Today;
}
public string EmailBody(string patID, string Organ)
{
return String.Format(PatOnHoldSuspension.emailBody, PatOnHoldSuspension.SECOND_ALERT_DAYS, patID, Organ);
}
public string EmailSubject(string patID)
{
return String.Format(PatOnHoldSuspension.emailSubject, PatOnHoldSuspension.SECOND_ALERT_DAYS, patID);
}
}
class ThirdEmailAlertDt : IEmailAlertDt
{
public bool CheckEmailAlertDt(PatWaitListStatReason reason)
{
if (reason.EmailAlertThirdDate == null)
return true;
else
return false;
}
public void UpdateEmailAlertDt(PatWaitListStatReason reason)
{
if (reason.EmailAlertThirdDate == null)
reason.EmailAlertThirdDate = DateTime.Today;
}
public string EmailBody(string patID, string Organ)
{
return String.Format(PatOnHoldSuspension.emailBody120, PatOnHoldSuspension.THIRD_ALERT_DAYS, patID, Organ);
}
public string EmailSubject(string patID)
{
return String.Format(PatOnHoldSuspension.emailSubject120, patID);
}
}
</code></pre>
<p>The things that bother me is that there are different small methods like <code>CheckEmailAlertDt</code>, with minor difference. In the first <code>date1</code> is used and in seconds one <code>date2</code> is used. Is there any way I can further optimise/streamline this code?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:26:17.833",
"Id": "76105",
"Score": "0",
"body": "Could you explain why are you trying to avoid `switch`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:30:44.977",
"Id": "76108",
"Score": "0",
"body": "Also, I'm not sure I can ignore names that are as bad as `classDt` or `derclass1`. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:31:13.447",
"Id": "76111",
"Score": "0",
"body": "I don't want to combine everything in the `switch` and with our constantly changing requirement it is easy to make mistakes. As I mentioned, in the question, you can ignore names for this question. In the actual App, there are better names used"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:37:38.943",
"Id": "76115",
"Score": "0",
"body": "@gmailuser Is it not possible to post the actual code in question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:45:36.953",
"Id": "76120",
"Score": "0",
"body": "I just change the names of objects. The structure is same. Besides that there is a lot of code I've to include here to post actual code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:00:53.277",
"Id": "76121",
"Score": "0",
"body": "@dreza, as requested, I've posted the actual code"
}
] | [
{
"body": "<ol>\n<li><p>I really like your use of a <code>Dictionary</code> with <code>Functions</code>, that is one of my favorite things to do in C# for some reason. </p></li>\n<li><p>Your methods that look like this</p>\n\n<pre><code>public bool CheckEmailAlertDt(PatWaitListStatReason reason)\n{\n if (reason.EmailAlertFirstDate == null)\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p>could be written much simpler as</p>\n\n<pre><code>public bool CheckEmailAlertDt(PatWaitListStatReason reason)\n{\n return reason.EmailAlertFirstDate == null;\n}\n</code></pre></li>\n<li><p>Use <code>switch</code> Statements.... Or not, if not... this is probably as optimized the code is going to get. Here is my rendition of what your code will look like if using switches instead. I just switched the regular flag enums, although you'll probably want to bitwise OR them with the rest of the values as you were doing in your OP</p>\n\n<pre><code>class EmailAlertDt\n{\n public EmailAlertType EmailAlertType { get; private set; }\n\n public EmailAlertDt(EmailAlertType emailAlertType)\n {\n EmailAlertType = emailAlertType;\n }\n\n public bool CheckEmailAlertDt(PatWaitListStatReason reason)\n {\n switch (EmailAlertType)\n {\n case EmailAlertType.FirstAlert: return reason.EmailAlertFirstDate == null;\n case EmailAlertType.SecondAlert: return reason.EmailAlertSecondDate == null;\n case EmailAlertType.ThirdAlert: return reason.EmailAlertThirdDate == null;\n case EmailAlertType.NoAlert: return false;\n default: throw new SomeThingException(\"My alerts type is all messed up =\\\\ \");\n }\n }\n\n public void UpdateEmailAlertDt(PatWaitListStatReason reason)\n {\n switch (EmailAlertType)\n {\n case EmailAlertType.FirstAlert: _updateEmailAlertDt(reason.EmailAlertFirstDate); break;\n case EmailAlertType.SecondAlert: _updateEmailAlertDt(reason.EmailAlertSecondDate); break;\n case EmailAlertType.ThirdAlert: _updateEmailAlertDt(reason.EmailAlertThirdDate); break;\n case EmailAlertType.NoAlert: break;\n default: throw new SomeThingException(\"My alerts type is all messed up =\\\\ \");\n }\n }\n\n private void _updateEmailAlertDt(ref DateTime emailAlertDate)\n {\n if (emailAlertDate == null)\n emailAlertDate = DateTime.Today;\n }\n\n public string EmailBody(string patID, string Organ)\n {\n object days;\n\n switch (EmailAlertType)\n {\n case EmailAlertType.FirstAlert: days = PatOnHoldSuspension.FIRST_ALERT_DAYS; break;\n case EmailAlertType.SecondAlert: days = PatOnHoldSuspension.SECOND_ALERT_DAYS; break;\n case EmailAlertType.ThirdAlert: days = PatOnHoldSuspension.THIRD_ALERT_DAYS; break;\n case EmailAlertType.NoAlert: throw new SomeThingException(\"Halp\");\n default: throw new SomeThingException(\"My alerts type is all messed up =\\\\ \");\n }\n return String.Format(PatOnHoldSuspension.emailBody120, days, patID, Organ);\n }\n\n public string EmailSubject(string patID)\n {\n return String.Format(PatOnHoldSuspension.emailSubject120, patID);\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:58:42.757",
"Id": "44155",
"ParentId": "43968",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:41:18.687",
"Id": "43968",
"Score": "6",
"Tags": [
"c#",
"optimization",
".net",
"email"
],
"Title": "Optimizing email alert code"
} | 43968 |
<p>I have this piece of code that is running too slow. I was wondering if anyone can help me optimize it as I can't seem to find any more shortcuts. I'm not sure if using <code>List<></code> is going to help me but I need complex operation such as Union and Overlap. </p>
<p>Also, <code>List</code> is desirable because I don't know how many unique partitions an Image Region is going to be before running.</p>
<p><code>u1.length</code> = 13254 which is the number of distinct elements in <code>RevisedListMeanH</code>
<code>RevisedListMeanH.Count</code> = 90000</p>
<p>The purpose of the first piece of code is to group together pixels via horizontal comparison and vertical comparison. This runs for about 70 seconds.</p>
<p>The second portion combines both vertical and horizontal pixel blocks into a 2D-block. This section runs for about 120 seconds. My goal is to have both of these loops complete under 10 seconds. </p>
<p>These numbers are from a 300x300 pixel region comparisons of a 4000x3000 image.</p>
<pre><code>watch.Start();
for (int s = 0; s < u1.Length; s++ )//iterate through uniquelist
{
List<int> ConnectedBlocksH = new List<int>();
List<int> ConnectedBlocksV = new List<int>();
float[] RH = RevisedListMeanH.ToArray();
float[] RV = RevisedListMeanV.ToArray();
for (int a = 0; a < RevisedListMeanH.Count; a++)//iterate through bitmap with res
{
if (u1[s] == RH[a])
{
ConnectedBlocksH.Add(a);//add the index
}
}
for (int a = 0; a < RevisedListMeanV.Count; a++)//iterate through bitmap with res
{
if (u1[s] == RV[a])
{
ConnectedBlocksV.Add(a);//add the index
}
}
ArrayOfConnectedBlocksH[s] = ConnectedBlocksH;//where the data IS
ArrayOfConnectedBlocksV[s] = ConnectedBlocksV;//where the data IS
}
watch.Stop();
long asasasdda = watch.ElapsedMilliseconds; //71 sec
watch.Reset();
watch.Start();
//if intersects then union the two lists
//iterate through both list
List<List<int>> ListOfConnectedBlocks = new List<List<int>>();
for (int a = 0; a < ArrayOfConnectedBlocksH.Length; a++ )
{
HashSet<int> i = new HashSet<int>(ArrayOfConnectedBlocksH[a]);
//trigger means it scanned and there was no overlap to add to the group
while (true)
{
bool trigger = true;
for (int b = 0; b < ArrayOfConnectedBlocksV.Length; b++)
{
if (i.Overlaps(ArrayOfConnectedBlocksV[b]))
{
i.UnionWith(ArrayOfConnectedBlocksV[b]);//combines all overlaps into one group
ArrayOfConnectedBlocksV[b].Clear();//merged so just remove
trigger = false;
}
}
if (trigger)
{
break;
}
trigger = true;
for (int c = 0; c < ArrayOfConnectedBlocksH.Length; c++)//now cycle through horizontal
{
if (i.Overlaps(ArrayOfConnectedBlocksH[c]))
{
i.UnionWith(ArrayOfConnectedBlocksH[c]);//combines all overlaps into one group
ArrayOfConnectedBlocksH[c].Clear();//merged so just remove
trigger = false;
}
}//first cycle to get T0
if(trigger)
{
break;
}
}
if (i.Count != 0)
{
ListOfConnectedBlocks.Add(i.ToList<int>());
}
}
watch.Stop();
long asasasda = watch.ElapsedMilliseconds;//122 seconds
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:35:43.733",
"Id": "76114",
"Score": "0",
"body": "I personally get rather annoyed when I see `List.Add()` in a loop inside an `if`, because to me that means its just begging for an `.AddRange()` and a `.Where()`, but the fact that you're adding the index makes that far too difficult. Still, creating two arrays each iteration and growing them one by one in the inner loops is certainly worth looking carefully at when trying to determine what's slowing you down."
}
] | [
{
"body": "<p>First of, I'm gonna give you a basic idea...</p>\n\n<p>Instead of doing 2 loops over two different arrays, check their sizes first. Create a loop for the smaller of both array sizes. In that loop you will process that Array, and then create another loop for the remainder of unprocessed data.</p>\n\n<p>This can be done for your two double fors you have in there. This way you could reduce the complexity from O(n+m) to O(n+(m-n))</p>\n\n<p>The pseudo code is this...</p>\n\n<pre><code>if(Arr1 > Arr2)\n{ \n process(Arr1, Arr2);\n}\nelse if (Arr2 > Arr1)\n{\n process(Arr2, Arr1);\n}\nelse //They're the same size!\n{\n for(idx = 0; idx != count(any will do); ++idx)\n {\n //process Arr1\n //process Arr2\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:46:08.160",
"Id": "43977",
"ParentId": "43969",
"Score": "2"
}
},
{
"body": "<p>Your mileage may vary, but LINQifying a bit makes it a heck of a lot more readable...</p>\n\n<pre><code> watch.Start();\n\n // if intersects then union the two lists\n // iterate through both list\n var listOfConnectedBlocks = new List<List<int>>();\n\n foreach (var i in ArrayOfConnectedBlocksH.Select(t1 => new HashSet<int>(t1)))\n {\n // trigger means it scanned and there was no overlap to add to the group\n while (true)\n {\n var trigger = true;\n\n foreach (var t in ArrayOfConnectedBlocksV.Where(i.Overlaps))\n {\n i.UnionWith(t); // combines all overlaps into one group\n t.Clear(); // merged so just remove\n trigger = false;\n }\n\n if (trigger)\n {\n break;\n }\n\n trigger = true;\n\n // now cycle through horizontal\n foreach (var t in ArrayOfConnectedBlocksH.Where(i.Overlaps))\n {\n i.UnionWith(t); // combines all overlaps into one group\n t.Clear(); // merged so just remove\n trigger = false;\n }\n\n // first cycle to get T0\n if (trigger)\n {\n break;\n }\n }\n\n if (i.Any())\n {\n listOfConnectedBlocks.Add(i.ToList());\n }\n }\n\n watch.Stop();\n var asasasda = watch.ElapsedMilliseconds; // ? seconds\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T00:45:04.230",
"Id": "76174",
"Score": "0",
"body": "Thanks I'll add more Linq to my code. Just beginning to use them. But it does Linq does seem slow if its used in loops."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:30:02.117",
"Id": "43982",
"ParentId": "43969",
"Score": "1"
}
},
{
"body": "<p>Some suggestions which might make it faster:</p>\n\n<hr>\n\n<p>Move your ToArray() statements outside the loop so that you only execute them once and then reuse them:</p>\n\n<pre><code>float[] RH = RevisedListMeanH.ToArray();\nfloat[] RV = RevisedListMeanV.ToArray();\n\nfor (int s = 0; s < u1.Length; s++ )//iterate through uniquelist\n{\n ... etc ...\n</code></pre>\n\n<hr>\n\n<p>In the second loop, you convert a List to a HashSet:</p>\n\n<pre><code>HashSet<int> i = new HashSet<int>(ArrayOfConnectedBlocksH[a]);\n</code></pre>\n\n<p>You could avoid that by making ArrayOfConnectedBlocksH[a] i.e. ConnectedBlocksH a HashSet instead of a List to begin with.</p>\n\n<hr>\n\n<p>Might it be any faster if you cached the Length and Count property values instead of calling them repeatedly? For example:</p>\n\n<pre><code>for (int s = 0, int length = u1.Length; s < length; s++ )\n</code></pre>\n\n<hr>\n\n<p>The basic problem in your first loop is that you are iterating a lot of elements, and doing <code>u1.Length * (RevisedListMeanH.Count + RevisedListMeanV.Count)</code> comparisons.</p>\n\n<p>It might be faster although more complicated to do the following.</p>\n\n<p>Convert your <code>u1</code> list to a list of index/value pairs:</p>\n\n<pre><code>List<KeyValuePair<int,float>> u1Values = new List<KeyValuePair<int,float>>();\nfor (int s = 0; s < u1.Length; s++ )\n u1Values.Add(new KeyValuePair<int,float>(s, u1[s]));\n</code></pre>\n\n<p>Sort your index/value pairs by value:</p>\n\n<pre><code>u1Values.Sort((kvp1, kvp2) => kvp1.Value.CompareTo(kvp2.Value));\n</code></pre>\n\n<p>Do the same with your RevisedListMeanH and RevisedListMeanV lists.</p>\n\n<p>Now that your all arrays are sorted by value, it is easier/cheaper to find which elements match: you can do it by iterating through all the arrays once; something like:</p>\n\n<pre><code>int u = 0; // index into u1Values\nint v = 0; // index into vValues\n\nfor (;;)\n{\n int i = u1Values[u].Value.CompareTo(vValues[v].Value);\n if (i == 0)\n {\n // matches!\n int s = u1Values[u].Key;\n ArrayOfConnectedBlocksV[s].Add(vValues[v].Key);//add the index\n // which do we increment now: ++u or ++v?\n }\n else if (i > 0)\n {\n // u1Values[u] is too big\n if (++v == u1Values.Count)\n break;\n }\n else\n {\n if (++u == vValues.Count)\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T00:23:19.713",
"Id": "76171",
"Score": "0",
"body": "Thanks for the feedback\n\nI have found a solution. This runs about 100 ms instead of 70 seconds. This is for the first section. Thank you for your inputs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:35:42.057",
"Id": "44004",
"ParentId": "43969",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "44004",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:55:45.487",
"Id": "43969",
"Score": "3",
"Tags": [
"c#",
"performance",
"image"
],
"Title": "Loop optimization for image processing"
} | 43969 |
<p>I have decided to make a basic C++ implementation of the <code>std::map</code> class, and I was checking that it is fine, as I am not sure if the <code>operator[]</code> is done correctly: should I be using the <code>has_key</code> function? e.t.c</p>
<pre><code>template < typename _Key, typename _Ty, typename _Cmp = std::less<_Key>, typename _Alloc = std::allocator< std::pair<const _Key, _Ty> > > class map
{
public:
typedef map<_Key, _Ty, _Cmp, _Alloc> _Myt;
typedef _Key key_type;
typedef _Ty mapped_type;
typedef _Cmp compare_type;
typedef _Alloc allocator_type;
typedef std::pair<const key_type, mapped_type> value_type;
typedef value_type *pointer;
typedef const value_type *const_pointer;
typedef value_type *iterator;
typedef const value_type *const_iterator;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
map()
: size_(0), capacity_(20), data_(_Alloc().allocate(20))
{
}
map(const _Myt &_Rhs)
: size_(_Rhs.size_), capacity_(_Rhs.size_ + 20), data_(_Alloc().allocate(_Rhs.size_))
{
int count = 0;
for (iterator i = &_Rhs.data_[0]; i != &_Rhs.data_[_Rhs.size_]; ++i, ++count)
{
_Alloc().construct(&data_[count], *i);
}
}
~map()
{
if (!empty())
{
for (iterator i = begin(); i != end(); ++i)
{
_Alloc().destroy(i);
}
_Alloc().deallocate(data_, capacity_);
}
}
_Myt &insert(const value_type &_Value)
{
if (++size_ >= capacity_)
{
reserve(capacity_ * 2);
}
_Alloc().construct(&data_[size_ - 1], _Value);
return *this;
}
bool has_key(const key_type &_Key)
{
for (iterator i = begin(); i != end(); ++i)
{
if (i->first == _Key)
{
return true;
}
}
return false;
}
mapped_type &operator[](const key_type &_Key)
{
if (has_key(_Key))
{
for (iterator i = begin(); i != end(); ++i)
{
if (i->first == _Key)
{
return i->second;
}
}
}
size_type op = size_;
insert(value_type(_Key, mapped_type()));
return data_[op].second;
}
_Myt &reserve(size_type _Capacity)
{
int count = 0;
if (_Capacity < capacity_)
{
return *this;
}
pointer buf = _Alloc().allocate(_Capacity);
for (iterator i = begin(); i != end(); ++i, ++count)
{
_Alloc().construct(&buf[count], *i);
}
std::swap(data_, buf);
for (iterator i = &buf[0]; i != &buf[size_]; ++i)
{
_Alloc().destroy(i);
}
_Alloc().deallocate(buf, capacity_);
capacity_ = _Capacity;
return *this;
}
bool empty()
{
return size_ == 0;
}
iterator begin()
{
return &data_[0];
}
iterator end()
{
return &data_[size_];
}
private:
pointer data_;
size_type size_, capacity_;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T19:58:36.987",
"Id": "76568",
"Score": "4",
"body": "I am downvoting this for your use of reserved identifiers. You have been advised not to do this in all of your previous STL exercise that you put up here for review. Please STOP AND READ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T13:58:35.510",
"Id": "400394",
"Score": "0",
"body": "You also fail at some basic points of `std::map`: it must not allow insertion of duplicates (which you only prevent in `operator[]`, but not in `.insert()`), and it must store its elements in key order (which you make no effort at)."
}
] | [
{
"body": "<p>You are searching two times the entire arrays to find your key,pair value. This is highly inefficient. Instead you could extend your has type to take two arguments and in the second argument it could store the value. This way you only iterate once. </p>\n\n<p>Otherwise yes, reusing your code is a yes yes, just don't iterate two times when you could easily done it once. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:32:41.533",
"Id": "43974",
"ParentId": "43972",
"Score": "0"
}
},
{
"body": "<p><strong>Readability</strong></p>\n\n<p>With your lengthy <code>template</code> statement, I'd put the <code>class</code> statement onto the next line:</p>\n\n<pre><code>template </*...*/>\nclass map\n</code></pre>\n\n<p><strong>Naming standards</strong></p>\n\n<p>According to <a href=\"https://stackoverflow.com/a/228797\">this answer</a>, identifiers in the form <code>_Identifier</code> are reserved:</p>\n\n<blockquote>\n <p><strong>7.1.3 Reserved identifiers</strong></p>\n \n <p>Each header declares or defines all identifiers listed in its\n associated subclause, and optionally declares or defines identifiers\n listed in its associated future library directions subclause and\n identifiers which are always reserved either for any use or for use as\n file scope identifiers.</p>\n \n <ul>\n <li>All identifiers that begin with an underscore and either an uppercase\n letter or another underscore are always reserved for any use.</li>\n </ul>\n \n <p>[...]</p>\n</blockquote>\n\n<p><strong>Const-correctness</strong></p>\n\n<ul>\n<li><p>You have iterators, but you should also have <code>const</code> iterators:</p>\n\n<pre><code>const_iterator cbegin() const\n{\n return &data_[0];\n}\n\nconst_iterator cend() const\n{\n return &data_[size_];\n}\n</code></pre></li>\n<li><p><code>empty()</code> should be <code>const</code>:</p>\n\n<pre><code>bool empty() const\n{\n return size_ == 0;\n}\n</code></pre></li>\n<li><p><code>has_key()</code> should be <code>const</code> <em>and</em> use the aforementioned <code>const</code> iterators:</p>\n\n<pre><code>bool has_key(const key_type &_Key) const\n{\n for (const_iterator i = cbegin(); i != cend(); ++i)\n {\n if (i->first == _Key)\n {\n return true;\n }\n }\n return false;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T23:31:46.097",
"Id": "77072",
"Score": "2",
"body": "Having `const_iterator begin() const;` is probably a higher priority than `cbegin()`, 'twas introduced first because it's the more useful, propagating `const` correctness in certain template situations. The lack of `const` correctness obviously led to `for (iterator i = &_Rhs.data_[0]; i != &_Rhs.data_[_Rhs.size_]; ++i, ++count)` - that can be cleaned up as `...i = rhs.begin(); i != rhs.end();...`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:36:54.437",
"Id": "43975",
"ParentId": "43972",
"Score": "10"
}
},
{
"body": "<blockquote>\n <p>[...] I am not sure if the operator[] is done correctly: should I be using the has_key function?</p>\n</blockquote>\n\n<p>It is done correctly (i.e. it does what the contract of its API should), but not efficiently. The operator iterates twice (once in <code>has_key</code> and once in the operator). You can replace both calls with a call to <code>std::find_if</code>, and remove the <code>has_key</code> function completely.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-11T12:57:50.677",
"Id": "44064",
"ParentId": "43972",
"Score": "6"
}
},
{
"body": "<p>I would use <code>std::vector</code> as internal container. It will simplify your code a lot.</p>\n<p>I also would store the array sorted. This will slow down adding the keys, but search will be O(log(N)). Removing the data will be faster too.</p>\n<p>I also would use "new" C++11 for:</p>\n<pre><code>bool has_key(const key_type &key) const\n{\n for (auto const &x : *this )\n if (x.first == key)\n return true;\n\n return false;\n}\n</code></pre>\n<p>Or if you can use C++17:</p>\n<pre><code>bool has_key(const key_type &key) const\n{\n for (auto const [k, v] : *this )\n if (k == key)\n return true;\n\n return false;\n}\n</code></pre>\n<p>You can also use <code>std::find</code> standard algorithm for this, but I personally would do it in C++11 way:</p>\n<pre><code>bool has_key(const key_type &key) const\n{\n return std::find(cbegin(), cend(), key) != cend();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T12:38:53.510",
"Id": "243979",
"ParentId": "43972",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:23:14.267",
"Id": "43972",
"Score": "6",
"Tags": [
"c++",
"reinventing-the-wheel"
],
"Title": "Implementation of std::map"
} | 43972 |
<p>I have currently been working on a program for a few days now, and I am just about done. The goal of my program is to ask the user for the amount they still owe on their credit card, and assign an appropriate monthly interest rate. I have commented the code to make it a bit easier to understand, and I believe it is correct for the most part. My only issue is I do not believed I have called my two other methods properly in <code>Main</code>.</p>
<pre><code>import java.util.*;
/**
* Creates an account statement for a client of a credit card company based
* on their input.
*/
public class CSCard {
private static double interestRate;
private static double newBalance;
private static double interest;
public static void main(String[] args) {
Scanner keyboard;
double priorBalance;
double addtlCharges;
double newBalance;
double minPayment;
// initialize needed variables here
keyboard = new Scanner(System.in);
// make sure that the number entered is a double and if so read it in.
// if not, use a default value of zero. No error message to the user.
System.out.print("Type the balance: ");
priorBalance = keyboard.nextDouble();
if (keyboard.hasNextDouble() == true) {
interestRate = 0.0;
} else {
interestRate = 0.02;
}
// make sure that the number entered is a double and if so read it in.
// if not, use a default value of zero. No error message to the user.
System.out.print("\nType the new charge amount: ");
addtlCharges = keyboard.nextDouble();
// perform the calculation of interest, new balance and minimum payment
newBalance = calculateInterest(priorBalance, addtlCharges);
minPayment = calculateMinPayment(newBalance);
// output the resulting statement (DO NOT CHANGE)
System.out.println("\n");
System.out.println("CS CARD International Statement");
System.out.println("===============================");
System.out.printf("Previous balance: $%,8.2f\n", priorBalance);
System.out.printf("Additional charges: $%,8.2f\n", addtlCharges);
System.out.printf("Interest: $%,8.2f\n\n", interest);
System.out.printf("New balance: $%,8.2f\n\n", newBalance);
System.out.printf("Minimum payment: $%,8.2f\n", minPayment);
}
/**
* This method will take in the previous balance and
* additional charges and compute the amount of interest.
* If the priorBalance is 0 or less, the interest is 0.
* If there was a priorBalance, the interest is 2% of the
* priorBalance plus the additional charges.
*
* @param priorBalance balance before the new charges are added
* @param addtlCharges charges added this month
* @return amount of interest to charge
*/
public static double calculateInterest(double priorBalance,
double addtlCharges) {
// first create a stub and get the input and output working
// then replace the stub later on with the calculation
interest = (priorBalance + addtlCharges) * interestRate;
return interest;
}
/**
* This method will take in the previous balance and
* additional charges and compute the minimum payment.
* $0.00 for new balance less than $0
* new balance for new balance between $0 and $49.99 (inclusive)
* $50.00 for new balance between $50 and $300 (inclusive)
* 20% of the new balance for new balance over $300
*
* @param balance after interest and charges are added
* @return minimum payment amount
*/
public static double calculateMinPayment(double balance) {
// first create a stub and get the input and output working
// then replace the stub later on with the calculation
if (newBalance < 0) {
balance = 0;
}
if (newBalance >= 0 && newBalance <= 49.99) {
balance = newBalance;
}
if (newBalance >= 50 && newBalance <= 300) {
balance = 50.0;
}
if (newBalance > 300) {
balance = (newBalance * 0.2) + newBalance;
}
return balance;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T18:28:34.670",
"Id": "76122",
"Score": "0",
"body": "Could you fix your formatting, and only include the code that's related to your issue? (Removing user input and output is a good start.) I'm also not sure what you mean by \"calling them properly\", and how it's related to your post title. Have you tested your code and is it actually behaving in a way you weren't expecting?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T18:30:31.290",
"Id": "76123",
"Score": "0",
"body": "Well, if you have a method that calculates interest, and you're assigning the result into a variable named `balance`, then either you're not calling the methods correctly or you're choosing some really bad names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T18:35:32.810",
"Id": "76124",
"Score": "0",
"body": "move this 2 method (`calculateMinPayment` & `calculateInterest`) in another class, something like `Calculate`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T19:11:50.187",
"Id": "76125",
"Score": "0",
"body": "Method `calculateMinPayment` takes a parameter that it never uses. It is passed `newBalance` by `main` but it refers to the static field `newBalance` directly, and it only uses its parameter `balance` as a local variable in which it calculates its return value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T19:33:01.247",
"Id": "76126",
"Score": "0",
"body": "@Austin You can always flag the question for mod attention to have it migrated, along with the comments and eventual answers that come here."
}
] | [
{
"body": "<p><strong>Watch your scope</strong> - in your class you keep your data in two places - local variables, and static members. I cannot see any thought behind choosing where to put them - you pass some around in your method signatures, but then you use the others in the same methods... The most acute case is in <code>calculateMinPayment</code> where you pass the static member <code>newBalance</code> as a parameter <em>and</em> use it inside the method, while totally ignoring (and overriding) the parameter...</p>\n\n<p>In the use-case above, in the name of encapsulation, I believe the correct way is to <em>only</em> keep the state as local variables, passing the needed data to the stateless helper methods, rather than keeping <em>anything</em> in the static state.</p>\n\n<p><strong>Comments</strong> - I personally think that comments are a <em>code smell</em>. When the code is clean and readable - comments are superfluous. You've got a lot of comments, and some are more confusing than helpful, since you put them in the wrong location:</p>\n\n<blockquote>\n<pre><code>// make sure that the number entered is a double and if so read it in.\n// if not, use a default value of zero. No error message to the user.\nSystem.out.print(\"Type the balance: \");\npriorBalance = keyboard.nextDouble();\n\nif (keyboard.hasNextDouble() == true) {\n interestRate = 0.0;\n} else {\n interestRate = 0.02;\n}\n</code></pre>\n</blockquote>\n\n<p>The above comments should be placed <em>after</em> setting <code>priorBalance</code>, since they describe <code>interestRate</code>... They are more confusing, since the code does not do what the comment say - it sets the <code>interestRate</code> at either <code>0.0</code> or <code>0.02</code>, then totally ignores the given information, and tries to get <code>nextDouble()</code> even if the last statement returned false.</p>\n\n<p>BTW - don't use <code>if (keyboard.hasNextDouble() == true)</code> - <code>if (keyboard.hasNextDouble())</code> does exactly the same, and is more readable.</p>\n\n<blockquote>\n<pre><code>// make sure that the number entered is a double and if so read it in.\n// if not, use a default value of zero. No error message to the user.\nSystem.out.print(\"\\nType the new charge amount: \");\naddtlCharges = keyboard.nextDouble();\n</code></pre>\n</blockquote>\n\n<p>Was that a result of an unfortunate copy+paste? Again - comment is not helpful, only confuses.</p>\n\n<p>I also believe the prompt <code>Type the new charge amount</code> will appear only <em>after</em> the user entered it, since you check <code>hasNextDouble()</code> before you print the prompt.</p>\n\n<blockquote>\n<pre><code>// first create a stub and get the input and output working\n// then replace the stub later on with the calculation\n</code></pre>\n</blockquote>\n\n<p>I don't even begin to understand what this means, and what it has to do with the code it describes... not the second time either...</p>\n\n<p><strong>Naming</strong> - give variables and methods names which imply their role in your code - what does this line do?</p>\n\n<pre><code>newBalance = calculateInterest(priorBalance, addtlCharges);\n</code></pre>\n\n<p>Calculates interest or the new balance?</p>\n\n<p>Also, don't be lazy say - <code>additionalCharges</code> - there are no fines for long names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:41:12.060",
"Id": "43985",
"ParentId": "43978",
"Score": "3"
}
},
{
"body": "<p>Your code doesn't quite work yet, due to some confusion when prompting for the interest rate. It will appear to hang at <code>if (keyboard.hasNextDouble() == true) …</code> since <code>System.in</code> has not reached <kbd>EOF</kbd>, yet the user has not been prompted to enter the interest rate.</p>\n\n<p>Your main problem is confusion regarding the use of variables. In particular, you have a <code>static</code> variable <code>newBalance</code> that is shadowed in <code>main()</code> by a local variable also named <code>newBalance</code>. For now, I recommend keeping things simple: use local variables only. Also, assign values at the same time that you declare variables whenever possible.</p>\n\n<p>You asked about how to return a value from <code>calculateMinPayment()</code>, and indeed there are some problems there. At first glance, since <code>balance</code> is a parameter, you would expect that the result of the function would vary according to the <code>balance</code>. What actually happens is a lot weirder. You are actually using <code>balance</code> as a local variable; instead, the <code>static</code> variable <code>newBalance</code> is the input.</p>\n\n<p>Another problem with <code>calculateMinPayment()</code> is that the cases don't completely cover all of the cases. What if the balance is $49.995? (The added interest could result in such oddball numbers.) You should probably interpret \"between $0 and $49.99 (inclusive)\" to mean \"between $0 (inclusive) and $50 (exclusive)\". Then, chain all the conditions together with if-elseif-elseif-else to make it clear that all cases are covered.</p>\n\n<pre><code>public class CSCard {\n\n public static void main(String[] args) {\n // make sure that the number entered is a double and if so read it in.\n // if not, use a default value of zero. No error message to the user.\n try (Scanner in = new Scanner(System.in)) {\n double priorBalance = promptDouble(in, \"Type the balance: \");\n double interestRate = promptDouble(in, \"Interest rate (e.g., 0.02): \");\n double addtlCharges = promptDouble(in, \"The new charge amount: \");\n\n // perform the calculation of interest, new balance and minimum payment\n double interest = calculateInterest(...);\n double newBalance = priorBalance + interest;\n double minPayment = calculateMinPayment(newBalance);\n\n // output the resulting statement (DO NOT CHANGE)\n System.out.println(\"\\n\");\n System.out.println(\"CS CARD International Statement\");\n System.out.println(\"===============================\");\n System.out.printf(\"Previous balance: $%,8.2f\\n\", priorBalance);\n System.out.printf(\"Additional charges: $%,8.2f\\n\", addtlCharges);\n System.out.printf(\"Interest: $%,8.2f\\n\\n\", interest);\n System.out.printf(\"New balance: $%,8.2f\\n\\n\", newBalance);\n System.out.printf(\"Minimum payment: $%,8.2f\\n\", minPayment);\n }\n }\n\n /**\n * Prompts for a double from <tt>System.in</tt>.\n *\n * @return 0.0 if the input is invalid\n */\n private static double promptDouble(Scanner in, String question) {\n try {\n System.out.print(question);\n System.out.flush();\n return in.nextDouble();\n } catch (InputMismatchException defaultToZero) {\n in.next(); // Consume a token\n System.out.println(\"Invalid input; interpreting it as 0.0.\");\n return 0.0;\n } finally {\n System.out.println();\n }\n }\n\n public static double calculateInterest(...) {\n /* TODO */\n }\n\n /**\n * This method will take in the previous balance and\n * additional charges and compute the minimum payment.\n * $0.00 for new balance less than $0\n * new balance for new balance between $0 and $49.99 (inclusive)\n * $50.00 for new balance between $50 and $300 (inclusive)\n * 20% of the new balance for new balance over $300\n *\n * @param balance after interest and charges are added\n * @return minimum payment amount\n */\n public static double calculateMinPayment(double balance) {\n if (balance < 0) {\n return 0;\n } else if (balance < 50) {\n return balance;\n } else if (balance <= 300) {\n return 50.0;\n } else {\n return 0.2 * balance;\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:52:04.337",
"Id": "43988",
"ParentId": "43978",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T18:25:51.020",
"Id": "43978",
"Score": "3",
"Tags": [
"java",
"finance"
],
"Title": "Assign monthly interest rate based on credit card input"
} | 43978 |
<p>This is a similar question to <a href="https://stackoverflow.com/questions/492716/reversing-a-regular-expression-in-python">this</a>, but I am looking for the set of <strong>all possible values</strong> that will match a regular expression pattern.</p>
<p>To avoid an infinite set of possible values, I am willing to restrict the regular expression pattern to a subset of the regular expression language.</p>
<p>Here's the approach I took (Python code):</p>
<pre><code>def generate_possible_strings(pattern):
'''
input: 'K0[2468]'
output: ['K02', 'K04', 'K06', 'K08']
generates a list of possible strings that would match pattern
ie, any value X such that re.search(pattern, X) is a match
'''
query = re.compile(pattern, re.IGNORECASE)
fill_in = string.uppercase + string.digits + '_'
# Build a re for a language subset that is supported by reverse_search
bracket = r'\[[^\]]*\]' #finds [A-Z], [0-5], [02468]
symbol = r'\\.' #finds \w, \d
expression = '|'.join((bracket,symbol)) #search query
tokens = re.split(expression, pattern)
for c in product(fill_in, repeat=len(tokens)-1):
candidate = ''.join(roundrobin(tokens, c)) #roundrobin recipe from itertools documentation
if query.match(candidate):
yield candidate
</code></pre>
<p>Supported subset of regular expressions language</p>
<ul>
<li>Supports <code>[]</code> set of characters (<code>[A-Z]</code>, <code>[0-5]</code>, etc)</li>
<li>Supports escaped special characters (<code>\w</code>, <code>\d</code>, <code>\D</code>, etc)</li>
</ul>
<p>Basically what this does is locate all parts of a regular expression that could match a single character (<code>[A-Z]</code> or <code>[0-5]</code> or <code>[02468]</code> or <code>\w</code> or <code>\d</code>), then for all of the valid replacement characters <code>A-Z0-9_</code> test to see if the replacement matches the regular expression.</p>
<p>This algorithm is slow for regular expressions with many fields or if <code>fill_in</code> is not restricted to just <code>A-Z0-9_</code>, but at least it guarantees finding every possible string that will match a regular expression in finite time (if the solution set is finite).</p>
<p>Is there a faster approach to solving this problem, or an approach that supports a larger percentage of the standard regular expression language?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:08:15.107",
"Id": "76129",
"Score": "1",
"body": "Are you looking to exhaustively test all possible inputs to this regex? That could get quickly out of hand, and some regex's could literally have an infinite number of possible inputs (you'll run out of memory or time before you test them all). How about some representative sample that covers all the things you want to test? It might even be possible to automatically generate such coverage (your intent, I believe)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:10:23.503",
"Id": "76130",
"Score": "0",
"body": "In line with comment from @PhilPerry - if your regex uses any \"closure\" type operations (e.g. `+` meaning one-or-more or `*` for zero-or-more), the set of possible matches will not be finite."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:12:48.077",
"Id": "76131",
"Score": "0",
"body": "Using a generator function, itertools.product, and itertools.roundrobin resolves the infinite memory problem, but you're right that this could require infinite time. I have do not need to support closure operators `*` or `+`. @PhilPerry I need the full solution set. A sample will not satisfy the problem I am solving."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:21:27.923",
"Id": "76132",
"Score": "0",
"body": "This is quite a challenge. Even short regexes with no closure operations can produce more strings than you could possibly store. For instance, \"\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\" matches a trillion different strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T06:48:35.267",
"Id": "76202",
"Score": "1",
"body": "Why do you call `query.match(candidate)`? Does your algorithm generate candidates that don't match?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:44:44.903",
"Id": "76292",
"Score": "0",
"body": "@JanneKarila The algorithm tries replacing each `[]`, `\\w`, or `\\d` with the possible fill_in characters `A-Z0-9_`. Only candidates that match are yielded by the generator function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T02:17:55.393",
"Id": "134276",
"Score": "0",
"body": "I've rolled back Rev 3 → 2. Please post your update as an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T19:02:10.317",
"Id": "141405",
"Score": "0",
"body": "[sre_yield](https://github.com/google/sre_yield/) is a well-written Python library that supports a larger set of the regular expression language and is probably faster/better in every way. `sre_yield` solves the same problem: given a regular expressions pattern, return a list of all possible strings that match the regular expression."
}
] | [
{
"body": "<p>A major inefficiency in your solution is that you try every <code>fill_in</code> character as a replacement for any character class in the pattern. Instead, you could use the character class to select matching characters from <code>fill_in</code> and only loop over those. </p>\n\n<pre><code>>>> pattern = 'K0[2468]'\n>>> re.findall(expression, pattern)\n['[2468]']\n>>> re.findall('[2468]', fill_in)\n['2', '4', '6', '8']\n</code></pre>\n\n<p>For a more complete existing solution, you may want to look into these:</p>\n\n<ul>\n<li><a href=\"http://qntm.org/lego\" rel=\"nofollow\">Regular expression parsing in Python</a></li>\n<li>invRegex.py in <a href=\"http://pyparsing.wikispaces.com/Examples\" rel=\"nofollow\">Pyparsing examples</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T16:05:50.130",
"Id": "76503",
"Score": "0",
"body": "Thank you! This helps a lot, particularly for cases like '\\d\\d\\d', where only 1000 of 50653 candidates are matches (given fill_in is [A-Z0-9_])"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T07:33:20.617",
"Id": "44129",
"ParentId": "43981",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:32:16.360",
"Id": "43981",
"Score": "3",
"Tags": [
"python",
"performance",
"regex"
],
"Title": "All possible values that will match a regular expression"
} | 43981 |
<p>I was wondering if anyone had some general clean up advice on my code. I believe that more helper functions would be my case but I could be wrong. 30 lines maximum per method is my rule. I can't seem to figure out how to clean this up more, though. </p>
<p><strong>Sample Input:</strong></p>
<p>(1/3) (1/5) - (40/1) * #</p>
<p>(2/3) B * #</p>
<p><strong>Sample Output</strong></p>
<blockquote>
<p>Expression 1 is: (1/3)(1/5)-(40/1)*</p>
<p>The value is: (16/3)</p>
<p>Intermediate results: (2/15)(16/3)</p>
<p>Expression 2 is: (2/3)B</p>
<p>Invalid Expression</p>
<p>Intermediate results:</p>
</blockquote>
<pre><code>import java.util.Scanner;
public class RpnEvaluator
{
private final int MAX_TOKEN = 100;
private Scanner stdin = new Scanner(System.in);
private Queue myQueue = new Queue(MAX_TOKEN);
private Stack myStack = new Stack(MAX_TOKEN);
public void run() throws java.io.IOException
{
int count = 1;
Fraction myInterMid;
while(stdin.hasNext())
{
runOnce(count++);
System.out.print("Intermediate results: ");
while(!myQueue.isEmpty())
{
myInterMid = (Fraction)myQueue.remove();
System.out.print(myInterMid.toString());
}
System.out.println();
clear(myStack, myQueue);
}
System.out.println("Normal Termination of Program 3.");
}
private boolean isOperator(String input)
{
String[] oprtr = {"+", "-", "*"};
for(String choice: oprtr)
if(choice.equals(input))
return true;
return false;
}
private boolean isOperand(String input)
{
if(input.charAt(0) == '(')
return true;
return false;
}
private Fraction runOperation(String choice, Fraction op2, Fraction op1)
{
Fraction newFract = new Fraction();
switch (choice)
{
case "*":
newFract = new Fraction(op1.times(op2));
break;
case "+":
newFract = new Fraction(op1.plus(op2));
break;
case "-":
newFract = new Fraction(op1.minus(op2));
break;
}
return newFract;
}
private void runOnce(int count)
{
Fraction op1 = null;
Fraction op2 = null;
clear(myStack, myQueue);
System.out.print("Expression " + count++ + " is: ");
doTypeCheck(op1, op2);
}
private void clear(Stack myStack, Queue myQueue)
{
myStack.clear();
myQueue.clear();
}
private void runTheOperator(Fraction op2, Fraction op1,
String readIn)
{
op1 = (Fraction)myStack.pop();
Fraction interMed = runOperation(readIn, op2, op1);
myStack.push(interMed);
myQueue.add(interMed);
}
private void doTypeCheck(Fraction op1, Fraction op2)
{
Fraction answer = null;
String readIn = "";
boolean valid = true;
readIn = stdin.next();
while(!readIn.equals("#") && valid == true)
{
if(!isOperator(readIn) && isOperand(readIn))
{
processOperand(readIn);
readIn = stdin.next();
}
else if(isOperator(readIn))
{
System.out.print(readIn);
if(myStack.isEmpty())
valid = false;
else
op2 = (Fraction)myStack.pop();
if(myStack.isEmpty())
{
valid = false;
throwLine(readIn);
}
else
{
runTheOperator(op2, op1, readIn);
readIn = stdin.next();
}
}
else
{
System.out.print(readIn);
valid = false;
throwLine(readIn);
}
}
System.out.println();
if(myStack.isEmpty())
valid = false;
else
answer = (Fraction)myStack.pop();
if(!myStack.isEmpty())
valid = false;
checkMessageValid(valid, answer);
}
private void checkMessageValid(boolean valid, Fraction answer)
{
if(valid == false)
System.out.println("Invalid Expression");
else
System.out.println("The value is: " + answer.toString());
}
private void throwLine(String line)
{
while(!line.equals("#"))
{
line = stdin.next();
}
}
private void processOperand(String readIn)
{
Fraction stringFract = null;
Fraction myFract = null;
stringFract = new Fraction(readIn);
System.out.print(stringFract.toString());
myFract = new Fraction(readIn);
myStack.push(myFract);
}
}
</code></pre>
| [] | [
{
"body": "<p>Reverse Polish Notation does not need parentheses, so that should actually be invalid input and should not be checked.</p>\n\n<p>To determine if something is an operand you should be able to use <code>stdin.hasNextInt()</code>. If that is false, then you should be able to use <code>stdin.next()</code> to get whatever the operator is. This could greatly simplify your type checking.</p>\n\n<p>Instead of terminating input with <code>#</code> you should just check for newlines.</p>\n\n<p>I'm not sure what the purpose of having <code>myQueue</code> is. You should only need a stack for processing RPN.</p>\n\n<p>I would recommend reading up on RPN to understand it more (the <a href=\"http://en.wikipedia.org/wiki/Reverse_Polish_notation\">Wikipedia</a> page has an algorithm for interpreting RPN) and see if that gives you ideas on how you might rethink your approach.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Assuming that the input format and output values are requirements, there are several things you can do to improve the code.</p>\n\n<ul>\n<li><code>MAX_TOKEN</code> should be <code>private static final</code>.</li>\n<li>You should rename your methods to better describe what they do. <code>runOnce()</code> is called in a loop, so it is not called once, and it doesn't explain what it does. I would recommend something like <code>processNextCalculation()</code>. <code>doTypeCheck()</code>, <code>throwLine()</code> and <code>checkMessageValid()</code> should also be renamed.</li>\n<li>You should move the output in <code>checkMessageValid()</code> to be in the same place as where you output the intermediate results. You will need to change some return values to propagate the results upward.</li>\n<li><code>isOperand()</code> can be reduced to <code>return input.charAt(0) == '(';</code></li>\n<li>In <code>run()</code> you don't use <code>myInterMid</code> elsewhere so you can remove references to it and simply <code>System.out.println(myQueue.remove());</code></li>\n<li>You should try to be consistent about using <code>my</code> as a prefix. Typically, it implies that the variable is an instance member variable, but you also use it for variables within methods. That is definitely confusing.</li>\n<li>I don't know what is in your <code>Fraction</code> class, but I imagine that the <code>times()</code>, <code>plus()</code>, and <code>minus()</code> methods are returning <code>Fraction</code>s, so you don't need to <code>new</code> one up from the result.</li>\n<li>You don't need to declare <code>op1</code> and <code>op2</code> in <code>runOnce()</code>, since you can just pass two nulls to <code>doTypeCheck()</code>. For that matter, you don't need to even have parameters for <code>doTypeCheck()</code>. Once you've done that, you should bring the rest of the method up to <code>run()</code> so you can keep your text output in the same place.</li>\n<li>Since you can't have both <code>isOperator()</code> and <code>isOperand()</code> be true, you don't need to check both in your first if condition in <code>doTypeCheck()</code>.</li>\n<li>You don't need to check <code>myStack.isEmpty()</code> twice, you should be able to check if <code>myStack.size()</code> is less than two. If your implementation of <code>Stack</code> doesn't have a <code>size()</code> method, well...I feel bad for you.</li>\n<li>Whenever <code>myStack.isEmpty()</code> is true, you can break out of the loop and your failure case will still show correctly.</li>\n<li>You only need one <code>Fraction</code> in <code>processOperand()</code> and you can initialize it on the same line as you declare it.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:53:47.313",
"Id": "76155",
"Score": "0",
"body": "Everything that I have is exactly how I need it to be. I'm looking for splitting up the lines of code into smaller methods and such. I've done an RPN with numbers, this one is with objects and Fraction objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:19:10.340",
"Id": "76160",
"Score": "0",
"body": "Queue is used for holding intermediate results **"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:41:19.217",
"Id": "76163",
"Score": "1",
"body": "What do you need the intermediate results for? Is it part of your requirement or just for debugging? Is the format of your input required to have parentheses around your fractions and # to mark the end of input?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T00:54:21.713",
"Id": "76175",
"Score": "0",
"body": "Yes all requirements. Its an ungraded project."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:39:53.810",
"Id": "43998",
"ParentId": "43984",
"Score": "8"
}
},
{
"body": "<p>Don't add more helper methods. The problem isn't that you need to split up your existing methods. Rather, it's that your existing helper methods aren't meaningful or elegant. For example, what does <code>runOperation()</code> do? How about <code>runTheOperator()</code>? Why do both methods exist, and why do they accept arguments in different orders? <a href=\"https://codereview.stackexchange.com/a/44028/9357\">What does <code>doTypeCheck()</code> do</a>, and why do you pass it two <code>null</code> arguments?</p>\n\n<p>Taking a big picture view… the beauty of Reverse Polish calculators is that they should be very simple to implement. Your code does not feel simple. Some of the complications are:</p>\n\n<ol>\n<li>You're implementing an RPN calculator that operates on rationals rather than integers. I can accept that, but you should recognize that the syntax/grammar is no longer pure and easy to parse.</li>\n<li>An RPN calculator normally needs just one data structure: a stack. You've introduced a queue to log the intermediate results, which complicates the code.</li>\n<li>You shouldn't feed the operands to an RPN operator; an RPN operator can work directly on the stack. A typical operator would pop two items and push one result, but other kinds of operators could exist as well. For example,\n\n<ul>\n<li>A <em>negate</em> operator would flip the sign of the top element</li>\n<li>A <em>clear</em> operator would remove everything from the stack</li>\n<li>A <em>swap</em> operator would pop the top two elements from the stack and push them back in reverse order</li>\n</ul></li>\n</ol>\n\n<p>My suggested remedies are:</p>\n\n<ol>\n<li>Implement an RPN calculator for integers first. Then, if you want to add support for fractions, do so by hacking the <code>Scanner</code>, not the core of your calculator. You should have to change little in the calculator itself other than a few data types and names of method calls.</li>\n<li>I recommend dropping the intermediate display feature. A typical RPN calculator would display either the top of the stack or the entire stack at every prompt. If the user wanted to see intermediate results, he/she could simply split up the input over several lines.</li>\n<li><p>Define a class for operators. A reasonable framework might be</p>\n\n<pre><code>public abstract class RpnOperator {\n private static final HashMap<String, RpnOperator> ALL = new HashMap<String, RpnOperator>();\n\n public final String symbol;\n\n public RpnOperator(String symbol) {\n this.symbol = symbol;\n ALL.put(symbol, this);\n }\n\n public static RpnOperator forSymbol(String symbol) {\n return ALL.get(symbol);\n }\n\n public abstract void operate(Stack<Fraction> calcStack) throws RpnException;\n}\n</code></pre>\n\n<p>Then, in the calculator, you could define</p>\n\n<pre><code>private static RpnOperator ADD = new RpnOperator(\"+\") {\n public void operate(Stack<Fraction> calcStack) {\n Fraction a = calcStack.pop();\n Fraction b = calcStack.pop();\n calcStack.push(a.plus(b));\n }\n};\n</code></pre></li>\n</ol>\n\n<p>You didn't post your <code>Fraction</code> class, but I suspect that there are problems there too. For example, you call <code>new Fraction(op1.plus(op2))</code> — why is <code>op1.plus(op2)</code> insufficient, such that you need to copy-construct that result into another <code>Fraction</code> object?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:37:53.780",
"Id": "44026",
"ParentId": "43984",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "43998",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:37:54.453",
"Id": "43984",
"Score": "7",
"Tags": [
"java",
"beginner",
"math-expression-eval",
"rational-numbers"
],
"Title": "Cleaning up Reverse Polish Notation evaluator"
} | 43984 |
<p>It might be easier to read the explanation of what I was trying to do, and implement it a completely different way, rather than go through the code. But the code does what I want it to do, just nowhere near any measurable efficiency.</p>
<p>This started off as an assignment that I got finished, but I know there has to be a decent amount of better ways to make this code work</p>
<p>The goal of this code is to take a matrices of 1's and 0's, and go through and any nodes (that are 1's) that are connected to the left, right, up, or down (no diagonals), to change to different numbers. Each group, the number goes up by one.</p>
<p>For example:</p>
<pre><code>1 1 0 0 1 1 1
1 0 0 0 0 0 0
1 1 1 0 1 0 1
1 0 0 0 1 1 1
1 0 1 0 1 1 1
1 1 0 0 0 0 0
1 0 0 0 0 1 1
</code></pre>
<p>would become:</p>
<pre><code>2 2 0 0 3 3 3
2 0 0 0 0 0 0
2 2 2 0 4 0 4
2 0 0 0 4 4 4
2 0 5 0 4 4 4
2 2 0 0 0 0 0
2 0 0 0 0 6 6
</code></pre>
<p>Here is my semi-verbal explanation of what the code does:</p>
<p>What my current code does, is works through this in 2 phases. First it goes through and finds the first 1, and changes it to 2, and changes every number to the left and right of that (assuming they are 1's) to 2's. And continues to work its way through.</p>
<p>After that, it goes through again, and finds every 2, and changes each number to the left, right, and down from that 2, to a 2 also (if it's not 0). And repeats that until it finds no more numbers connected to a 2. Then increments, and does that to 3's, and so on. </p>
<p>I know there has to be a simple way to do this recursively, and I've tried, but it's been a pretty big failure for me. Any help or insight would be greatly appreciated.</p>
<pre><code>package imagegrouping;
public class ImageGrouping {
public static void main(String[] args) {
int [][] originalMap = new int[][]{
{1, 1, 0, 0, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0},
{1, 1, 1, 0, 1, 0, 1},
{1, 0, 0, 0, 1, 1, 1},
{1, 0, 1, 0, 1, 1, 1},
{1, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 1}
};
int currentNumber = 2;
//loop for rows
for(int i = 0; i < 7; i++)
{
//loop for columns
for(int j = 0; j < 7; j++)
{
if(originalMap[i][j] == 1)
{
originalMap[i][j] = currentNumber;
//check each number to right, if 1, make currentNumber
for(int k = j+1; k < 7; k++)
{
if(originalMap[i][k] == 1)
{
originalMap[i][k] = currentNumber;
}
else{break;}
}//end checking right
//check each number below, if 1, make currentNumber
for(int l = i+1; l < 7; l++)
{
if(originalMap[l][j] == 1)
{
originalMap[l][j] = currentNumber;
}
else{break;}
}//end checking below
currentNumber++;
}
}//close loop for columns
}//close loop for rows
int changedNumber = 0;
//int tempNumber = 2;
for(int tempNumber = 2; tempNumber < 20; tempNumber++)
{
//start loop for rows
for(int i = 0; i < 7; i++)
{
//start loop for columns
for(int j = 0; j < 7; j++)
{
//find all tempNumbers, and check all around them to see if they have an adjacent node that should be the same number as them.
if(originalMap[i][j] == tempNumber)
{
//if node is at top left corner, only check down and right to stay in bounds
if(i == 0 && j == 0)
{
//check down
checkDown(originalMap, i, j, changedNumber, tempNumber);
//check right
checkRight(originalMap, i, j, changedNumber, tempNumber);
}
//else if node is in bottom left corner, only check up and right, to stay in bounds
else if(i == 6 && j == 0)
{
//check up
checkUp(originalMap, i, j, changedNumber, tempNumber);
//check right
checkRight(originalMap, i, j, changedNumber, tempNumber);
}
//else if node is in bottom right corner, only check up and left, to stay in bounds
else if(i == 6 && j == 6)
{
//check up
checkUp(originalMap, i, j, changedNumber, tempNumber);
//check left
checkLeft(originalMap, i, j, changedNumber, tempNumber);
tempNumber++;
}
//else if node is in top right corner only check left and bottom to stay in bounds
else if(i == 0 && j == 6)
{
//check down
checkDown(originalMap, i, j, changedNumber, tempNumber);
//check left
checkLeft(originalMap, i, j, changedNumber, tempNumber);
}
//else if any other case of node being on top row, don't check up, to stay in bounds
else if(i == 0)
{
//might not need since first step goes through all downs.
//check down
checkDown(originalMap, i, j, changedNumber, tempNumber);
//left
checkLeft(originalMap, i, j, changedNumber, tempNumber);
//check right
checkRight(originalMap, i, j, changedNumber, tempNumber);
}
//else if node is on left line, don't check left, to stay in bounds
else if(j == 0)
{
//check right
checkRight(originalMap, i, j, changedNumber, tempNumber);
//check up
checkUp(originalMap, i, j, changedNumber, tempNumber);
//check down
checkDown(originalMap, i, j, changedNumber, tempNumber);
}
//else if any node is on the right column, don't check right to stay in bounds
else if(j == 6)
{
//check up
checkUp(originalMap, i, j, changedNumber, tempNumber);
//check down
checkDown(originalMap, i, j, changedNumber, tempNumber);
//check left
checkLeft(originalMap, i, j, changedNumber, tempNumber);
}
//else if any node is on bottom row, don't check down, to stay in bounds
else if(i == 6)
{
//check up
checkUp(originalMap, i, j, changedNumber, tempNumber);
//check left
checkLeft(originalMap, i, j, changedNumber, tempNumber);
//check right
checkRight(originalMap, i, j, changedNumber, tempNumber);
}
//any other cases, check up down left right.
else
{
//check up
checkUp(originalMap, i, j, changedNumber, tempNumber);
//down,
checkDown(originalMap, i, j, changedNumber, tempNumber);
//check left,
checkLeft(originalMap, i, j, changedNumber, tempNumber);
//check right
checkRight(originalMap, i, j, changedNumber, tempNumber);
}
}
}//end loop for columns
}//end loop for rows
}
int finalSort = 2;
int numberCheck = 0;
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 7; j++)
{
if(originalMap[i][j] > finalSort && originalMap[i][j] != 0)
{
numberCheck = originalMap[i][j];
for(int x = 0; x < 7; x++)
{
for(int y = 0; y < 7; y++)
{
if(originalMap[x][y] == numberCheck)
{
originalMap[x][y] = finalSort + 1;
}
}
}finalSort++;
}
}
}
//print array
printArray(originalMap);
}
//check right method
public static void checkRight(int[][] originalMap, int i, int j, int changedNumber, int tempNumber)
{
if(originalMap[i][j+1] != tempNumber && originalMap[i][j+1] != 0)
{
//if the number below tempNumber == something besides tempNumber or 0, use changedNumber
changedNumber = originalMap[i][j+1];
//now find all changedNumbers, and change them to tempNumber
for(int x = 0; x < 7; x++)
{
for(int y = 0; y < 7; y++)
{
if(originalMap[x][y] == changedNumber)
{
originalMap[x][y] = tempNumber;
}
}
}
}
}
//check left method
public static void checkLeft(int[][] originalMap, int i , int j, int changedNumber, int tempNumber)
{
if(originalMap[i][j-1] != tempNumber && originalMap[i][j-1] != 0)
{
//if the number below tempNumber == something besides tempNumber or 0, use changedNumber
changedNumber = originalMap[i][j-1];
//now find all changedNumbers, and change them to tempNumber
for(int x = 0; x < 7; x++)
{
for(int y = 0; y < 7; y++)
{
if(originalMap[x][y] == changedNumber)
{
originalMap[x][y] = tempNumber;
}
}
}
}
}
//Check up method
public static void checkUp(int[][] originalMap, int i , int j, int changedNumber, int tempNumber)
{
if(originalMap[i-1][j] != tempNumber && originalMap[i-1][j] != 0)
{
//if the number below tempNumber == something besides tempNumber or 0, use changedNumber
changedNumber = originalMap[i-1][j];
//now find all changedNumbers, and change them to tempNumber
for(int x = 0; x < 7; x++)
{
for(int y = 0; y < 7; y++)
{
if(originalMap[x][y] == changedNumber)
{
originalMap[x][y] = tempNumber;
}
}
}
}
}
public static void checkDown(int[][] originalMap, int i , int j, int changedNumber, int tempNumber)
{
if(originalMap[i+1][j] != tempNumber && originalMap[i+1][j] != 0)
{
//if the number below tempNumber == something besides tempNumber or 0, use changedNumber
changedNumber = originalMap[i+1][j];
//now find all changedNumbers, and change them to tempNumber
for(int x = 0; x < 7; x++)
{
for(int y = 0; y < 7; y++)
{
if(originalMap[x][y] == changedNumber)
{
originalMap[x][y] = tempNumber;
}
}
}
}
}
//method to print array
public static void printArray(int[][] myArray) {
for(int x = 0; x < 7; x++)
{
for(int y = 0; y < 7; y++)
{
System.out.print(myArray[x][y]);
System.out.print(" ");
}
System.out.print("\n");
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Use the power of data structures...</p>\n<p><img src=\"https://i.stack.imgur.com/NS5oG.png\" alt=\"Data Structure Power\" /></p>\n<h3>Step one</h3>\n<p>You create a two different data structures consisting of pure indexes of your original matrix. On the first you create Objects that contain "pointers" (in your case references) to the top, left, right, and bottom elements.</p>\n<h3>Step two</h3>\n<p>Create a list of indexes of the elements that are not Zero every time the matrix changes. These indexes are also references.</p>\n<h3>Step three</h3>\n<p>The algorithm will change, here is some pseudocode</p>\n<pre><code>for(elements in idx_of_not_zero)\n{\n if(1){ change_adjacent(+1);\n}\n</code></pre>\n<p>In change adjacent you place the logic regarding the "if its two then don't change".</p>\n<p>This will take more memory, but it will be faster.</p>\n<p>Such is the tradeoff between memory and performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T00:44:16.303",
"Id": "76173",
"Score": "0",
"body": "As you can probably tell from the question, I'm a bit of a novice. I will try to implement this into code, and then ask further questions. But if anybody else has any ideas, feel free to throw them out there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T01:28:41.637",
"Id": "76180",
"Score": "3",
"body": "It doesn't matter that you are a novice, you got an implementation going, that's an awesome step in the right direction. Data Structures are breadth and butter and getting into that subject too soon may harm your productivity. The fact that you are trying speaks wonders of what you are doing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T23:25:31.053",
"Id": "44013",
"ParentId": "43987",
"Score": "3"
}
},
{
"body": "<p>I think your solution, and also the one proposed by Claudiordgz, are overkill.</p>\n\n<p>You mentioned recursion in your question, and, recursion is the 'simple' solution to this problem.</p>\n\n<p><strong>problem description:</strong></p>\n\n<blockquote>\n <p>The goal of this code is to take a matrices of 1's and 0's, and go through and any nodes (that are 1's) that are connected to the left, right, up, or down (no diagonals), to change to different numbers. Each group, the number goes up by one</p>\n</blockquote>\n\n<p>You can narrow this problem down in to four stages:</p>\n\n<ol>\n<li>Set up a 'region counter', starting at 2</li>\n<li>Scan the matrix for a 1</li>\n<li>When you find a 1, recursively join it to all of it's 1-value neighbours, setting them all to the region-counter. You only need to look at 1-value'd neighbours.</li>\n<li>When you have completed the recursive join, increment the region-counter, and continue scanning for 1's.</li>\n</ol>\n\n<p>You do have a problem in your code that you have <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\">the 'magic-number'</a> 7 embedded in your code. I have copied/pasted your code, and I have left the magic values in the <code>printArray()</code> method. Compare that with the other methods, and see how it can be done...</p>\n\n<p>I have also split your main method in to different methods, so the logic is more discrete.</p>\n\n<p>When you put it all together with a recursive method that 'handles' the out-of-bounds cases, it all looks pretty simple:</p>\n\n<pre><code>public class ImageGrouping {\n\n public static void main(String[] args) {\n int[][] originalMap = new int[][] {\n { 1, 1, 0, 0, 1, 1, 1 },\n { 1, 0, 0, 0, 0, 0, 0 },\n { 1, 1, 1, 0, 1, 0, 1 },\n { 1, 0, 0, 0, 1, 1, 1 },\n { 1, 0, 1, 0, 1, 1, 1 },\n { 1, 1, 0, 0, 0, 0, 0 },\n { 1, 0, 0, 0, 0, 1, 1 } };\n\n findGroups(originalMap);\n printArray(originalMap);\n\n }\n\n\n public static final void findGroups(int[][] map) {\n // step 1, set up the region count\n int regioncount = 2;\n // step 2, scan all cells of the map, looking for '1' values.\n for (int row = 0; row < map.length; row++) {\n for (int col = 0; col < map[row].length; col++) {\n if (map[row][col] == 1) {\n // step 3, recursively join 1-value cells.\n joinGroup(map, row, col, regioncount);\n // step 4, increment region count\n regioncount++;\n }\n }\n }\n }\n\n private static void joinGroup(int[][] map, int row, int col, int regioncount) {\n // expect the recursive calls to generate invalid co-ordinates.\n // ignore anything invalid.\n if (row < 0 || row >= map.length) {\n // illegal row.\n return;\n }\n if (col < 0 || col >= map[row].length) {\n // illegal col.\n return;\n }\n if (map[row][col] != 1) {\n // only join 1-value cells.\n return;\n }\n // set the group number.\n map[row][col] = regioncount;\n // check the neighbours...\n joinGroup(map, row - 1, col, regioncount);\n joinGroup(map, row + 1, col, regioncount);\n joinGroup(map, row, col - 1, regioncount);\n joinGroup(map, row, col + 1, regioncount);\n }\n\n // method to print array\n public static void printArray(int[][] myArray) {\n for (int x = 0; x < 7; x++) {\n for (int y = 0; y < 7; y++) {\n System.out.print(myArray[x][y]);\n System.out.print(\" \");\n }\n System.out.print(\"\\n\");\n }\n\n }\n}\n</code></pre>\n\n<p>In the recursive method, note how it expects there to be invalid values. This is a recursive technique that makes it the responsibility of the recursion to check it's bounds. The alternative is to check the bounds each time <em>before</em> you call the next recursive level. By doing it the way I suggest you can reduce the amount of code you write, but at the small expense of recursing one level more than you need to.</p>\n\n<p>The output from the above code, when I run it, is:</p>\n\n<blockquote>\n<pre><code>2 2 0 0 3 3 3 \n2 0 0 0 0 0 0 \n2 2 2 0 4 0 4 \n2 0 0 0 4 4 4 \n2 0 5 0 4 4 4 \n2 2 0 0 0 0 0 \n2 0 0 0 0 6 6\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T05:25:23.003",
"Id": "76199",
"Score": "0",
"body": "Oh so sorry! I meant to comment on the question. That's what I get for commenting on my phone. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T07:37:52.683",
"Id": "76207",
"Score": "0",
"body": "That's basically the solution I came up with. I suggest renaming `joinGroup()` to [`floodFill()`](http://en.wikipedia.org/wiki/Flood_fill#Stack-based_recursive_implementation_.28Four-way.29)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:37:53.807",
"Id": "76327",
"Score": "2",
"body": "Beautiful, thanks for the help. I can't wait till coding that clearly and effectively comes more easily. I've read through it, and it all makes perfect sense. I have some practising to do."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T02:50:47.170",
"Id": "44022",
"ParentId": "43987",
"Score": "8"
}
},
{
"body": "<p>You can use a fairly simple algorithm for two-pass <a href=\"http://en.wikipedia.org/wiki/Connected-component_labeling\" rel=\"nofollow\" title=\"Connected component labeling\">Connected component labeling</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:25:58.837",
"Id": "44103",
"ParentId": "43987",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44022",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T20:44:43.077",
"Id": "43987",
"Score": "5",
"Tags": [
"java",
"matrix",
"image"
],
"Title": "Image-grouping using bit matrices"
} | 43987 |
<p>What troubles me are the empty <code>/**/</code> brackets. Is there a cleaner way of handling this logic?</p>
<pre><code>if (opcode == OP_0) { /* continue */}
else if (opcode == OP_1NEGATE) { /* continue */}
else if (opcode >= OP_1 && opcode <= OP_16) { /* continue */}
else { throw new Exception("decodeFromOpN called on non OP_N opcode"); }
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:37:55.270",
"Id": "76444",
"Score": "7",
"body": "I see that most answers copy the indentation from the question. I would expect the `else if` chain to align with the initial `if`. When I see an indented `else` I tend to start looking for an `if` at the same level. In general, indent only once within a control structure, but keep the control structure *keywords* at the level where it starts."
}
] | [
{
"body": "<p>I don't like the empty blocks after the <code>if</code> statements. Its very confusing, and clutters up your code.</p>\n\n<p>I also don't like that you are throwing a general <code>Exception</code>. Create one and throw that exception instead.</p>\n\n<pre><code>public class InvalidOpCodeException : Exception\n{\n private int OpCode { get; private set; }\n\n public InvalidOpCodeException(int opCode)\n : base(string.Format(\"OpCode supplied is invalid {0}.\", opCode)\n {\n OpCode = opCode;\n }\n\n}\n</code></pre>\n\n<p>I would change it to just look for the error case</p>\n\n<pre><code>if (opcode != OP_0\n && opcode != OP_1NEGATE\n && (opcode < OP_1 || opcode > OP_16))\n{\n throw new InvalidOpCodeException(opcode);\n}\n\n// Rest of the code here\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:18:51.067",
"Id": "43993",
"ParentId": "43991",
"Score": "12"
}
},
{
"body": "<p>The <code>else</code> branch can only be executed if all the other conditions are false:</p>\n\n<pre><code>if (opcode != OP_0\n && opcode != OP_1NEGATE\n && (opcode < OP_1 || opcode > OP_16))\n{\n throw ...;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:19:41.127",
"Id": "43994",
"ParentId": "43991",
"Score": "13"
}
},
{
"body": "<p>I'm going to assume that <code>OP_0</code>...<code>OP_16</code> are contiguous and that <code>OP_0</code> is the smallest possible value. In that case, it's trivial to collapse the conditions together:</p>\n\n<pre><code>if (opcode > OP_16 && opcode != OP_1NEGATE)\n throw new Exception(\"decodeFromOpN called on non OP_N opcode\");\n</code></pre>\n\n<p>If, however, <code>OP_0</code> may not be contiguous with <code>OP_1</code> or values less than OP_0 are possible, that could fail.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:25:23.290",
"Id": "43996",
"ParentId": "43991",
"Score": "7"
}
},
{
"body": "<p>What you could use is a function that returns whether an opcode is valid.</p>\n\n<pre><code>private boolean isOpCode(Object opCode){\n return opcode == OP_0 || opcode == OP_1NEGATE || (opcode >= OP_1 && opcode <= OP_16);\n}\n</code></pre>\n\n<p>Then in your code you posted, call the function, and throw an exception if it returns false.</p>\n\n<pre><code>if(!isOpCode(opCode)){\n throw new OpCodeInvalidException(\"decodeFromOpN called on non OP_N opcode\");\n}\n</code></pre>\n\n<p>Replace <code>Object</code> with whatever the opcodes are.</p>\n\n<p>And make a new class that extends from <code>Exception</code>. It's generally bad practice to throw <code>Exception</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T04:59:11.693",
"Id": "76196",
"Score": "25",
"body": "The conditional OR operator (`||`) should be used instead of the bit-wise logical OR operator (`|`). Semantically it is closer to the meaning, and it can be short-circuited to avoid having to evaluate the entire expression."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T02:43:09.900",
"Id": "76399",
"Score": "1",
"body": "I see a lot of redundancy here. Why check through each opcode to see if such one exists, only to cycle through again looking for the action it performs? Switching just seems much simpler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T20:08:57.860",
"Id": "76570",
"Score": "0",
"body": "@Liamdev631, I agree with your idea, to make a switch statement for all of the opcodes, then go from there. **However**, he asked for a cleaner way of handling the logic. Also, if `OP_???` are integers, then calling `isOpCode` runs relatively quickly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:31:27.507",
"Id": "43997",
"ParentId": "43991",
"Score": "41"
}
},
{
"body": "<p>If you separated the three cases because the opcode values/ranges mean different things, and you chose the same action (accept/skip) for different reasons, I think your style is fine. A comment describing the meaning of each case is useful for the next person to read the code:</p>\n\n<pre><code>if (opcode == OP_0) { /* OP_0 (zero) is a no-op, ok */}\n else if (opcode == OP_1NEGATE) { /* flip register value */}\n else if (opcode >= OP_1 && opcode <= OP_16) { /* known allocated opcodes */}\n else { throw new Exception(\"decodeFromOpN called on non OP_N opcode\"); }\n</code></pre>\n\n<p>This way it's clearer that the cases had different meanings when you wrote it. As the code evolves, future maintainers can add/break out/consolidate cases as their meaning changes, and/or add debugging information or change actions for the individual cases if necessary.</p>\n\n<p>However, per others' answers, if the cases have roughly the same meaning in the local context of this code, consolidating the conditions makes sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:40:12.933",
"Id": "76355",
"Score": "2",
"body": "This sort of design may be particularly good if the same sequence of tests is done in several methods, and each case has a semantic meaning [possibly explicit no-op]. For example, if the code selects a sequence of `if` statements based upon an operating mode, a command to \"switch to XXX mode (if not already in that mode)\" could be handled as a no-op in the XXX mode `if`-block, but perform an action for the `if` blocks associated with other modes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T01:32:31.533",
"Id": "44018",
"ParentId": "43991",
"Score": "6"
}
},
{
"body": "<p>It might be more efficient to use a switch statement, then throw the exception if the opcode does not have a statement.</p>\n\n<pre><code>switch (opcode)\n{\n case OP_0: { /* do stuffs */}\n case OP_1NEGATE: { /* do other stuffs */}\n ....\n default: { throw new Exception(\"a no no\"); }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:08:27.360",
"Id": "44098",
"ParentId": "43991",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "43997",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:12:42.973",
"Id": "43991",
"Score": "24",
"Tags": [
"c#"
],
"Title": "Checking opcode values"
} | 43991 |
<p>I made an <code>isSorted</code> function in Scala and Java as well and when I measured the time of functions' run I saw that the Scala version was very slow. It ran about 3.2 sec for 10000 Int but java version just ran about 10 ms!</p>
<p>How can I make faster my Scala version?</p>
<p><strong>Scala:</strong></p>
<pre><code>def main(args: Array[String]) ={
println(isSorted(getArray, (x:Int,y:Int) => x<y ))
}
def isSorted[A](items : Array[A], cond: (A,A) => Boolean) : Boolean = items match{
case Array(_) => true
case Array(x,y) =>cond(x,y)
case Array(_*) => cond(items(0),items(1)) && isSorted(items tail,cond)
}
</code></pre>
<p><strong>Java:</strong></p>
<pre><code>public static void main(String... args){
Sorter sorter=new Sorter();
System.out.println(sorter.isSorted(sorter.getList(),new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}));
}
public <A> boolean isSorted(List<A> items, Comparator<A> cond){
for(int i=1;i<items.size();i++){
if(cond.compare(items.get(i-1), items.get(i)) < 0){
return false;
}
}
return true;
}
</code></pre>
<p>Any suggestions?</p>
<p>I would like to use Scala, but this bad performance scared me!
Can I keep Scala's syntactic sugar?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:28:38.623",
"Id": "76146",
"Score": "1",
"body": "Java 8, which will release in a week, will support Lambdas, so you can use some of the syntaxic sugar. Keep in mind though that Scala is much less verbose than Java is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:39:12.170",
"Id": "76150",
"Score": "0",
"body": "I think the Java version can be faster.... would that review be interesting to you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:50:08.013",
"Id": "76154",
"Score": "0",
"body": "Yes I know I wrote it down. I am interested in making faster the Scala version."
}
] | [
{
"body": "<p>The problem is simply that your two solutions are not equivalent. For example, you would probably not use <code>Array</code>, but barring that, a direct translation of the Java code to Scala would be:</p>\n\n<pre><code>def isSorted[A](items: Array[A], cond: (A, A) => Boolean): Boolean = {\n for (i <- 1 until items.length if !cond(items(i - 1), items(i))) {\n return false\n }\n return true\n}\n</code></pre>\n\n<p>However, using an <code>Array</code> in Scala is a bit uncommon, and one would rather use <code>Seq</code> instead. Especially, a <code>LinearSeq</code> promises an efficient <code>tail</code> operation but slow indexing, this is reversed for an <code>IndexedSeq</code>.</p>\n\n<pre><code>@tailrec // remind the compiler that the recursion can be eliminated\ndef isSorted[A](items: LinearSeq[A], cond: (A, A) => Boolean): Boolean = items match {\n case Seq() => true // you forgot to handle empty input!\n case Seq(_) => true \n case x :: tail => cond(x, tail.head) && isSorted(tail, cond)\n}\n</code></pre>\n\n<p>But in this specific case, destructuring is actually silly: The <code>isSorted</code> test should male sense for <em>any</em> iterable (let's hope that it terminates, but that isn't our problem). It doesn't actually matter that much here that we can't do much destructuring for a general trait like <code>Iterable</code>. This here is a fairly elegant solution, but I wouldn't make any bets about performance.</p>\n\n<pre><code>def isSorted[A](items: Iterable[A], cond: (A, A) => Boolean): Boolean =\n items.isEmpty || (items zip items.tail forall (pair => cond(pair._1, pair._2)))\n</code></pre>\n\n<p>The <code>zip</code> method joins two lists pairwise: <code>items = Seq(1, 2, 3, 4)</code> would then produce <code>((1, 2), (2, 3), (3, 4))</code>.</p>\n\n<p>I am not sure whether any of these solutions would actually be faster – it's to be expected that Scala is a bit slower than Java, but the difference for a careful implementation should not be as large as in your question.</p>\n\n<hr>\n\n<p>Style notes:</p>\n\n<ul>\n<li>Always annotate tail recursive functions with <code>@tailrec</code> (from the <code>scala.annotation</code> package). This will either perform a tail call optimization or produce an error if the compiler is unable to do so.</li>\n<li>When specifying the type of a variable, put a space after the <code>:</code>, but not before: <code>name: Type</code>. (<a href=\"http://docs.scala-lang.org/style/types.html#annotations\">source</a>)</li>\n<li>Invoke methods by using <code>.</code>, except when the method is an operator or takes a function as parameter – <code>items.tail</code> instead of <code>items tail</code> (<a href=\"http://docs.scala-lang.org/style/method-invocation.html\">source</a>)</li>\n<li>In general, the spacing around your operators is inconsistent. A comma should always be followed by a space, and binary operators like <code>=</code> or <code><</code> should have a space on either side. (<a href=\"http://docs.scala-lang.org/style/method-invocation.html#symbolic_methodsoperators\">source</a>)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:50:46.190",
"Id": "76166",
"Score": "1",
"body": "I just compared your last method to his Scala method and your's MUCH faster. The test was an array with 20000 numbered from 0 to 20000. His method took around 5.7 seconds on my machine. Your method took less than 50ms. I couldn't get your @tailrec method to run (I got a MatchError with both mutable and immutable collections). My code: https://gist.github.com/luiscubal/9476082 (sorry if this is not idiomatic, I'm new to Scala)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:20:01.047",
"Id": "44002",
"ParentId": "43992",
"Score": "7"
}
},
{
"body": "<p>Amon's solution is simple and functional but it doesn't work on arrays and other IndexedSeqs.\nIf you want a general isSorted method that works on any sequential datastructure and is very fast you need to use an iterator.</p>\n\n<pre><code>def isSorted[T](list: Iterable[T])(lt: (T, T) => Boolean): Boolean = {\n @tailrec\n def loop(last: T, iter: Iterator[T]): Boolean = {\n if(!iter.hasNext) true\n else {\n val elem = iter.next\n if(lt(elem, last)) false\n else loop(elem, iter)\n }\n }\n\n val iter = list.iterator\n !iter.hasNext || loop(iter.next, iter)\n}\n</code></pre>\n\n<p>As far as I know the only way to make this even faster is by specialisation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T23:57:09.207",
"Id": "47523",
"ParentId": "43992",
"Score": "1"
}
},
{
"body": "<p>I love languages for their quirks. I would use <code>list</code> and:</p>\n\n<pre><code>def IsSorted(l:List[Int]) = (l, l.tail).zipped.forall(_ <= _)\n</code></pre>\n\n<p><strong>source</strong>: <a href=\"https://stackoverflow.com/questions/7852471/idiomatic-construction-to-check-whether-a-collection-is-ordered\">stackoverflow</a> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-25T10:00:23.930",
"Id": "96675",
"Score": "0",
"body": "If you did not get my hint - \"If you plan on using something like ´.elements.toList´ then you are better of using list in the first place\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-25T09:55:11.110",
"Id": "55210",
"ParentId": "43992",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "44002",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:16:36.040",
"Id": "43992",
"Score": "5",
"Tags": [
"java",
"performance",
"scala",
"sorting"
],
"Title": "How can I make my isSorted function faster?"
} | 43992 |
<p>I'm somewhat new to network programming. I have a server that uses Ubuntu, which needs to send data quickly to about 50 clients.</p>
<p>As of now, I have about 50 concurrent connections (of course), and it needs to be scalable up to 500.</p>
<p>I've created a JSON-based protocol to handle the streams and binary. Can these 2 classes be reviewed for any potential problems, bad techniques, etc?</p>
<p><strong>JSONServer</strong></p>
<pre><code>package com.wordpress.waffalware.tcpson;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import org.json.JSONObject;
public class JSONServer {
private int connectedSocketLimit = 10000;
private RequestCallback onRequest;
private ErrorCallback onError;
private ServerSocket server;
private boolean connected;
public final ArrayList<JSONClient> clients = new ArrayList<JSONClient>();
public void setOnRequest(RequestCallback handler) {
onRequest = handler;
}
public void setOnError(ErrorCallback handler) {
onError = handler;
}
public boolean isConnected() {
return connected;
}
public void start(int port) throws IOException {
server = new ServerSocket();
server.setSoTimeout(5000);
server.setReuseAddress(true);
server.setPerformancePreferences(1, 0, 0);
server.bind(new InetSocketAddress(InetAddress.getByAddress(new byte[] {
0, 0, 0, 0 }), port));
Thread accepter = new Thread(new Runnable() {
@Override
public void run() {
while (connected) {
Socket client = null;
try {
client = server.accept();
} catch (SocketTimeoutException e) {
continue;
} catch (IOException e) {
if (onError != null) {
onError.onError(e);
}
}
if (client != null) {
handleClient(new JSONClient(client));
}
}
}
}, "JSONServer-accepter");
connected = true;
accepter.start();
}
public void close() {
connected = false;
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
server = null;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
private void handleClient(final JSONClient client) {
Thread clientThread = new Thread(new Runnable() {
@Override
public void run() {
try {
clients.remove(client);
clients.add(client);
client.setSoTimeout(5000);
while (connected) {
JSONPacket request = client.readPacket();
if (request == null) {
break;
}
JSONPacket response;
if (onRequest != null) {
response = onRequest.onRequest(request);
} else {
response = new JSONPacket(new JSONObject());
}
client.writePacket(response);
if (clients.size() > connectedSocketLimit) {
break;
}
}
} catch (SocketTimeoutException e) {
if (onError != null) {
onError.onError(e);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
client.close();
clients.remove(client);
}
}
}, "JSONServer-clientHandler");
clientThread.start();
}
public interface RequestCallback {
public JSONPacket onRequest(JSONPacket request);
}
public interface ErrorCallback {
public void onError(Exception e);
}
}
</code></pre>
<p><strong>JSONClient</strong></p>
<pre><code>package com.wordpress.waffalware.tcpson;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import org.json.JSONObject;
public class JSONClient {
private boolean connected;
private Socket client;
private static final byte[] VERSION1 = new byte[] { 0x17, 0x78 };
public static JSONPacket getResponse(String host, int port,
JSONPacket request) throws IOException {
JSONClient client = new JSONClient();
try {
client.setSoTimeout(5000);
client.connect(new InetSocketAddress(host, port));
client.writePacket(request);
return client.readPacket();
} finally {
client.close();
}
}
public JSONClient() {
client = new Socket();
}
protected JSONClient(Socket baseClient) {
client = baseClient;
connected = baseClient.isConnected() && !baseClient.isClosed();
}
public boolean isConnected() {
return connected;
}
public void connect(SocketAddress endpoint) throws IOException {
client.connect(endpoint);
connected = true;
}
public void close() {
connected = false;
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
client = new Socket();
}
/**
* Writes <code>packet</code> to the <code>Socket</code>.
*
* @param packet
* The <code>JSONPacket</code> to write to <code>Socket</code>.
* @throws IOException
* If an IO/Error has occurred.
*/
public void writePacket(JSONPacket packet) throws IOException {
try {
OutputStream str = client.getOutputStream();
byte[] payloadRaw = packet.getPayload().toString().getBytes();
byte[] extraData = packet.getExtraData();
byte[] buffer = ByteBuffer
.allocate(14 + payloadRaw.length + extraData.length)
.put(VERSION1).put(intToByteArray(0))
.put(intToByteArray(payloadRaw.length))
.put(intToByteArray(extraData.length)).put(payloadRaw)
.put(extraData).array();
str.write(buffer);
str.flush();
} catch (IOException e) {
close();
throw e;
}
}
/**
* Reads and creates a <code>JSONPacket</code> from the <code>Socket</code><br>
* <br>
* If <code>null</code> is returned, the other side of the
* <code>Socket</code> should be treated as incompatible, and the
* <code>Socket</code> be closed immediately.
*
* @param str
* The stream to read the <code>JSONPacket</code> from.
* @return A <code>JSONPacket</code> representing the data from the stream,
* or <code>null</code> if there were no bytes to read or the data
* does not follow the format.
* @throws IOException
* If an IO/Error has occurred.
*/
public JSONPacket readPacket() throws IOException {
try {
byte[] tempBytes;
JSONPacket ret = null;
InputStream str = client.getInputStream();
tempBytes = new byte[14];
if (str.read(tempBytes, 0, tempBytes.length) == tempBytes.length) {
if (VERSION1[0] == tempBytes[0] & VERSION1[1] == tempBytes[1]) {
// int reservedValue = byteArrayToInt(tempBytes, 2);
int payloadSize = byteArrayToInt(tempBytes, 6);
int extraDataSize = byteArrayToInt(tempBytes, 10);
if (payloadSize >= 0 & extraDataSize >= 0) {
tempBytes = new byte[payloadSize];
if (str.read(tempBytes, 0, tempBytes.length) == tempBytes.length) {
JSONObject payloadData = new JSONObject(new String(
tempBytes));
tempBytes = new byte[extraDataSize];
if (str.read(tempBytes, 0, tempBytes.length) == tempBytes.length) {
ret = new JSONPacket(payloadData, tempBytes);
}
}
}
}
}
return ret;
} catch (IOException e) {
close();
throw e;
}
}
public void setSoTimeout(int timeout) throws SocketException {
// TODO: Should the connection stop if an exception is thrown?
client.setSoTimeout(timeout);
}
private static int byteArrayToInt(byte[] buffer, int offset) {
return (buffer[offset] & 0xFF) << 24
| (buffer[offset + 1] & 0xFF) << 16
| (buffer[offset + 2] & 0xFF) << 8 | buffer[offset + 3] & 0xFF;
}
private static byte[] intToByteArray(int buffer) {
return new byte[] { (byte) ((buffer >> 24) & 0xFF),
(byte) ((buffer >> 16) & 0xFF), (byte) ((buffer >> 8) & 0xFF),
(byte) (buffer & 0xFF) };
}
}
</code></pre>
<p>The <code>JSONPacket</code> is just a holding object for a byte array, and a <code>JSONObject</code>.</p>
<p>A long time ago, the <code>accept</code> function kept throwing an <code>IOException</code> because there were "too many open files".
I suspected it was that I forgot to call <code>Socket.close()</code> after I called <code>accept</code>.</p>
<p><strong>Main Points</strong></p>
<ol>
<li>Are there any techniques I should be using?</li>
<li>Does the code above properly close sockets?</li>
<li>I have researched about <code>java.nio</code> and wondered, should I use that package in my current situation? I know it's meant for non-blocking sockets, and millions of connections, but I only expect to have up to 500 concurrent connections.</li>
<li>Am I using threads correctly? <code>1 socket --> 1 connection</code></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:32:39.367",
"Id": "76147",
"Score": "0",
"body": "Off-topic, but what's wrong with big headers?"
}
] | [
{
"body": "<p>There is a <em>lot</em> of ground to cover here...</p>\n<h1>General</h1>\n<h2>ToString</h2>\n<p>You do not have a <code>toString()</code> on your JSONClient code. These are invaluable for debugging, etc.</p>\n<h2>Configuration</h2>\n<p>There are a lot of values which are hard-coded in your program. Things like IP addresses to bind to (you have the 'wild-card' <code>0.0.0.0</code> hardcoded) can be specified on a per-interface basis, rather than hard-coded.</p>\n<p>Other items like timeouts and so on should be configurable as well.</p>\n<h2>Threads</h2>\n<p>You are using <code>new Thread(...)</code> a lot in your code.... but you are not <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon%28boolean%29\" rel=\"noreferrer\">setting the daemon-state of the threads with setDaemon(true)</a>. I would consider all your threads to be daemon.</p>\n<p>I am undecided whether to recommend that you actually use an ExecutorService to organize your threads, or whether to customize your thread-name a different way. Basically, you are going to have 500 threads all called 'JSONServer-clientHandler'. This is not useful. It would be better to call them 'Thread 1', 'Thread 2', etc. But, that is silly too. I would highly recommend naming the thread after the client-side of the connection, something like:</p>\n<pre><code>"Client Handler for " + socket.getRemoteAddress()\n</code></pre>\n<p>Actually, for that benefit alone, I would recommend you continue using your Thread implementation, but you need to extract out the anaonymous Runnable class in to a more concrete class... even perhaps making the JSONClient a Runnable? The anonymous class for such an important piece of code is a problem.</p>\n<p>Continuing on the thread theme, I don't like the anonymous class in the Server's start method either.... The server should be a complete class with a <code>run()</code> method too</p>\n<h2>Socket Timeout</h2>\n<p>Why are you setting <code>soTimeout(5000)</code> on the ServerSocket?</p>\n<p>Waiting 5 seconds is not a problem for a ServerSocket.... and, then it throws a timout exception, and 'continues' to block again. Why not just do the sensible thing and not have the <code>soTimeout()</code> set at all (or set it to 0)?</p>\n<h2>Socket Closing</h2>\n<p>You specifically ask if the sockets are being closed properly.</p>\n<p>The method you use will close all client sockets, yes, but the mechanism is cumbersome.</p>\n<p>You should be using the Java7 <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"noreferrer\">try-with-resources mechanisms for doing this</a>. It will make both the exception and normal-case usage a lot better.</p>\n<h2>Concurrency</h2>\n<p>You have the <code>connected</code> boolean value, but this is not used in a thread-safe way... the variable is not atomic, it is not volatile, and it is not read in a synchronized way, thus, it is possible that the server thread will never read it as it changes value.</p>\n<p>additionally, this code here:</p>\n<blockquote>\n<pre><code>clients.remove(client);\nclients.add(client);\n</code></pre>\n</blockquote>\n<p>is called from a new thread, but it affects the <code>client</code> List which is shared on all threads. But that instance is neither synchronized nor concurrent. There <strong>will</strong> be corruption to that list at some point.</p>\n<h2>Out-of-place logic</h2>\n<blockquote>\n<pre><code>if (clients.size() > connectedSocketLimit) {\n break;\n}\n</code></pre>\n</blockquote>\n<p>The above code is in the client-handling loop.</p>\n<p>This logic is mis-placed. You should not allow a client thread to start if it is going to violate a limit..... instead, you are allowing clients to start, and only after they have done a request-response do you (not-thread-safe) check the limits. Then you terminate the thread that checked the situation, instead of the thread which caused the situation.... Checking an error condition after the error has happened is not a best practice. Checking a condition before entering a broken state is best-practice</p>\n<p>While we are on this topic... if you are only expecting up to 500 clients, why is the limit set at 10,000? This seems inappropriate</p>\n<h2>JSON Client</h2>\n<p>This is added to the <code>public final ArrayList<JSONClient> clients</code> List, but, before it is added, it is removed:</p>\n<blockquote>\n<pre><code>clients.remove(client);\nclients.add(client);\n</code></pre>\n</blockquote>\n<p>but your JSONClient code does not implement <code>equals()/hashCode()</code> so the remove will do an identity check to do the comparison, and thus the remove() will never remove anything because you can never add a client twice. Why have the <code>remove()</code> ?</p>\n<p>Additionally, it appears that your JSONClient class is used as both the client-side class, as well as the server-side handler. I don't like this model. You should separate those concerns, and, if needed provide some abstract-class functionality that both sides can use.</p>\n<p>Having both concerns in a single class makes it complicated.</p>\n<hr />\n<h1>Performance</h1>\n<h2>General Performance</h2>\n<ul>\n<li><p>Don't start tuning things until you know you need to. Why do you have this line:</p>\n<blockquote>\n<pre><code>server.setPerformancePreferences(1, 0, 0);\n</code></pre>\n</blockquote>\n<p>Do you know that connection-time is a problem? Are you just imagining that it may be?</p>\n</li>\n</ul>\n<h2>Threads</h2>\n<p>In current Java versions there is no real limit to the number of threads you can have running. You are planning on about 500, and this is not particularly concerning. Obviously they will not all be able to be on-cpu at the same time, but that is OK. There is no need to change your thread model for this reason.</p>\n<p>Using the NIO non-blocking mechanisms may help you reduce thread-count, but for the past 5 or so years there has been a lot of debate as to whether there is any performance benefit from that. It is my opinion that the complexity of using non-blocking channels with selectors, etc. is not worth the effort. Allocating a thread-per-socket is just fine.</p>\n<hr />\n<h1>Conclusion</h1>\n<p>Your code has enough critical problems that I think you need to consider a re-factor. The anonymous-class thread models make spotting the logic hard.</p>\n<p>Additionally, there is a lot of stuff I did not cover here... the above details are just the most significant things I saw.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T08:17:31.783",
"Id": "76660",
"Score": "1",
"body": "Good answer proving that concurrency and, in some way, networking is quite hard stuff to begin with and requires much, much patience : )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-03T14:25:13.060",
"Id": "356148",
"Score": "0",
"body": "`Using the NIO non-blocking mechanisms may help you reduce thread-count, but for the past 5 or so years there has been a lot of debate as to whether there is any performance benefit from that.` It would be better if you explained it further with a reference. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:26:26.260",
"Id": "44003",
"ParentId": "43995",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "44003",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T21:20:38.717",
"Id": "43995",
"Score": "8",
"Tags": [
"java",
"socket",
"server",
"client"
],
"Title": "Multi-threaded server socket"
} | 43995 |
<p>I am trying to find the users who have the highest "Following vs. Friends" ratio in my Twitter timeline. </p>
<p>I have a SQLite database of the users in my Twitter timeline and each column contains data found in the <code>user</code> section of the tweet JSON.</p>
<p>Is there a better way that I could write this search query? </p>
<p>Why does it return zero when the user has a higher friends count than followers count? </p>
<p>Is there a way to shorten this search query?</p>
<pre><code>SELECT CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL), screen_name FROM following
ORDER BY CAST(
CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL)
AS INT)
DESC LIMIT 25;
</code></pre>
| [] | [
{
"body": "<p>Your code is not working well, and the SQL statement is not formatted nicely either.</p>\n\n<p>Reformatting your code in to logical sections produces.</p>\n\n<pre><code>SELECT CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL),\n screen_name\nFROM following\nORDER BY CAST(CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL) AS INT) DESC\nLIMIT 25;\n</code></pre>\n\n<p>SQLite is notorious for doing calculations based on the wrong affinity of the data values.</p>\n\n<p>I immediately suspected that the SQL was doing integer division on the values even though you are casting them to decimal.</p>\n\n<p>I put <a href=\"http://www.sqlfiddle.com/#!5/c8d44/8/0\">some examples together as an SQLFiddle here,</a> and I cast the values to float instead, then used the SQLite <code>round()</code> function to get things decent. Doing floating-point division is what solves the zero-value division before.</p>\n\n<p>This is the SQL I ended up with:</p>\n\n<pre><code>SELECT ROUND(CAST(followers_count AS float) / CAST(friends_count AS float), 2) as ratio,\n screen_name\nFROM following\nORDER BY CAST(followers_count AS float) / CAST(friends_count AS float) DESC\nLIMIT 25;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:56:39.593",
"Id": "44010",
"ParentId": "44000",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44010",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:10:13.950",
"Id": "44000",
"Score": "3",
"Tags": [
"sql",
"sqlite"
],
"Title": "Finding users with the highest Following vs. Friends ratio"
} | 44000 |
<p>This code uses a <code>ReaderWriterLockSlim</code> to store data (on a disk or wherever), so that only one thread can write and many threads can read.</p>
<p>All writers should be finished before reading, and the write should not block the caller.</p>
<p>Basically my solution would work, but it doesn't look and feel natural to .NET since 4.0 the <em>Task Parallel Library</em> (TPL) was introduced...</p>
<pre><code>class JsonApplicationContainerDAO : IApplicationContainerDAO
{
private static volatile IApplicationContainerDAO instance;
private static object syncRoot = new Object();
private readonly BlockingCollection<ICollection<IApplicationConfiguration>> itemsToSave = new BlockingCollection<ICollection<IApplicationConfiguration>>();
private readonly Thread writerThread ;
private readonly ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim();
public static IApplicationContainerDAO Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new JsonApplicationContainerDAO();
}
}
return instance;
}
}
private JsonApplicationContainerDAO()
{
writerThread = new Thread(WriteItems);
writerThread.Start();
}
private void WriteItems(object obj)
{
ICollection<IApplicationConfiguration> item = null;
while((item = itemsToSave.Take()) != null){
try
{
readerWriterLock.EnterWriteLock();
//do stream stuff here
}
finally
{
readerWriterLock.ExitWriteLock();
}
}
}
public ICollection<IApplicationConfiguration> LoadAll()
{
try
{
readerWriterLock.EnterReadLock();
//do stream stuff here
}
finally
{
readerWriterLock.ExitReadLock();
}
return null;
}
public void Persist(ICollection<IApplicationConfiguration> items)
{
itemsToSave.Add(items);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:18:48.063",
"Id": "76442",
"Score": "0",
"body": "and the question is? BTW: you start the writer thread in constructor but when does that thread end and when does `Take` return null? You seem to always \"append\" to the persistence layer (file) - do you ever need to remove items? Can multiple threads concurrently call `Persist`/why use `BlockingCollection`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T12:26:47.477",
"Id": "76688",
"Score": "0",
"body": "The question is, is there a better way with usage of the Task Parrallel Library\n\nBlocking queue is used i want to have the write in some kind transactional, so like a Queue i will write every object in the order it has been added to the collection...\n\ni abstracted the logic of the write here because it has nothing to do with the problem/question..\n\nThe in this sample the thread will never return"
}
] | [
{
"body": "<ol>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>try\n{\n readerWriterLock.EnterWriteLock();\n //do stream stuff here\n}\nfinally\n{\n readerWriterLock.ExitWriteLock(); \n}\n</code></pre>\n</blockquote>\n\n<p><code>EnterWriteLock</code> should be before the <code>try</code> statement.</p>\n\n<blockquote>\n <p>Suppose the <code>EnterWriteLock()</code> fails. For whatever reason.\n Then the one thing you shouldn't do is to Exit a lock you never Entered. </p>\n</blockquote>\n\n<p>Source: <a href=\"https://stackoverflow.com/q/7071103/843804\">C# - Lock question using EnterWriteLock</a></p></li>\n<li><p>Please note that singleton nowadays is rather an antipattern. They make testing harder and often hide dependencies which leads to spaghetti code which is really hard to work with. <a href=\"https://stackoverflow.com/a/138012/843804\">What is so bad about singletons?</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T00:28:03.857",
"Id": "44540",
"ParentId": "44001",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "44540",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:18:53.720",
"Id": "44001",
"Score": "6",
"Tags": [
"c#",
"multithreading"
],
"Title": "ReaderWriter Synchronization"
} | 44001 |
<p>I have started making a <strong><em>very basic</em></strong> networking library in C++. It is built on UDP, with both reliable and unreliable delivery options.
So far, I have made the base messaging class, so I will show the header, and the code behind a few functions.</p>
<p>Things to note:</p>
<ul>
<li>While this is thread safe, I'm not actually expecting this to be widely parallelized, hence the atomic variable lock, and not a mutex. There may be contention, but it will be in extremely rare cases.</li>
<li>The code you see is not the complete object.</li>
</ul>
<p>I would primarily like to hear of any logical flaws, or coding errors. The functionality depicted is about all I will need. This library is for my own use, not for public, but I would still like to hear <strong><em>short</em></strong> notes of best practices for a public library. I would not like to hear about packet structure, because that really comes down to what you are using the library for.</p>
<pre><code>//So I can load just the header first, check if message has already been received,
//and allocate appropriate length or discard duplicate messages etc.
struct NetMessageHeader {
union
{
struct
{
bool m_sequenced : 1;
bool m_control : 1;
bool m_fragment : 1; //Dubious as to whether I need this
bool : 1; //Unused field
char m_length_high_nibble : 4;
char m_length_low_byte : 8;
int m_sequence_number : 32; //Endianness - caution
};
struct
{
char m_raw_data[6];
};
};
};
class NetMessage
{
private:
atomic_flag m_locked;
NetMessageHeader *m_header;
char *m_message;
unsigned short m_capacity, m_read_position, m_write_position;
//write_position points to the next empty element.
//read_position points to the next element to read.
public:
static atomic<unsigned int> maximum_message_length;
NetMessage();
~NetMessage();
unsigned short GetLength();
bool GetSequence(unsigned int &dest);
bool _SetSequence(unsigned int value);
bool IsSequenced();
bool IsControl();
bool LoadHeader(char &headerBytes);
bool LoadData(char &data); //Loads an array containing all data, including header.
bool ReserveMemory(unsigned short length);
bool ReadChar(char &dest);
bool ReadChars(char &dest, unsigned short length);
bool WriteChar(char &source);
bool WriteChars(char &source, unsigned short length);
};
</code></pre>
<p>These are the two methods I need to be sure are correct:</p>
<pre><code>bool NetMessage::ReadChars(char &dest, unsigned short length)
{
bool data_read = false;
//Spinlock
while (m_locked.test_and_set(memory_order_seq_cst))
;
//Critical section begins
unsigned short remaining_bytes = m_write_position - m_read_position;
if (remaining_bytes >= length)
{
memcpy((char *)dest, m_message, length);
m_read_position += length;
data_read = true;
}
//Critical section ends
m_locked.clear(memory_order_release);
return data_read;
}
bool NetMessage::WriteChars(char &source, unsigned short length)
{
if ((length + HEADER_LENGTH) > maximum_message_length.load(memory_order_acquire))
return false;
bool data_written = false;
//Spinlock
while (m_locked.test_and_set(memory_order_acquire))
;
//Critical section begins
if (m_message == nullptr) //Empty message, create new one.
{
m_capacity = NearestPowerOf2(HEADER_LENGTH + length);
m_message = new char(m_capacity);
memcpy(m_message + HEADER_LENGTH, (char*) &source, length);
m_write_position = HEADER_LENGTH + length;
data_written = true;
}
else if (m_write_position + length < maximum_message_length.load(memory_order_acquire))
{
int remaining_bytes = m_capacity - m_write_position;
if (remaining_bytes < length)
{
do
{
m_capacity *= 2; //Capacity can exceed maximum message length, write position cannot.
if (m_capacity & (m_capacity - 1)) //If capacity is not a power of two
m_capacity = NearestPowerOf2(m_capacity);
}
while (remaining_bytes < length);
char* resized_message = new char(m_capacity);
memcpy(resized_message, m_message, m_write_position);
delete[](m_message);
m_message = resized_message;
m_header = (NetMessageHeader *)resized_message;
}
memcpy(m_message + m_write_position, (char*) &source, 1);
m_write_position += length;
data_written = true;
}
//Critical section ends
m_locked.clear(memory_order_release);
}
</code></pre>
<p>I am interested in hearing your comments; I've never posted here before, so I don't know (if?) just how bad my coding is...</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T23:09:30.833",
"Id": "76169",
"Score": "0",
"body": "From the looks of things, I'd give serious consideration to just using the standard RTP packet format, with a few parts (e.g., `contributing sources`) just zeroed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T23:20:10.200",
"Id": "76170",
"Score": "0",
"body": "This is mostly an academic exercise for me. I was going to implement this over raw sockets, so I'm not duplicating the length field, but that is just too much hassle. RTP also appears to be a hassle on the Raspberry Pi - I know I didn't say anything about it in the question, but it would be nice to have a networking library I can reuse on my Pi."
}
] | [
{
"body": "<p>Don't use your own spin lock (it is ah huge waste of resources).</p>\n\n<pre><code>while (m_locked.test_and_set(memory_order_seq_cst))\n ;\n</code></pre>\n\n<p>Use a condition variable.<br>\nAlso empty blocks are hard to spot and understand if you are going to use them then put a comment that it is deliberately empty.</p>\n\n<p>Never do a manual set and release:</p>\n\n<pre><code>m_locked.test_and_set(memory_order_seq_cst);\n// STUFF\nm_locked.clear(memory_order_release);\n</code></pre>\n\n<p>This is not exception safe. Use RAII.</p>\n\n<p>Basically it looks like C code that happens to be wrapped in a class. As it stands not very good as it is easy to use incorrectly. The whole point of C++ is to design the class so it can not be misused (not just write C in a class).</p>\n\n<p>What I would expect as a C++ design.</p>\n\n<pre><code> // OK. Its unlikely to be this simple but.\n // Along these lines.\n class Message\n {\n public:\n void sendMessage(int fd)\n {\n write(fd, <Generic Header + Type Info>);\n this->serialize(fd);\n }\n static std::unique_ptr<Message> getMessage(int fd)\n {\n read(fd, <Generic Header + Type Info>);\n auto result Factory::getMessate(<TypeInfo>);\n result->deserialize(fd);\n return result;\n }\n private:\n // Each message type knows how to send itself.\n virtual void serialize(int fd) = 0;\n\n virtual void deserialize(int fd) = 0;\n };\n\n class Network\n {\n public:\n void sendMessage(Message const& m)\n {\n // network STUFF\n m.sendMessage(fd);\n }\n std:unique_ptr<Message> getMessage()\n {\n // Network STUFF\n return Message::getMessage(fd);\n }\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:19:28.833",
"Id": "76313",
"Score": "0",
"body": "Oh yeah. Exceptions would totally screw with the critical section. Thanks. Any suggestions in regards to the design? As [kolyunya](http://codereview.stackexchange.com/questions/30761/object-oriented-linux-networking-library?rq=1) phrased my exact motives so well - **\"I would like to know community's opinion if I made some design or implementation mistakes, if there could be done some improvements and if the library could be useful in some way to somebody. Any feedback is appreciated.\"**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T23:21:49.967",
"Id": "76383",
"Score": "0",
"body": "Design wise. Your code is like C. You are asking the user to do the work. A better design is to abstract the message. So you have a message object (you don't ask the user to add stuff to the message the message knows what it is). When you send the message to the network it will serialize itself on the send end and deserialize on the receiver end. This should **NOT** be a multiple step processes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T23:34:04.690",
"Id": "76384",
"Score": "0",
"body": "To send a message I should not be making multiple calls to the interface in the correct order and checking the status result of these calls."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:10:29.007",
"Id": "44081",
"ParentId": "44005",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44081",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:41:26.260",
"Id": "44005",
"Score": "0",
"Tags": [
"c++",
"thread-safety",
"library",
"networking"
],
"Title": "Threadsafe network message"
} | 44005 |
<p>I'm not particularly Python savy and <a href="https://github.com/megawac/iris/commit/fed82b8a6a4c9168fda4ee12a657fde5bddfc337" rel="nofollow noreferrer">recently wrote</a> a <code>LocalizationEngine</code> for <code>Twisted</code>.</p>
<p>The strategy I implemented was to make a dictionary from <code>base.json</code> and then merge with any existing files set in the <code>Accept-Language</code> set in the URL (or cookie). For instance the <code>Accept-Language</code> of <code>en-US,en;q=0.8,es;q=0.6</code> would merge <code>base.json, en.json, en-US.json</code> in that order. The folder layout looks like this:</p>
<p><img src="https://i.imgur.com/KeTl7IN.png" alt="folder layout"></p>
<pre><code>from twisted.web import resource, server, static, error as http_error
import json
import os
## load the JSON resource from the path and return the parse obj (dict in this case)
def getJSON(path):
file = open(path)
data = json.load(file)
file.close()
return data
class LocalizationEngine(resource.Resource):
isLeaf = True
localePath = "static/lang/"
def __init__(self, prefix):
pass
def render_GET(self, request):
return self.getLocale(request)
def getLocale(self, request):
"""
Request a localization and respond with json object of appropriate locale
"""
setLocales = request.getCookie("i18n") #preferred locale (todo implement)?
locales = []
if setLocales:
locales = json.load(setLocales)
else:
lang_header = request.headers.get("Accept-Language", "en") # for example en-US,en;q=0.8,es;q=0.6
locales = [locale.split(';')[0] for locale in lang_header.split(',')]
basePath = self.localePath + (request.args.get("path", [""])[0])
if not basePath.endswith("/"):
basePath += "/"
if not os.path.exists(basePath):
raise http_error.NoResource().render(request)
lang = getJSON(basePath + "base.json")
# reverse so specificity overrides
for locale in reversed(locales):
path = basePath + locale + ".json"
if os.path.exists(path):
lang.update(getJSON(path))
cache(request)
request.write(json.dumps(lang))
request.finish()
return True
</code></pre>
<p><strong>cache.py</strong></p>
<pre><code>from wsgiref.handlers import format_date_time as format_date
from datetime import date, timedelta
from time import mktime
'''
Sets the cache headers for a (static resource) request
'''
def cache(request, expires=30, public=True):
#set expires header
expiry = (date.today() + timedelta(expires)).timetuple()
request.responseHeaders.setRawHeaders("expires" , [format_date(mktime(expiry))])
#set cache control
cache_control = "max-age=" + str(int(60*60*24*expires))
if public:
cache_control += ", public"
else:
cache_control += ", private"
request.responseHeaders.setRawHeaders("cache-control", [cache_control])
return request
</code></pre>
<p>A code review of the above implementation or suggesting an existing Twisted/Python Internationalization implementation (couldn't find one) would be great answers :)</p>
| [] | [
{
"body": "<p>I haven't worked with Twisted, \nand also cannot recommend existing internationalization implementations,\nbut I can code review in terms of Python in general.</p>\n\n<p>You are not following <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>,\nthe official coding style guide of Python.\nThe coding style violations are not so bad but they are noticeable.\nI won't comment on those one by one,\nI suggest to give the doc a good read and follow it.</p>\n\n<p>It's nice that you documented this method with a comment:</p>\n\n<blockquote>\n<pre><code>## load the JSON resource from the path and return the parse obj (dict in this case)\ndef getJSON(path):\n file = open(path)\n data = json.load(file)\n file.close()\n return data\n</code></pre>\n</blockquote>\n\n<p>Why not go all the way and document with a proper docstring?\nAlso, closing files manually is old-fashioned. \nThe recommend way is simpler and better:</p>\n\n<pre><code>def getJSON(path):\n \"\"\"\n load the JSON resource from the path and return the parse obj (dict in this case)\n\n @param path: JSON file to parse\n @return: parsed object as a dict\n \"\"\"\n with open(path) as fh:\n return json.load(fh)\n</code></pre>\n\n<p>In this code, the initialization of <code>locales = []</code> is unnecessary,\nbecause you assign to the variable in both branches of the <code>if</code>, so you can remove it:</p>\n\n<blockquote>\n<pre><code> locales = []\n if setLocales:\n locales = json.load(setLocales)\n else:\n lang_header = request.headers.get(\"Accept-Language\", \"en\") # for example en-US,en;q=0.8,es;q=0.6\n locales = [locale.split(';')[0] for locale in lang_header.split(',')]\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T07:28:31.230",
"Id": "74374",
"ParentId": "44006",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:44:30.783",
"Id": "44006",
"Score": "5",
"Tags": [
"python",
"i18n",
"twisted"
],
"Title": "Twisted Internationalization"
} | 44006 |
Event-driven networking engine written in Python. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:52:26.580",
"Id": "44009",
"Score": "0",
"Tags": null,
"Title": null
} | 44009 |
<p>Cross-browser refers to the ability of a website, web application, HTML construct or client-side script to function in environments that provide its required features and to bow out or degrade gracefully when features are absent or lacking.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T23:21:49.600",
"Id": "44011",
"Score": "0",
"Tags": null,
"Title": null
} | 44011 |
Cross-browser refers to the ability of a website, web application, HTML construct or client-side script to function in environments that provide its required features and to bow out or degrade gracefully when features are absent or lacking. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T23:21:49.600",
"Id": "44012",
"Score": "0",
"Tags": null,
"Title": null
} | 44012 |
<p>I have the following method which basically converts an input audio file to a monophonic FLAC file.</p>
<p>Now I am getting <em>Member has cyclomatic complexity of 21 (105%)</em> message in Visual Studio, while I've taken care of improving it as in the beginning it was longer, now there's not much I can remove from it as it pretty much fulfills my needs.</p>
<p>Should I just ignore this warning ?</p>
<pre><code>private static void Convert(string inputFile, string outputFile, IProgress<double> progress = null)
{
if (inputFile == null) throw new ArgumentNullException("inputFile");
if (outputFile == null) throw new ArgumentNullException("outputFile");
int stream = 0;
int mixer = 0;
try
{
stream = Bass.BASS_StreamCreateFile(inputFile, 0, 0,
BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
if (stream == 0) throw new BassException("Could not create stream");
var info = Bass.BASS_ChannelGetInfo(stream);
if (info == null) throw new BassException("Could not retrieve stream info");
var freq = info.freq;
mixer = BassMix.BASS_Mixer_StreamCreate(freq, 1,
BASSFlag.BASS_MIXER_END | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE);
if (mixer == 0) throw new BassException("Could not create mixer");
bool addChannel = BassMix.BASS_Mixer_StreamAddChannel(mixer, stream, BASSFlag.BASS_MIXER_NORAMPIN);
if (!addChannel) throw new BassException("Could not add stream to mixer");
long getLength = Bass.BASS_ChannelGetLength(stream);
if (getLength == -1) throw new BassException("Could not get channel length");
var encoder = new EncoderFLAC(mixer)
{
Force16Bit = true,
FLAC_Verify = true,
OutputFile = outputFile
};
if (!encoder.Start(null, IntPtr.Zero, false))
throw new InvalidOperationException("Could not start encoder");
const int samples = 65536;
const int bytes = (samples * sizeof(float)) | (int)BASSData.BASS_DATA_FLOAT;
var buffer = new float[samples];
long bytesRead = 0;
while (Bass.BASS_ChannelIsActive(mixer) == BASSActive.BASS_ACTIVE_PLAYING)
{
int getData = Bass.BASS_ChannelGetData(mixer, buffer, bytes);
bytesRead += getData;
if (progress != null) progress.Report(1.0d / getLength * bytesRead);
}
encoder.Stop();
if (getLength / sizeof(short) != bytesRead)
throw new InvalidOperationException("Output length not equal to input length");
}
catch (Exception ex)
{
throw new InvalidOperationException("Conversion failed", ex);
}
finally
{
if (stream != 0) Bass.BASS_StreamFree(stream);
if (mixer != 0) Bass.BASS_StreamFree(mixer);
}
}
</code></pre>
| [] | [
{
"body": "<p>I think your code would become much simpler and more readable if you encapsulated all the BASS-related functionality from into separate types.</p>\n\n<p>Something like:</p>\n\n<pre><code>class Stream\n{\n private readonly int handle;\n\n // add overload that supports setting offset and lenght, if you need that\n public Stream(string inputFile, BASSFlag flags)\n {\n handle = BASS_StreamCreateFile(inputFile, 0, 0, flags);\n\n if (handle == 0)\n throw new BassException(\"Could not create stream\");\n }\n\n public ChannelInfo GetInfo()\n {\n var result = Bass.BASS_ChannelGetInfo(stream);\n\n if (result == null)\n throw new BassException(\"Could not retrieve stream info\");\n\n return result;\n }\n\n // etc.\n}\n</code></pre>\n\n<p>This would simplify the start of your code to just:</p>\n\n<pre><code>Stream stream = new Stream(inputFile,\n BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);\nvar info = stream.GetInfo();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T01:15:46.880",
"Id": "44016",
"ParentId": "44014",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44016",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T00:35:59.373",
"Id": "44014",
"Score": "2",
"Tags": [
"c#",
"audio",
"cyclomatic-complexity"
],
"Title": "Converting an input audio file to a monophonic FLAC file"
} | 44014 |
<p>I have written this code to search for a string in a <code>.txt</code> file. Is it possible to optimize the code so that it searches for the string in fastest manner possible? Assuming the text file would be a large one (500MB-1GB)</p>
<p>I don't want to use regex.</p>
<pre><code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StringFinder {
public static void main(String[] args)
{
double count = 0,countBuffer=0,countLine=0;
String lineNumber = "";
String filePath = "C:\\Users\\allen\\Desktop\\TestText.txt";
BufferedReader br;
String inputSearch = "are";
String line = "";
try {
br = new BufferedReader(new FileReader(filePath));
try {
while((line = br.readLine()) != null)
{
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
}
}
if(countBuffer > 0)
{
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Times found at--"+count);
System.out.println("Word found at--"+lineNumber);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:06:23.200",
"Id": "76308",
"Score": "1",
"body": "Have you done any research on what algorithms to use? When searching for a fixed string (i.e., no wildcards), [Knuth-Morris-Pratt](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) is significantly faster than naive matching, for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:25:38.020",
"Id": "76342",
"Score": "0",
"body": "This could probably make a difference, use `StringBuilder` http://stackoverflow.com/questions/4645020/when-to-use-stringbuilder-in-java"
}
] | [
{
"body": "<p>Fast comes at a price.... code complexity and perhaps readability.</p>\n\n<p>Assuming that your code produces the right results now.... and it is a big assumption because:</p>\n\n<ul>\n<li>it expects the word to be at the beginning/end of the line, or surrounded by spaces (not commas, punctuation, etc.)</li>\n<li>it does not look for the word inside another string, it will match 'are', but not 'bare'.</li>\n</ul>\n\n<p>OK, a much faster way (keeping it as Java), is to do the following:</p>\n\n<ol>\n<li>Convert the search string ('are') to a byte-array in the same encoding as the file.</li>\n<li>Open a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#map%28java.nio.channels.FileChannel.MapMode,%20long,%20long%29\">memory-mapped byte-buffer</a> from a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#open%28java.nio.file.Path,%20java.nio.file.OpenOption...%29\">File-Channel on the file</a>.</li>\n<li>Scan the ByteBuffer, looking for matches to the search byte-array</li>\n<li>count the newlines as you go.</li>\n<li>close the ByteBuffer</li>\n</ol>\n\n<p>If the file is larger than your memory, you will have to re-position the byte-buffer occasionally. I recommend using a emopry-mapped size of about 4MB plus the size of the search-string. That way you can search the 4MB window, and then start the next window at the next 4mb boundary.</p>\n\n<p>Once you get in to it, it will make sense.</p>\n\n<p>This system will be fast because you will never have to copy the file's data in to Java. Everything will actually happen in the native side of things.</p>\n\n<p>There is a lot to read to make it work.</p>\n\n<p>I would start with a tutorial....</p>\n\n<ul>\n<li><a href=\"http://www.studytrails.com/java-io/Channels.jsp\">StudyTrails</a></li>\n<li><a href=\"http://www.yaldex.com/java_tutorial/0600410861.htm\">Yaldix</a></li>\n<li><a href=\"http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_029.htm\">LinuxTopia</a></li>\n</ul>\n\n<p>of course, if you want really fast, use grep.</p>\n\n<p>Here is some example code that may get you started:</p>\n\n<pre><code>import java.io.IOException;\nimport java.nio.MappedByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.channels.FileChannel.MapMode;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardOpenOption;\n\n\npublic class NIOGrep {\n\n public static void main(String[] args) throws IOException {\n if (args.length != 2) {\n throw new IllegalArgumentException();\n }\n String grepfor = args[0];\n Path path = Paths.get(args[1]);\n\n String report = searchFor(grepfor, path);\n\n System.out.println(report);\n\n }\n\n private static final int MAPSIZE = 4 * 1024 ; // 4K - make this * 1024 to 4MB in a real system.\n\n private static String searchFor(String grepfor, Path path) throws IOException {\n final byte[] tosearch = grepfor.getBytes(StandardCharsets.UTF_8);\n StringBuilder report = new StringBuilder();\n int padding = 1; // need to scan 1 character ahead in case it is a word boundary.\n int linecount = 0;\n int matches = 0;\n boolean inword = false;\n boolean scantolineend = false;\n try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {\n final long length = channel.size();\n int pos = 0;\n while (pos < length) {\n long remaining = length - pos;\n // int conversion is safe because of a safe MAPSIZE.. Assume a reaosnably sized tosearch.\n int trymap = MAPSIZE + tosearch.length + padding;\n int tomap = (int)Math.min(trymap, remaining);\n // different limits depending on whether we are the last mapped segment.\n int limit = trymap == tomap ? MAPSIZE : (tomap - tosearch.length);\n MappedByteBuffer buffer = channel.map(MapMode.READ_ONLY, pos, tomap);\n System.out.println(\"Mapped from \" + pos + \" for \" + tomap);\n pos += (trymap == tomap) ? MAPSIZE : tomap;\n for (int i = 0; i < limit; i++) {\n final byte b = buffer.get(i);\n if (scantolineend) {\n if (b == '\\n') {\n scantolineend = false;\n inword = false;\n linecount ++;\n }\n } else if (b == '\\n') {\n linecount++;\n inword = false;\n } else if (b == '\\r' || b == ' ') {\n inword = false;\n } else if (!inword) {\n if (wordMatch(buffer, i, tomap, tosearch)) {\n matches++;\n i += tosearch.length - 1;\n if (report.length() > 0) {\n report.append(\", \");\n }\n report.append(linecount);\n scantolineend = true;\n } else {\n inword = true;\n }\n }\n }\n }\n }\n return \"Times found at--\" + matches + \"\\nWord found at--\" + report;\n }\n\n private static boolean wordMatch(MappedByteBuffer buffer, int pos, int tomap, byte[] tosearch) {\n //assume at valid word start.\n for (int i = 0; i < tosearch.length; i++) {\n if (tosearch[i] != buffer.get(pos + i)) {\n return false;\n }\n }\n byte nxt = (pos + tosearch.length) == tomap ? (byte)' ' : buffer.get(pos + tosearch.length); \n return nxt == ' ' || nxt == '\\n' || nxt == '\\r';\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T05:13:56.977",
"Id": "76197",
"Score": "2",
"body": "This idea can maybe made to be faster with a map-reduce style algorithm, where several areas of the file are searched at the same time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:08:31.007",
"Id": "76310",
"Score": "2",
"body": "`\"This system will be fast because you will never have to copy the file's data in to Java. Everything will actually happen in the native side of things.\"` Not exactly true, you are copying the data to java, one byte at a time with `buffer.get(i)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:13:19.133",
"Id": "44024",
"ParentId": "44021",
"Score": "22"
}
},
{
"body": "<p>Since you want to find the line numbers where the match succeeds, I would try make improvements based on your current strategy based on <code>BufferedReader.readLine()</code>, and resort to more exotic means such as NIO only if necessary.</p>\n\n<p>Two somewhat costly operations are string splitting and string concatenation.</p>\n\n<p>When you split a line into words, it has to allocate and copy the characters of a new <code>String</code> for each word, as well as an array to store the results in. Instead, you could search within the line, and check whether there the beginning and end of the match occur at word boundaries.</p>\n\n<pre><code>int len = inputSearch.length();\nint countInLine = 0;\nint pos = -1;\nwhile ((pos = line.indexOf(inputSearch, pos + 1)) >= 0) {\n if ((pos == 0 || Character.isWhitespace(line.charAt(pos - 1))) &&\n (pos + len == line.length() || Character.isWhitespace(line.charAt(pos + len))) {\n countInLine++;\n }\n}\n</code></pre>\n\n<p>You should probably treat punctuation as well as whitespace as word boundaries.</p>\n\n<p>The other inefficiency is repeated string concatenation. Strings in Java are immutable. Whenever you write <code>a + b</code> for strings <code>a</code> and <code>b</code>, the code actually compiles to <code>new StringBuilder(a).append(b).toString()</code>. Therefore, <code>lineNumber</code> should be a <code>StringBuilder</code> instead, so you can keep appending to it efficiently.</p>\n\n<p>Note that <code>FileNotFoundException</code> is a kind of <code>IOException</code>. You could use one catch-block to handle both. However, if an <code>IOException</code> occurs, you probably shouldn't try to report the word count, which will probably be invalid. To accomplish that, you could just eliminate all try-catch blocks from <code>main()</code>, and declare that <code>main(String[] args) throws IOException</code>. Then, in case of error, it will just print a stack trace and exit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:42:31.933",
"Id": "76331",
"Score": "0",
"body": "Now that we handle white-space.\nThere would be loads of punctuations to deal with."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T06:58:14.977",
"Id": "44038",
"ParentId": "44021",
"Score": "4"
}
},
{
"body": "<p>If you want to go for performance, you could try a different algorithm. This is what <code>grep</code> does :</p>\n\n<blockquote>\n <p>GNU grep uses the well-known Boyer-Moore algorithm, which looks first for the final letter of the target string, and uses a lookup table to tell it how far ahead it can skip in the input whenever it finds a non-matching character.</p>\n</blockquote>\n\n<p>from <a href=\"http://lists.freebsd.org/pipermail/freebsd-current/2010-August/019310.html\">Why GNU grep is fast</a> (you'll find on this page other smart ideas).</p>\n\n<p>You can find more details on the <a href=\"http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm\">corresponding Wikipedia page</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:36:39.757",
"Id": "44042",
"ParentId": "44021",
"Score": "8"
}
},
{
"body": "<p>You could search a string as a byte array: check my version of <code>public static int search(byte[] input, byte[] searchedFor)</code> on <a href=\"https://stackoverflow.com/questions/22234021/search-for-a-string-as-an-byte-in-a-binary-stream/22236277#22236277\">https://stackoverflow.com/questions/22234021/search-for-a-string-as-an-byte-in-a-binary-stream/22236277#22236277</a> </p>\n\n<p>Of course while doing the byte-search you have to catch all \"newline\" chars and count them, in order to give to the user a line number of where the matches were found.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:38:39.727",
"Id": "44058",
"ParentId": "44021",
"Score": "1"
}
},
{
"body": "<p>If you are looking to match \"are\" with spaces around it, simply add spaces like so: \" are \" and see if the line contains that string (taking some edge cases into account).</p>\n\n<pre><code> String paddedInput = \" \" + inputSearch + \" \";\n String paddedInputStart = inputSearch + \" \";\n String paddedInputEnd = \" \" +inputSearch ;\n\n while((line = br.readLine()) != null)\n {\n countLine++;\n\n if(line.equals(inputSearch) || \n line.startsWith(paddedInputStart) ||\n line.endsWith(paddedInputEnd) || \n (line.contains(paddedInput)) {\n lineNumber += countLine + \",\";\n }\n }\n</code></pre>\n\n<p>Do the least expensive to fail checks first. Equals will check string length first so it's a quick check unless the line is equally long to the search space (not so frequent). Functions <code>startsWith</code> and <code>endsWith</code> are fast checks as they do not perform a search; <code>contains</code> is done last because it's the most expensive.</p>\n\n<p>The above avoids the splitting (that can be slow) and iteration over the word list. Instead letting the string API that is most likely implemented in native code do the work for you. The strings used must be constructed before the loop to avoid repeated string operations although I think that the java compiler will optimize that, I'm not sure.</p>\n\n<p>A good implementation of <code>String.contains()</code> would use Boyer-Moore but it is not necessary that it will. Java does not dictate which algorithm it is. If you want to be sure, see link in the answer: <a href=\"https://codereview.stackexchange.com/a/44042/36120\">https://codereview.stackexchange.com/a/44042/36120</a> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:38:39.200",
"Id": "76328",
"Score": "0",
"body": "Yeh @Emily you are right.\nThe only thing that bothers me now is that i have to handle all the punctuations.\nEg: Punctuations like \",.!)'->/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:53:52.993",
"Id": "76333",
"Score": "0",
"body": "In that case it is easier use `int i = String.indexOf(inputSearch)` and `if (i != -1)`, then look at `line.charAt(i-1)` and `line.charAt(i+inputSearch.length)` for punctuation or space (with the obvious checks for range of the line). If the match failed, search for the next ocurrance with `String.indexOf(inputSearch, i + inputSearch.length)` and repeat."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:18:39.963",
"Id": "44065",
"ParentId": "44021",
"Score": "6"
}
},
{
"body": "<blockquote>\n <p>I don't want to use regex.</p>\n</blockquote>\n\n<p>Maybe you should.</p>\n\n<p>A little known fact is that a <code>Matcher</code> does not take a <code>String</code> as an argument but a <code>CharSequence</code>. And <code>String</code> implements that interface.</p>\n\n<p>Since you are dealing with large text files, well, I have just the library for you: <a href=\"https://github.com/fge/largetext\" rel=\"nofollow\">largetext</a>. It implements <code>CharSequence</code> over a large text file, which means a <code>LargeText</code> instance is directly usable with a <code>Matcher</code>:</p>\n\n<pre><code>private static final Pattern PATTERN = ...\nprivate static final LargeTextFactory = LargeTextFactory.defaultFactory();\n\n// in code;\n\nfinal Path path = Paths.get(\"...\");\n\ntry (\n final LargeText largeText = factory.fromPath(...);\n) {\n final Matcher m = PATTERN.matcher(largeText);\n // do stuff with m\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-17T14:38:20.917",
"Id": "177863",
"Score": "0",
"body": "I tried your library and got it working--well done!--but the problem is that is only returns the index of the match not the line number, so although LargeText is cool, I'm not sure it's a good fit for this task."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-17T15:55:09.320",
"Id": "177895",
"Score": "0",
"body": "@james.garriss eh, sorry, `Matcher` also has its limitations ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T12:40:38.993",
"Id": "48567",
"ParentId": "44021",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T02:46:50.807",
"Id": "44021",
"Score": "26",
"Tags": [
"java",
"algorithm",
"strings",
"search",
"file"
],
"Title": "Fast way of searching for a string in a text file"
} | 44021 |
<p>Is there any way to take this chunk of an else if and make it its own method? I would need the values of valid and throwLine() to be done in the method containing this if else statement, but I'm around 45 lines in my method which is 15 more than I'm allowed to have for simplicity. </p>
<pre><code> else if(isOperator(readIn))
{
System.out.print(readIn);
if(myStack.isEmpty())
valid = false;
else
op2 = (Fraction)myStack.pop();
if(myStack.isEmpty())
{
throwLine(readIn);
valid = false;
}
else
{
runTheOperator(op2, op1, readIn);
readIn = stdin.next();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:17:52.087",
"Id": "76189",
"Score": "1",
"body": "This question would benefit from a little more context. Don't include the full enclosing function (or do as it will suffice), but include at least the method's signature and final return statement. In any case, 30 lines is 25 more than recommended in *Clean Code*, and I'm inclined to agree even though I often write 10- and 15-line methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:42:45.793",
"Id": "76192",
"Score": "1",
"body": "@DavidHarkness Context is in [this other question](http://codereview.stackexchange.com/q/43984/9357)."
}
] | [
{
"body": "<p>As @DavidHarkness points out, you didn't provide enough context for this question to make sense. However, I see that this code comes from a <code>doTypeCheck()</code> method, which is at the heart of your <a href=\"https://codereview.stackexchange.com/q/43984/9357\">RPN calculator implementation</a>. I'll reproduce that method here, along with its call site:</p>\n\n<pre><code>private void doTypeCheck(Fraction op1, Fraction op2)\n{\n Fraction answer = null;\n String readIn = \"\";\n boolean valid = true;\n readIn = stdin.next();\n\n while(!readIn.equals(\"#\") && valid == true)\n {\n if(!isOperator(readIn) && isOperand(readIn))\n {\n processOperand(readIn);\n readIn = stdin.next();\n }\n else if(isOperator(readIn))\n {\n System.out.print(readIn);\n if(myStack.isEmpty())\n valid = false;\n else\n op2 = (Fraction)myStack.pop();\n\n if(myStack.isEmpty())\n {\n valid = false;\n throwLine(readIn);\n }\n else\n {\n runTheOperator(op2, op1, readIn);\n readIn = stdin.next();\n }\n }\n else\n { \n System.out.print(readIn);\n valid = false;\n throwLine(readIn);\n }\n }\n System.out.println();\n if(myStack.isEmpty())\n valid = false;\n else\n answer = (Fraction)myStack.pop(); \n if(!myStack.isEmpty())\n valid = false;\n checkMessageValid(valid, answer);\n}\n\nprivate void runOnce(int count)\n{\n Fraction op1 = null;\n Fraction op2 = null;\n clear(myStack, myQueue);\n\n System.out.print(\"Expression \" + count++ + \" is: \");\n doTypeCheck(op1, op2); \n }\n</code></pre>\n\n<hr>\n\n<p>The root problem is that your method has no clear purpose, and tries to do many things:</p>\n\n<ul>\n<li>Read tokens from the input stream, and decide whether they are operands or operators</li>\n<li>If it sees invalid input, discard the rest of the input and display an error</li>\n<li>Pop an operand from the stack, with error handling</li>\n<li>Feed two operands to the calculating function</li>\n<li>Check that the stack is empty afterwards</li>\n<li>Display the answer</li>\n</ul>\n\n<p>As I mentioned in my <a href=\"https://codereview.stackexchange.com/a/44026/9357\">other answer</a>, that's not a good way to write an RPN calculator.</p>\n\n<p>The main loop of an RPN evaluator should probably look something like this:</p>\n\n<pre><code>try {\n while (in.hasNext()) {\n String token = in.next();\n RpnOperator op = RpnOperator.forSymbol(token);\n if (op != null) {\n op.operate(calcStack);\n } else {\n calcStack.push(new Fraction(token));\n }\n }\n System.out.println(calcStack.peek());\n} catch (EmptyStackException emptyStack) {\n System.out.println(\"Error: empty stack\");\n}\n</code></pre>\n\n<p>That's all! To summarize:</p>\n\n<ul>\n<li>Let the operators manipulate the stack. The main loop just needs to dispatch to the appropriate operators.</li>\n<li>Use exceptions for error handling.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T04:14:21.713",
"Id": "44028",
"ParentId": "44023",
"Score": "6"
}
},
{
"body": "<p>Well, if you are not wanting to change all your code as others suggested, I would use the following version:</p>\n\n<pre><code>private boolean tryFurtherOperator(String curLine, Stack stack, Fraction op1) {\n boolean valid = false;\n if(stack.isEmpty()){\n throwLine(curLine);\n } else {\n Fraction op2 = (Fraction)stack.pop();\n runTheOperator(op2, op1, curLine);\n valid = true;\n }\n return valid;\n}\n\n\n/* etc ...*/ else if(isOperator(readIn)){\n System.out.print(curLine);\n\n if(tryFurtherOperator(curLine, stack, op1)){\n curLine = stdin.next();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:28:25.373",
"Id": "44056",
"ParentId": "44023",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:01:47.380",
"Id": "44023",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Executing an operator in an RPN evaluator"
} | 44023 |
<h1>Specification</h1>
<p>A simple PHP script resizes images on-the-fly. The script is called by the web server's 404 handler to return a scaled version of the original. For example, if the original image is at:</p>
<pre><code>http://localhost/images/filename.jpg
</code></pre>
<p>Then valid requests for scaled versions include:</p>
<pre><code>http://localhost/images/filename-200x.jpg
http://localhost/images/filename-x200.jpg
http://localhost/images/filename-200x200.jpg
</code></pre>
<p>All requests maintain the aspect ratio. The first request scales to the image to 200px wide; the second scales the image to 200px high; the third request ensures neither the width nor height exceeds 200x200px.</p>
<p>This is similar to how Google Picasa works.</p>
<h1>Assumptions</h1>
<p>The code is called with the following known constraints:</p>
<ul>
<li>The file names are hashed.</li>
<li>The images are valid.</li>
<li>The images are in a format recognized by the WideImage library.</li>
<li>Each image typically resides in its own folder, nested a few directories deep.</li>
</ul>
<h1>Questions</h1>
<p>I am wondering:</p>
<ul>
<li>What security holes are present?</li>
<li>How would you address them?</li>
<li>What optimizations are possible (e.g., use a <a href="http://phpthumb.sourceforge.net/" rel="nofollow">faster library</a>)?</li>
</ul>
<p>Other non-security criticisms are also welcome.</p>
<h1>Code</h1>
<p>The code follows:</p>
<pre><code><?php
/**
* This file handles dynamically caching and resizing thumbnails. This
* file is called when the web server encouters a 404 error on a thumbnail
* image. The image is created and returned, which will prevent subsequent
* 404s on that image. The file names must be formatted as:
*
* <pre>
* filename-#x.ext
* filename-x#.ext
* filename-#x#.ext
* </pre>
*
* The examples specify: (1) width; (2) height; (3) width and height. The
* aspect ratio is maintained.
*
* For security purposes, only a specific set of dimensions are allowed.
*/
include 'WideImage/WideImage.php';
// Limit the number of possible cached images (i.e., do not allow arbitrary
// dimensions to create cached files).
$ACCEPT_DIMENSIONS = array( 200, 1024, 2048, 4096 );
// The "images" suffix comes from the URL.
$IMAGES_DIRECTORY = "/home/data";
$DIVIDER = "x";
/**
* Given an integer value, this will find its nearest value within an
* array of values.
*
* @param $needle The value whose nearest value is sought.
* @param $haystack The valid values.
*
* @return The value in $haystack that is nearest to $needle.
* @see http://stackoverflow.com/a/5464961/59087
*/
function nearest( $needle, $haystack ) {
$near = null;
foreach( $haystack as $hay ) {
if( $near == null || abs( $needle - $near ) > abs( $hay - $needle ) ) {
$near = $hay;
}
}
return $near;
}
/**
* Returns the minimum dimension of $dim_a or $dim_b such that the resulting
* value is nearest to the acceptable array of dimensions.
*
* @param $dim_a The first dimension for comparison.
* @param $dim_b The second dimension for comparison.
*
* @return The smaller of dim_a and dim_b evaluated to the nearest value
* in the ACCEPT_DIMENSIONS array.
*/
function minimum( $dim_a, $dim_b ) {
global $ACCEPT_DIMENSIONS;
return nearest( min( $dim_a, $dim_b ), $ACCEPT_DIMENSIONS );
}
// Separate the query string into its path parts (filename, directory, etc.).
$path = pathinfo( $_SERVER["QUERY_STRING"] );
// Get the filename without the extension.
$filename = $path["filename"];
// Get the path to the image (appended to $IMAGES_DIRECTORY).
$dirname = $path["dirname"];
// Get the image extension, which will be used when saving the scaled file.
$extension = $path["extension"];
// Locate the position of the last hyphen in the filename.
$index = strpos( $filename, "-" );
// When one hyphen is present, it indicates dimensions might be specified...
if( $index > 1 && substr_count( $filename, "-", $index ) === 1 ) {
// Grab the filename without the specified dimensions.
$original_filename = substr( $filename, 0, $index );
$dimensions = substr( $filename, $index + 1 );
// If the x isn't present, ensure it will be parsed and used in the
// output filename.
if( strpos( $dimensions, $DIVIDER ) === false ) {
$dimensions .= $DIVIDER;
$filename .= $DIVIDER;
}
// Split a maximum of 2 values: the width and height. The "x" is always
// present.
list( $width, $height ) = explode( $DIVIDER, $dimensions, 2 );
// Ensure no funny stuff has happened with the numbers.
$width = intval( $width );
$height = intval( $height );
// Determine the full path to the original file.
$source = "$IMAGES_DIRECTORY$dirname/$original_filename.$extension";
// Open the original image to scale to the given dimensions.
$image = WideImage::load( $source );
// Scaling cannot exceed original dimensions; the resize API requires
// "null" values to maintain aspect ratios.
// @see http://wideimage.sourceforge.net/
$width = empty( $width ) ? null : minimum( $width, $image->getWidth() );
$height = empty( $height ) ? null : minimum( $height, $image->getHeight() );
// If the current URI differs from the sanitized URI then updates are needed.
$requested = "$IMAGES_DIRECTORY$_SERVER[REQUEST_URI]";
$sanitized = "$IMAGES_DIRECTORY$dirname/$original_filename-$width$DIVIDER$height.$extension";
// Set to false when resizing and saving is not required.
$update = true;
// If the requested filename and the filename with acceptable dimensions
// differ, then create the file with acceptable dimensions, provided it
// does not already exist.
if( $requested !== $sanitized ) {
if( file_exists( $sanitized ) ) {
// Load up the existing image for sending to the browser.
$image = WideImage::load( $sanitized );
// No need to resize or save.
$update = false;
}
}
if( $update ) {
$image = $image->resize( $width, $height );
}
$image->output( $extension );
if( $update ) {
// Save the file (so that the web server can find it next time). This
// could fail silently, so prefer sending the image before saving it.
$image->saveToFile( $sanitized );
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T06:59:36.253",
"Id": "76203",
"Score": "0",
"body": "Comments such as `Locate the position of the last hyphen in the filename.` don't tell us anything new, and your code might be cleared up without those comments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:24:41.573",
"Id": "76260",
"Score": "0",
"body": "Assuming you do this for mobile, you should consider also passing `quality` to `saveToFile`, it can make a big difference in image size."
}
] | [
{
"body": "<p>This code does not do what the comment says:</p>\n\n<pre><code>// Locate the position of the last hyphen in the filename.\n$index = strpos( $filename, \"-\" );\n</code></pre>\n\n<hr>\n\n<p>Consider parsing the path using a regular expression.</p>\n\n<p>For security, I've explicitly listed the allowed characters for the image filename.</p>\n\n<pre><code># You probably want to analyze PATH_INFO rather than QUERY_STRING\n$path = pathinfo($_SERVER['PATH_INFO']);\nif (!preg_match('!^([A-Za-z0-9_]+)-(\\d+)?x(\\d+)?$!', $path['filename'], $matches)) {\n header('HTTP/1.0 404 Not Found');\n return;\n}\n$orig_image = sprintf('%s%s/%s.%s',\n $IMAGES_DIRECTORY, $path['dirname'],\n $matches[1], $path['extension']);\n$width = $matches[2];\n$height = $matches[3];\nif (!file_exists($orig_image)) {\n header('HTTP/1.0 404 Not Found');\n return;\n}\n\n# That's it for the URL parsing code! Let's get on with the real work!\nserve_image($orig_image, $width, $height);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T06:20:36.207",
"Id": "76409",
"Score": "0",
"body": "Your test has an extra layer of quotes around the regex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T07:35:30.330",
"Id": "76416",
"Score": "1",
"body": "The code works for the three examples stated in your specification. What's the failure? If you want `filename-200.jpg` to be treated as if it were `filename-200x.jpg`, you can easily tweak the regex to make the `x` optional (by putting a question mark after `x`.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:57:09.463",
"Id": "44095",
"ParentId": "44025",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44095",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:29:44.510",
"Id": "44025",
"Score": "4",
"Tags": [
"php",
"security",
"file-system",
"image"
],
"Title": "Security: Scale and cache images"
} | 44025 |
<p>I've created a regular expression (regex) parsing library in C, and would like some feedback on it. Speed is really important to me, but any and all suggestions are acceptable.</p>
<pre><code>#include <ctype.h>
static int regex_matchHere(const char *regex, char *s, int *len);
static int regex_matchGroup(int c, int group);
static int regex_matchQuantity(int quant, int c, const char *regex, char *s, int *len);
int regex_match(const char *regex, char *s, int *len)
{
char *p = s;
/* force match from the beginning of the string */
if (regex[0] == '^') return (regex_matchHere(regex + 1, s, len) ? 0 : -1);
/* iterate the string to find matching position */
do
{
*len = 0;
if (regex_matchHere(regex, p, len)) return (int)(p - s);
} while (*p++ != '\0');
return -1;
}
static int regex_matchHere(const char *regex, char *s, int *len)
{
int c = regex[0];
if (regex[0] == '\0') return 1; /* end of regex = full match */
else if (regex[0] == '$' && regex[1] == '\0') return (*s == '\0'); /* check end of string */
else if (regex[0] == '\\' && regex[1] != '\0') /* check escaped symbol */
{
c = regex[1];
if (c != '^' && c != '$' && c != '\\' && c != '+' && c != '*' && c != '-' && c != '?') c = c | 0x100;
regex = regex + 1;
}
/* check for special operators *,+,?,- */
if (regex[1] == '*' || regex[1] == '+' || regex[1] == '-' || regex[1] == '?') return regex_matchQuantity(regex[1], c, regex+2, s, len);
else if (*s != '\0' && regex_matchGroup(*s, c))
{
*len = *len + 1;
return regex_matchHere(regex+1, s+1, len);
}
return 0;
}
static int regex_matchGroup(int c, int group)
{
if ((group & 0xff) == '.') group ^= 0x100;
if (group < 0x100) return c == group; /* a single char */
/* a meta char, like \d, ... */
switch (group & 0xff)
{
case 'd': return isdigit(c);
case 's': return isspace(c);
case 'D': return !isdigit(c);
case 'S': return !isspace(c);
case '.': return 1;
}
return 0;
}
static int regex_matchQuantity(int quant, int c, const char *regex, char *s, int *len)
{
if (quant == '?')
{
if (regex_matchGroup(*s, c))
{
*len = *len + 1;
s = s + 1;
}
return regex_matchHere(regex, s, len);
}
if (quant == '+' || quant == '*') /* match as much as possible */
{
char *p;
for (p = s; *p != '\0' && regex_matchGroup(*p, c); p++) *len = *len + 1;
if (quant == '+' && p == s) return 0;
do
{
if (regex_matchHere(regex, p, len)) return 1;
*len = *len - 1;
} while (p-- > s);
}
else if (quant == '-') /* match as little as possible */
{
do
{
if (regex_matchHere(regex, s, len)) return 1;
*len = *len + 1;
} while (*s != '\0' && regex_matchGroup(*s++, c));
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:50:03.887",
"Id": "76281",
"Score": "2",
"body": "Although it *can* be divined from the code, it wouldn't hurt to explicitly state the exact sort of regular expressions this is intended to parse/match."
}
] | [
{
"body": "<h3>What you did well</h3>\n\n<p>The code seems clean and logically organized. I like your 0x100-bit hack to indicate special characters. You could make that convention more obvious in the comments, though.</p>\n\n<h3>What you could improve on</h3>\n\n<ol>\n<li><p>The return value of <code>regex_match()</code> is weird. I'd like it to return a non-zero value if the match succeeded, and a zero value if the match failed, so that I can call it like this:</p>\n\n<pre><code>if (regex_match(...)) {\n // Do stuff for successful match\n} else {\n // Do stuff for failed match\n}\n</code></pre>\n\n<p>Trying to return the position of the match just leads to confusion, reminiscent of the way PHP's <a href=\"http://php.net/strpos\"><code>strpos()</code></a> returns 0 to indicate a successful match at the beginning of the subject (but <code>FALSE</code> to indicate a non-match). You don't want to be like PHP, do you?</p>\n\n<p>I suggest that the signature for <code>regex_match()</code> should look like this:</p>\n\n<pre><code>/**\n * Returns 1 if matched, 0 if not matched.\n *\n * Pass a pointer to a match_result if you care to find out the\n * details of the match (its length, position, and possibly other\n * information supported in the future, such as parenthesized\n * capture groups), or pass a NULL if you don't care about the details.\n */\nint regex_match(const char *regex, const char *subject, struct match_result *result);\n</code></pre>\n\n<p>Alternatively, return a pointer to a new <code>struct match_result</code> if the match succeeded. The caller would have to <code>free()</code> the result later, though, so I don't like it as much.</p></li>\n<li><p>Regular expressions often include modifier flags, such as a case-insensitive flag or a continue-searching-where-the-previous-match-ended flag. You might want to plan your interfaces accordingly. (To support the latter, the <code>struct match_result*</code> would probably become an in-out parameter rather than an out-parameter.)</p></li>\n<li><p>For performance, regular expressions are frequently compiled into an automaton. You interpret the regular expressions as you go. You may wish design the library's interface to have a <code>regex_compile()</code> function that transforms the expression into a struct that is meaningful to your library but opaque to the user. For now, the \"compilation\" could just be the identity transformation; you can enhance it later when the need for better performance arises or when you enhance the feature set of the regular expressions.</p></li>\n<li><p>The function name <code>regex_matchGroup()</code> confuses me. \"Group\" implies something like parentheses, I think. <code>regex_matchAtom()</code> might be a more appropriate name.</p></li>\n<li><p>You <em>need</em> unit tests!</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:50:41.980",
"Id": "76214",
"Score": "4",
"body": "This is a nice review, except for the part about the return value – returning an index an expecting the caller to do `if (0 <= regex_match(...))` is perfectly natural. The problem with PHP is that it took a C-ish idiom and messed it up by returning `false` instead of `-1`, but that does not discredit the original idiom."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T05:55:05.933",
"Id": "44033",
"ParentId": "44027",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "44033",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T03:47:55.470",
"Id": "44027",
"Score": "12",
"Tags": [
"performance",
"c",
"parsing",
"regex",
"library"
],
"Title": "A regular expression parsing library in C"
} | 44027 |
<p>Here is what I'm trying:</p>
<p>Please review the code:</p>
<pre><code>function quicklyChangePageTitle() {
var currentTitle = document.title; // remember original title
document.title = "temp title"; // change to the temporary title
setTimeout(function() { // revert back to original title
document.title = currentTitle;
}, 1);
}
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.keyCode == 68) { // Ctrl + D
quicklyChangePageTitle();
}
});
</code></pre>
| [] | [
{
"body": "<p>That seems like a very fragile thing to do. If it works at all, you would still only succeed on browsers where the keyboard shortcut is <kbd>Control</kbd><kbd>D</kbd>. It probably won't work on a Mac or on a mobile device. It will probably break if the user interface is in a non-English locale with different keyboard shortcuts. It would also have no effect if the user initiates the bookmark creation using the menu rather than a keyboard shortcut.</p>\n\n<p>You should probably step back and consider why such a hack is necessary in the first place. Ideally, you should design the page titles such that they already make reasonable bookmark titles.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T04:24:24.423",
"Id": "44030",
"ParentId": "44029",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44030",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T04:15:14.980",
"Id": "44029",
"Score": "2",
"Tags": [
"javascript",
"timer",
"event-handling"
],
"Title": "Auto change page title while bookmarking a page"
} | 44029 |
<p>I'm wondering if it's bad practice to couple my DTO to my domain object like this and pass the object itself into <code>Create()</code>. Is it better to just give the parameters needed to perform the creation?</p>
<pre><code>public static Playlist Create(PlaylistDto playlistDto, IUserManager userManager, IPlaylistManager playlistManager)
{
Playlist playlist = new Playlist
{
Id = playlistDto.Id,
Items = PlaylistItem.Create(playlistDto.Items, playlistManager),
Sequence = playlistDto.Sequence,
Title = playlistDto.Title,
User = userManager.Get(playlistDto.UserId)
};
return playlist;
}
</code></pre>
| [] | [
{
"body": "<p>If the Playlist is an external dependency then it might make sense to use an extension method like:</p>\n\n<pre><code>public static Playlist Create(this PlaylistDto playlistDto, IUserManager userManager, IPlaylistManager playlistManager)\n{\n Playlist playlist = new Playlist\n {\n Id = playlistDto.Id,\n Items = PlaylistItem.Create(playlistDto.Items, playlistManager),\n Sequence = playlistDto.Sequence,\n Title = playlistDto.Title,\n User = userManager.Get(playlistDto.UserId)\n };\n\n return playlist;\n}\n</code></pre>\n\n<p>other than that, if the code is under your control, why not just make another constructor and do away with the static method</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T05:54:23.833",
"Id": "44032",
"ParentId": "44031",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T05:16:35.763",
"Id": "44031",
"Score": "2",
"Tags": [
"c#",
"dto"
],
"Title": "Passing a DTO into a static domain 'Create' method"
} | 44031 |
<p>This is a follow up to the following questions:</p>
<p><a href="https://codereview.stackexchange.com/q/36482/18427">RPSLS Game in C#</a></p>
<p><a href="https://codereview.stackexchange.com/q/43965/18427">Ensuring user input is an integer in a range</a></p>
<p>I haven't made my way to <code>DecideWinner()</code> yet, but that is next on my To-Do List. I would like the majority of the focus to go into what I have done with the rest of the code, but would still enjoy some input on what to do with my nasty <code>if then else</code> statements. </p>
<p>I did not change to using an Enumeration for my <code>Gestures</code>. I read the Microsoft page for Enumeration and it didn't seem like it would be a good fit, maybe I didn't understand fully though either.</p>
<p>I also used <code>while</code> loops instead of <code>do while</code> loops because I like them better. not really a good reason I guess other than that I prefer <code>while</code> loops.</p>
<p>I am not afraid to say that I am still learning, so here is the code:</p>
<pre><code>/// <summary>
/// Thanks to
/// https://codereview.stackexchange.com/users/38054/benvlodgi
/// https://codereview.stackexchange.com/users/4318/eric-lippert
/// https://codereview.stackexchange.com/users/23788/mats-mug
/// https://codereview.stackexchange.com/users/30346/chriswue
/// </summary>
namespace RPSLSGame
{
class MainClass
{
public static void Main (string[] args)
{
/* Here are your rules:
"Scissors cuts paper,
paper covers rock,
rock crushes lizard,
lizard poisons Spock,
Spock smashes scissors,
scissors decapitate lizard,
lizard eats paper,
paper disproves Spock,
Spock vaporizes rock.
And as it always has, rock crushes scissors."
-- Dr. Sheldon Cooper */
List<string> Gestures = new List<string>{"rock","paper","scissors", "lizard","spock"};
int win = 0;
int lose = 0;
int tie = 0;
var newGame = true;
while (newGame)
{
var playerGesture = "";
Console.WriteLine("Please choose your Gesture ");
PrintMenu(Gestures);
playerGesture = Gestures[PromptForNumber("Please choose your gesture",1,Gestures.Count)-1];
var computerPlay = GetRandomOption(Gestures);
Console.WriteLine ("Computer: " + computerPlay);
Console.WriteLine ("your Gesture: " + playerGesture);
if (playerGesture == computerPlay)
{
tie++;
Console.WriteLine ("you have tied with the computer");
Console.WriteLine ("Computer: " + computerPlay);
Console.WriteLine ("your Gesture: " + playerGesture);
}
else
{
if (playerGesture == "rock")
{
if (computerPlay == "lizard" || computerPlay == "scissors")
{
Console.WriteLine ("You Win, " + playerGesture + " Crushes " + computerPlay);
win++;
}
else if (computerPlay == "paper")
{
Console.WriteLine ("You Lose, Paper Covers Rock");
lose++;
}
else if (computerPlay == "spock")
{
Console.WriteLine ("You Lose, Spock Vaporizes Rock");
lose++;
}
}
else if (playerGesture == "paper")
{
if (computerPlay == "spock")
{
Console.WriteLine ("You Win, Paper Disproves Spock");
win++;
}
else if (computerPlay == "rock")
{
Console.WriteLine ("You Win, Paper Covers Rock");
win++;
}
else if (computerPlay == "lizard")
{
Console.WriteLine ("You Lose, Lizard Eats Paper");
lose++;
}
else if (computerPlay == "scissors")
{
Console.WriteLine ("You Lose, Scissors Cut Paper");
lose++;
}
}
else if (playerGesture == "scissors")
{
if (computerPlay == "paper")
{
Console.WriteLine ("You Win, Scissors Cut Paper");
win++;
}
else if (computerPlay == "lizard")
{
Console.WriteLine ("You Win, Scissors Decapitate Lizard");
win++;
}
else if (computerPlay == "rock")
{
Console.WriteLine ("You Lose, Rock Crushes Scissors");
lose++;
}
else if (computerPlay == "spock")
{
Console.WriteLine ("You Lose, Spock Smashes Scissors");
lose++;
}
}
else if ( playerGesture == "lizard")
{
if (computerPlay == "paper")
{
Console.WriteLine ("You Win, Lizard Eats Paper");
win++;
}
else if (computerPlay == "spock")
{
Console.WriteLine ("You Win, Lizard Poisons Spock");
win++;
}
else if (computerPlay == "scissors")
{
Console.WriteLine ("You Lose, Scissors Decapitates Lizard");
lose++;
}
else if (computerPlay == "rock")
{
Console.WriteLine ("You Lose, Rock Crushes Lizard");
lose++;
}
}
else if (playerGesture == "spock")
{
if (computerPlay == "rock")
{
Console.WriteLine("You Win, Spock Vaporizes Rock");
win++;
}
else if (computerPlay == "scissors")
{
Console.WriteLine ("You Win, Spock Smashes Scissors");
win++;
}
else if (computerPlay == "paper")
{
Console.WriteLine ("You Lose, Paper Disproves Spock");
lose++;
}
else if (computerPlay == "lizard")
{
Console.WriteLine("You Lose, Lizard Poisons Spock");
lose++;
}
}
}
Console.WriteLine ("Your Score is (W:L:T:) : {0}:{1}:{2}", win, lose, tie);
if(!Choice ("Would you like to play again? Y/N"))
{
if (Choice("Would you like to reset your score?"))
{
win = 0;
lose=0;
tie=0;
}
if (!Choice ("Would you like to play another game?"))
{
newGame=false;
}
}
}
Console.WriteLine("Goodbye");
Console.ReadLine ();
}
public static void DecideWinner ()
{
//TODO: Create Method for Deciding the Winner.
}
static int PromptForNumber (string prompt, int lower, int upper)
{
int? pick = null;
while (pick == null) {
Console.WriteLine(prompt);
pick = Console.ReadLine().BoundedParse (lower, upper);
}
return pick.Value;
}
public static void PrintMenu (List<string> List)
{
for (int i=0; i<List.Count; i++) {
Console.WriteLine ((i+1) + ": " + List[i]);
}
}
public static string GetRandomOption (List<string> options)
{
Random rand = new Random();
return options[rand.Next(0,options.Count)];
}
public static Boolean Choice (string prompt)
{
while(true)
{
Console.WriteLine (prompt);
switch (Console.ReadKey (true).Key)
{
case ConsoleKey.Y:
{
Console.Write ("Y\n");
return true;
}
case ConsoleKey.N:
{
Console.Write ("N\n");
return false;
}
}
}
}
}
static class Extensions
{
/// <summary>
/// Parses the Input for an Integer between the lower and upper bounds
/// </summary>
/// <returns>
/// null or integer
/// </returns>
/// <param name='str'>
/// String to be parsed for an Integer
/// </param>
/// <param name='lower'>
/// Lower Bound of the Acceptable range of input integers
/// </param>
/// <param name='upper'>
/// Upper bound of the acceptable range of the input integers
/// </param>
public static int? BoundedParse (this string str, int lower, int upper)
{
if (str == null) {
return null;
}
int result;
bool success;
success = int.TryParse (str, out result);
if (!success) {
return null;
}
if (result < lower) {
return null;
}
if (result > upper) {
return null;
}
return result;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:29:32.143",
"Id": "76213",
"Score": "1",
"body": "have you seen the update from BenVlodgi on your old question? http://codereview.stackexchange.com/a/43654/37660"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:43:31.040",
"Id": "76249",
"Score": "0",
"body": "are you talking about figuring out the `DecideWinner` method? I just haven't gotten to that method yet. I like the tuple idea, but there was something that someone said on someone else's RPSLS post that really stuck with me that I want to try."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:09:35.047",
"Id": "76311",
"Score": "1",
"body": "@Malachi: As this is presumably a learning exercise, you could also try playing with something like [stateless](http://code.google.com/p/stateless/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:19:45.193",
"Id": "76314",
"Score": "0",
"body": "@Brian, that might take me a little time to figure out, but looks like a lot of fun as well. are you talking about using this for the `DecideWinner` method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:07:40.390",
"Id": "76341",
"Score": "0",
"body": "Yes. I admit that using stateless for `DecideWinner` is massive overkill, but from a learning perspective it makes for a fun approach."
}
] | [
{
"body": "<p>I like the <code>while</code> loop. It states the exit condition from the start, so you know right away what you're getting yourself into.</p>\n\n<p>However I don't like the multi-screen <code>if</code> block.</p>\n\n<p>What if you had a method to handle each of the player's possible moves? Say you have a method to increment losses and another to increment wins - you'd have to promote <code>win</code>, <code>lose</code> and <code>tie</code> to instance variables for this to work:</p>\n\n<pre><code>private void PlayerWins(string playerGesture, string verb, string computerGesture)\n{\n win++;\n Console.WriteLine (\"You Win, {0} {1} {2}\", playerGesture, verb, computerGesture);\n}\n\nprivate void ComputerWins(string computerGesture, string verb, string playerGesture)\n{\n lose++;\n Console.WriteLine (\"You Lose, {0} {1} {2}\", computerGesture, verb, playerGesture);\n}\n\nprivate void NobodyWins()\n{\n tie++;\n Console.WriteLine (\"Tie!\");\n}\n</code></pre>\n\n<p>Then you could have a method to handle each player moves:</p>\n\n<pre><code>private void PlayRock(string computerGesture)\n{\n var playerGesture = \"rock\";\n if (computerGesture == \"lizard\" || computerGesture == \"scissors\")\n {\n PlayerWins(playerGesture, \"crushes\", computerGesture);\n }\n else if (computerGesture == \"paper\")\n {\n ComputerWins(computerGesture, \"covers\", playerGesture);\n }\n else if (computerGesture == \"spock\")\n {\n ComputerWins(computerGesture, \"vaporizes\", playerGesture);\n }\n}\n</code></pre>\n\n<p>And then your main loop could \"branch\" on a method depending on the player's move - you can set up a <code>Dictionary<string,Action<string>></code> to do that (<code>Action<string></code> is a delegate that returns <code>void</code> and takes a <code>string</code> parameter.. which matches the signatures of your <code>PlayXXXXX</code> methods):</p>\n\n<pre><code>var plays = new Dictionary<string,Action<string>> {\n { \"rock\", PlayRock },\n { \"paper\", PlayPaper },\n { \"scissors\", PlayScissors },\n { \"lizard\", PlayLizard },\n { \"spock\", PlaySpock }\n };\n</code></pre>\n\n<p>This way you can invoke the appropriate <code>Action</code> delegate simply by getting the dictionary entry for the <code>playerGesture</code>:</p>\n\n<pre><code>plays[playerGesture](computerGesture);\n</code></pre>\n\n<p>...this invocation replaces the entire <code>if</code> block in the main loop, and as a bonus you now have a separate method for each playable move.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:52:47.453",
"Id": "44076",
"ParentId": "44034",
"Score": "10"
}
},
{
"body": "<p>I agree with Mat's Mug that the huge if-block in the middle of the loop makes the loop hard to read. I'd factor that out into its own method.</p>\n\n<p>I'd also think about ways to minimize that huge if-block into something smaller. </p>\n\n<p>Let's consider the nature of rock-paper-scissors-spock-lizard. If we assign numbers </p>\n\n<pre><code>rock = 0\npaper = 1 \nscissors = 2\nspock = 3\nlizard = 4\n</code></pre>\n\n<p>then (assuming you've already taken out ties) <code>x</code> beats <code>y</code> can be computed as </p>\n\n<pre><code>bool xWins = (((y + 5 - x) % 5) % 2) == 0;\n</code></pre>\n\n<p>Try it: if x is scissors (2) and y is lizard (4) then <code>y + 5 - x</code> is 7, that gives remainder 2 when divided by 5, and that gives remainder 0 when divided by 2, so the expression is true, and in fact scissors does beat lizard.</p>\n\n<p>You can use this formula to greatly simplify the computation of whether the player wins, ties or loses. Once you know that, you can use a table lookup to figure out what \"x beats y\" message to display.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:56:01.570",
"Id": "76305",
"Score": "1",
"body": "This formula is highly non-obvious (at least to me). Encoding the who-wins-who into a data structure would be very much preferable, but even the original code has the advantage over your shortcut that it's easy to understand and extend. This is Code Review, not Code Golf ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:04:05.483",
"Id": "76307",
"Score": "3",
"body": "@amon: I agree that it is non-obvious. RPS-like games have the following structure: we agree on an odd number, let's say 5. Now we both pick a number from 0 through 4. We take their difference mod 5, producing a game number that is also between 0 and 4. If the game number is zero then we tie. Otherwise, we have 1, 2, 3 or 4 to divide between us. I take the evens, you take the odds, and there's therefore a 50-50 chance for each of us, so its a fair game. Now does the formula make sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:08:17.527",
"Id": "76309",
"Score": "1",
"body": "@amon: Now all we have to do is assign funny names to each choice and order them such that the formula produces an \"x beats y\" relationship that makes sense with the funny names. But that's just window dressing; the game fundamentally is \"pick two numbers, take their difference, assign half the possible differences to each side\" whether it is rock-paper-scissors, cowboy-ninja-bear or rock-paper-scissors-spock-lizard-dog-gun."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:16:31.063",
"Id": "76312",
"Score": "0",
"body": "@EricLippert: Your formula starts seeming more reasonable once you have a massive enough set of RPS choices (e.g., for RPS-101). However, if you're already storing verbs in a matrix, sticking the results in the table strikes me as more reasonable. The formula is a result of your table design, rather than the reverse. You can make the existence of such a formula more obvious by arranging your matrix so that the formula is visible in the table itself (probably by ensuring that the cells marked as \"win\" form a parallelogram). Bonus points if the table is loaded from disk."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:23:15.767",
"Id": "76319",
"Score": "0",
"body": "I was thinking about something like a table (multiplication style) as well, because I think that would be easier to visualize while coding, but I am not sure how to set that up. but a two dimensional array sounds about right, right now. I will try to code that tonight and then post it as an answer here if I can get it to work the way I am hoping that it will"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:29:15.573",
"Id": "76322",
"Score": "0",
"body": "I think others have been suggesting something similar to what I am thinking of"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:36:08.283",
"Id": "76326",
"Score": "4",
"body": "Although it is a functional formula, I wouldn't use it. Not only because it can be considered obfuscation, but mostly because it would break the logic if you wanted to switch the order of the items. Trust me, [**it has happened before**](http://codereview.stackexchange.com/questions/36916/weekend-challenge-poker-hand-evaluation#comment60836_36936)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:52:14.557",
"Id": "76344",
"Score": "4",
"body": "@SimonAndréForsberg: That's an excellent point; you'd need to make sure that the number associated with an action *for the purposes of the calculation* and the number associated with *the order in which they are displayed* are carefully made distinct."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:27:46.570",
"Id": "44078",
"ParentId": "44034",
"Score": "6"
}
},
{
"body": "<p>Some of what I say may be repeats of what I said in my <a href=\"https://codereview.stackexchange.com/a/43654/38054\">original review</a>.</p>\n\n<ol>\n<li><p>Rename your <code>win</code>, <code>lose</code>, <code>tie</code> counters to <code>_wins</code>, <code>_loses</code>, <code>_ties</code>. They should be plural, underscore is optional. It is easy to mass rename variables in VS, just click on the variable in the text editor and press <kbd>Ctrl</kbd> + <kbd>R</kbd> + <kbd>R</kbd> and a dialog will popup which will allow you to rename that symbol through your whole project.</p></li>\n<li><p>Remove that massive if-else block in the middle of your program, it looks as though you were going to separate that out and use the <code>DecideWinner</code> method you created. Here again is how I did it before with my original review.</p>\n\n<pre><code>switch (WhoWon(playerGesture, computerGesture))\n{\n case 0: ties++; Console.WriteLine(\"You have tied with the the computer.\"); break;\n case 1: wins++; Console.WriteLine(\"You win, \" + GetReason(playerGesture, computerGesture)); break;\n case 2: loses++; Console.WriteLine(\"You lose, \" + GetReason(computerGesture, playerGesture)); break;\n}\n</code></pre></li>\n<li><p>From a usability standpoint, it is annoying to a user when they have to answer the same question twice. In this case, after playing a game, they are asked twice if they want to quit. I've re-written the end of your loop to better handle this situation.</p>\n\n<pre><code>Console.WriteLine(\"Your Score is (W:L:T:) : {0}:{1}:{2}\", win, lose, tie);\n\nnewGame = Choice(\"Would you like to play another game?\");\n\nif (newGame && Choice(\"Would you like to reset your score?\"))\n win = lose = tie = 0;\n</code></pre>\n\n<p>Now the user is only asked once if they want to play again, and if they do choose to play again, only then are they asked if they want to reset their score.</p></li>\n<li><p>Instead of using a <code>nullable int</code>, I decided to follow the pattern used by Microsoft with their <code>TryParse</code> </p>\n\n<pre><code>static class Extensions\n{\n /// <summary>Tries to parse the string, returning true if successful and if the parsed value falls between the given bounds.</summary>\n /// <param name=\"str\">The string to parse.</param>\n /// <param name=\"lower\">The lower bound.</param>\n /// <param name=\"upper\">The upper bound.</param>\n /// <param name=\"value\">The parsed value.</param>\n public static bool TryBoundedParse(this string str, int lower, int upper, out int value)\n {\n return int.TryParse(str, out value) && value >= lower && value <= upper;\n }\n}\n</code></pre>\n\n<p>This would result in your <code>PromptForNumber</code> looking like this.</p>\n\n<pre><code>public static int PromptForNumber (int min = int.MinValue, int max = int.MaxValue, string prompt = \"Please enter an Integer: \")\n{\n int parsedValue;\n do { Console.Write(prompt); }\n while (!Console.ReadLine().TryBoundedParse(min, max, out parsedValue));\n return parsedValue;\n}\n</code></pre>\n\n<p>If you do still want to use the <code>BoundedParse</code> Method you could simplify it by writing it like this instead. Which simply sums up all of your conditions into one statement, and doesn't utilize early returns as I know you like to avoid.</p>\n\n<pre><code>public static int? BoundedParse(this string str, int lower, int upper)\n{\n int result;\n return (int.TryParse(str, out result) && result >= lower && result <= upper) ? (int?)result : null;\n}\n</code></pre></li>\n<li><p>In your <code>GetRandomOption</code> you can inline the creation of the Random object with your call to get a random option, which would save you a whole line of code :P</p>\n\n<pre><code>public static string GetRandomOption(List<string> options)\n{\n return options[new Random().Next(0, options.Count)];\n}\n</code></pre></li>\n<li><p>The Choice method does not need to use the { brackets } because switch statements end when there is a <code>break</code> or a <code>return</code>. So you can write it like this</p>\n\n<pre><code>Console.WriteLine(prompt);\nswitch (Console.ReadKey(true).Key)\n{\n case ConsoleKey.Y:\n Console.Write(\"Y\\n\");\n return true;\n case ConsoleKey.N:\n Console.Write(\"N\\n\");\n return false;\n}\n</code></pre>\n\n<p>However it looks way cooler if you just one line the case statements because they have identical layouts and similar functionality. Which makes it easy to distinguish between the statements at a glance and use a DO-WHILE!... because they're awesome.</p>\n\n<pre><code>public static Boolean Choice(string prompt)\n{\n do\n {\n Console.WriteLine(prompt);\n switch (Console.ReadKey(true).Key)\n {\n case ConsoleKey.Y: Console.Write(\"Y\\n\"); return true;\n case ConsoleKey.N: Console.Write(\"N\\n\"); return false;\n }\n } while (true);\n}\n</code></pre></li>\n<li><p>Use <code>enums</code> from the start and not a list of <code>strings</code>. Then just look at my entire <a href=\"https://codereview.stackexchange.com/a/43654/38054\">suggested implementation</a> using <code>enums</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:53:39.960",
"Id": "76332",
"Score": "0",
"body": "I actually tried Number 5 and the Compiler didn't like it. or maybe I tried to make it Global...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:55:21.830",
"Id": "76334",
"Score": "0",
"body": "@Malachi making it class level and/or the way I showed both work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:59:43.657",
"Id": "76335",
"Score": "0",
"body": "I was actually thinking that I should move the reset question before the new game question. and possibly give the user a \"don't show this again\" option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:01:00.023",
"Id": "76336",
"Score": "0",
"body": "I think I went to high on the scope ladder, I will try it again later, because if I want to use another random number somewhere I shouldn't just create another *Random* object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:01:51.980",
"Id": "76337",
"Score": "1",
"body": "@Malachi try running your program with just that updated... you'll find it is nicer, and to be honest it would be more annoying if you asked them every time to never show this again, thats just an extra prompt to say no to. Although to be honest they will probably say yes just to avoid 2 popups, which will mean they will then forever lose that option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T07:09:36.023",
"Id": "76414",
"Score": "2",
"body": "just a tip. you can create keyboard keys by using the pseudotag <kbd>"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:49:08.417",
"Id": "44088",
"ParentId": "44034",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "44088",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T06:04:57.877",
"Id": "44034",
"Score": "12",
"Tags": [
"c#",
"beginner",
"game",
"community-challenge",
"rock-paper-scissors"
],
"Title": "RPSLS is less messy now, but is it clean?"
} | 44034 |
<p>While trying to learn some more C, I decided to implement a linked list and perform a few operations on it.</p>
<p>The first thing I wanted to do was read from a .csv of numbers (ex: 1,2,3,...) and store the numbers in a Linked List. </p>
<p>Once I have the linked list, I want to reverse the linked list and then I want the user to be prompted with the number to remove from the linked list. </p>
<p>Upon receiving the value, the removal operation will search for the value within the linked list and remove it. </p>
<p>After removal, the contents of the linked list will be printed out. </p>
<p>Can somebody look at what I have and give me some pointers on what I did wrong and how I can make it better? One thing I am rather worried about is how I am handling memory allocation and what I am doing is causing any memory leaks.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
//Defining the linked list struct
typedef struct node{
int data;
struct node* next;
} LList;
//Method to print out the values in a linked list
void printList(LList * head){
LList* current = head;
while(current != NULL){
printf("%d -> ",current->data);
current = current->next;
}
printf(" NULL\n");
}
//Method to reverse a linked list
LList* reverse(LList * head,LList * reverseHead){
LList * current = head;
while(current != NULL){
if(reverseHead == NULL){
LList * temp = malloc(sizeof(LList));
temp -> data = current -> data;
temp -> next = NULL;
current = current -> next;
reverseHead = temp;
}else{
LList * temp = malloc(sizeof(LList));
temp -> data = current -> data;
current = current -> next;
temp -> next = reverseHead;
reverseHead = temp;
}
}
return reverseHead;
}
//Method to remove an element from the list
LList* removeFromList(LList *head, int elem){
LList * current = head->next;
LList * prev = head;
LList * modifiedList = head;
while(current != NULL){
if(head -> data == elem){
head -> data = head -> next -> data;
head -> next = head -> next -> next;
return modifiedList;
}
else if(current-> data == elem){
prev -> next = current -> next;
return modifiedList;
}else{
prev = prev -> next;
current = current -> next;
}
}
printf("\nEntry %d not found\n",elem);
return modifiedList;
}
void listRemoverRunner(LList * head){
//While user doesn't enter q
//Prompt for the element that needs to be removed
//Call List removal that takes the current list and value and removes the
//value from the List
char buf[100];
printf("\nEnter list entry to delete(from the original list, not the reversed), exit by entering 'q'\n");
while (fgets(buf, sizeof buf, stdin) != NULL) {
if (buf[0] == 'q') {
break;
}
char *end;
int listEntry = (int) strtol(buf, &end, 0);
printf("\nRemoving entry %d from the list\n",listEntry);
removeFromList(head,listEntry);
printf("\nList after removal of entry %d\n",listEntry);
printList(head);
}
}
int main(){
LList *head = NULL;
LList *current = NULL;
FILE * input;
int digit;
//head = malloc(sizeof(LList));
//Read the input from the file
input = fopen("input.txt","r");
//For each integer read, store the value in the linked list
if(input){
while(fscanf(input,"%d,",&digit)!= EOF){
//printf("The number is %d\n",digit);
LList *temp = malloc(sizeof(LList));
temp -> data = digit;
if(head == NULL){
//printf("Adding the digit %d to the list\n",digit);
head = temp;
current = head;
temp = NULL;
current -> next = NULL;
}else{
//printf("Adding the digit %d to the list\n",digit);
current -> next = temp;
current = temp;
current -> next = NULL;
}
}
}
//Close the file
fclose(input);
//Print the values in the linked list
printf("\nPrinting out the original linked list\n");
printList(head);
//Reverse the original linked list
LList * reversedList = NULL;
reversedList = reverse(head,reversedList);
//Print the reversed linked list
printf("\nPrinting out the reversed linked list\n");
printList(reversedList);
listRemoverRunner(head);
}
</code></pre>
| [] | [
{
"body": "<p>I have 5 Suggestions.</p>\n\n<ul>\n<li>No need to pass the <strong>reverseHead</strong> in <code>LList* reverse(LList * head,LList * reverseHead)</code> method</li>\n</ul>\n\n<p>Change that to:</p>\n\n<pre><code>LList* reverse(LList * head)\n</code></pre>\n\n<ul>\n<li>There is <strong>memory leaks</strong> in your code. When you are removing an entry from the linked list, you need to release the memory associated with that node.</li>\n<li>I won't prefer <strong>multiple return statements</strong> from a method</li>\n<li>There are a lot of <strong>wild pointers</strong> is your code. wild pointers are dangerous, so whenever you declare a pointer, initialize it (At-least initialize it with <code>NULL</code>)</li>\n<li>For the current purpose I don't think you need this statement <code>fgets(buf, sizeof buf, stdin)</code>. Instead, you can use <code>gets(buf)</code>.</li>\n</ul>\n\n<p>You can change your <code>removeFromList</code> method like:</p>\n\n<pre><code>LList* removeFromList(LList *head, int elem)\n{\n LList * current = head->next;\n LList * prev = head;\n LList * modifiedList = head;\n LList * deleteNode = NULL;\n int flag = 1;\n while((prev != NULL) && flag)\n {\n if(head -> data == elem)\n {\n if(head->next != NULL)\n {\n head -> data = head -> next -> data;\n deleteNode = head->next;\n head -> next = head -> next -> next;\n }\n else\n {\n deleteNode = head;\n modifiedList = NULL;\n }\n flag = 0;\n }\n else if(current-> data == elem)\n {\n deleteNode = prev->next;\n prev -> next = deleteNode -> next;\n flag = 0;\n }\n else\n {\n prev = prev -> next;\n }\n }\n if (flag)\n {\n printf(\"\\nEntry %d not found\\n\",elem);\n }\n free(deleteNode);\n deleteNode = NULL;\n return modifiedList;\n}\n</code></pre>\n\n<p>And change the method calls like:</p>\n\n<pre><code>head = removeFromList(head,listEntry);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T06:38:55.373",
"Id": "44037",
"ParentId": "44035",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44037",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T06:05:36.407",
"Id": "44035",
"Score": "5",
"Tags": [
"c",
"linked-list",
"memory-management"
],
"Title": "Linked List implementation and manipulations in C"
} | 44035 |
<pre><code>def uniop_nested(func,o_list):
def inner(i_list):
if isinstance(i_list[0],np.ndarray):
return map(func, i_list)
else:
return map(inner, i_list)
return inner(o_list)
def binop_nested(func, o1, o2):
if not isinstance(o1,np.ndarray):
return [binop_nested(func, i1, i2) for (i1,i2) in zip(o1,o2)]
else:
return func(o1,o2)
def add_nested(s1,s2):
return binop_nested(np.add,s1,s2)
</code></pre>
<p>My code need to work with lists of <code>ndarrays</code> and list of lists of <code>ndarrays</code>. Profiling shows this is some of the most performance critical code in my project.</p>
<ol>
<li>How can I optimise it?</li>
<li>Can I rewrite the recursion as a loop?</li>
<li>Is there nice way to rewrite, them as Cython or a C extention? (I have no experience with this)</li>
</ol>
<p>My Stack Overflow question here indicates <a href="https://stackoverflow.com/questions/22291526/fast-array-list-type-for-holding-numpy-ndarrays">that changing datatypes is probably not going to the solution.</a></p>
<p>More info:</p>
<ul>
<li>Operands (o1 o2, s1, s2) are short lists. Profiling has shown me that using <code>it.izip</code> is slower.</li>
<li>Function return results are unlikely to be repeated. As the ndarrays are full of floats being tweaked with mathematical operations based of floats. (We are talking a large segment of R<sup>n</sup> possible values)</li>
<li>Functions being applied are simple, the <code>add_nested</code> is the most common op by far, but there are a few onthers like <code>uniop_nested(np.zeros_like, o_list)</code>.</li>
<li>ndarrays are of different sizes/shapes. (so a multidimentional ndarray won't work)</li>
</ul>
<p><strong>Context:</strong><br>
This is being used for training Restricted Boltzmann Machines (RBMs) and Neural network. <br>
I have a generic "Trainer" class, <br>
that takes a Trainee class as a parameter. <br>
the Trainee class exposes a few methods like: </p>
<ul>
<li>Get_update_gradient - a function that returns (for a RBM [Restricted Boltzmann Machine]) a list containing a ndarray of weight changes and 2 ndarrays of bias changes, or (for a multilayer neural net) a list containing a list of weight matrix changes and a list of bias changes</li>
<li>knowledge: a property exposing either a list containing (for a RBM) a 2 bias arrays and a weight matrix or (for a neural net) a list of weight matrixes and bias arrays</li>
</ul>
<p>It may seem that the Trainer class is simple, and unnesc, however it is moderately complex, and its use is common between the RBM and neural net classes. (Both benefit from the use of momentum and minibatchs)
A typical use is: </p>
<pre><code>trainee.knowledge = binop_nested(lambda current_value,update: learning_rate*update+current_value, trainee.knowledge, updates)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:02:49.790",
"Id": "76215",
"Score": "1",
"body": "If you're mostly interested in lists of ndarrays, why not replace recursion with a simple loop without all the 'isinstance' stuff?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:58:46.233",
"Id": "76222",
"Score": "0",
"body": "arager: Because it need to dig down the list (of list) til it gets down to ndArrays"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:03:45.150",
"Id": "76234",
"Score": "0",
"body": "Another idea - if you know in advance at which depth the list turns into ndarray, pass that depth as an extra argument. I feel that `isinstance` is what causing the performance hit. Getting rid of branching would be better though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:38:56.107",
"Id": "76239",
"Score": "0",
"body": "Hmm, could be done (for certian parts at least), it means tracking a state variable though. conviently in the palce this can be done, there is very few statevariables, so it isn't too bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:26:53.043",
"Id": "76246",
"Score": "1",
"body": "Does the profiling tell you how much time is spent in this code vs. in the `func` called from here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:12:37.003",
"Id": "76464",
"Score": "1",
"body": "still not clear what you are trying to do, can you just give a simple example of what you are trying to do, and what the expected result is? With real functions and a chunk of your real data, since right now it still sounds a bit too fuzzy/abstract/..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T14:19:11.517",
"Id": "77118",
"Score": "0",
"body": "I agree with @usethedeathstar. You need to give us more context so we can understand what you are trying to achieve. Iterating over a list of `ndarray` is usually an anti-pattern (better to use a multi-dimensional `ndarray` if possible)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T14:37:33.263",
"Id": "77120",
"Score": "0",
"body": "Ok, I hopefully I have added as much context as I can.\n(I'm out of ideas for what other useful information i can give)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:16:33.133",
"Id": "77553",
"Score": "0",
"body": "@Oxinabox: What is \"tringing\"? (Typo for \"training\"?) What is an RBM? (A Restricted Boltzmann machine?) What is an RMB? (Typo for \"RBM\"?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T12:21:33.297",
"Id": "77555",
"Score": "0",
"body": "@GarethRees: Fixed. Your guesses were correct. Thanks."
}
] | [
{
"body": "<p>For recursion, you can try adding an @memoize decorator to it, to speed it up. </p>\n\n<pre><code>import functools\n\ndef memoize(f):\n cache= {}\n @functools.wraps(f)\n def memf(*x):\n if x not in cache:\n cache[x] = f(*x)\n return cache[x]\n return memf\n</code></pre>\n\n<p>Not sure if in your case it will speed up a lot, but if you try with fibonacci, you will see that it vastly speeds up the recursions, since it caches previous results. </p>\n\n<p>This is something that speeds up recursion things in general. For your specific case, we need a bit more info, on what your functions are, and what you want to achieve to get a more specific answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:59:33.440",
"Id": "76223",
"Score": "0",
"body": "Won't work as this is not a pure function. It has state. Actually it might be pure. But in anycase the same result is almpst never returned twice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:09:14.953",
"Id": "76226",
"Score": "0",
"body": "Added more info to question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:02:59.723",
"Id": "76451",
"Score": "1",
"body": "@Oxinabox, not sure what's that about \"not a pure function,\" but the function decorated with this `memoize` **does** always return the same output for the same input arguments (which have a limitation that they must be [hashable](http://docs.python.org/2/glossary.html#term-hashable) or [immutable](http://docs.python.org/2/glossary.html#term-immutable))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T06:03:45.607",
"Id": "76650",
"Score": "0",
"body": "Memorisation can only be done on Pure Functions:\nhttp://en.wikipedia.org/wiki/Pure_function\n\nIn my case the functions may be pure (maybe),\nbut it doesn't matter because I never call the function with the same inputs twice. \n\nMemoration is a great technique, for recursive functions, under the right circumstances.\nUnfortunatly for me, this is not them.\n(Not saying antyhing is wrong with your answer though, I +1 it)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:58:45.727",
"Id": "44045",
"ParentId": "44039",
"Score": "2"
}
},
{
"body": "<p>Cython function calls are much faster.\n(I suspect cython type checking is too).</p>\n\n<p>I recompiled your code with cython,\na simple matter of changing they file name to <code>.pyx</code>,\nadding: <code>cimport cython</code> to the top,\nand <a href=\"http://docs.cython.org/src/reference/compilation.html#compilation-reference\" rel=\"nofollow noreferrer\">compiling it</a></p>\n\n<p>Here is a simple test:</p>\n\n<pre><code>a = np.arange(788)\nb = np.asarray([0.01]*200)\nvalues = [[a,0.1*a,0.01*a],[a,0.1*a,0.01*a],b,b]\n\n%timeit add_nested(values,values) #Define in this IPython notebook\n10000 loops, best of 3: 32 µs per loop\n%timeit c_add_nested(values,values) #Define in this IPython notebook with cythonmagic\n10000 loops, best of 3: 32 µs per loop\n%timeit numpyutil.add_nested(values,values) #In a seperate file called numpyutil.pyx/so\n10000 loops, best of 3: 32 µs per loop\n</code></pre>\n\n<p>That is about a 25% speed increase.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-12T07:33:24.117",
"Id": "44130",
"ParentId": "44039",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:21:51.973",
"Id": "44039",
"Score": "4",
"Tags": [
"python",
"optimization",
"recursion",
"numpy",
"cython"
],
"Title": "Recursive function, high performance critical"
} | 44039 |
<p>I have a WPF/MVVM form that contains sections for managing Recipient Contacts, CC Contacts and BCC Contacts.</p>
<p>Each of the three sections has buttons/ICommands for 'Add', 'Clear', 'Previous' and 'Next' that move through the collection of objects.</p>
<p>I'm trying to work out how I can remove the repeated code.</p>
<p>I wire up the commands in my constructor:</p>
<pre><code> this.AddressBookRecipientCommand = new GenericCommand(AddressBookRecipientPressed);
this.ClearRecipientCommand = new GenericCommand(ClearRecipientPressed, CanClearRecipient);
this.NextRecipientCommand = new GenericCommand(NextRecipientPressed, CanPressNextRecipient);
this.PrevRecipientCommand = new GenericCommand(PrevRecipientPressed, CanPressPrevRecipient);
this.AddressBookCCCommand = new GenericCommand(AddressBookCCPressed);
this.ClearCCCommand = new GenericCommand(ClearCCPressed, CanClearCC);
this.NextCCCommand = new GenericCommand(NextCCPressed, CanPressNextCC);
this.PrevCCCommand = new GenericCommand(PrevCCPressed, CanPressPrevCC);
this.AddressBookBCCCommand = new GenericCommand(AddressBookBCCPressed);
this.ClearBCCCommand = new GenericCommand(ClearBCCPressed, CanClearBCC);
this.NextBCCCommand = new GenericCommand(NextBCCPressed, CanPressNextBCC);
this.PrevBCCCommand = new GenericCommand(PrevBCCPressed, CanPressPrevBCC);
</code></pre>
<p>Then I have the various command code:</p>
<pre><code> public ICommand AddressBookRecipientCommand { get; set; }
public void AddressBookRecipientPressed()
{
this.Recipient = this.Details.Recipients.ReplaceAndReturn(this.Recipient, this.Outlook.GetContact());
}
public ICommand PrevRecipientCommand { get; set; }
public bool CanPressPrevRecipient()
{
return Details.Recipients.IndexOf(Recipient) != 0;
}
public void PrevRecipientPressed()
{
int i = Details.Recipients.IndexOf(Recipient);
Recipient = Details.Recipients[i - 1];
}
public ICommand NextRecipientCommand { get; set; }
public bool CanPressNextRecipient()
{
return !Recipient.IsNullOrEmpty() && Details.Recipients.IndexOf(Recipient) != MaxRecipients;
}
public void NextRecipientPressed()
{
if (Details.Recipients.IndexOf(Recipient) + 1 == Details.Recipients.Count)
{
Recipient = new Contact();
Details.Recipients.Add(Recipient);
}
else
{
int i = Details.Recipients.IndexOf(Recipient);
Recipient = Details.Recipients[i + 1];
}
}
public ICommand ClearRecipientCommand { get; set; }
public bool CanClearRecipient()
{
return !Recipient.IsNullOrEmpty();
}
public void ClearRecipientPressed()
{
int i = this.Details.Recipients.IndexOf(this.Recipient);
if (i + 1 == this.Details.Recipients.Count)
this.Recipient.Clear();
else
{
this.Details.Recipients.Remove(this.Recipient);
this.Recipient = this.Details.Recipients[i];
}
}
</code></pre>
<p>This code is repeated for CC and BCC.</p>
| [] | [
{
"body": "<p>If I understand correctly what you're doing, I think what you need is a <code>UserControl</code> that encapsulates some <code>AddressBookCommand</code>, <code>ClearCommand</code>, <code>NextCommand</code> and <code>PreviousCommand</code> commands.</p>\n\n<p>Your main <em>view</em> would have 3 instances of that control, one for each field (\"To\", \"CC\", \"BCC\"), and each would have its own <em>data context</em>, some <code>IList<Contact></code> I'd guess.</p>\n\n<p>Also you're not showing your entire class so it's hard to tell, but since you mention MVVM I believe a lot of this code belongs in a <em>ViewModel</em> class, not in the <em>View</em>'s code-behind; the XAML markup uses <em>DataBinding</em> markup extensions to bind visual element properties to properties in the <em>ViewModel</em> - the Window's <code>DataContext</code> property is set to the instance of the <em>ViewModel</em> class.</p>\n\n<p>The reason I mention this, is because ideally in MVVM the <em>View</em> should only be caring for <em>presentation</em> concerns, which clearly <code>Details.Recipients.Add(Recipient);</code> isn't.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T07:44:58.670",
"Id": "76658",
"Score": "0",
"body": "Thanks. I haven't used UserControls before. I'll take a look.\nYes, the code above is from the ViewModel."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:38:33.227",
"Id": "44154",
"ParentId": "44040",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44154",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:25:42.923",
"Id": "44040",
"Score": "5",
"Tags": [
"c#",
"wpf",
"email"
],
"Title": "Managing Contact Collections"
} | 44040 |
<p>I created a very basic "image projector" that shows the current one and shows the next on clicking into the image.</p>
<p>And yeah, it works, but I don't think that's a very elegant way to do it. Any advice please?</p>
<p>Bear in mind I'm just starting my JavaScript classes and that's my third assignment, but the teacher is not really helpful when it comes to clean code, for him if it works, it works :/</p>
<p>Anyway, here's the full code: <a href="http://jsfiddle.net/AngelCJ/F5Hg7/" rel="nofollow">http://jsfiddle.net/AngelCJ/F5Hg7/</a></p>
<p>And the messy part:</p>
<pre class="lang-javascript prettyprint-override"><code>/* loads the first image of the ul element using the n counter */
window.onload = function loadFirst() {
var n=0;
document.getElementById("list").children[n].style.display="block";
/* onclick event, add +1 to the counter */
document.getElementById("btn").onclick = function slider(){
n++;
/* and display the corresponding image */
document.getElementById("list").children[n].style.display="block";
/* while deleteing the previous one */
document.getElementById("list").children[n-1].style.display="none";
/* if we reach the final image */
if(n==3) {
/* shows the final image */
document.getElementById("list").children[3].style.display="block";
/* and after we click on it */
document.getElementById("btn").onclick = function slider(){
/* deletes it to leave the space to the first one */
document.getElementById("list").children[3].style.display="none";
/* returning to it loading the function to start again */
loadFirst();
}
return;
}
}
}
</code></pre>
| [] | [
{
"body": "<pre><code>window.onload = function loadFirst() {\n var n = 0; //Initial counter \n var images = document.getElementById(\"list\").children; //get length of images carousel\n images[n].style.display = \"block\"; //set first image visible\n document.getElementById(\"btn\").onclick = function slider() {\n //(n % images.length) will give previous child's index\n images[n % images.length].style.display = \"none\"; //set previous image invisible\n n++; //increase initial counter\n i = n % images.length; //(n%images.length) will give next child's index\n images[i].style.display = \"block\"; //set display visible of next image\n }\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/F5Hg7/3/\" rel=\"nofollow\">Fiddle</a></p>\n\n<p>Or With <strong>IIFE</strong></p>\n\n<pre><code>(function () {\n var images = document.getElementById(\"list\").children; //get length of images carousel\n var n = images.length - 1; //Initial counter \n var btn = document.getElementById(\"btn\");\n function carousel() {\n images[n % images.length].style.display = \"none\"; //set previous image invisible\n n++;\n i = n % images.length;\n images[i].style.display = \"block\"; //set next image visible\n }\n window.onload = btn.onclick =carousel;\n})();\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/F5Hg7/4/\" rel=\"nofollow\">fiddle</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:10:23.137",
"Id": "76216",
"Score": "0",
"body": "Could you [edit] your answer to explain what you've improved and why you did this? As it stands, this is a code dump, not a code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:19:06.757",
"Id": "76218",
"Score": "0",
"body": "Apologies..I m new to this site..Kindly suggest if my answer is appropriate..Thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:05:57.383",
"Id": "44046",
"ParentId": "44044",
"Score": "1"
}
},
{
"body": "<p>In your example you're adding events inside events, this is not good idea because it creates unnecessary closures and can lead to memory leaks.</p>\n\n<p>First I would cache the elements so you only query the DOM once, improving performance. Then you can create a function to hide all images, and a function to go to the next image, and reuse that function for both events:</p>\n\n<pre><code>// IIFE (Immediately invoked function expression)\n// to not leak variables to global scope\n(function(){\n // Cache elements\n var list = document.getElementById('list');\n var btn = document.getElementById('btn');\n\n var current = 0;\n\n // Hide all images\n function hide() {\n for (var i=0; i<list.children.length; i++) {\n list.children[i].style.display = 'none';\n }\n }\n\n // Go to next image\n function next() {\n hide();\n list.children[current++].style.display = 'block';\n // Did we reach the end?\n if (current >= list.children.length) {\n current = 0;\n }\n }\n\n // Reuse function\n window.onload = btn.onclick = next;\n}());\n</code></pre>\n\n<p><strong>Demo:</strong> <a href=\"http://jsfiddle.net/F5Hg7/2/\" rel=\"nofollow\">http://jsfiddle.net/F5Hg7/2/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:11:56.297",
"Id": "44048",
"ParentId": "44044",
"Score": "3"
}
},
{
"body": "<p>Don't use the <code>onXXX</code> properties to assign events. This only allows you to attach one listener to an event, so that any other scripts doing the same with overwrite each other. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener\" rel=\"nofollow\"><code>addEventLister</code></a> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:00:07.170",
"Id": "44050",
"ParentId": "44044",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:56:11.017",
"Id": "44044",
"Score": "0",
"Tags": [
"javascript",
"dom",
"image"
],
"Title": "Image Carousel in JavaScript"
} | 44044 |
<p>Magic numbers are bad... I totally agree. But there's one magic number I find hard to fix:</p>
<blockquote>
<p><strong>'100' is a magic number.</strong></p>
</blockquote>
<p>Consider this code:</p>
<pre><code>public double getPercent(double rate) {
return rate * 100;
}
public double getRate(double percent) {
return percent / 100;
}
</code></pre>
<p>SonarQube will raise 2 violations, one for each use of 100. I could replace 100 with a constant variable, but what would be a good name for it? Is that really a good idea? If somebody ever changes its value that will be a disaster. I could also just add <code>// NOSONAR</code> to all the lines that use 100.</p>
<p>What is the best practice for dealing with the magic number 100?</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>From the answers, the most useful bit for me was this:</p>
<blockquote>
<p><strong>Practical Magic Number rule</strong>: A literal is a not a magic number if the most meaningful variable name for it is the same as the spoken name of the literal.</p>
</blockquote>
<p>So by this logic, 100 is NOT a magic number.</p>
<p>However, to make the violation go away, I decided to replace the 100 with a constant:</p>
<pre><code>public static final double HUNDRED = 100; // change it and I'll kill you
</code></pre>
<p>In my real project there are many lines using 100, and if I put <code>// NOSONAR</code> on all those lines that might cover up other potential problems that other developers might inadvertently add later.</p>
<p>Not sure if there will be any real benefits using this constant. A small one may be that when I do <code>git grep 100</code> I see a lot of matches from resource files in the project, while <code>git grep HUNDRED</code> turns up just the the Java code that uses this.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:24:28.643",
"Id": "76219",
"Score": "17",
"body": "I've written a [rant on stupid linters](http://programmers.stackexchange.com/a/223625/60357) over on programmers. Adding a named constant for the `100` here would just be obfuscation. However, I feel you aren't looking for a code review of that very small snippet, but for best practices regarding such cases, which unfortunately is an opinion-based question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:00:07.057",
"Id": "76284",
"Score": "9",
"body": "What is adding insult to injury is the underlying reason: you shouldn't have magic numbers but meaningful identifiers. _But that's exactly why there is a meaningful identifier on the previous line_: `getPercent` !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:38:51.193",
"Id": "76303",
"Score": "5",
"body": "Well, it will allow you to more easily change it if the percentage of 1 ever changes... ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:05:45.593",
"Id": "76339",
"Score": "2",
"body": "It’s not your fault that real life did not adhere to best practice and made 100 a magic number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:05:47.667",
"Id": "76340",
"Score": "15",
"body": "You could name it PERCENT_TO_RATE_RATIO = 100"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:35:08.693",
"Id": "76354",
"Score": "22",
"body": "`HUNDRED` is absolutely as useless as `100`, and potentially even more harmful since someone could ignore your comment and change it. If anything it proves that it matches the \"practical magic number rule\" and shouldn't be a variable, final or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:37:22.587",
"Id": "76368",
"Score": "2",
"body": "_The benefit of using the constant instead of the value 100 is that I can easily lookup usages_ -- What happens if you search for \"`100`\": do you find other, non-percentage-related places where it's being used? IMO the intent of the \"practical\" rule was to say that if \"HUNDRED\" is the best you can do then 100 is valid as a hard-coded number and is not an 'invalid, magic' number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T09:47:48.353",
"Id": "76430",
"Score": "1",
"body": "Im with Kevin on this one. Using constants as \"HUNDRED\" or similar doesnt really make them less magic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:47:36.830",
"Id": "76433",
"Score": "5",
"body": "http://www.xkcd.com/1275/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T11:19:57.500",
"Id": "76683",
"Score": "1",
"body": "Similarly, in our code base, someone left `c_chf constant varchar2(3) := 'CHF'`. This stupidity can only be explained for tools such as sonar. Leave the 100 as 100, everybody understands it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T13:47:16.043",
"Id": "76705",
"Score": "0",
"body": "One advantage of a variable is to have the compiler check for typos. Not very relevant for a hundred, might be more so for a billion. But as other people have been saying, the usual reasons for avoiding magic numbers don't apply here, and things like int THREE = 3; are very silly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-19T03:51:00.427",
"Id": "134780",
"Score": "0",
"body": "[Relevant Q&A on Programmers](http://programmers.stackexchange.com/q/266717/142319)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-18T11:57:04.477",
"Id": "147249",
"Score": "0",
"body": "Sonar has an option to flag an issue has a False Positive. This seems most appropriate to situations like these. No editing rules, no preventing analysis on certain lines."
}
] | [
{
"body": "<p>Speaking as a human programmer (i.e. I am not Lint software), your use of \"100\" there looks fine to me.</p>\n\n<p>Wikipedia has an article (without citations) titled <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Accepted_limited_use_of_magic_numbers\">Accepted limited use of magic numbers</a>: IMO your \"100\" is in the same category as these other \"accepted\" magic numbers.</p>\n\n<hr>\n\n<p><a href=\"http://c2.com/cgi/wiki?MagicNumber\">This Wiki describing magic numbers</a> says two things.</p>\n\n<p>Firstly,</p>\n\n<blockquote>\n <p><strong>Practical Magic Number rule</strong>: A literal is a not a magic number if the most meaningful variable name for it is the same as the spoken name of the literal.</p>\n</blockquote>\n\n<p>That's applicable here: you're looking for a named constant like <code>HUNDRED</code> or <code>CENTUM</code>.</p>\n\n<p>Secondly, it also suggests loading \"magic\" numbers (e.g. a \"discount rate\") from a configuration file:</p>\n\n<pre><code>static final double DISCOUNT_PERCENT = getProperty( \"sales.discount_percent\" );\nstatic final double DISCOUNT_FACTOR = 1 - (DISCOUNT_PERCENT / 100);\n\n// ...\n\nsalePrice = DISCOUNT_FACTOR * regularPrice;\n</code></pre>\n\n<p>Note that though this example code carefully loaded <code>DISCOUNT_PERCENT</code> from a configuration, the \"100\" used to calculate the <code>DISCOUNT_FACTOR</code> is hard-coded.</p>\n\n<hr>\n\n<p>If you use \"100\" instead of <code>HUNDRED</code>, it's easier for a programmer to understand, and to verify that it's correct.</p>\n\n<p>IMO the only benefit to using <code>HUNDRED</code> is to find the several methods which use the same magic number (in your example it's used by <code>getPercent</code> and <code>getRate</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:24:40.753",
"Id": "76229",
"Score": "0",
"body": "Thanks for your comment. Yes, 0, 1, 2 don't raise violations in our tools. But 100 does. Maybe you're right and I can consider these false positives."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:31:42.237",
"Id": "76324",
"Score": "15",
"body": "@janos then you can do `return rate * 2 * 2 * 5 * 5;`. Much easier since it doesn't contain magic numbers. Much easier to read as well since it's been factorized /s"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:34:58.957",
"Id": "76367",
"Score": "4",
"body": "I don’t even agree with the “only benefit” you mention: searching for “HUNDRED” is no easier than searching for “100”. 100 is *not* a magic number here and there’s no reason to reduce clarity in order to kowtow to some linter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:42:32.380",
"Id": "76369",
"Score": "2",
"body": "@bdesham Conceivably there are other places where \"100\" is being used: as an error code, in huffman code tables, in some enum value, in resource files, etc. It _is_ the only benefit that I can think of; but I agree with you that it's not a sufficient benefit to make it worthwhile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T08:30:24.633",
"Id": "76426",
"Score": "10",
"body": "@WernerCD: Sorry, only 0,1 and 2 are not magic. ITYM `(rate << 2) * (2*2+1) * (2+2+1)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:45:46.780",
"Id": "76445",
"Score": "30",
"body": "@WernerCD Too complicated! `1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1` ftw."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T16:29:05.773",
"Id": "76510",
"Score": "7",
"body": "My first thought was that surely you shouldn't be converting between rate and percentage in code since you'd use rate for all calculations and percentage only when displaying to the user. Does Java not have any nice number formatting methods that will format a double as a percentage string?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:21:30.813",
"Id": "44051",
"ParentId": "44047",
"Score": "82"
}
},
{
"body": "<p>Some numbers are called 'magic' because it is unclear where they come from. I think in this particular case, it is clear that 100 originates from the definition of percent. However, if you wish you can define a constant <code>PERCENTS_IN_UNIT_RATE=100</code> instead of using it directly.</p>\n\n<p>Violations reported by code analysis tools are really only suggestions and it is okay to disagree with them. If in doubt ask other programmers who work on the same project, or toss a coin and move to the next task! :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:39:04.833",
"Id": "76232",
"Score": "6",
"body": "I don't think `HUNDRED` is any more readable than 100. Yes, it will satisfy the immediate tool complaints, but you probably use the tool to raise code quality, and as I mentioned it does not do so in my opinion. `MAX_PERCENT` is better but still may raise questions. `PERCENT_MAX` sounds similar to `INT_MAX` and may be slightly better yet. `PERCENTS_IN_UNIT_RATE` is imho most understandable but is also too long. Hence, I'd vote for keeping literal 100."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:51:43.670",
"Id": "76233",
"Score": "1",
"body": "`MAX_PERCENT` seems misleading in that it implies that the 100 is just an arbitrary constant that could be changed any time. It would seem to me that outside of dodgy accounting practices, 100 is pretty immutable :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:13:54.517",
"Id": "76235",
"Score": "1",
"body": "`A100PERCENTS` or `ONE100PERCENTS` or `PERCENTS_100` or `X100PERCENTS` would all work IMO. I like these because they include numeric 100, and also include word *percent*, making both numeric value and context apparent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:39:10.000",
"Id": "76329",
"Score": "1",
"body": "If I buy a goat for $1 and sell it for $8, then I've sold it for 800% of its original price. `MAX_PERCENT` should probably be a constant equal to `DBL_MAX`. Just use 100 and avoid confusion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T22:12:44.230",
"Id": "76377",
"Score": "0",
"body": "I have no idea where `RATE` in `PERCENTS_PER_UNIT_RATE` came from. Because you're working on an interest rate? But that has absolutely no effect on conversion between percentage and scale. I'd suggest `PERCENT_PER_UNITY` or something like that."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:23:37.023",
"Id": "44053",
"ParentId": "44047",
"Score": "27"
}
},
{
"body": "<p>I am on the fence about the 100 being a named constant or not.</p>\n\n<p>I habitually make magic numbers named constants, but not all the time.... it is not unusual for me to have constants called <a href=\"https://codereview.stackexchange.com/a/42544/31503\"><code>HUNDRED</code> or <code>MILLION</code></a>. I also regularly have trivial numbers as magic-number constants .... </p>\n\n<p>But, in this case, and what I particularly want to draw attention to, is that your value should be a floating-point, not an integral value.</p>\n\n<p>When you have constants they should be in the most convenient form for users to understand. For example, your value <code>100</code> should really be <code>100.0</code> which makes the fact that it is a double value obvious.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:09:34.063",
"Id": "76347",
"Score": "7",
"body": "When you use a constant called `HUNDRED`, is it `100` or `100.0`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:10:12.830",
"Id": "76348",
"Score": "0",
"body": "@JoonasPulakka I would make it `private static final double HUNDRED = 100.0;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T07:36:39.570",
"Id": "76418",
"Score": "3",
"body": "Ok, but that's just one possibility. `HUNDRED` could as well be a `BigInteger`, or `BigDecimal`, or `byte`, just to mention a few. With number literals, the type is immediately obvious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T20:09:14.833",
"Id": "76571",
"Score": "7",
"body": "If you end up dealing with large numbers a lot, i think things like `MILLION` could come in handy just because it could be very easy to mistake 1000000 for 10000000 etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T06:27:49.983",
"Id": "76873",
"Score": "1",
"body": "If you use `HUNDRED` in lots of places, then, when you need to change it in a subset of these places and try to change the constant... you're messed up. This would be no better than doing something like `sed 's/100/101/g'` for all of your project codebase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-14T18:43:40.153",
"Id": "228880",
"Score": "2",
"body": "@DLeh `1_000_000`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:25:59.430",
"Id": "44055",
"ParentId": "44047",
"Score": "20"
}
},
{
"body": "<p>It technically is since both those 100's have the same context. Similar to me using 32 as a width in several different places. It depends how nitpicky you want to be. In this case I might use something like <code>MAX_PERCENT</code>. It does help with readability as well since when I see that I know the calculations have to do with percentages.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T04:38:43.467",
"Id": "76403",
"Score": "2",
"body": "I would be rather amused if I saw code that used `MAX_PERCENT`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:12:01.373",
"Id": "76536",
"Score": "0",
"body": "Poor attempt at brevity I guess. Though being amused by something helps remember it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:27:20.380",
"Id": "44089",
"ParentId": "44047",
"Score": "2"
}
},
{
"body": "<p>If forced to use a symbol, I might call it N100. That way you can tell what its value is. A long time ago I saw this done for common constants. And negative numbers were prefixed with \"M\". Why did they do this? Because the computer instruction set couldn't load numbers in line (\"immediate\"); they had to be fetched from a memory location. And the assembler used symbols to refer to those locations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T06:33:36.073",
"Id": "44127",
"ParentId": "44047",
"Score": "1"
}
},
{
"body": "<p>Although <code>100</code> should be fine in source-code, I'm surprised nobody has offered the most <em>readable</em> alternative yet. This should be acceptable for both humans and lint-code:</p>\n\n<p>Define your constant <code>PERCENT=0.01</code>.</p>\n\n<p>Then, when you need to do a conversion:</p>\n\n<pre><code>rate = discount*PERCENT\n</code></pre>\n\n<p>or</p>\n\n<pre><code>discount = rate/PERCENT\n</code></pre>\n\n<p>This can completely eliminate your short functions (which are, indeed, trivial). You could have additional constants <code>PERMILLE</code>, <code>PPM</code>, <code>PPB</code>, etc., and it should be obvious for humans what is happening.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:37:29.277",
"Id": "76544",
"Score": "1",
"body": "+100 Or if you *really* must make it clear what the constant means, name it `PER_CENT` as in \"per one hundred\"--the definition of percent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T02:24:26.237",
"Id": "76635",
"Score": "5",
"body": "Created an account just to vote this up. This is way better than the other answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:12:54.553",
"Id": "80620",
"Score": "8",
"body": "very good, but there are some caveats, I believe, with the internal representation... you may need to have one per types of data (float, double float, etc)... 100 (or a constant valued at 100) is safer to use.See: [Java Double value = 0.01 changes to 0.009999999999999787](http://stackoverflow.com/questions/7408566/java-double-value-0-01-changes-to-0-009999999999999787) or [why-not-use-double-or-float-to-represent-currency](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) or [rounding-errors](http://stackoverflow.com/questions/960072/rounding-errors)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T01:33:46.333",
"Id": "96863",
"Score": "3",
"body": "I can't really call this more readable. In particular, `discount = rate/PERCENT` feels rather contorted. Without *very* clear names, and perhaps even with, it'd be way too easy to forget whether `PERCENT` is 0.01 or 100. Perhaps if it were called `ONE_PERCENT` or something, i dunno...but as is, it's more magical than if it were left a \"magic number\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-01T19:49:02.707",
"Id": "117856",
"Score": "14",
"body": "*Sigh*. `discount*0.01` and `rate/0.01` is *not* the same as `discount/100` and `rate*100`. While `100` is exact, `0.01` is not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-01T21:38:31.617",
"Id": "117889",
"Score": "0",
"body": "@DavidOngaro Oops, indeed. But as the context seems to involve money, using Decimal seems prudent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-02T02:41:11.777",
"Id": "117930",
"Score": "0",
"body": "@gerrit: I don't see that context in the question. But the accepted answer uses a price calculation as an example, which is surely an anti-example when done with float arithmetic."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:03:15.640",
"Id": "44157",
"ParentId": "44047",
"Score": "64"
}
},
{
"body": "<p>I think 100 IS a magic number here.</p>\n\n<p>Percentage is vastly used, but also per mille (1/1000) is often used, and basis point (1/10.000) and percent mille (1/100.000) are used enough to have their own name.</p>\n\n<p>I would change your function to <code>getPerPart(value, part)</code> and <code>getFromPart(value, part)</code>, maybe with a default <code>getPerPart(value)</code> and <code>getFromPart(value)</code>, which use <code>DEFAULT_PART_VALUE = 100</code>.</p>\n\n<p>Also, you may still want to write a <code>getPercent</code>, in which case the use of hardcoded 100 is fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T05:55:50.260",
"Id": "77088",
"Score": "0",
"body": "You are really going to make functions for multiplication and division? Why not allow your formatter to display numbers how the user wants to see them? You're not going to use these functions in calculations."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T11:11:48.710",
"Id": "44247",
"ParentId": "44047",
"Score": "1"
}
},
{
"body": "<p>Others have already stated why they believe that 100 is an acceptable constant here. This answer shows how you can get Sonar to accept that.</p>\n\n<p>Under <code>your-sonar-domain/profiles/</code>, you can edit quality profiles, and the rules in them. The \"Magic Number\" rule is customisable, you can specify certain numbers for the rule to ignore. Simply specify \"100\" as a number to ignore.</p>\n\n<p><img src=\"https://i.stack.imgur.com/YfiTr.png\" alt=\"Change ignoreNumbers to include "100!\"></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-02T15:35:54.630",
"Id": "55895",
"ParentId": "44047",
"Score": "15"
}
},
{
"body": "<p>Any number that remains unnamed remains a magic number. It's not related common usage as common usage is relative. The problem with it is \"when\" or \"where\" to draw a line... when does a number changes its state to non-magic...</p>\n\n<p>2,71828... may not be magic for mathematicians (Euler)</p>\n\n<p>1760 may not be a magic number for anglo saxons (Yards per mile)</p>\n\n<p>10000000 may not be magic for south inhabitant of south asia (crore)</p>\n\n<p>1 may not be magic in the context of multiplication (neutral element)</p>\n\n<p>The relative approach will lead to a discussion that will evolve a local aggreement. And the result to consider a number to be non-magic, will depend on when and where you start the discussion. Unfortunally this discussion has to be lead for each number separately.</p>\n\n<p>The absolute approach is simple an clear: Every number that is not named is a magic number. Discussion over... for all numbers... Of course this is only a (one) definition. But this definition has inherent properties that will make it possible to evaluate it exactly.</p>\n\n<p>So if you want to discuss, go for the relative approach. You will find the discussions never ending. And if you think it is over another number comes along.</p>\n\n<p>Or you go and find a definition that can be used in boolean expressions that will evaluate to true or false.</p>\n\n<p>I go the second way with following definition: Every unnamed number is magic. Even if you practically ignore it the statement stays the same.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-26T12:09:13.780",
"Id": "129368",
"ParentId": "44047",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "44051",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:06:46.817",
"Id": "44047",
"Score": "99",
"Tags": [
"java",
"constants"
],
"Title": "'100' is a magic number"
} | 44047 |
<p>This is a very basic script. If the screen width is larger than say a tablet, and a portfolio link is hovered over, it will fade out the original text and replace it with the text held in the 'data-portfolio' attribute. I'm fairly new to jQuery so any improvements will be welcomed.</p>
<p>You can see it working <a href="http://joshuajohnson.co.uk/" rel="nofollow">here</a>.</p>
<pre><code>(function () {
width = $(window).width();
if(width >= 620) {
$('.portfolio-piece__link').hover(function(){
var $this = $(this);
prev = $this.text();
data = $this.attr('data-portfolio');
$this.fadeOut(300, function(){
$this.text(data).fadeIn(300);
});
}, function(){
var $this = $(this);
$this.fadeOut(300, function(){
$this.text(prev).fadeIn(300);
});
});
}
})();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:06:11.150",
"Id": "76225",
"Score": "0",
"body": "By the looks of it you have a bunch of implicit global variables, `width`, `prev` and `data`. Are those really meant to be global? Are we missing some code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:40:22.767",
"Id": "76241",
"Score": "0",
"body": "You are not missing code so I've clearly declared them incorrectly ha!"
}
] | [
{
"body": "<p>First off, you should clean up the indention. Currently the wrong indention makes the code hard to read.</p>\n\n<p>The next problem is that your variables <code>width</code>, <code>prev</code> and <code>data</code> are lacking the <code>var</code> keyword making them global und thus making the surrounding <a href=\"http://en.wikipedia.org/wiki/Immediately-invoked_function_expression\">IIFE</a> pointless. Unfortunatly you are actually reading the <code>prev</code> variable in the second hover function globally. This will go especially wrong if you happen to have multiple elements with the class <code>portfolio-piece__link</code> one one page. <s>You may want to move the definition of those variables outside of your hover functions and declare them locally inside the IIFE. That way it also has the advantage that you don't need to create them on each hover.</s></p>\n\n<p>Then what you need to consider is your code will not react to window resizes. What happens if the user originally opens your page with a small window size (< 640) and then resizes the window. BTW, why do you want this effect only on larger window sizes in the first place?</p>\n\n<p>Finally you may want to consider writing this to be generic and not hard code it to only work with that specific class and property name.</p>\n\n<p><strong>EDIT:</strong>\nMoving the variables outside the hover functions is of course not sensible, if you have multiple elements. I wrote that before I realized that. Instead you should store the old text, for example using jQuery's <code>data</code> method. Example:</p>\n\n<pre><code>function replaceText($element, text) {\n element.fadeOut(300, function(){\n $this.text(text).fadeIn(300);\n }); \n}\n\n$('.portfolio-piece__link').each(function() {\n // Store original text\n var $this = $(this);\n $this.data('original-text', $this.text());\n}).hover(function(){\n var $this = $(this);\n var data = $this.attr('data-portfolio');\n\n replaceText($this, data);\n}, function(){ \n var $this = $(this); \n var text = $this.data('original-text');\n\n replaceText($this, text);\n});\n</code></pre>\n\n<p>BTW, I forgot one thing originally: You have duplicate code for replacing the text. You should replace it with a method as I did above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:39:21.980",
"Id": "76240",
"Score": "0",
"body": "Thanks for giving such a detailed reply! Are you referring to the indention of variables or just the code in general - doesn't seem too off to me? Also, how would I go about declaring the \"prev\" variable for example, outside the hover fucntion? Surely if I put it outside, it wouldn't know what $this is and therefore not grab the previous text? I decided to apply the effect on larger screens purely for usability - on touch devices it just doesn't work as well. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:57:42.397",
"Id": "76242",
"Score": "0",
"body": "Most of the code is indented incorrectly - noticeable because the last line `})();` isn't formatted properly. For the prev variable see my edit. However you have an error in reasoning: A small screen does not mean it's a phone/tablet. Not all vehicles with four wheel are cars. Not all cars have four wheels. Instead of checking the screen size, you should be checking if the browser is capable of hover events. Unfortunately I can't recall how you do that properly. Let me research it and I'll come back if I find something suitable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:21:52.947",
"Id": "44052",
"ParentId": "44049",
"Score": "7"
}
},
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>This:</p>\n\n<pre><code>var $this = $(this);\n prev = $this.text();\n data = $this.attr('data-portfolio');\n</code></pre>\n\n<p>should have been this:</p>\n\n<pre><code>var $this = $(this), //<- Comma, not semicolon\n prev = $this.text(), //<- Comma, not semicolon\n data = $this.attr('data-portfolio');\n</code></pre></li>\n<li><p>Be consistent with single comma separated <code>var</code> statements:</p>\n\n<pre><code>}, function(){ \n var $this = $(this), //<- Comma here\n text = $this.data('original-text');\n\n replaceText($this, text);\n});\n</code></pre></li>\n<li>As @elclanrs mentioned, <code>prev</code> is global, the only reason why your code works by the way..</li>\n</ul>\n\n<p>If you think about it, both handlers do pretty much the same thing, so I would counter propose this:</p>\n\n<pre><code>function portfolioHoverHandler( $element ){\n var newText = $element.attr('data-portfolio');\n $element.attr('data-portfolio', $element.text()); \n element.fadeOut(300, function(){\n $this.text(newText).fadeIn(300);\n }); \n}\n\n$('.portfolio-piece__link').hover(portfolioHoverHandler, portfolioHoverHandler);\n</code></pre>\n\n<p>I am not sure if the hovers can be missed, if you were to have 2 consecutive hover in's or hover out's, then this code would mess up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:49:54.797",
"Id": "44062",
"ParentId": "44049",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44052",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:58:37.960",
"Id": "44049",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"beginner",
"html5"
],
"Title": "Data attribute text() swap on hover"
} | 44049 |
<p>I've written a query to compare the clients in our database with the people in a list that I've received. It needs to check if anyone from the list is one of our clients. I've created a temporary table which has been filled with the names and the query below makes a cross-join with the two tables. That query works very slowly (two very large tables), so I was wondering if there's any way to speed this up.
Would it be faster to just join everything in the database and compare strings in code (java or something similar)?</p>
<p>(The second list was just names, so I can't use any indexed columns in our database.)</p>
<pre class="lang-sql prettyprint-override"><code>select C.NUMCLI, C.NAAM, T.FULLNAME, (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME))
as DIFF from (select LASTNAME ||' '|| FIRSTNAME ||' '|| MIDDLENAME as FULLNAME from
TMP_CONTROL) T, (select NUMCLI, NOMCLI ||' '|| PRNCLI as NAAM from CLIENT
where CODLAN = 3 and STAANN <> 'D') C
where (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) >= 60
</code></pre>
<p>NOTE: A large portion of people on the list may have their name written in a slightly different manner, which is why I'm using the <code>EDIT_DISTANCE SIMILARITY >= 60</code>. The goal is just to filter out the large differences, so I can easily compare the smaller ones.</p>
<hr>
<h2>Update</h2>
<p>This is the explain-plan for the query: </p>
<p>SQL> SET LINESIZE 130<br>
SQL> SET PAGESIZE 0<br>
SQL> SELECT *<br>
2 FROM TABLE(DBMS_XPLAN.DISPLAY);<br>
Plan hash value: 1462516232</p>
<pre><code>---------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
---------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 74M| 3041M| 2197K (3)| 07:19:29 |
| 1 | NESTED LOOPS | | 74M| 3041M| 2197K (3)| 07:19:29 |
|* 2 | TABLE ACCESS FULL| CLIENT | 71843 | 2174K| 2386 (2)| 00:00:29 |
|* 3 | TABLE ACCESS FULL| TMP_CONTROL| 1033 | 12396 | 31 (4)| 00:00:01 |
---------------------------------------------------------------------------------
</code></pre>
<h2>Predicate Information (identified by operation id):</h2>
<pre><code>2 - filter("STAANN"<>'D' AND TO_NUMBER("CODLAN")=3)
3 - filter("UTL_MATCH"."EDIT_DISTANCE_SIMILARITY"("NOMCLI"||'
'||"PRNCLI","LASTNAME"||' '||"FIRSTNAME"||' '||"MIDDLENAME")>=60)
</code></pre>
<p>17 rows selected.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T22:27:14.663",
"Id": "76378",
"Score": "0",
"body": "Rolled back the change you made in Rev 3. (Please don't edit questions in a way that invalidates answers.)"
}
] | [
{
"body": "<p>Fundamentally, at some point, you have to do a cross-join to calculate your results. Performance will be a problem... but there are things that can be done.</p>\n\n<p>First though, why the ugly SQL? Formatting SQL to make it readable is not hard to do:</p>\n\n<pre><code>select C.NUMCLI,\n C.NAAM,\n T.FULLNAME,\n (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) as DIFF\nfrom (\n select LASTNAME ||' '|| FIRSTNAME ||' '|| MIDDLENAME as FULLNAME\n from TMP_CONTROL\n ) T,\n (\n select NUMCLI,\n NOMCLI ||' '|| PRNCLI as NAAM\n from CLIENT\n where CODLAN = 3\n and STAANN <> 'D'\n ) C \nwhere (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) >= 60\n</code></pre>\n\n<p>We can see a few things in here.....</p>\n\n<ul>\n<li>Your source data contains a middle-name but your main table does not. Are you sure you want to be joining them this way? Will it create the correct results?</li>\n</ul>\n\n<p>Now, about those performance improving options....</p>\n\n<p>Let's assume that the best way to solve this problem is to do a cross-product of the two tables. Compare each value in table a with all values in table b. Oracle ha a few options for doing this. I will list them in what I consider to be a worst-to-best order:</p>\n\n<ul>\n<li><code>true cross-product</code> - It can do a true Cartesian product of the data - build an in-memory join of each value in the temp table joined to each value in the primary table, and then scan the results once, calculating the edit distance, and then discarding those results which are < 60. It can either calculate the string concatenation of the names before or after the Cartesian product, either option will be (very) slow.</li>\n<li><code>nested-loop T->C</code> - It can loop through each temp table value, and for each of them, it can do the name-concatenation, and then it will need to join to the primary table (with the conditions), do the name-concatenation, and discard bad edit-distances.</li>\n<li><code>nested-loop C->T</code> - It can loop through each value in the primary table, check the conditions, and for each successful value, it can do the String-concatenation, it can scan all values in the temp table, compute the name-concatenation, and then calculate the edit distance, and discard the bad results.</li>\n<li><code>nested-loop C'->T' or T'->C'</code> - It can produce a temporary, or in-memory version of the pre-filtered C table and name-concatenated T and C tables, and then do a nested-loop of these two in-memory tables, discarding bad edit distances.</li>\n</ul>\n\n<p>Your SQL is written to suggest you want it to do the last option, create two in-memory data sets, each of them pre-computed to contain just the name-concatenated values, and then you only perform the cross-product on these tables.... but, just because you wrote the SQL that way does not mean that Oracle will do the process that way....</p>\n\n<p>... have you done an explain-plan to figure out which option it has taken?</p>\n\n<p>My guess is that it has chosen <code>nested-loop T->C</code>, with a second possibility of <code>nested-loop C->T</code>. The reasons?</p>\n\n<ol>\n<li>the temp table probably does not have statistics up to date, and is not indexed at all</li>\n<li>the primary table probably has some indexes on <code>CODLAN</code> and/or <code>STAAN</code></li>\n<li>when Oracle optimizes the query, it will likely decide the temp-space required to store all the name-concatenated values will require too much memory, or even physical IO</li>\n</ol>\n\n<p>Now, we want/need Oracle to choose the most efficient cross-join mechanism... and we do not want it calculating the name-concatenation on the fly because it will need to repeat that many times for at least one side of the cross-product.</p>\n\n<p>The solution is to force Oracle's plan to do what we want, and the way to do that is to pre-compute the data needed for the cross-product.</p>\n\n<p>Your temp table should already have the pre-computed name-concatenated values... why are you having to do the name-concatenation as part of the query? Call this column <code>FULLNAME</code></p>\n\n<p>Then, create a second table as:</p>\n\n<pre><code>create table TMP_CLIENTNAME (\n NUMCLI INTEGER NOT NULL,\n NAAM NVARCHAR(255) NOT NULL)\n)\n\ninsert into TMP_CLIENTNAME\nselect NUMCLI,\n NOMCLI ||' '|| PRNCLI as NAAM\nfrom CLIENT\nwhere CODLAN = 3\n and STAANN <> 'D'\n</code></pre>\n\n<p>Then your cross-product query becomes:</p>\n\n<pre><code>select C.NUMCLI,\n C.NAAM,\n T.FULLNAME,\n (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) as DIFF\nfrom TMP_CONTROL T,\n TMP_CLIENTNAME C\nwhere (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) >= 60\n</code></pre>\n\n<p>This query forces Oracle not to do any calculations other than the edit-distance in the join. This will make a difference....</p>\n\n<p>The down-side is that you need additional storage for the data.</p>\n\n<p>Once you have your data in this format you can consider some other options.... (which will likely affect the results of the edit-distance calculations)</p>\n\n<ul>\n<li>index the first letter of each name, and only calculate the edit distances where the first letters are the same.</li>\n<li>only calculate the edit distance when the length of the two names are less than say 5 characters different.</li>\n<li>.....</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:14:44.013",
"Id": "76273",
"Score": "0",
"body": "1) A number of clients have a middlename added to their firstname, and not all people on the list have a middlename. 2) We're normally not allowed to make temporary tables (I had to get permission to add a table to the DB), so I'd rather not add more. 3) Would it be better if I loaded the data in another program? (just combine the data in oracle, then do the similarity search in java/C++/...) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T22:39:50.460",
"Id": "76379",
"Score": "0",
"body": "Somewhat related to your last question : http://blog.jooq.org/2014/03/10/please-run-that-calculation-in-your-rdbms/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T22:51:26.413",
"Id": "76380",
"Score": "1",
"body": "@Andreas you can probably [create temporary tables](http://docs.oracle.com/cd/B28359_01/server.111/b28310/tables003.htm#ADMIN11633)... and populate/use those"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T08:17:51.393",
"Id": "76422",
"Score": "0",
"body": "@Josay not using hibernate (just jdbc), so no."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T08:19:46.683",
"Id": "76423",
"Score": "0",
"body": "@rolfl Not allowed to create temporary tables & given the size of the resulting table, it's probably not a good idea (I need to run the query on our production DB). (Would be a good idea in other circumstances, so +1 for that)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:43:39.513",
"Id": "44070",
"ParentId": "44054",
"Score": "6"
}
},
{
"body": "<p>Given the comments on my other answer, here is a second answer.</p>\n\n<p>Notes:</p>\n\n<ol>\n<li><em><strong>... have you done an explain-plan to figure out which option it has taken?</em></strong> I suggested this in the first answer... have you done it?</li>\n<li>If the explain plan shows that the code is producing a temp-table for the name-concat of the TMP_CONTROL data, and that it does a nested-loop scan of the CLIENT -> temp-table to calculate the Edit Distance - then there is nothing you can do that will be faster.</li>\n<li>If you really, really can't create the tables manually, then it is likely that the best result you will be able to achieve will be to externalize the data and process it outside the database.</li>\n</ol>\n\n<p>But, this is hard work, and, to match the DB performance, you will need a decent machine (lots of memory), and be willing to process the data in parallel, etc.</p>\n\n<p>You suggested this before, using Java.</p>\n\n<p>The basic algorithm I would use in Java (Java7) is as follows:</p>\n\n<ul>\n<li>Create a JDBC session to the database.</li>\n<li>Select the string-concatenation of the names from the TMP_CONTROL table.</li>\n<li>save these values in to an <code>ArrayList<String></code> (or, if you do not have enough memory, to a file on disk - one name per line)</li>\n<li>Create an ExecutorService with about as many threads as you have 'logical' CPUs (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int,%20java.util.concurrent.ThreadFactory%29\"><code>Executors.newFixed...</code></a>).</li>\n<li>Set up an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorCompletionService.html\"><code>ExecutorCompletionService</code></a> to handle results...</li>\n<li>Select the ID and the string-concatenation of the names from the CLIENT table. Save each record in to a new <code>CLient</code> class. This Client class will look something like:</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code> public class Client implements Callable<Client> {\n private final int id;\n private final String fullname;\n private final Map<String, Integer> matches = new HashMap<>();\n\n // constructor\n\n // getters for ID and fullname\n\n public void addMatch(String naam, int score) {\n matches.put(naam, score);\n }\n\n public Client call() {\n // Loop over each of the TMP names we stored earlier...\n for (String othername : tempnames) {\n // calculate the EditDistance from our name.\n // if it is > 60, do:\n if (editdistance > threshold) {\n addMatch(othername, editdistance);\n }\n } \n return this;\n }\n }\n</code></pre>\n\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorCompletionService.html#submit%28java.util.concurrent.Callable%29\">submit this Client</a> to your ExecutorCompletionHandler</li>\n<li>Have a separate thread that retrieves completed Clients from the ExecutorCompletionHandler with the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorCompletionService.html#take%28%29\"><code>Future<Client> future = handler.take();</code></a></li>\n<li>Process the matching names as you feel fit....</li>\n</ul>\n\n<p>That's about how I would do it in Java.....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T09:03:08.327",
"Id": "76670",
"Score": "0",
"body": "If I'm reading my explain plan correctly, it's using a nested loop C->T (added it to my main post). Since I'm running this on a production server, I have to make sure the query uses minimal resources (also, there's software that uses our database that is very sensitive to changes on the DB - I'm not allowed to add extra indexes to the db, etc...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T13:30:11.200",
"Id": "76696",
"Score": "0",
"body": "@Andreas Alright, it is not using any temp space, which means it has to re-calculate the name-concatenation of the TMP_CONTACT 74K times more than it should. You TMP_CONTACT table is much smaller than I expected.... you should alter the table, add a FULLNAME column, and pre-compute the concatenation.... really. 74M rows is not that large either.... are your statistics up to date? Why don't you join the CodeReview Chat room... the [2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T13:39:08.617",
"Id": "76701",
"Score": "0",
"body": "that's because I limited the resultset for the tmp_control subquery for tests. that table normally contains 20.100 rows (not that much compared to the 170.000 rows from my client table, but when you cross join both). I did a few optimizations in my queries and they seem to be a bit faster already (by removing subqueries and adding stuff to the main query)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T14:04:23.343",
"Id": "76709",
"Score": "0",
"body": "Solved on 2nd Monitor: Exported the data in a different DB where I could get full control."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:45:37.080",
"Id": "44162",
"ParentId": "44054",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44162",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:07:32.083",
"Id": "44054",
"Score": "11",
"Tags": [
"optimization",
"performance",
"sql",
"oracle",
"edit-distance"
],
"Title": "Comparing client lists with Cross Joins"
} | 44054 |
<p>Is there a way I can write this function with less code?</p>
<p><strong>jQuery</strong></p>
<pre><code>function displayError(display, string, xhr) {
var args = arguments;
var $error = $("div#error");
var visible = $error.is(":visible");
if(args.length == 1 && typeof display === "boolean" && display == false) {
if(visible) {
$error.slideUp();
}
} else if(args.length == 2 && typeof display === "boolean" && display == true && typeof string == "string") {
if(visible) {
$error.fadeOut(function () {
$(this).html('<b style="color: #ce1919;">(!)</b> '+string).fadeIn();
});
} else {
$error.html('<b style="color: #ce1919;">(!)</b> '+string).slideDown();
}
} else if(args.length == 3 && typeof display === "boolean" && display == true && typeof string == "string" && typeof xhr === "object") {
if(visible) {
$error.fadeOut(function () {
$(this).html('<b style="color: #ce1919;">('+xhr.status+")</b> "+string).fadeIn();
});
} else {
$error.html('<b style="color: #ce1919;">('+xhr.status+")</b> "+string).slideDown();
}
}
}
</code></pre>
<p><strong>Based on Marco's answer I came up with this:</strong></p>
<pre><code>function displayError(display, string, xhr) {
var $error = $("div#error");
var errVisible = $error.is(":visible");
var errStatus = typeof xhr === "object" ? xhr.status : "!";
var errMsg = '<b style="color: #ce1919;">(' + errStatus + ")</b> " + string;
if(display) {
if(errVisible) {
$error.fadeOut(function() {
$(this).html(errMsg).fadeIn();
});
} else {
$error.html(errMsg).slideDown();
}
} else {
$error.slideUp();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:52:05.613",
"Id": "76253",
"Score": "0",
"body": "You should remove the `b` element and its hard-coded color and move the styling to the CSS."
}
] | [
{
"body": "<p>I don't use Javascript, but i could write it in this way:</p>\n\n<pre><code>function displayError(display, string, xhr) \n{\n var args = arguments;\n var $error = $(\"div#error\");\n var visible = $error.is(\":visible\");\n\n if (!display)\n {\n $error.slideUp();\n }\n else\n {\n\n if (visible) \n {\n switch (args.length) \n {\n case 1:\n case 2:\n $error.fadeOut(function () \n {\n $(this).html('<b style=\"color: #ce1919;\">(!)</b> ' + string).fadeIn();\n });\n break;\n case 3:\n $error.fadeOut(function () \n {\n $(this).html('<b style=\"color: #ce1919;\">(' + xhr.status + \")</b> \" + string).fadeIn();\n });\n break;\n }\n } \n else \n {\n $error.html('<b style=\"color: #ce1919;\">(' + xhr.status + \")</b> \" + string).slideDown();\n }\n }\n}\n</code></pre>\n\n<p>But why you use args.length == 1/2/3 if you don't do anything with it?\nYou could just write:</p>\n\n<pre><code>function displayError(display, string, xhr) {\n var $error = $(\"div#error\");\n var visible = $error.is(\":visible\");\n var status = typeof xhr === \"object\" ? xhr.status : \"!\";\n\n if (display) {\n if (visible) {\n $error.fadeOut(function () {\n $(this).html('<b style=\"color: #ce1919;\">(' + status + ')</b> ' + string).fadeIn();\n });\n\n } else {\n $error.html('<b style=\"color: #ce1919;\">(' + status + \")</b> \" + string).slideDown();\n }\n } else {\n $error.slideUp();\n }\n}\n</code></pre>\n\n<p>I used <code>var status = typeof xhr === \"object\" ? xhr.status : \"!\";</code> so you will get the status if <code>xhr</code> is an <code>object</code>, or <code>!</code> if not.</p>\n\n<p>I removed all typeof parts since i found it useless, you will always get a string so why you worry about it</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:27:02.960",
"Id": "76247",
"Score": "0",
"body": "Very nice answer for someone who doesn't use JavaScript, +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:23:29.213",
"Id": "44060",
"ParentId": "44057",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44060",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:28:30.513",
"Id": "44057",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Shorter way of writing my displayError() function?"
} | 44057 |
<p>I want to optimize a Perl function which is frequently used in my application. The function creates a special datastructure from the results of <code>DBI::fetchall_arrayref</code> which looks like:</p>
<pre><code>$columns = ['COLNAME_1','COLNAME_2','COLNAME_3']
$rows = [ ['row_1_col_1', 'row_1_col_2', 'row_1_col_3'],
['row_2_col_1', 'row_2_col_2', 'row_2_col_3'],
['row_3_col_1', 'row_3_col_2', 'row_3_col_3']
];
</code></pre>
<p>The new datastructure must contain the data in the following form (all row-values for every column in a single arrayref)</p>
<pre><code>$retval = {
row_count => 3,
col_count => 3,
COLNAME_1 => ['row_1_col_1', 'row_2_col_1', 'row_3_col_1' ],
COLNAME_2 => ['row_1_col_2', 'row_2_col_2', 'row_3_col_2' ],
COLNAME_3 => ['row_1_col_3', 'row_2_col_3', 'row_3_col_3' ]
}
</code></pre>
<p>The new datastructure is a Hash of Arrays and is used in the whole application. I cannot change the format (its too frequently used). I wrote a function for this conversion. I've already done some some performance optimization after profiling my application. But it's not enough. Now the function looks like:</p>
<pre><code>sub reorganize($$) {
my ($self,$columns,$rows) = @_;
my $col_count = scalar(@$columns);
my $row_count = scalar(@$rows);
my $col_index = 0;
my $row_index = 0;
my $retval = { # new datastructure
row_count => $row_count,
col_count => $col_count
};
# iterate through all columns
for($col_index=0; $col_index<$col_count; $col_index++) {
# create a arrayref for all row-values of the current column
# set it to the correct size and assign all values to this arrayref
my $tmp = [];
$#{$tmp} = $row_count-1; # set size of array to the number of rows
# iterate through all rows
for($row_index=0; $row_index<$row_count; $row_index++) {
# assign values to arrayref (which has the correct size) instead of a "slow" push
$tmp->[$row_index] = $rows->[$row_index][$col_index];
}
# Assign the arrayref to the hash. The hash-key is the name of the column
$retval->{$columns->[$col_index]} = $tmp;
}
return $retval;
}
</code></pre>
<p>My Question: </p>
<p>Is there a way to further optimize this function (maybe using $<em>[...])? I found some hints <a href="http://de.slideshare.net/perrin_harkins/top-10-perl-performance-tips-11845463" rel="nofollow">here</a> at page 18 and 19, but I don't have any experience in using $</em> in different contexts. </p>
<p>I have to say that the function listed above is the best I can do. There may be other ways to do some optimization which I have never heard of.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:12:11.327",
"Id": "76245",
"Score": "0",
"body": "Just a note: It seems (`$self`) you are using the subroutine as a method. You can remove the prototypes `($$)` as they are ignored in method calls anyway."
}
] | [
{
"body": "<p>The following code is about 35% faster (measured with <a href=\"http://p3rl.org/Benchmark\" rel=\"nofollow\">Benchmark</a>). The tricks:</p>\n\n<ul>\n<li><p>no anonymous array created for <code>$tmp</code>.</p></li>\n<li><p>explicit <code>return</code> removed.</p></li>\n<li><p>variables created in place where their value is needed.</p></li>\n</ul>\n\n<p>Some of the tricks added just a 3%, the first one seemed the most important. YMMV.</p>\n\n<p>I experimented with <code>$_</code> and <code>map</code>s, too, but it seems the plain old C-style loop is the fastest.</p>\n\n<pre><code>sub faster {\n my ($self, $columns, $rows) = @_;\n my $retval = {\n row_count => my $row_count = @$rows,\n col_count => my $col_count = @$columns,\n };\n for (my $col_index = 0 ; $col_index < $col_count ; $col_index++) {\n my $tmp;\n for (my $row_index = 0 ; $row_index < $row_count ; $row_index++) {\n $tmp->[$row_index] = $rows->[$row_index][$col_index];\n }\n $retval->{$columns->[$col_index]} = $tmp;\n }\n $retval\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:45:19.937",
"Id": "76250",
"Score": "0",
"body": "Thanks you very much. The first and second tricks are really interesting and from a c-style point of view very strange. i will try it with NYTProf asap."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:47:21.227",
"Id": "76251",
"Score": "0",
"body": "@some_coder: Forget the C-style point of view when optimizing Perl :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:24:42.300",
"Id": "76261",
"Score": "0",
"body": "In my benchmark (yay!) I've observed foreach loop was faster (and, what's even more important, more readable), so please change C-style fors to `for my $col_index (0 .. $col_count - 1)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:26:01.633",
"Id": "76262",
"Score": "0",
"body": "@Xaerxess: In my Benchmark, switching to this style loop was slower."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:55:47.437",
"Id": "76271",
"Score": "0",
"body": "@choroba I guess it depends on how many iterations you're doing - see [this gist](https://gist.github.com/Xaerxess/9486043), for-c outperforms foreach only up to 4-8 elements to iterate over. Still, in terms of readability, foreach wins, and that said I wish I'd never have to optimize fors."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:35:19.463",
"Id": "44061",
"ParentId": "44059",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44061",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T11:55:05.273",
"Id": "44059",
"Score": "3",
"Tags": [
"performance",
"perl"
],
"Title": "Performance optimization in function for datastructure mapping"
} | 44059 |
<p>I have a strongly typed enum and <code>std::vector</code> of this type.</p>
<pre><code>enum class Colors { red, green, blue };
std::vector v = { Colors::blue, Colors::red };
</code></pre>
<p>I trying to output <code>v</code> to standard output via <code>std::copy</code>.</p>
<pre><code>std::copy(v.begin(), v.end(), std::ostream_iterator<Colors>(std::cout, " ");
</code></pre>
<p>Compilation failed because compiler do not know how to print <code>Colors</code>. I can define <code>operator <<</code> for colors, but it looks too excessive for me. Then try print <code>int</code> values of <code>v</code> elements.</p>
<pre><code>std::copy(v.begin(), v.end()
, std::ostream_iterator<std::underlying_type<Colors>::type>>(std::cout, " ");
</code></pre>
<p>Compilation failed because it is prohibited to print <code>Colors</code> to <code>std::ostream_iterator<int></code>. Ok. Then <code>std::transform</code> can help.</p>
<pre><code>std::transform(v.begin(), v.end()
, std::ostream_iterator<std::underlying_type<Colors>::type>(std::cout, " ")
, [&](Colors &c) -> std::underlying_type<Colors>::type
{
return std::underlying_type<Colors>::type(c);
}
);
</code></pre>
<p>However, this lambda looks ugly. Is there neater way to <code>copy</code> or <code>transform</code> vector of <code>Colors</code>? Maybe boost has some way? </p>
<p>Of course, a loop can print, but I'd prefer to avoid explicit loop.</p>
<pre><code>for(auto c : v)
{
std::cout << std::underlying_type<Colors>::type(c) << std::endl;
}
</code></pre>
<hr>
<p>I have a lot of different <code>enum class</code>es in my project. All of them I need to print out. I don't like idea to create <code>operator <<</code> for each one individually. However, if I try to make templated <code>operator <<</code> then I've got a global redefinition of this operator. And this is not what I actually want.</p>
<pre><code>template <typename T>
std::ostream &operator << (std::ostream &_os, const T &_t) {
_os << typename std::underlying_type<T>::type(_t);
return _os;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:08:58.390",
"Id": "76257",
"Score": "0",
"body": "Why do you want to avoid defining an `operator<<` or using a range-based for loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:29:33.480",
"Id": "76264",
"Score": "0",
"body": "I avoid defining an `operator<<` because I do not want to multiply entities, if it possible. If it's not possible, then I will use the operator. I avoid loop because I like more \"functional\" style."
}
] | [
{
"body": "<p>It seems to me that if you want to insert an object into a stream, the \"right\" way to do it is normally to define an <code>operator<<</code> for that type. That goes for strongly typed enums just as much as it does for class/struct objects.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <utility>\n#include <iterator>\n\nenum class colors { red, green, blue };\nstd::vector<colors> v = { colors::blue, colors::red };\n\nstd::ostream &operator<<(std::ostream &os, colors const &c) {\n return os << std::underlying_type<colors>::type(c);\n}\n\nint main() {\n std:copy(v.begin(), v.end(), std::ostream_iterator<colors>(std::cout, \"\\n\"));\n}\n</code></pre>\n\n<p>That seems simple and straightforward enough that I'd be at least a little surprised to see a substantially cleaner/simpler solution (at least in C++ as it's currently defined; obviously, it's open to argument that some other language or some future definition of C++ could make things cleaner).</p>\n\n<p>Using something like <code>std::transform</code> puts the burden in the wrong place. It requires that <em>all</em> code that uses the type in question contain and encode \"knowledge\" of the internals of the enumeration. What you generally want is to contain the complexity and the internals of the type in one place, so the rest of the code can just work with its external interface. An external interface of <code>stream << object</code> is simple and straightforward. Forcing the rest of the world to work with an interface of <code>stream << std::underlying_type<colors>::type(c);</code> anything but straightforward <em>or</em> simple. It's ugly and nasty.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:31:59.700",
"Id": "44068",
"ParentId": "44063",
"Score": "10"
}
},
{
"body": "<p>You can do this using SFINAE to fail instantiating your global <code>operator<<</code> overload for non-enums:</p>\n\n<pre><code>template<typename EnumT>\ntypename std::enable_if<std::is_enum<EnumT>::value, std::ostream>::type &operator<<(std::ostream &os, EnumT x) {\n return os << typename std::underlying_type<EnumT>::type(x);\n}\n</code></pre>\n\n<p>Full, working source, including an abi demangle to pretty-print the enums:</p>\n\n<pre><code>#include <iostream>\n#include <iterator>\n#include <type_traits>\n#include <typeinfo>\n#include <cxxabi.h>\n#include <memory>\n#include <cstdlib>\n#include <vector>\n\ntemplate<typename EnumT>\ntypename std::enable_if<std::is_enum<EnumT>::value, std::ostream>::type &operator<<(std::ostream &os, EnumT x) {\n int status;\n std::unique_ptr<char, void(*)(void*)> demangled_enum(abi::__cxa_demangle(typeid(EnumT).name(), NULL, NULL, &status), std::free);\n std::unique_ptr<char, void(*)(void*)> demangled_underlying(abi::__cxa_demangle(typeid(typename std::underlying_type<EnumT>::type).name(), NULL, NULL, &status), std::free);\n os << demangled_enum.get() << \":\" << demangled_underlying.get() << \"(\" << typename std::underlying_type<EnumT>::type(x) << \")\";\n return os;\n}\n\nenum EnumA { a, b, c };\nenum class EnumB : short { a, b, c };\n\nint main() {\n std::cout << 3 << std::endl;\n std::cout << EnumA::b << std::endl;\n std::cout << EnumB::c << std::endl;\n std::cout << \"foo\" << std::endl;\n char bar[] = \"bar\";\n std::cout << bar << std::endl;\n char *baz = bar;\n std::cout << baz << std::endl;\n std::cout << std::string(baz) << std::endl;\n\n std::vector<EnumB> v = { EnumB::a, EnumB::c };\n std::copy(v.begin(), v.end(), std::ostream_iterator<EnumB>(std::cout, \"\\n\"));\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>3\nEnumA:unsigned int(1)\nEnumB:short(2)\nfoo\nbar\nbar\nbar\nEnumB:short(0)\nEnumB:short(2)\n</code></pre>\n\n<p>The various non-enum <code><<</code> calls are just there to show that our overload is not being called for them. It took me a while to get this to work -- I had my overload called for non-const strings as I was working on it. It beats me why this doesn't work when <code>std::enable_if</code> is used on the <code>EnumT x</code> argument, or for partial instantiation of a helper struct (all of which I tried) -- I'll leave that to somebody else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-08T12:37:31.360",
"Id": "96223",
"ParentId": "44063",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:53:52.373",
"Id": "44063",
"Score": "9",
"Tags": [
"c++",
"c++11",
"enum",
"boost",
"container"
],
"Title": "Converting data when output std container via ostream_iterator"
} | 44063 |
<p>I am writing an application that uses <code>ASP.NET MVC</code> for its front end, and for the back end, it uses <code>RavenDB</code> to store data. This has so far worked out great, but I am hitting a huge wall with the use of <code>enum</code> in selecting things.</p>
<p>The problem comes with front end interaction. I have many places where I want enums to be selectable via drop down lists and the like. This works okay on the surface, but I ran across an issue with the actual relationship between enums and JSON as a language/format. These issues were <strong>not</strong> overcome by using the traditional <code>[JsonConverter(typeof(StringEnumConverter))]</code> attribute in my models.</p>
<p>Essentially put, MSDN reports the following; from the <a href="http://msdn.microsoft.com/en-us/library/bb412170.aspx">MSDN</a></p>
<blockquote>
<p>Enumeration member values are treated as numbers in JSON, which is
different from how they are treated in data contracts, where they are
included as member names. For more information about the data contract
treatment, see Enumeration Types in Data Contracts.</p>
<p>For example, if you have public enum Color {red, green, blue, yellow,
pink}, serializing yellow produces the number 3 and not the string
"yellow".</p>
<p>All enum members are serializable. The EnumMemberAttribute and the
NonSerializedAttribute attributes are ignored if used.</p>
<p>It is possible to deserialize a nonexistent enum value - for example,
the value 87 can be deserialized into the previous Color enum even
though there is no corresponding color name defined.</p>
<p>A flags enum is not special and is treated the same as any other enum.</p>
</blockquote>
<p>Now what this meant is that even if I used fancy footwork to convert my enums into strings for my dropdownlists, they still get saved back to the database as integers; Or rather it is more sufficient to say that they get saved in Raven as strings, but still 'considered' as integers upon deserialization back to the javascript components/MVC.</p>
<p>Using a lot of time and patience, I did manage to find "work arounds" for this; They were cumbersome and obtuse, I did not like them. It made plugging my enums into various UI javascript packages difficult. In the end, I elected to just do away with enums entirely and go with a different approach.</p>
<p>So what I did is create a base class <code>Listable</code>.</p>
<pre><code>public class Listable : IHasIdentity, IHasName, IHasLabel, IHasStyle {
public Listable(): base() { }
public string Id { get; set; }
public string Name { get; set; }
public string Label { get; set; }
public string CSS { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public string Keyword { get; set; }
}
</code></pre>
<p>Listable is used to form a collective association within my program, so there is another base class known as a <code>Listing</code>.</p>
<pre><code>[RavenTag("listings")]
public class Listing : IHasIdentity, IHasName, IMayTransform, IRavenIdentity {
public Listing(): base() {
Items = new List<Listable>();
}
public string Id { get; set; }
public string Name { get; set; }
public List<Listable> Items { get; set; }
/// <summary>
/// The identity for raven to generate for this document when it is created.
/// </summary>
/// <returns>
/// The complete identity for Raven to use for this object.
/// </returns>
public string Identity() {
return string.Format("listings/{0}", Name.AsIdentity());
}
}
</code></pre>
<p>So then, a <code>Listing</code> has many items, and upon being created it uses an extension method to save an identity for each item in the listing, defined here;</p>
<pre><code>public static class TypeExtensions {
public static Models.Listing ToIdentities(this Models.Listing obj) {
// set the identity of each item in the collection
foreach (var item in obj.Items)
item.Id = string.Format("list/{0}/{1}",
obj.Name.ToLower().Replace(" ", "-").Replace("/", "-"),
item.Name.ToLower().Replace(" ", "-").Replace("/", "-"));
return obj;
}
}
</code></pre>
<p>This seems like a lot of work just to get a simple list, but in the end it paid off because now I have a user interface where my staff members can define any number of lists, with any number of items, and edit them; And then these can be easily bound to javascript controls in any way we need like standard objects. An example of such a list is as follows;</p>
<pre><code>{
"Name": "Genders",
"Items": [
{
"Id": "list/genders/male",
"Name": "Male",
"Label": "Male",
"CSS": null,
"Description": null,
"Order": 0,
"Keyword": null
},
{
"Id": "list/genders/female",
"Name": "Female",
"Label": "Female",
"CSS": null,
"Description": null,
"Order": 1,
"Keyword": null
},
{
"Id": "list/genders/none",
"Name": "None",
"Label": "",
"CSS": null,
"Description": null,
"Order": 2,
"Keyword": null
}
]
}
</code></pre>
<p>And then these are easy to query, a simple service on my controllers makes it trivial.</p>
<pre><code>[HttpGet]
[Route("list/named/{name}")]
public JsonResult Named(string name) {
// query for all known list items
var listable = RavenSession
.Load<Listing>(String.Format("listings/{0}", name))
.Items
.OrderBy(n => n.Order)
.ToList();
return Json(listable, JsonRequestBehavior.AllowGet);
}
</code></pre>
<p>So with this, I can plug this into anything that expects JSON data, for example in my situation, I am using <code>Kendo UI</code> and their <code>DropDownList</code> component with <code>RemoteDataSource</code>, it is easy to make drop down lists bound to simple objects.</p>
<pre><code>$("#genders").kendoDropDownList({
dataTextField: "Name",
dataValueField: "Id",
optionLabel: "Select ... ",
dataSource: {
dataType: "json",
transport: {
read: {
url: "/list/named/genders"
}
}
}
});
</code></pre>
<p>Because I am dealing with simple JSON, and not Enums, this does everything I want. It gives me infinite list flexibility, it allows more verbose data that I may want in the future, and it provides a convenient model for repeating the process in multiple places.</p>
<h1>The Question</h1>
<p>I recently came under fire by a co-worker who saw this and claimed that it was "bad practice", and I should just use enums and deal with the problems of converting them all the time. To me, that seems troublesome and like it leaves so many gaps, and causes so many issues and leaves it so confusing. But their reasoning is that because enums are so much smaller in size, it will improve performance.</p>
<p>So I wanted to get the opinions of more people who may have experienced this. There are about 37+ lists in the entire program so far, and this is running great for me, and my control panel users love the flexibility. It has also made testing a lot simpler, and upgrading simpler.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:43:21.660",
"Id": "76280",
"Score": "0",
"body": "I'm confused, why where you using an enum for a user defined drop down list? because that's what it sounds like you're describing but an enum is not user defined."
}
] | [
{
"body": "<p>It seems like you've gone to more trouble to avoid using <code>enum</code> than you would have had just using them. <code>enums</code> are just numbers with a mask, converting to an int to an <code>enum</code> and vica versa is quite simple in C#, they also have a <code>ToString</code> which makes using their string value super simple as-well. I probably don't grasp the troubles you were having with using <code>enums</code>, but they are certainly more efficient than using <code>strings</code>. I think the helper methods you've created are great and it the implementation details of your project are certainly up to your team, and depending on the size and longevity of the project you may decide to continue using the <code>string</code> system. However in the future I would highly recommend using <code>enums</code> instead, and perhaps make similar helper methods which help with the troublesome conversions.</p>\n\n<p>Short story: Your co-worker is right, <code>enums</code> are better, but it is ultimately up to your team on the implementation of this. If it is worth your time, change it, else use <code>enums</code> on your next project.</p>\n\n<hr>\n\n<p><strong>Edit</strong>: Use <a href=\"http://james.newtonking.com/json\" rel=\"nofollow noreferrer\">Json.Net</a> to better serialize enums</p>\n\n<p><a href=\"https://stackoverflow.com/a/2870420/1812944\">https://stackoverflow.com/a/2870420/1812944</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:56:57.510",
"Id": "76282",
"Score": "0",
"body": "But it isn't possible to get enums to cooperate with the way the data needs to be displayed. They can only get recognized by JSON as integers, but they need to be strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:59:33.513",
"Id": "76283",
"Score": "0",
"body": "I basically had to do a ton of extra conversion to make sure things stayed correct, and then if we ever had to update the enums with new values, it destroyed all of the existing ones."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:38:17.860",
"Id": "76302",
"Score": "0",
"body": "@Ciel Do you have a database you can store your enums in, and just pull the appropriate strings in when needed. And Look at the edit I just made... It may be something that can help you out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-05T17:46:22.400",
"Id": "529959",
"Score": "0",
"body": "It's also worth noting that converting back and forth between enum and string is quite literally 20x slower and uses 24x more memory than using strings directly (you'll have to look at the ToString() implementation and you'll see why. \"Magic Strings\" aren't always as \"Magic\" as they seem. They're only bad practice __within a process boundary__, but when you're crossing (like in an API), you're technically receiving magic strings so really you're just using Enums as passive validation which is saves you time but is completely unnecessary."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:51:29.813",
"Id": "44072",
"ParentId": "44066",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44072",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:24:08.230",
"Id": "44066",
"Score": "6",
"Tags": [
"c#",
"json",
"enum",
"asp.net-mvc"
],
"Title": "Concerned with Enums, JSON, and ASP.NET MVC"
} | 44066 |
<p>The following code is used to find the usual_gp(General Practitioner) from <code>gpCollection</code> variable of type <code>TreeMap<Long(Date)</code>, <code>SummableMap<String(GPId)</code>, <code>Integer(GPCount)>></code> and store result (usual GP) along with date on <code>usualGPCollection</code> Map.</p>
<p>Does this code follow common best practices? Logic implemented on below code is</p>
<p><img src="https://i.stack.imgur.com/qqJfe.png" alt="enter image description here"></p>
<pre><code> Long startDate = gpCollection.firstKey();
Long endDate = gpCollection.lastKey();
TreeMap<Long, String> usualGPCollection = new TreeMap<Long, String>();
for (Long i = startDate; i <= new DateTime(endDate).plusYears(1).getMillis(); i = i + new DateTime(i).plusMonths(1).getMillis()) {
Long beforeOneYearDate = new DateTime(i).minusMonths(12).getMillis();
Long beforeSixMonthDate = new DateTime(i).minusMonths(6).getMillis();
Long beforeThreeMonthDate = new DateTime(i).minusMonths(3).getMillis();
List<String> returnGPCollection = customSubMap(gpCollection, beforeOneYearDate, i);
if(returnGPCollection.size() == 1) {
usualGPCollection.put(i, returnGPCollection.get(0));
} else if(returnGPCollection.size()>1){
returnGPCollection = customSubMap(gpCollection, beforeSixMonthDate, i);
if(returnGPCollection.size() == 1) {
usualGPCollection.put(i, returnGPCollection.get(0));
}else if(returnGPCollection.size()>1){
returnGPCollection = customSubMap(gpCollection, beforeThreeMonthDate, i);
if(returnGPCollection.size() == 1) {
usualGPCollection.put(i, returnGPCollection.get(0));
} else if(returnGPCollection.size()>1){
// returnGPCollection = customSubMap(gpCollection, i);//todo
}
}
returnGPCollection = customSubMap(gpCollection, beforeOneYearDate, i);
}
}
// customSubMap() Function is used to find max count GP on given date range.
private List<String> customSubMap(TreeMap<Long, SummableMap<String, Integer>> gpCollectionMap, Long fromDate, Long toDate) {
List<String> returnMap = null;
SortedMap<Long, SummableMap<String, Integer>> temp = gpCollectionMap.subMap(fromDate, toDate);
Collection values = temp.values();
Iterator<SummableMap<String, Integer>> test = values.iterator();
SummableMap<String, Integer> resultMap = new SummableMap<String, Integer>();
TreeMap<Integer, List<String>> reverseTree = new TreeMap<Integer, List<String>>();
while (test.hasNext()) {
resultMap.putAll(test.next());
// String key = test.next().clone();
}
List mapValues = new ArrayList(resultMap.values());
Collections.sort(mapValues);
NavigableMap<String, Integer> resultMapUpdated = sortHashMapByValuesD(resultMap);
String firstKey = resultMapUpdated.firstKey();
String secondKey = resultMapUpdated.lowerKey(firstKey);
Integer firstValue = resultMapUpdated.get(firstKey);
Integer secondValue = resultMapUpdated.get(secondKey);
if(firstValue == secondValue){
returnMap.add(firstKey);
returnMap.add(secondKey);
}else {
returnMap.add(firstKey);
}
return returnMap;
}
private List<String> customSubMap(TreeMap<Long, SummableMap<String, Integer>> gpCollectionMap, Long toDate) {
List<String> returnMap = null;
Long beforeThreeMonthDate = new DateTime(toDate).minusMonths(3).getMillis();
SortedMap<Long, SummableMap<String, Integer>> temp = gpCollectionMap.subMap(beforeThreeMonthDate, toDate);
String latestGP = temp.get(temp.lastKey()).keySet().iterator().next();
returnMap.add(latestGP);
return returnMap;
}
</code></pre>
| [] | [
{
"body": "<p>When you have cascading conditions like you have, it can become 'messy'. At some point the design-pattern <a href=\"http://en.wikipedia.org/wiki/Chain_of_responsibility_pattern\">'Chain of responsibility'</a> becomes useful....</p>\n\n<p>Consider an interface:</p>\n\n<pre><code>public interface GPSelector {\n String selectGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate);\n}\n</code></pre>\n\n<p>Then, consider an array of concrete implementations of that interface:</p>\n\n<pre><code>private static final GPSelector[] GPRULES = new GPSelector[] {\n\n // 1-year rule\n new GPSelector() {\n public String selectGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate) {\n List<String> lastyear = customSubMap(gpCollection, new DateTime(i).minusMonths(12).getMillis(), calcdate);\n if (lastyear.size() == 1) [\n return lastyear.get(0);\n }\n return null;\n }\n },\n\n // 6-month rule\n new GPSelector() {\n public String selectGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate) {\n // return not-null String if there is a successful 6-month candidate....\n }\n },\n\n .......\n\n};\n</code></pre>\n\n<p>OK, so now you have an ordered array of rules that progressively select the right UsualGP candidate.</p>\n\n<p>I your code, you can now simply have the following:</p>\n\n<pre><code>public String selectUsualGP(TreeMap<Long, SummableMap<String, Integer>> gpCollection, Long calcdate) {\n for (GPSelector rule : GPRULES) {\n String gp = rule.selectGP(gpCollection, calcdate);\n if (gp != null) {\n return gp;\n }\n }\n return null; // nothing matched.... :(\n}\n</code></pre>\n\n<p>Adding a new rule is easy, just insert it in to the chain at the appropriate place....</p>\n\n<p>I hope the above is enough to show how the chain-of-responsibility pattern can be applied.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:12:59.473",
"Id": "76296",
"Score": "0",
"body": "Woow Great Answer... Thanks @rolfl. I really appreciate your effort."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:49:10.407",
"Id": "44075",
"ParentId": "44069",
"Score": "5"
}
},
{
"body": "<p>I feel that <code>customSubMap()</code> is complicated and confusingly named.</p>\n\n<p>I would devise a solution based around a <code>Counter</code> object, inspired by <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\">Python's <code>collections.Counter</code></a> class. A <code>Counter</code> would be a more generically useful object than a <code>GPSelector</code>, and furthermore, selecting visits in a date range is trivially taken care of already by <code>NavigableMap.tailMap()</code>.</p>\n\n<pre><code>/**\n * Finds the \"usual GP\" according to the specification.\n *\n * @param gpCollection A record of the patient's GP visits.\n * Keys are visit times (in milliseconds since 1970).\n * Values are the names of the GPs.\n * @return the usual GP, or null if gpCollection is empty\n */\npublic static String usualGP(NavigableMap<Long, String> gpCollection) {\n if (gpCollection.isEmpty()) {\n return null;\n }\n\n // I assume that the date thresholds should be relative to the date\n // of the last visit, rather than today.\n DateTime lastVisitDate = new DateTime(gpCollection.lastKey());\n final long[] dateThresholds = new long[] {\n lastVisitDate.minusYears(1).getMillis(),\n lastVisitDate.minusMonths(6).getMillis(),\n lastVisitDate.minusMonths(3).getMillis()\n };\n\n for (long threshold : dateThresholds) {\n SortedMap<Long, String> recentVisits = gpCollection.tailMap(threshold);\n Counter<String> countRecent = new Counter<String>(recentVisits.values());\n Map.Entry<String, Integer>[] mostCommon = countRecent.mostCommon(2);\n\n // Is there a tie?\n if ( mostCommon.length > 1 &&\n mostCommon[0].getValue() > mostCommon[1].getValue() ) {\n return mostCommon[0].getKey();\n }\n }\n\n return gpCollection.lastEntry().getValue();\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public class Counter<T> {\n public Counter(Iterable<T> values) {\n for (T value : values) {\n this.add(value);\n }\n }\n\n public void add(T value) {\n ...\n }\n\n /**\n * Returns a list of the n most common elements and their counts\n * from the most common to the least. Elements with equal counts\n * are ordered arbitrarily.\n */\n public Map.Entry<T, Integer>[] mostCommon(int n) {\n ...\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:54:24.117",
"Id": "77924",
"Score": "0",
"body": "I've posted a [follow-up question of my own](http://codereview.stackexchange.com/q/44772/9357) for the `Counter`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:30:58.207",
"Id": "44090",
"ParentId": "44069",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "44075",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:35:32.370",
"Id": "44069",
"Score": "5",
"Tags": [
"java",
"optimization"
],
"Title": "General practitioner collection"
} | 44069 |
<p>I always see comments about how a Unit Test should only be testing one piece of functionality. For the most part, I definitely agree with that assessment. However, I'm working on testing a method right now that has me pondering if being laxer on this ideal would be a better thing, so I'm curious to everyone's opinions.</p>
<p>The method that I'm testing is one that gathers Messages created between a user-defined date range, and groups them by Date, with totals of each type of Message per day. (Request, Offer, Dialog, and Referral).</p>
<p>So for a range of two days (for simplicity), I'll return an <code>IEnumerable<MessageDay></code>, where <code>MessageDay</code> is defined as such:</p>
<pre><code>public class MessageDay() {
public DateTime Date { get; set; }
public int Requests { get; set; }
public int Offers { get; set; }
public int Dialogs { get; set; }
public int Referrals { get; set; }
public int Total {
get {
return this.Requests + this.Offers + this.Dialogs + this.Referrals;
}
}
}
</code></pre>
<p>I have my Mock setup for my unit test with several of each type of Message, ranging from DateTime.MinValue, DateTime.Now, and DateTime.MaxValue.</p>
<p>Should I create a Unit Test with the same parameters going into the method I'm testing repeatedly? (i.e. first test will test a count of the days, second test will test the total Requests for day 1, etc for each type of Message, for each date)</p>
<p>I'm thinking that having so many tests (up to 13 per date range with 4 different date parameter possibilities) would be ridiculous, however I would like to know the standard, accepted way to do this.</p>
<p><strong>EDIT</strong>
Here is my Mock data that I have set up:</p>
<pre><code>[TestInitialize()]
public void TestInitialize() {
var mock = new Mock<IReportingRepository>();
var now = DateTime.Now;
mock.Setup(m => m.Messages).Returns(new Message[] {
new Request { CreatedOn = now },
new Request { CreatedOn = DateTime.MinValue },
new Request { CreatedOn = DateTime.MaxValue },
new Offer { CreatedOn = DateTime.MinValue },
new Offer { CreatedOn = DateTime.MinValue },
new Offer { CreatedOn = DateTime.MaxValue },
new Dialog { CreatedOn = now },
new Dialog { CreatedOn = DateTime.MaxValue },
new Referral { CreatedOn = now },
new Referral { CreatedOn = DateTime.MinValue }
}.AsQueryable());
controller = new ReportingController(mock.Object);
}
</code></pre>
<p>This would be along the lines of my "fewest number of tests":</p>
<pre><code>[TestMethod]
public void CanFindAllCounts() {
var result = (MessageResponse)controller.GetMessageAnalytics(new MessageRequest()).Data;
Assert.AreEqual(3, result.Days.Count());
var day = result.Days.FirstOrDefault();
Assert.AreEqual(4, day.Total);
Assert.AreEqual(1, day.Requests);
Assert.AreEqual(2, day.Offers);
Assert.AreEqual(0, day.Dialogs);
Assert.AreEqual(1, day.Referrals);
day = result.Days.Where(d => d.Date.Date == DateTime.Now.Date).FirstOrDefault();
Assert.AreEqual(3, day.Total);
Assert.AreEqual(1, day.Requests);
Assert.AreEqual(0, day.Offers);
Assert.AreEqual(1, day.Dialogs);
Assert.AreEqual(1, day.Referrals);
day = result.Days.Last();
Assert.AreEqual(3, day.Total);
Assert.AreEqual(1, day.Requests);
Assert.AreEqual(1, day.Offers);
Assert.AreEqual(1, day.Dialogs);
Assert.AreEqual(0, day.Referrals);
}
</code></pre>
<p>The other extreme would of course be a test for each of those Asserts. Being that I'm using Moq, it's not a huge deal and would run quickly, but I just feel that it's overkill.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:33:28.223",
"Id": "76278",
"Score": "0",
"body": "Possibly Programmers? I can imagine this question working here though, if you include the tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:37:39.910",
"Id": "76279",
"Score": "0",
"body": "I included what I'm doing for the one set of parameters. If you want me to go with some of the extrapolated tests as an alternate to this, that'd be fine. I also don't want my question to be thousands of lines long, as I've found on Stack Overflow that the more concise questions get more attention, and the longer they get can be too intimidating."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:06:56.383",
"Id": "76295",
"Score": "1",
"body": "That's much better. I'd venture to say that either this is correct (you're just validating the result of a single method), or you ought to abstract it in such a way that the validation is simpler and requires a single assert; this could possibly be done by making a custom assert, or defining an `.Equals()` method on your Day class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:30:04.647",
"Id": "76299",
"Score": "0",
"body": "Interesting ideas. It kinda seems like overkill to add an `.Equals()` method to an object for nothing other than Unit Testing. (This could also be violating Separation of Concerns). I guess all of this is why they're guidelines. ;) But, I'm just trying to improve my skills too, should I look for a new job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:34:34.047",
"Id": "76300",
"Score": "2",
"body": "I don't think I'd consider `.Equals()` overkill, because it's part of `System.Object`. You have one, but it isn't useful for comparisons at the moment, because it only checks reference equality. It wouldn't be much of a stretch to imagine calling it in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:39:14.253",
"Id": "76304",
"Score": "0",
"body": "Sounds like a good approach. Would you want to create an answer so I can accept it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:19:44.133",
"Id": "76490",
"Score": "1",
"body": "Your test could fail if `TestInitialize` runs just before and `TestMethod` runs just after midnight. Read `DateTime.Now` just once and use the result (or some constant value) in both setup and execution of the test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:55:43.913",
"Id": "76501",
"Score": "0",
"body": "Thanks. I did catch that already because I do a `GroupBy()` on the datetime properties, and that was creating multiple groups. So I already changed to a single variable set to DateTime.Now and used that instead, and reworked my query to group on the dates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T03:09:52.420",
"Id": "79104",
"Score": "1",
"body": "+1 to @Magus' `Equals` comment. Even more so because `Equals` declares something about the design of that class. It is not merely a mechanism to DRY up test code. AND of course `Equals` must be tested too."
}
] | [
{
"body": "<p>In this case, what you're really trying to do is validate three <code>MessageDay</code>s, as the return values of one method. As you are only testing one thing (the successful return of a method), you need not worry about testing too many things. I would, however, reduce the amount of asserts to three by implementing <code>.Equals()</code> on <code>MessageDay</code>.</p>\n\n<p>While it may seem like overkill, <code>.Equals()</code> is a virtual method on <code>System.Object</code>, so you do already have an implementation of it available (just not the one you need, as it is currently a reference comparison).</p>\n\n<p>I can't predict whether or not you'll need it again in the future, but I don't consider that a problem when implementing the method in question, because all objects have it. The effort is small, and the chances of using it somewhere other than just testing are high.</p>\n\n<p>The downside is, of course, that your test will have to declare expected values, which may mean that it becomes no shorter, and the reduced number of asserts means your test is slightly less granular. For the second point, that's probably fine, because it also frees you to redesign the class without changing the test. The length could be reduced by comparing with values saved in the test initialization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:30:48.323",
"Id": "76323",
"Score": "3",
"body": "+1 This is the cleanest and most conventional way of doing it. I advise following the guidelines for [Implementing the Equals Method](http://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx). Providing an override for ToString is also helpful so failed tests output something meaningful rather than just the type names."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T16:47:07.873",
"Id": "44079",
"ParentId": "44071",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "44079",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:45:06.373",
"Id": "44071",
"Score": "6",
"Tags": [
"c#",
"unit-testing",
"assertions"
],
"Title": "How should I structure my Unit tests for minimal Asserts?"
} | 44071 |
<p>Is this the good way to create a portfolio article in HTML5 or do you have any suggestions?</p>
<p>Not sure about the section but I need it as overlay over the image. Is it better to use a DIV instead?</p>
<pre><code><article class="three columns remove-all project">
<section class="project-information">
<header>
<h4>Ski Trail</h4>
<time datetime="2010-03-20">20th March, 2010</time>
</header>
<p>
<span class="tag">Graphic</span>
</p>
</section>
<img src="http://placehold.it/291x216" class="img-scale" alt="">
</article>
</code></pre>
| [] | [
{
"body": "<p>A good reference for element semantics would be <a href=\"http://html5doctor.com/\" rel=\"nofollow noreferrer\">HTML5 Doctor</a>. You can read all about the tags and their intended purposes. From their overview for <a href=\"http://html5doctor.com/element-index/#section\" rel=\"nofollow noreferrer\"><code><section></code></a>, <a href=\"http://html5doctor.com/element-index/#article\" rel=\"nofollow noreferrer\"><code><article></code></a> and <a href=\"http://html5doctor.com/element-index/#div\" rel=\"nofollow noreferrer\"><code><div></code></a>:</p>\n<blockquote>\n<h1>Section</h1>\n<p>Represents a generic document or application section. In this context, a section is a thematic grouping of content, typically with a header, possibly with a footer. Examples include chapters in a book, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A web site's home page could be split into sections for an introduction, news items, contact information.</p>\n<h1>Article</h1>\n<p>Represents a section of a page that consists of a composition that forms an independent part of a document, page, or site. This could be a forum post, a magazine or newspaper article, a Web log entry, a user-submitted comment, or any other independent item of content.</p>\n<h1>Div</h1>\n<p>The div element has no special meaning at all. It represents its children. It can be used with the class, lang, and title attributes to mark up semantics common to a group of consecutive elements.</p>\n</blockquote>\n<p>Their analogy of <code><section></code> is a chapter, an <code><article></code> is <em>a section of the page</em>. Chapters contain articles, not the other way around. A <code><div></code> might be more appropriate, since it has no meaning.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:30:10.763",
"Id": "44092",
"ParentId": "44073",
"Score": "3"
}
},
{
"body": "<ul>\n<li>You probably don’t want to use a <code>section</code> there, as it’s a sectioning content element which creates an entry in the outline. If you need a wrapping element, use <code>div</code>.</li>\n<li>The tags would typically be part of a <code>footer</code> element of this <code>article</code>, unless you’d consider them part of this <code>article</code>’s main content.</li>\n</ul>\n\n<p>So it could look like:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><article>\n <div>\n <header>\n <h4>Ski Trail</h4> <!-- you could also use <h1> instead -->\n <time datetime=\"2010-03-20\">20th March, 2010</time>\n </header>\n\n <footer>\n <span>Graphic</span> <!-- may want to use a <ul> -->\n </footer>\n </div>\n\n <img src=\"…\" alt=\"…\">\n</article>\n</code></pre>\n\n<p>Note that the main content of this <code>article</code> (which is a sectioning content element) would be the image, as the content in <code>header</code> and <code>footer</code> would be considered metadata.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T03:57:19.120",
"Id": "44121",
"ParentId": "44073",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T14:03:10.327",
"Id": "44073",
"Score": "7",
"Tags": [
"html",
"html5"
],
"Title": "Is this a good way to create an article in HTML5?"
} | 44073 |
<p>I'm in the middle of a project that was built around Microsoft's Message Queue service. During development all of our machines are on a domain and we were able to create a public queue accessible from the server and client.</p>
<p>When moving this to our test server, I discovered that both the test server and production servers are running in workgroup mode, no public queues available.</p>
<p>I'm experimenting with creating a webservice broker backed by a MemoryCache. Here is what I've got so far. Each key is posted into a FIFO queue due to the needs of the project.</p>
<p>Has anyone else done something similar? What about concurrency? Any other gotchas I should be concerned about?</p>
<p>UPDATED: Added suggested changes, and handled differences resulting from use of ConcurrentQueue and Lazy instantiation.</p>
<pre><code> [WebMethod]
public bool Push(string key, string value)
{
if (String.IsNullOrWhiteSpace(key) || String.IsNullOrWhiteSpace(value)) return false;
// input validation removed for brevity
var queue = GetQueue(key);
queue.Enqueue(value);
return true;
}
[WebMethod]
public string Pop(string key)
{
var queue = GetQueue(key);
string result = "";
if (queue.TryDequeue(out result))
{
return result;
}
return null;
}
[WebMethod]
public List<string> RemoveAll(string key)
{
var queue = GetQueue(key);
var list = queue.ToList();
queue.Clear();
return list;
}
private ConcurrentQueue<string> GetQueue(string key)
{
var cache = MemoryCache.Default;
var queue = (Lazy<ConcurrentQueue<string>>) (cache.AddOrGetExisting(key.ToLowerInvariant(),new Lazy<ConcurrentQueue<string>>() , new CacheItemPolicy
{
AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration,
SlidingExpiration = TimeSpan.FromMinutes(5)
}) ?? cache[key.ToLowerInvariant()]);
return queue.Value;
}
</code></pre>
<p>I also added an extension for the ConcurrentQueue to clear it.</p>
<pre><code>public static class ConcurrentQueueExtensions
{
public static void Clear<T>(this ConcurrentQueue<T> queue)
{
T item;
while (queue.TryDequeue(out item))
{
// do nothing
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:57:55.960",
"Id": "76285",
"Score": "2",
"body": "Just use private queues, they are still accessable remotely. See http://technet.microsoft.com/en-us/library/cc778392(v=ws.10).aspx. Public queues are a pain anyways, so this would be better overall."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:34:34.430",
"Id": "76286",
"Score": "0",
"body": "I went ahead and created my memory cache web service. It has been a great addition to our applications, providing an extremely lightweight messaging service without any of the fuss."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T15:47:21.287",
"Id": "76293",
"Score": "0",
"body": "MSMQ persists messages to disk"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T21:42:35.130",
"Id": "76590",
"Score": "0",
"body": "@ChrisW In this case, we don't need to persist the data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T08:24:21.417",
"Id": "82400",
"Score": "1",
"body": "What about concurrency in multi threaded scenarios. Is it possible that Pop() and Push() is being called concurrently, because then the GetQueue() might turn out to be a problem. The time from looking up the queue in the memory cache and until you try to add it, might turn out to be a race-condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:06:24.277",
"Id": "82409",
"Score": "0",
"body": "@andershybertz I've updated my original answer with an implementation that relies on AddOrGetExisting"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:17:22.530",
"Id": "82410",
"Score": "0",
"body": "@andershybertz Not sure I like this one either, because each access to GetQueue will end up creating a new ConcurrencyQueue, most of which will just be discarded.\n\nI guess the next question is whether MemeoryCache.Default will return the same instance for all threads, or if it accesses a shared memory object internally. I'm assuming that AddOrGetExisting would be unnecessary if it did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T19:56:34.590",
"Id": "82451",
"Score": "0",
"body": "@andershybertz I just added a Lazy wrapper around the ConcurrencyQueue. It should handle concurrency properly now. Thanks for your comment!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:55:04.813",
"Id": "82474",
"Score": "0",
"body": "Looks much better now. The fact that you don't need to use lock or ReaderWriterLockSlim makes the code simpler to maintain. Performance wise I also think you should be okay, but of cause a stress test might be suitable, if you have explicit requirements."
}
] | [
{
"body": "<p>What you have here is, IMHO, excellent.</p>\n\n<p>Couple nitpicks: </p>\n\n<ul>\n<li>I don't get why <code>RemoveAll</code> is returning the original content instead of <code>void</code> - also I'm expecting an exception to be thrown in <code>GetQueue</code> if the specified <code>key</code> doesn't exist.</li>\n<li><p>This part (in the <code>Pop(string)</code> method):</p>\n\n<pre><code>var queue = GetQueue(key);\nstring result = \"\";\n</code></pre>\n\n<p>Would look more consistent if written like this:</p>\n\n<pre><code>var queue = GetQueue(key);\nvar result = string.Empty;\n</code></pre>\n\n<p>Or, since it's used as an <code>out</code> parameter value on the next line (and therefore is compiler-enforced to be initialized after the call to <code>TryDequeue(out string)</code>), simply like this:</p>\n\n<pre><code>var queue = GetQueue(key);\nstring result;\n</code></pre></li>\n</ul>\n\n<p>As for the <code>Clear</code> extension method, there's a potential tiny little issue here - see this <a href=\"http://social.msdn.microsoft.com/Forums/en-US/accf4254-ee81-4059-9251-619bc6bbeadf/clear-a-concurrentqueue?forum=rx\" rel=\"nofollow\">MSDN thread</a>:</p>\n\n<blockquote>\n <p><code>ConcurrentQueue<T></code>'s implementation is based on a particular lock-free algorithm that doesn't permit atomically clearing of the collection, hence why no Clear method is exposed. As such, you have two primary options.</p>\n \n <p>The first is simply to create a <code>new ConcurrentQueue<T></code> instead of clearing the original, and then swap in the new for the original.</p>\n \n <p>The second is to continually remove from the collection until it's empty, e.g. <code>T ignored; while(cq.TryDequeue(out ignored));</code>. Which you choose is largely dependent on the needs of your application. </p>\n \n <p>The former will be faster, but you also run the risk of losing some items you didn't intend to lose (then again, if the whole point is to empty the collection, that might not matter), and it only works if you have access to all of the variables holding references to the queue. </p>\n \n <p>The latter is effective, but it runs the risk of running indefinitely if other threads are concurrently appending; it's also more expensive that simply allocating a new queue.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:06:20.430",
"Id": "82644",
"Score": "1",
"body": "Perhaps RemoveAll would be clearer if it were PopAll instead. As this is now in production, I'll leave the name alone.\n\nI'm not throwing an exception because it's not needed in my case, returning null has the same net effect. I might also return an empty string. Also due to the implementation, this will always either add or get a new queue, if the key isn't null or empty.\n\nI'll update with String.Empty. Bad habits on my part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:13:42.900",
"Id": "82646",
"Score": "0",
"body": "@B2K hey! nice to hear from you! (never sure with migrated questions..) - sorry this post took forever to get an answer, I really hope future Code Review experiences will be better! (I'm out of votes right now, but I'll come back tonight to upvote your question here ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:16:15.883",
"Id": "82647",
"Score": "1",
"body": "Regarding the Clear extension, assigning a new queue would not update the entry in the cache. The original reference in the cache would remain unchanged.\n\nThere is a possibility that new items could get removed before they have been read, in my case, it's not critical, as the incremental results are superseded by the completion of an asynchronous callback. (It's the quote page for http://www.autoquoter.com -- zipcode=60610)\n\nIf retrieval of all results is required, pop could always be used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:25:37.700",
"Id": "84307",
"Score": "0",
"body": "@Mats I've updated the question with a fix. AddOrGetExisting returns a null if the item is added. One more comment on the Clear extension. Since the cached queue is set to timeout after 5 minutes, there was always a possibility that items posted to the queue would disappear before they were read."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:19:02.740",
"Id": "47161",
"ParentId": "44077",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47161",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:44:53.567",
"Id": "44077",
"Score": "3",
"Tags": [
"c#",
"memory-management",
"queue"
],
"Title": "MemoryCache as a message broker?"
} | 44077 |
A function is said to be idempotent when it can be called multiple times without changing the result. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:27:09.563",
"Id": "44084",
"Score": "0",
"Tags": null,
"Title": null
} | 44084 |
<p>My task was to create a menu that displays three items <code>(A,B,C)</code>, and has two nav buttons <code><-</code> and <code>-></code>. So for example, a menu of <code>(A, B, C, D, E)</code> starts off showing <code>A,B,C</code> and can press <code>-></code> twice to display <code>C,D,E</code>.</p>
<p>My questions beyond general code review feedback are:</p>
<ol>
<li>How would you view the "programmer" behind this code in terms of ability/thought?</li>
<li>How would you feel if you were working on legacy code and for whatever reason, had to edit a menu or add to a menu or debug this code?</li>
<li>(Maybe overlap as the first question) - if you were a hiring manager on an interview, what kind of impression would this code give you?</li>
</ol>
<p>I feel as though I have a ton to learn so I'm not expecting great reviews or anything, so your brutal honesty is appreciated.</p>
<p>Here are the flaws I noticed myself:</p>
<ul>
<li>Img paths are hard-coded as <code>../images/misc/foo.png</code> instead of of having the include path defined as a constant</li>
<li>The container with <code>id=dataPreserve</code> may seem unclear in its purpose/messy? This was my first time using jQuery's <code>data</code> function and I discovered that updating the entire container with <code>.html();</code>, also overwrote the data (!), and that I had to leave an outer-most container untouched during <code>.html();</code>s so as to preserve jQuery <code>.data</code>.</li>
</ul>
<p>Here is the code:</p>
<p><strong>HTML page</strong></p>
<pre><code> <div id="mbpCont">asdf
</div>
<script>
var uniqueName = 'mbp';
var subtitles = ['NAME 1', 'NAME 2', 'NAME 3', 'NAME 4', 'NAME 5'];
var icons = ['ph.png', 'ph2.png', 'ph3.png', 'ph4.png', 'ph.png'];
var descripts = ['Ut enim ad minim veniam, quis nostrud exercitation.', 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ', 'final string'];
var links = ['prism.php', 'rp9.php', 'sa.php', 'ap.php', 'dd.php'];
var pos = 0;
var length = subtitles.length;
var isMoving = false;
mbpSlider = new Slider(uniqueName, subtitles, icons, descripts, links, pos, length, isMoving);
</script>
</code></pre>
<p><strong>(sliders.js)</strong></p>
<pre><code>function Slider(uniqueName, subtitles, icons, descripts, links, pos, length, isMoving){
var thisSlider = '#'+uniqueName+'Cont';
$(thisSlider).html('<div class="sliderContainer" id="'+uniqueName+'">\
<div class="sliderArrowContainer">\
<a href="javascript:void(0);" id="matSliderLeft"><img class="sliderLeft" id="'+uniqueName+'Left" src="../images/misc/lArrowGrey.png"></a>\
</div>\
<div id="dataPreserve'+uniqueName+'" style="display:inline-block; *display:inline;zoom:1;">\
<div class="sliderBlock">\
<div class="sliderIconHolder"><img class="sliderImg" src="../images/misc/'+icons[0]+'"></div>\
<div class="sliderSubtitle" id="'+uniqueName+'">'+subtitles[0]+'</div>\
<div class="sliderText">'+descripts[0]+'</div>\
</div>\
<div class="sliderBlock">\
<div class="sliderIconHolder"><img class="sliderImg" src="../images/misc/'+icons[1]+'"></div>\
<div class="sliderSubtitle">'+subtitles[1]+'</div>\
<div class="sliderText">'+descripts[1]+'</div>\
</div>\
<div class="sliderBlock">\
<div class="sliderIconHolder"><img class="sliderImg" src="../images/misc/'+icons[2]+'"></div>\
<div class="sliderSubtitle">'+subtitles[2]+'</div>\
<div class="sliderText">'+descripts[2]+'</div>\
</div>\
</div>\
<div class="sliderArrowContainer">\
<a href="javascript:void(0);" id="matSliderRight"><img class="sliderRight" id="'+uniqueName+'Right" src="../images/misc/rArrowGreen.png"></a>\
</div>\
</div>');
$('#'+uniqueName).data( { subtitles: subtitles, icons: icons, descripts: descripts, links: links, pos: pos, length:length, isMoving:isMoving } );
}
function formatId(eventTarget){
if (eventTarget){
var formatted = eventTarget.substr(0,3);
return formatted;
} else {return null;}
}
function canGoLeft(cur){
var pos = getPos(cur);
//alert('checking left: pos = '+pos);
if (pos > 0) {
return true;
} else {
return false;
}
}
function canGoRight(cur){
var pos = getPos(cur);
var max = getMaxLength(cur);
max = max - 3;
if (pos < max) {
return true;
} else {
return false;
}
}
function getPos(cur){
var pos = $('#'+cur).data('pos');
return pos;
}
function getMaxLength(cur){
var max = $('#'+cur).data('length');
return max;
}
function isUpdating(cur){
var moving = $('#'+cur).data('isMoving');
if (moving){
return true;
} else {
return false;
}
}
function setMoving(cur, state){
if (state){
$('#'+cur).data('isMoving', true);
} else {
$('#'+cur).data('isMoving', false);
}
}
function updateDisplay(cur, direction){
if (updatePosition(cur, direction)){
updateHtml(cur);
setMoving(cur, false);
} else {
//alert('Error at updateDisplay');
return null;
}
}
function updatePosition(cur, direction){
var pos = getPos(cur);
pos = pos+direction;
//alert('new pos should be ' + pos);
if (pos>=0){
$('#'+cur).data('pos', pos);
return true;
} else {
return false;
}
}
function updateHtml(cur){
var thisSlider = '#dataPreserve'+cur;
var pos = getPos(cur);
updateArrows(cur);
$(thisSlider).hide().html('<div class="sliderBlock">\
<div class="sliderIconHolder"><img class="sliderImg" src="../images/misc/'+icons[pos]+'"></div>\
<div class="sliderSubtitle" id="'+cur+'">'+subtitles[pos]+'</div>\
<div class="sliderText">'+descripts[pos]+'</div>\
</div>\
<div class="sliderBlock">\
<div class="sliderIconHolder"><img class="sliderImg" src="../images/misc/'+icons[pos+1]+'"></div>\
<div class="sliderSubtitle">'+subtitles[pos+1]+'</div>\
<div class="sliderText">'+descripts[pos+1]+'</div>\
</div>\
<div class="sliderBlock">\
<div class="sliderIconHolder"><img class="sliderImg" src="../images/misc/'+icons[pos+2]+'"></div>\
<div class="sliderSubtitle">'+subtitles[pos+2]+'</div>\
<div class="sliderText">'+descripts[pos+2]+'</div>\
</div>\
').fadeIn(600);
}
function getLArrowString(cur){
var pos = getPos(cur);
var str = '../images/misc/lArrowGrey.png';
if (pos>0){
str = '../images/misc/lArrowGreen.png';
}
return str;
}
function getRArrowString(cur){
var pos = getPos(cur);
var max = getMaxLength(cur);
max = max - 3;
var str = '../images/misc/rArrowGrey.png';
if (pos<max){
str = '../images/misc/rArrowGreen.png';
}
return str;
}
function updateArrows(cur){
var lArrowId = '#'+cur+'Left';
var rArrowId = '#'+cur+'Right';
var lString = getLArrowString(cur);
var rString = getRArrowString(cur);
$(lArrowId).attr("src", lString);
$(rArrowId).attr("src", rString);
}
/******************** ON CLICKS ************************/
$(".sliderLeft").live("click", function() {
var cur = formatId(this.id);
if(canGoLeft(cur)){
if ( !isUpdating(cur) ){
//alert('is not moving');
setMoving(cur, true);
updateDisplay(cur, -1);
} else {
//alert('is moving');
}
} else {
//alert('cant go left');
}
});
$(".sliderRight").live("click", function() {
var cur = formatId(this.id);
if(canGoRight(cur)){
if ( !isUpdating(cur) ){
//alert('is not moving');
setMoving(cur, true);
updateDisplay(cur, 1);
} else {
//alert('is moving');
}
} else {
//alert('cant go right');
}
});
</code></pre>
| [] | [
{
"body": "<p>I guess my first thought is that I'm not sure why JavaScript is being used to generate the HTML, when the information, or view model, so to speak, is hard coded. It seems the HTML markup could all be written directly on the page. </p>\n\n<p>If it is dynamic in nature, I think I would use an object or class for each image, which contains all its info, instead of individual arrays for each type of information. </p>\n\n<p>Just first impressions. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:31:05.727",
"Id": "76761",
"Score": "0",
"body": "For libraries that are \"drop-in\" and with minimal config, being able to be *self-contained* is a good attribute. Just add the library, a bit of config and the script does the HTML, CSS and JS."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T01:08:23.857",
"Id": "44114",
"ParentId": "44085",
"Score": "3"
}
},
{
"body": "<h1>Template</h1>\n\n<p>The first thing that comes into mind when building widgets is how the HTML is written. I'd avoid the HTML concatenated strings in JS. They're just so messy. I prefer templates instead, like <a href=\"https://github.com/janl/mustache.js/\">Mustache</a>.</p>\n\n<h3>Template in <code><script></code></h3>\n\n<p>The parser will ignore since <code>type</code> is unknown to the browser:</p>\n\n<pre><code><script type=\"text/template\" id=\"myTemplate\">\n <ul>\n {{#someArray}}\n <li>Current value: {{.}}</li>\n {{/someArray}}\n </ul>\n</script>\n</code></pre>\n\n<p>Grab the HTML string:</p>\n\n<pre><code>var template = $('#myTemplate').html();\n</code></pre>\n\n<h3>HTML string:</h3>\n\n<p>If you want self-contained, like for a plugin, design the HTML and compress to this:</p>\n\n<pre><code>var template = '<ul>{{#someArray}}<li>Current value: {{.}}</li>{{/someArray}}</ul>';\n</code></pre>\n\n<h1>Semantics</h1>\n\n<p>You are creating a menu. In HTML terms, it's a list. Make it like so in static. Makes for good fallback when JS is disabled, or if something prevents the code from running, like lacking APIs or something:</p>\n\n<pre><code><ul>\n <li>\n <img src=\"IMAGE_SOURCE\" />\n <h4>TITLE_TEXT</h4>\n <p>ITEM_TEXT</p>\n </li>\n ...\n</ul>\n</code></pre>\n\n<ul>\n<li>Additional data can be embedded as <code>data-*</code> attributes. Since this is per item, it would make more sense if it was placed in <code><li></code></li>\n</ul>\n\n<p>You can them morph it in JS to add the slider:</p>\n\n<pre><code><div class=\"container\">\n <div class=\"fixed-width-container\">\n <ul>\n <li data-icon=\"ICON_PATH\" data-something=\"SOME_MORE_DATA\">\n <img src=\"IMAGE_SOURCE\" />\n <h4>TITLE_TEXT</h4>\n <p>ITEM_TEXT</p>\n </li>\n ...\n </ul>\n </div>\n <a class=\"arrow-left\">Left</a>\n <a class=\"arrow-right\">Right</a>\n</div>\n</code></pre>\n\n<ul>\n<li><code>.container</code> would house the entire mechanism, </li>\n<li><code>.fixed-width-container</code> with <code>overflow:hidden</code> to hide the off-screen elements in the list. </li>\n<li>The <code><ul></code> width would be the <code>.fixed-width-container</code> width multiplied by the number of items. This makes the slider expand beyond the container. If you need to display 3 items at a time, that would be (<code>.fixed-width-container</code> width / 3) * number of items.</li>\n<li>The arrows positioned absolutely to the left and right of the container.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T02:08:49.280",
"Id": "44117",
"ParentId": "44085",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44117",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:28:57.840",
"Id": "44085",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"dom"
],
"Title": "Horizontal menu for 3 items"
} | 44085 |
<p>This is a user login (some session wrapper I managed to put together after a lot of web searching).</p>
<p>It's for a simple CMS I'm trying to build. It only needs one user and there is no need for multiple user log in at the same time. It works, the problem being I think it has safety issues.</p>
<p>It works like this:</p>
<ol>
<li>The user accesses CMS index page, and inserts the user and password.</li>
<li>If one of them does not coincide with the data in the database it does not set the session and triggers a "die" or a error message.</li>
<li>If the info is ok then it sets the session and redirects the user from the index page to an admin.php page as you can see in the code below.</li>
</ol>
<p>I commented it quite well. If you see any safety issues please point them out as I can't seem to notice them.</p>
<p>The form is a simple user, password and submit form.</p>
<p>The class:</p>
<pre><code> <?php
class Session{
private static $_user;
private static $_password;
private static $_sessionStart = false;
//here we check if the data inserted by the user in the form coincides with the rows in the db
//if it does it sets the session for the user
public static function CheckLog($received_user,$received_password){
self::$_user = $received_user;
self::$_password = $received_password;
$db = Database::getInstance();
$mysqli = $db->getConnection();
$sql = 'SELECT * FROM utilizatori ';
$sql .= 'WHERE user = "'.self::$_user.'" AND password = "'.self::$_password.'" ';
$result = $mysqli->query($sql) or die (mysqli_error());
if($row = $result->fetch_assoc()){
if(($row['user'] === self::$_user)&&($row['password'] === self::$_password)){
self::set('user',self::$_user);
self::set('key',session_id());
}
}
}
//this method starts the session
public static function start(){
if(self::$_sessionStart == false){
session_start();
self::$_sessionStart = true;
}
}
//this function sets the session values
public static function set($key,$value){
$_SESSION[$key] = $value;
}
public static function get($key){
if(isset($_SESSION[$key])){
return $_SESSION[$key];
}
else{
return false;
}
}
}
//from here is the handeling of the data in the "index" page:
include("class_def/database.inc");
include("class_def/user.inc");
Session::start(); //here we start the session
$up = strip_tags($_POST['user']); //post the user name
$pp = strip_tags($_POST['password']); //post the password
//check if the variables are set and access the CheckLog method
if((isset($up))&&(isset($pp))){
Session::CheckLog($up,$pp);
}
//get the name of the current file
$current_file = basename($_SERVER["SCRIPT_FILENAME"], '.php');
//if the current page is index and the key is set redirect to admin.php
if(isset($_SESSION['key'])){
if($current_file == 'index')
{ echo '
<script type="text/javascript">
<!--
window.location = "admin.php"
//-->
</script>';
}
}
else{ //if the key is not set and the page is any other than index die and display message
if($current_file != 'index'){
die('You must log in first');
}
else{ // if the page is index echo out an error message
$error_msj = 'Wrong user or pass';
}
}
?>
</code></pre>
| [] | [
{
"body": "<h1>MVC</h1>\n<p>If you're trying to make a CMS, then there's a possibility that this CMS will become bigger than you first though. More pages, more modules, more code. You might want to consider doing an <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\" rel=\"noreferrer\">MVP approach</a> to splitting code (rather than <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"noreferrer\">MVC</a>).</p>\n<p>A good reference framework for this is <a href=\"http://ellislab.com/codeigniter\" rel=\"noreferrer\">CodeIgniter</a>. Presenter (CodeIgninter calls it the Controller) receives a request, then operates the data on the model (the model layer + database), then grabs a view (A template, your HTML) and renders it ("echo" the template).</p>\n<h1>SQL Injection</h1>\n<p>Then I notice this part:</p>\n<pre><code>$sql = 'SELECT * FROM utilizatori '; \n$sql .= 'WHERE user = "'.self::$_user.'" AND password = "'.self::$_password.'" ';\n</code></pre>\n<p>You should read more about <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"noreferrer\">SQL injection</a>. In a gist, it allows users to run arbitrary SQL, even be able to fake logins, see through existing usernames and passwords, as well as drop entire databases.</p>\n<h1>Sessions</h1>\n<p>Then there's sessions. For simple situations, that's fine. But for security, there's a lot to consider. If I can shoot malicious code through the forms, then I just might be able to fake my session. Read on <a href=\"https://stackoverflow.com/q/328/575527\">this post</a> for things to consider with sessions.</p>\n<h1>Validation</h1>\n<p>I see you use <code>strip_tags()</code> but it only does what it does, <em>strip tags</em>. It does not strip the other stuff, like backticks and quotes which can still be used to break in. A good example is the story of <a href=\"http://bobby-tables.com/\" rel=\"noreferrer\">Little Bobby Tables</a>. No tags, still broke through the database.</p>\n<h1>Redirect</h1>\n<pre><code>window.location = "admin.php"\n</code></pre>\n<p>This operates on the browser. This means that <code>index.php</code> is actually served before redirecting, possibly rendering the page before this runs. I suggest you do a <a href=\"http://www.php.net/manual/en/function.header.php\" rel=\"noreferrer\">header redirect</a>. It does not serve the page to the browser. It just tells the browser directly to load another page instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:06:26.090",
"Id": "44091",
"ParentId": "44087",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "44091",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T17:47:13.457",
"Id": "44087",
"Score": "5",
"Tags": [
"php",
"beginner",
"session",
"authentication"
],
"Title": "Safety issues in PHP log-in system"
} | 44087 |
<p>I'm trying to login into a webapi2 site from a desktop application. After a lot of googling, I cobbled together a working prototype. Since we are talking about security I wanted to do a peer review. I'm just starting with security design and I'm not exactly sure about my design.</p>
<p>The WebAPI site that is targeted is a wepapi 2 standard template out of visual studio.</p>
<p>I'm mainly looking for security issuesut general issues are also greatly appreciated.</p>
<p>One issue I'm aware of is that SSL should be added and with that ssl validation. I haven't implemented it yet.</p>
<pre><code>static internal async Task<string> GetWebAPIReguest(string siteUrl, string APIController, string userName, string Password)
{
TokenResponseModel Token = await GetBearerToken(siteUrl, userName, Password);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(siteUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.AccessToken);
return await client.GetStringAsync(APIController);
}
static internal async Task<TokenResponseModel> GetBearerToken(string siteUrl, string Username, string Password)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(siteUrl);
client.DefaultRequestHeaders.Accept.Clear();
HttpContent requestContent = new StringContent("grant_type=password&username=" + Username + "&password=" + Password, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);
if (responseMessage.IsSuccessStatusCode)
{
string jsonMessage;
using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));
return tokenResponse;
}
else
{
return null;
}
}
class TokenResponseModel
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("userName")]
public string Username { get; set; }
[JsonProperty(".issued")]
public string IssuedAt { get; set; }
[JsonProperty(".expires")]
public string ExpiresAt { get; set; }
}
</code></pre>
| [] | [
{
"body": "<p>I don't like that the password is hard coded here</p>\n\n<pre><code>HttpContent requestContent = new StringContent(\"grant_type=password&username=\" + Username + \"&password=\" + Password, Encoding.UTF8, \"application/x-www-form-urlencoded\");\n</code></pre>\n\n<p>I am sure that you could move it into a configuration file or something.</p>\n\n<hr>\n\n<p>and this is a bit wordy</p>\n\n<pre><code>if (responseMessage.IsSuccessStatusCode)\n{\n string jsonMessage;\n using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())\n {\n jsonMessage = new StreamReader(responseStream).ReadToEnd();\n }\n\n TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));\n\n return tokenResponse;\n}\nelse\n{\n return null;\n}\n</code></pre>\n\n<p>I would wrap more inside the using statement so that I could combine some things like this</p>\n\n<pre><code>if (responseMessage.IsSuccessStatusCode)\n{\n using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())\n {\n return (TokenResponseModel)JsonConvert.DeserializeObject(new StreamReader(responseStream).ReadToEnd(), typeof(TokenResponseModel));\n }\n}\nelse\n{\n return null;\n}\n</code></pre>\n\n<hr>\n\n<p>@Rolfl made a very good observation/point.</p>\n\n<p>If we negate the condition and return null we can make it so that the using block is not nested inside of an if statement. so it would look like this</p>\n\n<pre><code>if (!responseMessage.IsSuccessStatusCode) { return null;}\n\nusing (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())\n{\n return (TokenResponseModel)JsonConvert.DeserializeObject(new StreamReader(responseStream).ReadToEnd(), typeof(TokenResponseModel));\n}\n</code></pre>\n\n<p>This is far cleaner than the OP code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-25T10:53:10.707",
"Id": "110645",
"Score": "0",
"body": "Why have the else block at all. The `if` block returns, so the else is redundant. Also, if you negate the if condition `if (!responseMessage.IsSuccessStatusCode) { return null;}` it will also reduce the nesting on the using block."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T19:41:16.330",
"Id": "60746",
"ParentId": "44097",
"Score": "5"
}
},
{
"body": "<p>I was going to make a very large post with altered code, but I don't fully understand what your code is doing so all I will suggest is that</p>\n\n<ol>\n<li>You need to use a consistent code style. <code>camelCase</code> for variables/arguments, <code>PascalCase</code> for runtime constants (types/constants) and properties, and <code>_camelCase</code> for private fields on an object.</li>\n<li>Your methods are simply doing way too much. Your 2 methods there are connecting to two different web pages, composing two URLs, parsing JSON into a POCO (and then back out again), and doing authentication on top of all of that.</li>\n<li>You aren't managing the lifecycle of <code>HttpClient</code>. There is a <a href=\"https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed\">general consensus</a> that creating and disposing <code>HttpClient</code>s is not the best use of a class. At the very least you should be Disposing of your <code>HttpClient</code>s but all you're doing in your current code is letting your <code>HttpClient</code>s leak. Consider that your functions do not need to know how to create a <code>HttpClient</code>, they just need to know how to connect to a Url - let the caller of the function do the heavy lifting for you.</li>\n</ol>\n\n<p>Once again I'd give you a code sample but I just don't understand what your code is trying to do, which is my own fault, because I haven't really used much HTTP in .NET.</p>\n\n<p>Here are the responsibilities of your <strong>two</strong> methods so far:</p>\n\n<ul>\n<li>Create a HttpClient</li>\n<li>Decode JSON into a POCO</li>\n<li>Create authentication token</li>\n<li>Compose url from base url, secondary url and a query string</li>\n<li>Apply authentication token to HttpClient</li>\n<li>Handle the response of one of the HttpClients</li>\n<li>Prepare HttpClient headers</li>\n</ul>\n\n<p>The majority of these should be in their own function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T20:05:07.947",
"Id": "60748",
"ParentId": "44097",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:07:09.907",
"Id": "44097",
"Score": "11",
"Tags": [
"c#",
"security",
"api"
],
"Title": "Logging into WebAPI 2 site from c# desktop application"
} | 44097 |
<p>I created my own <code>indexOf</code> function. I was wondering if anyone could help me come up with a way to make it more efficient. I am practicing for interviews so the catch is that I cannot use any <code>String</code> methods. I believe the runtime of this method is O(n<sup>2</sup>) with space of O(n). Correct me if I am wrong.</p>
<p>Also, I want to ensure the program runs safely and correctly, the only test case I can think of it the length comparison.</p>
<pre><code>public static int myIndexOf(char[] str, char[] substr) {
int len = str.length;
int sublen = substr.length;
int count = 0;
if (sublen > len) {
return -1;
}
for (int i = 0; i < len - sublen + 1; i++) {
for (int j = 0; j < sublen; j++) {
if (str[j+i] == substr[j]) {
count++;
if (count == sublen) {
return i;
}
} else {
count = 0;
break;
}
}
}
return -1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T00:24:15.933",
"Id": "76389",
"Score": "6",
"body": "Wikipedia has a list of string substring searching algorithms with their time and space complexity. The faster it goes, the more complicated (and cool and innovative!) it is, but knowing the internals of a nice and fast one could be something to talk about in an interview, perhaps? http://en.wikipedia.org/wiki/String_searching_algorithm"
}
] | [
{
"body": "<p>Other answers are already covering what maybe matters more to you: space, time complexity, safety, correctness. I think you can do further steps in order to improve the code readability: if it was a production code it would be hard to maintain. Consider the following suggestions:</p>\n\n<ul>\n<li>variables should go nearest their utilization as possible: avoid broad global declaration as far as you can;\n\n<ul>\n<li>for example, why is <code>count</code> initialized before the first exit point, that is where it could never be used? It should go just before the for instruction (the first for? - on a first reading I couldn't say it)</li>\n</ul></li>\n<li><code>len - sublen + 1</code> should be stored in a final variable (constant) with a good name: what does it mean that value?</li>\n<li>the default return value (<code>-1</code>) should be declared in one point, with a meaningful name (no magic numbers). What if later you would want to change the default not-found value?</li>\n<li>the function has three exit points, with a further <code>break</code> in a nested loop, causing a difficult reading of its logical branches (they remember insane <code>goto</code>s)</li>\n<li>the main exit point <code>count == sublen</code> should go inside a meaningful boolean variable: why is this an exit condition? How would you explain it to your coworker?</li>\n</ul>\n\n<p>If you want to see a different approach to <code>indexOf</code> (but on byte arrays) you could check the following code, with also should be more readable:</p>\n\n<pre><code> public static int search(byte[] input, byte[] searchedFor) {\n //convert byte[] to Byte[]\n Byte[] searchedForB = new Byte[searchedFor.length];\n for(int x = 0; x<searchedFor.length; x++){\n searchedForB[x] = searchedFor[x];\n }\n\n int idx = -1;\n\n //search:\n Deque<Byte> q = new ArrayDeque<Byte>(input.length);\n for(int i=0; i<input.length; i++){\n if(q.size() == searchedForB.length){\n //here I can check\n Byte[] cur = q.toArray(new Byte[]{});\n if(Arrays.equals(cur, searchedForB)){\n //found!\n idx = i - searchedForB.length;\n break;\n } else {\n //not found\n q.pop();\n q.addLast(input[i]);\n }\n } else {\n q.addLast(input[i]);\n }\n }\n\n return idx;\n }\n</code></pre>\n\n<p>(<a href=\"https://stackoverflow.com/questions/22234021/search-for-a-string-as-an-byte-in-a-binary-stream/22236277#22236277\">Original post</a>) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:51:47.860",
"Id": "76551",
"Score": "0",
"body": "This is not really a code review answer, is it? At least you should explain in how far the code would help to improve the ops code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T19:01:22.530",
"Id": "76556",
"Score": "0",
"body": "I proposed it because I think it is more readable. What do you mean by \"ops code\"? And where can I find code review's rules? Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T19:41:06.740",
"Id": "76564",
"Score": "0",
"body": "With \"ops\" I meant \"OP's\" (Original Poster's). There are [some discussions on meta](http://meta.codereview.stackexchange.com/a/913/30346) around what a good code review is. Basically your answer would be more useful if you include some explanation of why and how your version is more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T20:29:55.807",
"Id": "76578",
"Score": "0",
"body": "I've just updated the answer with my considerations on code readability - I hope I made my point clearer, thanks for your feedbacks"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:39:07.217",
"Id": "44105",
"ParentId": "44100",
"Score": "9"
}
},
{
"body": "<h2>Complexity</h2>\n\n<p>Pedantically, the time-complexity is \\$ O( m \\times n ) \\$, where <code>m</code> is <code>str.length</code> and <code>n</code> is <code>substr.length</code>. This matters when \\$ \\left| m-n \\right| \\$ is large.</p>\n\n<p>The Space complexity is \\$ O(1) \\$. You do not allocate any size-based memory structures.</p>\n\n<h2>Safety</h2>\n\n<p>It all looks good. There are no threading issues, no leaks, no problems.</p>\n\n<h2>Correctly</h2>\n\n<p>Nope, I don't like the lack of neat handling for invalid inputs.... you should be null-checking, etc. Getting a raw 'NullPointerException' looks bad.</p>\n\n<p>Edit: <em>Note that</em> <a href=\"https://codereview.stackexchange.com/a/44107/31503\">Josay has pointed out</a> that your code (and my code below) produce different behaviour to <code>String.indexOf()</code> when the search term is the empty-string/empty-array.</p>\n\n<h2>Alternative</h2>\n\n<p>I think your code is fine, but... I tend to use loop break/continue more than most... and, this saves a bunch of code in this case...</p>\n\n<p>Also, for readability, I often introduce a <code>limit</code> variable when the loop-terminator can be complicated....</p>\n\n<p>Consider the following loops which do not need the <code>count</code> variable:</p>\n\n<pre><code>int limit = len - sublen + 1;\nsearchloop: for (int i = 0; i < limit; i++) {\n for (int j = 0; j < sublen; j++) {\n if (str[j+i] != substr[j]) {\n continue searchloop;\n }\n }\n return i;\n}\nreturn -1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:46:07.540",
"Id": "44106",
"ParentId": "44100",
"Score": "31"
}
},
{
"body": "<p>There is a problem in your code and this hilights it :</p>\n\n<pre><code>class Class_Test {\n\n public static int myIndexOf(char[] str, char[] substr) {\n int len = str.length;\n int sublen = substr.length;\n int count = 0;\n if (sublen > len) {\n return -1;\n }\n for (int i = 0; i < len - sublen + 1; i++) {\n for (int j = 0; j < sublen; j++) {\n if (str[j+i] == substr[j]) {\n count++;\n if (count == sublen) {\n return i;\n }\n } else {\n count = 0;\n break;\n }\n }\n }\n return -1;\n }\n\n public static boolean compareFunc(String s1, String s2)\n {\n int r1 = s1.indexOf(s2);\n int r2 = myIndexOf(s1.toCharArray(), s2.toCharArray());\n boolean ret = (r1==r2);\n System.out.println(ret + \" for '\" + s1 + \"' '\" + s2 + \"' -> \" + r1 + \" \" + r2);\n return ret;\n }\n\n public static void main (String[] args)\n {\n // Empty string\n compareFunc(\"\", \"\");\n compareFunc(\"A\", \"\");\n compareFunc(\"AB\", \"\");\n compareFunc(\"\", \"A\");\n compareFunc(\"\", \"AB\");\n // Equal non-empty strings\n compareFunc(\"A\", \"A\");\n compareFunc(\"AB\", \"AB\");\n compareFunc(\"ABC\", \"A\");\n // Match at the beginning\n compareFunc(\"A\", \"AB\");\n compareFunc(\"AB\", \"ABC\");\n compareFunc(\"ABC\", \"ABD\");\n // Match at the end\n compareFunc(\"B\", \"AB\");\n compareFunc(\"BC\", \"ABC\");\n compareFunc(\"ABC\", \"DBC\");\n // Match at the middle\n compareFunc(\"BC\", \"ABCD\");\n compareFunc(\"CD\", \"ABCDEF\");\n // No match on longer strings\n compareFunc(\"QWERTYUIOPASDFGHJKL\", \"ZXCVBNM\");\n compareFunc(\"ZXCVBNM\",\"QWERTYUIOPASDFGHJKL\");\n System.out.println(\"Test successful\");\n }\n}\n</code></pre>\n\n<p>Good reviews have been given and I have nothing to add.</p>\n\n<p>Edit : additional details for what it is worth : </p>\n\n<ul>\n<li>an additional test case should be added to check that <em>first</em> occurence is found</li>\n<li>your implementation corresponds to the naive way of searching. In the litterature, you'll find <a href=\"http://en.wikipedia.org/wiki/String_searching_algorithm\">other algorithms</a> with potentially better performances.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:51:06.217",
"Id": "76371",
"Score": "0",
"body": "Good spotting... for what it is worth, I have never been certain I like the `String.indexOf(\"\")` handling in Java...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:54:21.267",
"Id": "76373",
"Score": "0",
"body": "Your answer goes through all tests properly so you implicitly agree with this behavior ;-) (and have my +1)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T16:34:37.547",
"Id": "76512",
"Score": "0",
"body": "I think some of the test cases are switched around. The ones that are commented with a match, do not match."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T22:15:41.140",
"Id": "76597",
"Score": "0",
"body": "Well I'm not quite sure what you mean but in any case, your function should probably have a behaviour as close as possible to the original method. Let me know (or fell free to edit my answer) if there is anything wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T02:41:47.453",
"Id": "76638",
"Score": "0",
"body": "@Josay sorry I wasn't clear. What I meant was in your test cases, `compareFunc(\"BC\", \"ABCD\");` I think you meant `compareFunc(\"ABCD\", \"BC\");`? Because there isn't an actual match in any of the middle, beginning, and end cases you provided. I am assuming this is what you wanted to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T06:32:36.637",
"Id": "76653",
"Score": "0",
"body": "In right, indeed. I'll fix this in a couple of hours. Thanks for spotting :-)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T21:46:20.053",
"Id": "44107",
"ParentId": "44100",
"Score": "16"
}
},
{
"body": "<p>This looks good to me.</p>\n\n<p>For efficiency, you have two options:</p>\n\n<ol>\n<li><p>Reduce the number of operations in the inner loop. Let's look at that.</p>\n\n<pre><code>for (int j = 0; j < sublen; j++) {\n if (str[j+i] == substr[j]) {\n count++;\n if (count == sublen) {\n return i;\n }\n ...\n}\n</code></pre>\n\n<p>Here, the addition <code>j+i</code> seems like something you should be able to, somehow, replace with a single initial addition outside the loop, and an increment inside the loop. There also seems to be correlation between <code>j</code> and <code>count</code> (if anyone which line you are on, you'll have either <code>count == j</code> or <code>count == j+1</code>. It follows that the test <code>j < sublen</code> is false if and only if <code>count == sublen</code> it true, so you could probably get rid of one of them.</p>\n\n<p>At this point I want to emphasise that this kind of analysis will give you performance increases so small that they are almost certainly not worth the effort. That leads us to:</p></li>\n<li><p>Look for a different algorithm. This is likely the only way to get a significant increase in performance. A good place to start is the classical Boyer-Moore algorithm.</p>\n\n<p>For complexity, recall the inputs:</p>\n\n<pre><code>public static int myIndexOf(char[] str, char[] substr)\n</code></pre>\n\n<p>If <code>str</code> is of length n and <code>substr</code> is of length m, your implementation executes the outer loop roughly n times and, in the worst case, each of those n iterations executes the inner loop m times. The running time of your implementation is thus no worse than O(n*m).</p>\n\n<p>When considering space complexity, one should not count the space used for inputs, only the <em>additional</em> space used. Your implementation uses only a fixed number of variables (<code>len, sublen, count, i</code>) of primitive type. The amount of space it uses is independent of the sizes n and m of the input strings, and so we say that your implementation uses \"constant space\", written O(1). </p>\n\n<p>Finally, I want to mention that your implementation is not far from the actual implementation of the Java standard library; check it out <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/String.java#String.indexOf%28java.lang.String%2Cint%29\" rel=\"noreferrer\">here</a>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:31:40.923",
"Id": "76540",
"Score": "0",
"body": "I wish Java had an array type which could be read and written as 1, 2, 4, or 8 byte values; many kinds of string-related algorithms could benefit from processing things in multi-character chunks, even if one would have to use special-case logic for different alignments, and to handle the starting and ending bits of a string (e.g. to look for the string \"ABRACADABRA\", start by examining every other 64-bit word, ignoring everything that isn't ABRA, CADA, BRAC, ADAB, RACA, DABR, or ACAD). Either endianness could be simulated at a cost of at most one extra instruction per access."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T22:27:54.020",
"Id": "44109",
"ParentId": "44100",
"Score": "13"
}
},
{
"body": "<p>One thing which does not seem to have been mentioned in other answers,</p>\n\n<pre><code>for (int i = 0; i < len - sublen + 1; i++) {\n</code></pre>\n\n<p>Instead of checking <strong>less than</strong> x <strong>plus one</strong>. You can do <em>less than <strong>or equal to</em></strong> x.</p>\n\n<pre><code>for (int i = 0; i <= len - sublen; i++) {\n</code></pre>\n\n<p>I find this a bit easier to read and understand.</p>\n\n<p>This can also be applied to the monkey's (@rolfl's) code:</p>\n\n<pre><code>int limit = len - sublen;\nsearchloop: for (int i = 0; i <= limit; i++) {\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:06:46.487",
"Id": "44147",
"ParentId": "44100",
"Score": "15"
}
}
] | {
"AcceptedAnswerId": "44107",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T20:33:38.930",
"Id": "44100",
"Score": "29",
"Tags": [
"java",
"performance",
"algorithm",
"strings",
"search"
],
"Title": "Custom indexOf() without String methods"
} | 44100 |
<p>I thought I would try and write a solution to the Wolf, Goat and Cabbage problem in Java 8 to try and get to grips with lambdas.</p>
<p>I am looking for any feedback you might provide. The feedback I am looking for is mainly on code structure and where I could make more, or more simple, use of new Java 8 features.</p>
<p>The basic idea of the code is to try and encapsulate the behaviour of the elements of the problem in an OO fashion and process them using lambdas.</p>
<p>I started with an <code>enum Member</code> to encapsulate the players of the game. It should be self explanatory.</p>
<pre><code>enum Member {
FARMER,
WOLF,
CABBAGE {
@Override
public boolean isSafe(final Set<Member> others) {
return others.contains(FARMER) || !others.contains(GOAT);
}
},
GOAT {
@Override
public boolean isSafe(final Set<Member> others) {
return others.contains(FARMER) || !others.contains(WOLF);
}
};
public boolean isSafe(final Set<Member> others) {
return true;
}
}
</code></pre>
<p>Next is the <code>class Bank</code>, this encalsulates a river bank:</p>
<pre><code>import static com.google.common.base.Preconditions.checkState;
public final class Bank {
public static Bank all() {
return new Bank(EnumSet.allOf(Member.class));
}
public static Bank none() {
return new Bank(ImmutableSet.of());
}
private final ImmutableSet<Member> members;
public Bank(final Set<Member> members) {
this.members = ImmutableSet.copyOf(members);
}
public Bank accept(final Member member) {
checkState(!members.contains(member) && !members.contains(Member.FARMER));
final Set<Member> ms = Sets.newHashSet(members);
ms.add(member);
ms.add(Member.FARMER);
return new Bank(ms);
}
public Bank evict(final Member member) {
checkState(members.contains(member) && members.contains(Member.FARMER));
final Set<Member> ms = Sets.newHashSet(members);
ms.remove(member);
ms.remove(Member.FARMER);
return new Bank(ms);
}
public boolean farmerIsHere() {
return members.contains(Member.FARMER);
}
public boolean hasAllMembers() {
return equals(all());
}
public boolean isEmpty() {
return members.isEmpty();
}
public boolean isFeasible() {
return members.stream().allMatch((m) -> m.isSafe(members));
}
public Stream<Member> stream() {
return members.stream();
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + Objects.hashCode(this.members);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Bank other = (Bank) obj;
return Objects.equals(this.members, other.members);
}
}
</code></pre>
<p>This class allows the transferal of items from bank to bank according to the rules of the puzzle.</p>
<p>The next class encapsulates the state of play at any given time:</p>
<pre><code>final class State {
private final Bank leftBank;
private final Bank rightBank;
public State(final Bank leftBank, final Bank rightBank) {
this.leftBank = leftBank;
this.rightBank = rightBank;
}
public Bank leftBank() {
return leftBank;
}
public Bank rightBank() {
return rightBank;
}
public boolean isInitialState() {
return leftBank.hasAllMembers() && rightBank.isEmpty();
}
public boolean isSolution() {
return rightBank.hasAllMembers() && leftBank.isEmpty();
}
public boolean isFeasible() {
return leftBank.isFeasible() && rightBank.isFeasible();
}
public State moveToRight(final Member member) {
return new State(leftBank.evict(member), rightBank.accept(member));
}
public State moveToLeft(final Member member) {
return new State(leftBank.accept(member), rightBank.evict(member));
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + Objects.hashCode(this.leftBank);
hash = 97 * hash + Objects.hashCode(this.rightBank);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final State other = (State) obj;
if (!Objects.equals(this.leftBank, other.leftBank)) {
return false;
}
if (!Objects.equals(this.rightBank, other.rightBank)) {
return false;
}
return true;
}
}
</code></pre>
<p>This has various methods for determining whether that state is a solution etc.</p>
<p>Next I have the <code>interface Action</code> and <code>class ActionImpl</code>, this stores the "graph" of the solution - so that the path to the solution can be determined:</p>
<pre><code>public interface Action<T> {
Action<T> previous();
T data();
Collection<Action<T>> children();
void children(Collection<Action<T>> children);
}
public class ActionImpl<T> implements Action<T> {
private final Action<T> previous;
private final T data;
private Collection<Action<T>> children;
public ActionImpl(final Action<T> previous, final T data) {
this.previous = previous;
this.data = data;
}
@Override
public Action<T> previous() {
return previous;
}
@Override
public T data() {
return data;
}
@Override
public Collection<Action<T>> children() {
return children;
}
@Override
public void children(Collection<Action<T>> children) {
this.children = children;
}
@Override
public int hashCode() {
int hash = 5;
hash = 43 * hash + Objects.hashCode(this.data);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ActionImpl<?> other = (ActionImpl<?>) obj;
return Objects.equals(this.data, other.data);
}
}
</code></pre>
<p>Now for the meat of the puzzle, this is the <code>class</code> that solves the puzzle:</p>
<pre><code>public class App {
public static void main(final String[] args) throws Exception {
final State initalState = new State(Bank.all(), Bank.none());
final Action<State> finalState = calculateGraph(new ActionImpl<>(null, initalState));
final List<State> solution = ImmutableList.copyOf(getSoltutionPath(finalState));
final ListIterator<State> solIter = solution.listIterator(solution.size());
while (solIter.hasPrevious()) {
System.out.println(solIter.previous());
}
}
private static Action<State> calculateGraph(final Action<State> parent) {
final Collection<Action<State>> states = calculateChildren(parent);
parent.children(states);
return states.stream().filter((n) -> n.data().isSolution()).findFirst().orElse(parent);
}
private static Collection<Action<State>> calculateChildren(final Action<State> parent) {
final State s = parent.data();
if (s.leftBank().farmerIsHere()) {
return process(parent, calculateMoves(s.leftBank(), (m) -> s.moveToRight(m)));
}
if (s.rightBank().farmerIsHere()) {
return process(parent, calculateMoves(s.rightBank(), (m) -> s.moveToLeft(m)));
}
throw new IllegalStateException("We seem to have lost the farmer.");
}
private static Collection<Action<State>> process(final Action<State> parent, final Collection<State> children) {
final Set<State> path = getSoltutionPath(parent);
return children.stream().
filter((s) -> !path.contains(s)).
map((s) -> calculateGraph(new ActionImpl<>(parent, s))).
collect(Collectors.toSet());
}
private static Set<State> calculateMoves(final Bank bank, final Function<Member, State> mover) {
return bank.stream().map(mover).filter(State::isFeasible).collect(Collectors.toSet());
}
private static Set<State> getSoltutionPath(Action<State> leaf) {
final ImmutableSet.Builder<State> lb = ImmutableSet.builder();
while (leaf != null) {
lb.add(leaf.data());
leaf = leaf.previous();
}
return lb.build();
}
}
</code></pre>
<p>The idea is to recursively walk the graph of feasible moves and bubble the target state up through the recursion. The solution can then be determined by walking back up the parent nodes in the solution graph.</p>
<p>For completeness the output of running the code is:</p>
<pre><code>State(leftBank=Bank(members=[FARMER, WOLF, CABBAGE, GOAT]), rightBank=Bank(members=[]))
State(leftBank=Bank(members=[CABBAGE, WOLF]), rightBank=Bank(members=[GOAT, FARMER]))
State(leftBank=Bank(members=[CABBAGE, WOLF, FARMER]), rightBank=Bank(members=[GOAT]))
State(leftBank=Bank(members=[WOLF]), rightBank=Bank(members=[GOAT, CABBAGE, FARMER]))
State(leftBank=Bank(members=[GOAT, WOLF, FARMER]), rightBank=Bank(members=[CABBAGE]))
State(leftBank=Bank(members=[GOAT]), rightBank=Bank(members=[CABBAGE, WOLF, FARMER]))
State(leftBank=Bank(members=[GOAT, FARMER]), rightBank=Bank(members=[CABBAGE, WOLF]))
State(leftBank=Bank(members=[]), rightBank=Bank(members=[GOAT, CABBAGE, WOLF, FARMER]))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T01:39:45.980",
"Id": "76394",
"Score": "2",
"body": "That project lombok link is noisy (literally) and irritating. Makes a very, very bad first impression."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T01:47:01.907",
"Id": "76395",
"Score": "0",
"body": "@rolfl I've changed the link to their features page rather than their landing page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:33:08.637",
"Id": "76477",
"Score": "0",
"body": "I'm not aware of Java8. So forgive me if I'm asking a bad question. But where are the concrete implementation of `Action`'s methods in `ActionImpl` class? All I'm seeing is fields with same name as method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:41:38.207",
"Id": "76497",
"Score": "0",
"body": "@tintinmj that's where the Lombok annotations come in. It allows, for example getters and setters, to be automatically generated - check out the [`@Data`](http://projectlombok.org/features/Data.html) annotation. This removes quite a lot of the code clutter usually associated with Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T16:17:41.453",
"Id": "76505",
"Score": "0",
"body": "But how does it implement abstract methods from the interface such as `previous`,`children` etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T16:24:35.413",
"Id": "76506",
"Score": "1",
"body": "@tintinmj those are just getters and setters using the slightly newer fluent convention - `@Accessors(fluent = true, chain = false)` says accessors should be generated fluent (`children()` rather than `getChildren`) and not chained - setters should return `void`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T10:41:34.987",
"Id": "76676",
"Score": "0",
"body": "Where is `Bank.checkState()` defined?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T10:47:31.940",
"Id": "76677",
"Score": "0",
"body": "@200_success sorry, I missed that one. That is a static import for [`Preconditions.checkState`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkState(boolean))."
}
] | [
{
"body": "<h2>Commentry</h2>\n<blockquote>\n<p>So, this is not working code. I don't consider code to be working if\nneeds pre-processing, and the pre-processor is not shipped as part of\nthe standard toolchain.</p>\n<p>This code is nearly useless to anyone unless they have lambok.</p>\n<p>If I pull the code in to Eclipse, or any other standard tools, it is\nfull of compiler errors, missing methods, broken annotations, etc.</p>\n<p>As such the program is broken.</p>\n<p>I understand that it works for you, and that is about the only reason\nI am not voting to close</p>\n</blockquote>\n<p>I have <a href=\"https://codereview.meta.stackexchange.com/questions/1616/code-requiring-a-third-party-pre-processor-to-make-it-work\">created a Meta question to this effect....</a>.</p>\n<h2>Review - Everything except the App class.</h2>\n<p>Apart from the <code>App</code> class, there is only one place where Java8 systems are used:</p>\n<blockquote>\n<pre><code>public boolean isFeasible() {\n return members.stream().allMatch((m) -> m.isSafe(members));\n}\n</code></pre>\n</blockquote>\n<p>In this case, the code is quite clean and unambiguous. The only slight hesitation I have is the nested call to <code>members</code>... you are streaming the members, and for each member you call <code>isSafe(members)</code>. I cannot think of a better way to do that, or even if it is wrong... but it is just a little odd. Maybe it will grow on me. It is too early to say whether it violates a 'best practice'. I can't imagine it can go wrong, as long as the <code>isSafe</code> call does not modify the contents of the <code>members</code>, then it is fine. I think that is my concern... you are 'leaking' access to the <code>members</code> Collection while simultaneously streaming it.</p>\n<p>As for the rest of the code, it does indeed appear clean, and uncluttered. Not having any of the support methods like <code>toString</code>, <code>hashCode</code>, etc. means that there is less code to review, but that is a <em>big concern</em> because it is precisely in those sorts of methods where things can go wrong. Does the <code>equals()</code> method produce the right results? If it does not, it will be disastrous.</p>\n<p>Do we have to review the Annotations?</p>\n<h2>App class</h2>\n<p>I dislike disconnected recursion. You have a complicated recursive call:</p>\n<pre><code>main() calls calculateGraph()\n calculateGraph() calls calculateChildren()\n calculateChildren() calls process()\n process() calls calculateGraph() ( ... inside a lambda ...)\n</code></pre>\n<p>This disconnect makes the recursion really hard to follow. Recursive methods should be easy to see, clear, and uncomplicated.</p>\n<p>This is not.</p>\n<p>You use the class <code>ImmutableList</code>. I presume this is the Guava implementation.</p>\n<p>In your method:</p>\n<blockquote>\n<pre><code>private static Set<State> getSoltutionPath(Action<State> leaf) {\n final ImmutableSet.Builder<State> lb = ImmutableSet.builder();\n while (leaf != null) {\n lb.add(leaf.data());\n leaf = leaf.previous();\n }\n return lb.build();\n}\n</code></pre>\n</blockquote>\n<p>you take an ordered structure of data and load it in to a <code>Set</code>. This relies on the internals of Guava. You use the result of this method to populate the ordered data in your output. at no point though, is <code>Set</code> member order guaranteed. If you are using the properties of a specific Set implementation for any reason, then you should ensure that you return the right implementation type/subtype.</p>\n<p>In this case, you should be returning <code>ImmutableSet<State></code> and not <code>Set<State></code></p>\n<p>Additionally, in the <code>main()</code> method, you take a 'copy of' the Set, except the copy is a <code>List<State></code> instead of a <code>Set<State></code>. This is because you need to do a backward iteration on the results.</p>\n<blockquote>\n<pre><code> final List<State> solution = ImmutableList.copyOf(getSoltutionPath(finalState));\n final ListIterator<State> solIter = solution.listIterator(solution.size());\n while (solIter.hasPrevious()) {\n System.out.println(solIter.previous());\n }\n</code></pre>\n</blockquote>\n<p>The meaning and structure of your data as it passes through these different layers of obfuscation are completely lost. The fact that the order is significant is only apparent when you work backwards from the end... and understand that you need to loop backwards through this data to get the right-ordered report... then, you need a List to do that (for the <code>ListIterator</code>), and from that you realize that the (badly named) <code>copyof</code> method converts a Set to a List, and (magically, because the signatures do not tell you) despite being a Set, it actually has a pre-defined order (which Sets normally don't have), and that defined order is the result of a bottom-up traversal of a tree.</p>\n<p>Just saying that is confusing. There has to be a better way.</p>\n<h2>Conclusion....</h2>\n<p>The Java8 parts of your code appear fine, but they are completely lost in the fog that comes up from needing to understand the lambok system, and the poor use of collections that are worsened by the use of inappropriate classes from Guava.</p>\n<p>At a personal level, this was not much fun to review. Not enough background information was available. The use of Guava was undocumented. The lambok system is kludgey, and unfriendly for reviewers. Expecting a reviewer to learn an esoteric system to do a decent review is 'not cool'. If the meta question referenced above results in saying that questions like this are 'on topic', then I intend to ensure that they are all tagged appropriately so I can ignore them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:33:58.390",
"Id": "76616",
"Score": "0",
"body": "I see your point about the collections. I wanted a `Set` that maintains insertion order - which `ImmutableSet` does - sadly there is no `interface` or `Abstract class` in Java that declares that behaviour. I think using `ImmutableSet` as a return type would indeed be a better choice. As far a Lombok goes, noted. A question though - is the same true for all 3rd party libraries (for example Guava?). As Lombok is an annotation processor you only need to include it on the compile classpath for it to work; this is the same as for other 3rd party libraries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:41:52.293",
"Id": "76618",
"Score": "0",
"body": "@BoristheSpider How far do I have to go? I include the lombok (1.12.6) in my class path, get the imports right for the annotations, but now I have things like `the blank final field previous may not have been initialized` and similar messages for all the final fields in ActionImpl, and still the errors about not implementing the override methods. There must be something else that needs doing before it will work in eclipse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:43:06.170",
"Id": "76619",
"Score": "0",
"body": "I can only speak for NetBeans, maybe there is something else that needs to be done for Eclipse. In any case I have removed the Lombok stuff as suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:43:25.787",
"Id": "76620",
"Score": "0",
"body": "Should I *need* to care about these things to understand/review your code? As for the Guava... I avoid Guava for corporate reasons... and I would avoid reviewing questions if I know ahead of time ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:50:32.327",
"Id": "76622",
"Score": "0",
"body": "@BoristheSpider - thanks for the delombok... call me old fashioned, but I don't trust the machines ;-) The code looks so much more logical now.... I am not accustomed to looking for implementation-logic in annotations. Not saying that is a good thing, but, it sure is common. You will have problems getting other people to review the code when you don't use common practices."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T01:26:38.987",
"Id": "44217",
"ParentId": "44115",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T01:20:22.280",
"Id": "44115",
"Score": "15",
"Tags": [
"java"
],
"Title": "Wolves, Goats and Cabbages in Java"
} | 44115 |
<p>This is a partial code of my JavaScript app.</p>
<p>The <code>openDoc</code> function's task is:
call <code>newDoc</code> if use uploads a file through <code>fileInput</code>.
Or, when user drag and drop a file in the <code>document</code>.</p>
<p>I want to review my logic and code.</p>
<pre><code> function stopDefault(event) {
event.stopPropagation();
event.preventDefault();
}
function openDoc(event) {
var files = event.target.files || event.dataTransfer.files,
file = files[0],
reader = new FileReader();
if (file) { // prevent TypeError
stopDefault(event); // prevent default file drop behavior
reader.readAsText(file);
}
reader.addEventListener("load", function(event) {
newDoc(event.target.result, file.name);
});
}
fileInput.addEventListener("change", openDoc);
document.addEventListener("dragover", stopDefault);
document.addEventListener("drop", openDoc);
</code></pre>
<p>If you're interested, checkout the full code - <a href="https://dl.dropboxusercontent.com/u/92126558/app.js" rel="nofollow">https://dl.dropboxusercontent.com/u/92126558/app.js</a></p>
| [] | [
{
"body": "<p>There is a not a lot to review, from a once over:</p>\n\n<ul>\n<li>Indenting is not good for <code>stopDefault</code>, but I guess that's from copy pasting</li>\n<li>There is no sense in calling <code>addEventListener</code> if <code>file</code> is not set, it should be part of your <code>if</code> block</li>\n<li>Personally I would first add the listener, then starting reading text</li>\n<li>I like your use of <code>stopDefault</code></li>\n<li>JsHint could find nothing wrong</li>\n<li>Looks easy to maintain and to grok</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T17:55:20.730",
"Id": "44176",
"ParentId": "44124",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T06:05:59.547",
"Id": "44124",
"Score": "2",
"Tags": [
"javascript",
"html",
"html5",
"api"
],
"Title": "Drag and normal upload code"
} | 44124 |
<p>This is my code for running a background thread. I believe it is very poor in naming and code structure.</p>
<pre><code>package com.ocs.socialshare.bloggershare;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.gdata.util.AuthenticationException;
public class MainActivity extends Activity implements OnClickListener{
private Thread doinBackground;
private EditText username,password,blogurl;
private Button login;
private String user,pass,bloglink;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
setOnclickListenerRegister();
}
private void findViewById() {
// TODO Auto-generated method stub
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
blogurl = (EditText) findViewById(R.id.blogurl);
login = (Button) findViewById(R.id.login);
}
private void setOnclickListenerRegister() {
// TODO Auto-generated method stub
login.setOnClickListener(this);
}
private void blogShare(final String user,final String pass,final String bloglink) {
// TODO Auto-generated method stub
doinBackground =new Thread(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
BloggerClient blog = new BloggerClient(getApplicationContext());
try {
blog.oAuthBlogger(user,pass,bloglink);
}
catch (AuthenticationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
doinBackground.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
int viewid = view.getId();
if(viewid == R.id.login)
{
validateFeild();
blogShare(user,pass,bloglink);
}
}
private void validateFeild() {
// TODO Auto-generated method stub
user = username.getText().toString();
pass = password.getText().toString();
bloglink = blogurl.getText().toString();
}
}
</code></pre>
| [] | [
{
"body": "<p>The first thing I would say is to use an <code>AsyncTask</code> here instead of normal Thread/Runnable. <code>AsyncTask</code> helps you to work better with the thread and UI thread better.</p>\n\n<p>It's a login system, so disable login buttons while the application is login to avoid the user to press multiple times on Login.</p>\n\n<p><a href=\"http://developer.android.com/reference/android/os/AsyncTask.html\" rel=\"nofollow\">http://developer.android.com/reference/android/os/AsyncTask.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T06:34:17.810",
"Id": "76411",
"Score": "0",
"body": "I read one blog asynctask is produce problem with orientation changes. is that true?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T06:45:46.383",
"Id": "76412",
"Score": "0",
"body": "AsyncTask could give problems sometimes (never had problem by myself (except the activity killed before async finish). my login system uses asynctask) but could happen the asynctask is executed and the activity not exist anymore or some cases similar (too long for a comment, for me) but you could do some checks and avoid some problems. Anyway you could write something like a Service (they don't spawn a new thread! ) and put logic here then say back response to activity (but its pretty the same thing)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T06:26:56.273",
"Id": "44126",
"ParentId": "44125",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>Please remove all <code>// TODO Auto-generated method stub</code> comments. Your methods are implemented. You don't need those comments any more.</p></li>\n<li><p>Indentation. If you're using Eclipse, select all code and press Ctrl + Shift + I to ident your code properly. If you're using NetBeans, press Alt + Shift + F. Your try-catch inside the <code>blogShare</code> method is incorrectly indented.</p></li>\n<li><p>The correct spelling is <code>validateField</code></p></li>\n<li><p><code>user</code>, <code>pass</code> and <code>bloglink</code> are only set within <code>validateField</code> and only read directly after that method invocation. Get rid of the <code>validateField</code> method (which currently doesn't do any actual <strong>validation</strong> so it's a poorly named method). Use local variables within the <code>onClick</code> method.</p></li>\n<li><p><code>int viewid = view.getId();</code> is IMO not needed to set as a variable, as you only check it once, use <code>view.getId()</code> directly.</p></li>\n<li><p><code>setOnclickListenerRegister</code> is only called once from <code>onCreate</code> and this method only contains one line, so what you have done is to extract one statement to it's own method and then call that method which were only called once. This extraction is not worth it. Remove this method and put <code>login.setOnClickListener(this);</code> back to the <code>onCreate</code> method where it belongs.</p></li>\n<li><p>I <strong>totally</strong> agree with Marco that you should use <code>AsyncTask</code>. <strong>If</strong> you encounter any problems with orientation changes, deal with those correctly. Don't avoid using <code>AsyncTask</code> just because you're <strong>afraid</strong> that it will cause problems.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:31:43.207",
"Id": "76541",
"Score": "1",
"body": "`I totally with Marco` should probably be `I totally agree`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:41:25.227",
"Id": "76546",
"Score": "0",
"body": "@Marc-Andre Fixed, thanks for reviewing my review!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:57:16.753",
"Id": "44144",
"ParentId": "44125",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "44126",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T06:15:14.010",
"Id": "44125",
"Score": "7",
"Tags": [
"java",
"beginner",
"android"
],
"Title": "Android Thread and Runnable"
} | 44125 |
<p>While trying to learn more about linked lists, I thought I should try the exercise of reading two BigInts from an input file and then adding them up. My strategy was to store the two numbers in two different linked lists and then add the entries of the linked lists while traversing through them. I have my implementation down below and it will be great if somebody could review what I have done here. The current implementation is geared towards adding two numbers. It will be great if somebody could give me a few pointers on extending it for an arbitrary number of BigInts.</p>
<p>My "input.txt" is as follows:</p>
<pre><code>65368023423432568512973371196238845129776544789456
553245642579324556736835497210698463523456234
</code></pre>
<p>And my implementation is as follows:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
int data;
struct node* next;
} LList;
LList* pushToResult(LList* resultList,int entry){
LList * temp = malloc(sizeof(LList));
temp -> data = entry;
temp -> next = resultList;
resultList = temp;
return resultList;
}
LList* convertToList(LList * list,char* line){
//Get the size of the string
//Create a new list
int i;
int strSize = strlen(line);
LList * temp = NULL;
for(i=0;i<strSize-1;i++){
char num = line[i];
if(temp == NULL){
temp = malloc(sizeof(LList));
temp -> data = num - '0';
temp -> next = NULL;
}else{
LList * current = malloc(sizeof(LList));
current -> data = num - '0';
current -> next = temp;
temp = current;
}
}
list = temp;
return list;
}
void printList(LList * list){
LList * counter = list;
while( counter != NULL){
printf(" %d ",counter -> data);
counter = counter -> next;
}
printf("\n\n");
}
int main(){
//Read number 1 from the input file into a linked list
//The unit's place is the head and the mot significant number is the tail
//Read number 2 from the input file into a linked list
//The unit's place is the head and the most significant number is the tail
//Create temporary List where the elements will be added
//Create the carry variable that will consist of the element's carry over after addition
int counter = 0;
ssize_t read;
size_t len = 0;
char * line = NULL;
int carry = 0;
LList* num1 = NULL;
LList* num2 = NULL;
LList* result = NULL;
//Opening the file for the input
FILE * input = fopen("input.txt","r");
if(input == NULL){
exit(EXIT_FAILURE);
}
while((read = getline(&line,&len,input)) != -1){
printf("Read the line %s",line);
//If it's the first line
if(counter == 0){
//printf("Counter is 0\n");
num1 = convertToList(num1,line);
printf("Printing the list containing the num1(it will be in reversed order)\n");
printList(num1);
}else{
num2 = convertToList(num2,line);
printf("Printing the list containing the num2(it will be in reversed order)\n");
printList(num2);
}
counter++;
}
//Closing the input file
fclose(input);
while((num1 != NULL) || (num2 != NULL)){
if(num1 != NULL){
carry = carry + (num1->data);
num1 = num1 -> next;
}
if(num2 != NULL){
carry = carry + (num2 -> data);
num2 = num2 -> next;
}
//Get the carry and the left over
int carryOver = carry / 10;
int leftOver = carry % 10;
result = pushToResult(result,leftOver);
carry = carryOver;
}
//Done with traversing the linked lists,if the carry is zero no need to push the value to the result
//else push the value to the result
if(carry != 0){
result = pushToResult(result,carry);
}
//Print the result here
printf("Printing out the result of the addition\n");
printList(result);
}
</code></pre>
| [] | [
{
"body": "<p>Just two things:</p>\n\n<ol>\n<li><p>In <code>convertToList()</code> you don't really use the first argument at all. You can code that function with receiving only the (read-only) input string.</p>\n\n<pre><code>LList *convertToList(const char *line) {\n /* ... */\n return temp;\n}\n</code></pre></li>\n<li><p>You really should get into the habit of releasing memory once you no longer need it.\nFor each <code>malloc()</code> there should be a <code>free()</code>. This includes the result from <code>getline()</code>.</p></li>\n<li><p><em>(extra)</em> Don't comment the obvious</p>\n\n<pre><code> //Closing the input file\n fclose(input); \n</code></pre>\n\n<p>This is OK though :)</p>\n\n<pre><code> //Get the carry and the left over\n int carryOver = carry / 10;\n int leftOver = carry % 10;\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T06:22:55.437",
"Id": "76651",
"Score": "0",
"body": "Thanks for your response. Can you clarify which malloced elements can I free in this code. Being a newbie to C I lack the intuition about when to free the elements. I thought since every element of the Linked List is in use, I do not need to free any elements. It will be great to hear your rationale for free'ing any of these elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T09:39:57.440",
"Id": "76671",
"Score": "1",
"body": "Current Operating System will free the memory your program leaked once the program finishes but **it is a good idea to free it yourself** nonetheless! You can free the memory allocated in `pushToResult()` and `convertToList()` at the end of main, after the call to `printList()` (I'd make a function for that and name it something like `freeList()`). As for the memory allocated with `getline()` you can free that at the end of the loop, right before (or after) closing the input file."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:05:38.597",
"Id": "44136",
"ParentId": "44128",
"Score": "4"
}
},
{
"body": "<p>If you want to make it more (memory) efficient and thereby also faster, you could make every list node represent 9 digits from the input. Your highest possible value in a node would be 999999999 and adding two of these would still not overflow the range of <code>int</code>. You are thus encoding your values base 1000000000. Of course, you could also try using <code>long long</code> and encode 18 digits of a value in a node.</p>\n\n<p>I know that you are primarily interested in learning about linked lists, but I think learning to use them efficiently is part of that task.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T06:32:23.143",
"Id": "76652",
"Score": "0",
"body": "Thanks for your response. Can you explain what you meant by \"You are thus encoding your values base 1000000000.\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T09:43:13.143",
"Id": "76672",
"Score": "1",
"body": "In your `struct node` what values can the element `data` have? `0` to `9`, 10 distinct values. That's the base. Base 10. If you allowed `data` to have values `0` and `1` only, that would be base 2; for values from `0` to `15` would be base 16, ..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T20:03:27.830",
"Id": "44188",
"ParentId": "44128",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "44136",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T07:27:40.237",
"Id": "44128",
"Score": "5",
"Tags": [
"c",
"linked-list",
"memory-management"
],
"Title": "Adding two BigInts using linked lists in C"
} | 44128 |
<p>I've seen others use && for conditionally continuing execution in bash, and found it effective but rather ugly. (I'm not sure if there's a better name for this technique.)</p>
<pre><code>do_something && something_else && the_next_thing
</code></pre>
<p>Then I found out that you can simply wrap things in parentheses just because you feel like it. (And in my original motivation was to return to easily return to the calling folder.)</p>
<p>So in the following script, I tried combining those techniques. (The motivation for the script is an <a href="https://github.com/rabbitvcs/rabbitvcs/issues/11" rel="nofollow">attempt</a> to install <a href="http://rabbitvcs.org" rel="nofollow">RabbitVCS</a> for development.)</p>
<p>Questions:</p>
<ul>
<li>is combining && and () in this way "idiomatic" for bash?</li>
<li>similarly, is using () to return to the calling folder appropriate</li>
<li>how's my indentation? (I normally program in Python ;) )</li>
</ul>
<pre><code> #! /bin/bash
# CC0 To the extent possible under law, the person who associated CC0
# with this work has waived all copyright and related or neighboring
# rights to this work. https://creativecommons.org/publicdomain/zero/1.0/
# Required folders (must exist beforehand):
# * Source code and script folders (see export statements below)
# * Nautilus 3: ~/.local/share/nautilus/python-extensions
# * CLI: /usr/bin (always exists)
# * GEdit: ~/.local/share/gedit/plugins
# Out of scope for this script:
# * Setting up folders above
# * Keeping RabbitVCS source code up-to-date
# Set customisable folder paths:
# Source code, cloned from GitHub
export SOURCE_FOLDER=~/Code/rabbitvcs
# User scripts location for RabbitVCS CLI (must be in .bashrc or equivalent)
export SCRIPT_FOLDER=~/Code/scripts
if [ "$1" = "--help" ] || [ -z $1 ] || [ "$2" ];
then
# if "--help" is called, or too many or too few parameters given, display help
echo "Install specified branch of RabbitVCS with Nautilus, Gedit and CLI clients."
echo "(Assumes prerequisites are installed and target branch and folders exist.)"
echo "Usage: install-rabbitvcs-branch "
else
( # parentheses so that we return to original folder
# install all prerequisites, even the obvious ones
# (package names as used in Ubuntu 13.10)
# (also triggers prompt for sudo password as soon as possible)
sudo apt-get install gedit git hicolor-icon-theme ipython meld subversion python python-configobj python-dbus python-dulwich python-gobject python-gobject-2 python-gtk2 python-gtkspell python-nautilus python-simplejson python-support python-svn -qq && (
# kill existing Nautilus and RabbitVCS processes (if they exist)
pgrep -f nautilus && nautilus -q
pgrep -f service.py && xargs kill
# checkout requested branch
cd $SOURCE_FOLDER && git checkout $1 && (
# (re)install RabbitVCS library
sudo python setup.py check && sudo python setup.py install && (
# (re)install RabbitVCS clients
echo "Installing RabbitVCS clients..."
cp clients/nautilus-3.0/RabbitVCS.py ~/.local/share/nautilus/python-extensions
cp clients/gedit/rabbitvcs-plugin.py ~/.local/share/gedit/plugins
cp clients/gedit/rabbitvcs-gedit3.plugin ~/.local/share/gedit/plugins
cp clients/cli/rabbitvcs $SCRIPT_FOLDER
echo "done."
)
)
)
)
fi</code></pre>
| [] | [
{
"body": "<p><strong>Firstly</strong>, this will most likely do a wrong thing if the first argument is empty:</p>\n\n<pre><code>if [ \"$1\" = \"--help\" ] || [ -z $1 ] || [ \"$2\" ];\n</code></pre>\n\n<p>You should probably use something like this instead (note added quotes):</p>\n\n<pre><code>if [ \"$1\" = \"--help\" ] || [ -z \"$1\" ] || [ $# -gt 1 ];\n</code></pre>\n\n<p>In general you should quote all variables which are not guaranteed to be set, to be non-empty and to only contain alphanumeric characters.</p>\n\n<p><strong>Secondly</strong>, I would not call myself a seasoned bash hacker, but parenthesis are imo more common if you need to run a small command in another directory, e.g.</p>\n\n<pre><code>(cd -P \"$anotherdir\"; make fun)\n</code></pre>\n\n<p>When it comes to longer code pieces you can either use a function or simply pushd and popd, e.g.</p>\n\n<pre><code>pushd .\ncd \"$anotherdir\"\n# do something else\npopd\n</code></pre>\n\n<p><strong>As for formatting</strong>, I also use four-space indentation but prefer more dense code and therefore put <code>then</code> on the same line as <code>if</code>. Additionally, I usually write following code if I need several commands to run in sequence only if everything worked out fine:</p>\n\n<pre><code>stderr() {\n cat - 1>&2\n}\n\nfail() {\n printf \"%s\\n\" \"$@\" | stderr\n return 1\n}\n\ncommandA \"$arg1\" \"$arg2\" || fail \"ERROR: something went wrong\"\ncommandB \"$arg1\" \"$arg2\" || fail \"ERROR: something else went wrong\"\n</code></pre>\n\n<p>UPDATE: Incorporate rolfl's suggestion to use a fail() function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T08:56:17.377",
"Id": "44133",
"ParentId": "44131",
"Score": "3"
}
},
{
"body": "<p>The use of the parenthesis like you have it, is not 'idiomatic' in Bash.</p>\n\n<p>Each time you use it you are creating a sub shell, and that incurs an overhead that is typically avoided.</p>\n\n<p>Also, all those <code>cp</code> commands in the inner-block .... if one of them fails, you will just keep going, so your handling is incomplete anyway....</p>\n\n<p>Bash error handling can become cumbersome. I recommend <a href=\"http://phaq.phunsites.net/2010/11/22/trap-errors-exit-codes-and-line-numbers-within-a-bash-script/\" rel=\"nofollow noreferrer\">reading some decent articles</a>, and looking in to traps and signals....</p>\n\n<p>Also, consider adding your <a href=\"https://codereview.stackexchange.com/a/43085/31503\">error handling as a simple function</a>...</p>\n\n<p>In other notes....</p>\n\n<p>Your test conditions are odd..... These lines:</p>\n\n<pre><code>if [ \"$1\" = \"--help\" ] || [ -z $1 ] || [ \"$2\" ];\nthen\n</code></pre>\n\n<p>would be better written as</p>\n\n<pre><code>if [[ \"$1\" = \"--help\" || -z \"$1\" || -n \"$2\" ]]; then\n</code></pre>\n\n<p>See these details on <a href=\"http://phaq.phunsites.net/2010/11/22/trap-errors-exit-codes-and-line-numbers-within-a-bash-script/\" rel=\"nofollow noreferrer\">the <code>\\[\\[ ... \\]\\]</code> test</a> and the <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions\" rel=\"nofollow noreferrer\">Bash conditionals</a>\nIBM has a <a href=\"http://www.ibm.com/developerworks/opensource/library/l-bash-test/index.html\" rel=\"nofollow noreferrer\">decent document describing the different test and conditional structures</a> in Bash.</p>\n\n<p>Note that I put the <code>then</code> on the same line as the <code>if</code>. This is because you have the <code>;</code> semi-colon on the <code>if</code> line, and the only reason to have the semi-colon is to allow the <code>then</code> to be on the same line.... It is standard in bash to put the <code>then</code> on the same line as the <code>if</code> (see <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs\" rel=\"nofollow noreferrer\">the documentation</a>....).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:58:04.593",
"Id": "76482",
"Score": "0",
"body": "I don't see why the [classic test command](http://wiki.bash-hackers.org/commands/classictest) (\"[\" and \"]\") should be replaced with the [Bash one](http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression) (\"[[\" and \"]]\"). Did you do this for a reason, or out of preference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:11:12.000",
"Id": "76486",
"Score": "0",
"body": "Did it for a reason... the `[[ ... || ... || ... ]]` is a single test operation embedded in bash, whereas the `[ ...] || [ ... ] || [ ... ]` are three tests (potentially) using the external command `[` (type `man test` on your commandline). Also, the `[[` is more versatile. In general I feel it is more bash-like (out of interest, type `[ --help` on your commandline ;-) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:30:45.270",
"Id": "76494",
"Score": "0",
"body": "Ok, now I understand why. However, I prefer `[` because I usually run scripts via `dash` which starts quicker than bash and has a built-in test command. I'm also trying to learn all features of POSIX shell before diving into bash, which is another reason."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:08:33.100",
"Id": "44152",
"ParentId": "44131",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T08:28:31.867",
"Id": "44131",
"Score": "2",
"Tags": [
"bash",
"error-handling"
],
"Title": "Is this an appropriate approach and layout for conditionally continuing execution in bash?"
} | 44131 |
<p>I want to refactor the following code because I don't feel comfortable about using assignment inside comparison operator. It looks like pretty idiomatic C, but do you think this is a good practice in Java?</p>
<pre><code>private void demoA(BufferedReader reader) throws IOException {
String line = null;
while ((line = reader.readLine()) != null) {
doSomething(line);
}
}
</code></pre>
<p>Here is an alternative.</p>
<pre><code>private void demoB(BufferedReader reader) throws IOException {
String line = reader.readLine();
while (line != null) {
doSomething(line);
line = reader.readLine();
}
}
</code></pre>
<p>UPDATE: I've stumbled across a <a href="https://stackoverflow.com/questions/4677411/iterating-over-the-content-of-a-text-file-line-by-line-is-there-a-best-practic">similar question</a> asked couple years ago. It seems that opinions on whether it's OK or not are divided. However, both <a href="https://stackoverflow.com/a/17655456/2517807">Guava</a> and <a href="https://codereview.stackexchange.com/a/44142/36217">Commons IO</a> provide alternative solutions for this issue. If I had any of these libs in the current project, I'd probably use them instead.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T09:32:43.847",
"Id": "76428",
"Score": "0",
"body": "You are mainly asking for a based-opinion answer, in my case the first approach has proven to be more clear when I need to choose between both, but it is just my case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T09:37:27.613",
"Id": "76429",
"Score": "0",
"body": "I assume that last `reader.readLine();` should be `line = reader.readLine();`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T09:50:24.903",
"Id": "76431",
"Score": "0",
"body": "tobias_k: yes, thanks. I've fixed it. \nmorgano: well, it is a question about coding guidelines, and most such questions are opinion-based. Still, I would like to know if majority prefers one of these options or if there is no strong preference. Thanks for you reply!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:52:05.427",
"Id": "76435",
"Score": "3",
"body": "I consider `demoA` to be idiomatic for Java. That said, there's an old SO question on the same topic: http://stackoverflow.com/questions/4677411/iterating-over-the-content-of-a-text-file-line-by-line-is-there-a-best-practic Especially the highest-rated (not accepted) answer is interesting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:49:39.203",
"Id": "76458",
"Score": "2",
"body": "I don't write `String line = null;` but `String line;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:05:49.253",
"Id": "76473",
"Score": "0",
"body": "I think one of the main things to consider here is that you're dealing with a `BufferedReader` and that has been using that idiom since the beginning of Java. If you did it with something OTHER than a buffered reader, people might not know what you're doing, but because you're reading a line at a time, that's something most Java developers have seen and will recognize immediately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T03:35:20.403",
"Id": "76858",
"Score": "0",
"body": "What about `while (null != (line = ...))`?"
}
] | [
{
"body": "<p>Assignment inside a condition is ok in this case, as the assignment is surrounded by an extra pair of parentheses – the comparison is obviously <code>!= null</code>, there is no chance that we wanted to type <code>line == reader.readLine()</code>.</p>\n\n<p>However, a <code>for</code> loop might actually be more elegant here:</p>\n\n<pre><code>for (String line = reader.readLine(); line != null; line = reader.readLine()) {\n doSomething(line);\n}\n</code></pre>\n\n<p>Alternatively, we could do this which also restricts the scope of <code>line</code> as with the <code>for</code>-loop, and additionally eliminates unnecessary repetition:</p>\n\n<pre><code>while (true) {\n final String line = reader.readLine();\n if (line == null) break;\n\n doSomething(line);\n}\n</code></pre>\n\n<p>I like this solution most because it doesn't mutate any variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:40:24.903",
"Id": "76432",
"Score": "9",
"body": "+1 for `for` loop. I hadn't thought about it before but that is clear and avoids having `line` outside of the loop scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:59:09.940",
"Id": "76446",
"Score": "2",
"body": "I also like the for loop solution. It is dense, readable and does not draw attention away from `doSomething(line)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:08:31.343",
"Id": "76461",
"Score": "0",
"body": "In the second loop: why always create a new final String and not put the a variable before the while?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:12:36.767",
"Id": "76463",
"Score": "0",
"body": "There's a special construct in C++ to keep the outer scope free of garbage variables: `while (int a = f()) { ... }`. I think that it's fine to write such code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:16:18.960",
"Id": "76466",
"Score": "5",
"body": "@FabioF. I do not create a `new String` each time, that happens anyway because of `readLine`. It is however considered a best practice to restrict the visibility of variables to the smallest possible scope. Here, this means the `line` should not be declared outside of the loop. Not reassigning variables and other aspects of immutability are a good habit I picked up when doing functional programming: This makes code easier to understand as the variable name and its value can be used interchangeably (“referential transparency”), there is no mutating state I have to keep in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:22:03.543",
"Id": "76468",
"Score": "0",
"body": "@amon what about\n `{String line; while(...){...}}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:24:48.940",
"Id": "76469",
"Score": "2",
"body": "@FabioF. While that would restrict the visibility properly, it adds an unnecessary level of indentation. And we might just as well use an equivalent `for (String line; ...;) { ... }` instead – all of the advantages, none of the downsides."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:21:45.337",
"Id": "76491",
"Score": "0",
"body": "Got my upvote... good answer, except for having the 1-liner suggestion: `if (line == null) break;` which is contrary to [Java code-style guidelines (7.4)](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#449)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:58:52.620",
"Id": "76502",
"Score": "2",
"body": "I like the last solution best. It's often a good idea to avoid having loop exit points which are separated by code that has meaningful side-effects, but if the natural location for the loop exit point is in the middle, it's better to use a while/break construct than duplicate the code which should precede the loop exit point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:01:35.837",
"Id": "76534",
"Score": "0",
"body": "The while (true) suggestion works especially well if the code to get the next item to be processed is less trivial than here. In trivial cases it doesn't really matter what pattern you use because it's trivial anyway, but this pattern works fine with complex cases as well. It avoids duplicating this code at the end of the loop, which is error prone if the code in the loop gets longer and might contain a continue statement. Which is quite common, if you structure your code like \"get line; exit if no more lines; check if line should be ignored; process line; \""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T14:16:20.530",
"Id": "76712",
"Score": "0",
"body": "@EmilyL., I disagree about the `for` loop. While the code is _functional_, a `for` loop is semantically for a specific number of iterations (including iterating over a collection/array) while a `while` loop is semantically for an unknown number of iterations (such as reading from a file). Both loop variants _can_ be constructed using the other, of course, but that's not the point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:30:06.580",
"Id": "76760",
"Score": "1",
"body": "@BrianS While true in the naive case, Java's introduction of the `for-each` construct in 1.5 has lead to a bit of coloring to the meaning of a `for` loop. To use in such a loop, an object must implement `Iterable`, but nothing about that interface implies that the number of objects produced by the iterator returned by `Iterable.iterator()` must be specific. A reasonable example would be the `Iterable` solution from Arian's answer; you do not know how many lines the `Iterable` will produce, but each line is its own element to operate on and thus the `each` still has meaning."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:05:44.090",
"Id": "44137",
"ParentId": "44135",
"Score": "71"
}
},
{
"body": "<p>You could increase the abstraction level of the code a little bit with an iterator-like pattern and the same time you could reuse an existing library (with the experience of the authors) for that: <a href=\"http://commons.apache.org/proper/commons-io/\" rel=\"nofollow noreferrer\">Apache Commons IO</a> <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/LineIterator.html\" rel=\"nofollow noreferrer\">LineIterator</a>. It would replace the null check to a little bit readable <code>hasNext()</code>/<code>nextLine()</code>.</p>\n\n<p>Using an iterator hides an unnecessary detail: the reader returns <code>null</code> when there is no more data. The <code>hasNext()</code> method is closer to the (English) language, the code is easier to read. You still can check the details inside <code>LineIterator</code> if you need that but usually readers/maintainers happier with a higher level overview of the method which is easier to understand. (<a href=\"https://codereview.stackexchange.com/a/42504/7076\">This answer</a> and question contain an expressive example.)</p>\n\n<p>A sample method:</p>\n\n<pre><code>private void demoC(BufferedReader reader) throws IOException {\n final LineIterator it = new LineIterator(reader);\n try {\n while (it.hasNext()) {\n String line = it.nextLine();\n // do something with line\n }\n } finally {\n it.close();\n }\n}\n</code></pre>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:01:24.187",
"Id": "76450",
"Score": "0",
"body": "We don't use Apache Commons IO on this project, but thanks for a pointer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:23:38.097",
"Id": "76454",
"Score": "0",
"body": "@mkalkov: It's just simple a class with a couple of lines, so you can create your own version or copy the implementation into your project (but check the license before that)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T18:03:40.157",
"Id": "76535",
"Score": "0",
"body": "Of course you can increase the abstraction level. But why would you? What are the benefits?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T21:55:03.400",
"Id": "76593",
"Score": "0",
"body": "@gnasher729: Good question, thanks! I've updated the answer, check it please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T11:20:52.487",
"Id": "76684",
"Score": "0",
"body": "For the sake of testing line = null, you now have to learn about a non-standard LineIterator class which is found deep in some library, you have to know that the iterator has a \"hasNext\" method, you have to know that you get the next line by calling \"nextLine\", you have to know to call \"close\" on the iterator, you added exception handling, there are 8 lines of boilerplate code instead of 3, the actual code is now three levels deeply nested before it even starts instead of two, excuse me if I'm not impressed at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T11:56:25.093",
"Id": "76687",
"Score": "0",
"body": "@gnasher729: Two things to consider: 1. `close` just closes the reader which is missing from the original code. 2. code is read more than written, so it's worth to optimize for reading."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T15:05:12.437",
"Id": "76721",
"Score": "2",
"body": "Why are you using this iterator manually instead of inside a foreach loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T15:13:03.670",
"Id": "76723",
"Score": "3",
"body": "@Phoshi: unfortunately foreach can't use `Iterator`, it needs and `Iterable`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T15:32:46.627",
"Id": "76731",
"Score": "2",
"body": "@palacsint: Ah, of course. I guess my question is then why on earth LineIterator doesn't implement Iterable, but I suppose that isn't something you can answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T15:40:46.220",
"Id": "76734",
"Score": "1",
"body": "@Phoshi: You can pass any reader (with any stream) to the `LineIterator`. Some of them might not support `reset` (and can be read only once, like a network socket). Rereading multiple times requires creating multiple iterators with `Iterable.iterator()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:00:16.547",
"Id": "76740",
"Score": "0",
"body": "@palacsint: Isn't that exactly the same scenario as here, though? A foreach loop effectively compiles down into the code you have here, you still can't iterate over either more than once safely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:33:44.597",
"Id": "76764",
"Score": "0",
"body": "@palacsint None of `Iterator`, `Iterable`, and `LineIterator` support `reset` either, so I'm not sure what your point is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:38:08.600",
"Id": "76765",
"Score": "0",
"body": "@JAB: reset is for streams. You could create a `LineIterable` whose `iterator()` method could call `reset` on the underlying stream. (It would have disadvantages, like it's not too easy to support concurrent iterators.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:39:32.840",
"Id": "76768",
"Score": "0",
"body": "@Phoshi: Yes, it is but foreach does not support that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:53:07.810",
"Id": "76771",
"Score": "0",
"body": "@palacsint: foreach just calls .next until .hasNext is false, the only issue would come around if you tried to enumerate /twice/... which is exactly the same in this case. I'm still not seeing why it couldn't be an iterable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:58:31.557",
"Id": "76773",
"Score": "0",
"body": "@palacsint Sure you could, and you could also subclass `LineIterator` into `ResettingLineIterator` and have the constructor reset the reader. The argument against `Iterable` at https://issues.apache.org/jira/browse/IO-181 is for implementing both interfaces on the same object and is perfectly reasonable, but any arguments against a `LineIterable` class separate from `LineIterator` that returns a new iterator for each `iterator()` call apply equally to `LineIterator` itself due to the nature of the underlying `Reader`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T17:11:21.687",
"Id": "76778",
"Score": "1",
"body": "(Not to mention that using multiple `LineIterator`s for concurrency would possibly be worse than a `LineIterable` class as each of those `LineIterator`s could close the `Reader`, which would invalidate any other `LineIterator`s on that `Reader` even if it were one supporting `mark`/`reset`/`skip` and the iterators were subclassed to keep track of their positions independently [though you could also override `LineIterator.close()` to not actually call `Reader.close()` until all iterators for that `Reader` have closed/been consumed - perhaps a concurrent `Map<Reader, Integer>` for the counts?])."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T17:28:42.283",
"Id": "76782",
"Score": "0",
"body": "Of course, in Java 8 you'd do something like `BufferedReader rf; if (reader instanceof BufferedReader) rf = (BufferedReader) reader; else rf = new BufferedReader(reader); rf.lines().forEach(line -> do_something(line));` and all this arguing goes away (to be replaced by arguing over whether a functional programming style is truly appropriate for Java and whether it improves readability or not and so on... though the ability of streams to be internally concurrent is pretty nice)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T20:27:28.657",
"Id": "76824",
"Score": "0",
"body": "@Phoshi: Oh, I see your point now. It could be `Iterable` but people at Apache didn't choose that. I think it would be easy to misunderstood and could cause some headache when one wants to use it in two foreach loops. So, it could be but I'm not sure that I would like that or not."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:28:26.597",
"Id": "44142",
"ParentId": "44135",
"Score": "21"
}
},
{
"body": "<p>Instead of wrapping the reader in an iterator, you could also wrap it in an <code>Iterable</code> that then returns the iterator.</p>\n\n<p>It would allow you to write the following</p>\n\n<pre><code>for (String line: linesOf(reader)) {\n // ...\n}\n</code></pre>\n\n<p>which makes very clean code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T20:36:49.180",
"Id": "44193",
"ParentId": "44135",
"Score": "13"
}
},
{
"body": "<p>In my opinion, <code>demoA()</code> is fine just as it is.</p>\n\n<p>Assignment as a side effect within a test is normally frowned upon, but this usage is an excellent example of why the language feature exists. It's compact, non-repetitive, idiomatic, and efficient. Use it, and don't feel guilty about it!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T23:47:57.067",
"Id": "44210",
"ParentId": "44135",
"Score": "5"
}
},
{
"body": "<p>Please realize that</p>\n\n<pre><code>if (cond(var = expr))\n</code></pre>\n\n<p>can usually be rewritten as</p>\n\n<pre><code>var = expr;\nif (cond(var)) ...\n</code></pre>\n\n<p>and</p>\n\n<pre><code>while (cond(var = expr))\n</code></pre>\n\n<p>can <em>always</em> be rewritten as</p>\n\n<pre><code>for (var = expr; cond(var); var = expr)\n</code></pre>\n\n<p>without even affecting the meaning of <code>break;</code> or <code>continue;</code> in the loop.</p>\n\n<p>So there is quite rarely a definite need for cramming assignments into conditionals' conditions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T09:50:35.850",
"Id": "44331",
"ParentId": "44135",
"Score": "2"
}
},
{
"body": "<p>You can probably do something like this as well:</p>\n\n<pre><code>Files.lines(path)\n</code></pre>\n\n<p>It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list and write to the output file.</p>\n\n<p>This answer gives you a functional programming approach. Most part of the method is self-explanatory.</p>\n\n<pre><code>Files.lines(Paths.get(path)).map(--Your business logic--);\n</code></pre>\n\n<p>There are various functions available in the steam API which can make your processing easy.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-29T05:11:56.817",
"Id": "193182",
"ParentId": "44135",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44137",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T09:24:30.523",
"Id": "44135",
"Score": "54",
"Tags": [
"java",
"stream"
],
"Title": "Is it OK to use while ((line = r.readLine()) != null) construct?"
} | 44135 |
<p>I suppose this is a two-part question. The first part is just a simple implementation of a Binary Tree (<code>BTree</code>), with pre-order, post-order, and in-order searches implemented by default. The second is the <code>AmorphousBTreeCreator</code>(amorphous because the trees sit in a sort of limbo until they are assembled into their final form). The advantage to this is the ability to add nodes (sub-trees) in any order, and then create a Binary Tree out of all those sub-trees. I have a few concerns with each, so any feedback would be much appreciated.</p>
<p>Part 1:</p>
<pre><code>class BTree<T>
{
private Node<T> head;
public BTree(T head)
{
this.head = new Node<T>(head);
}
public BTree(Node<T> head)
{
this.head = head;
}
public void addLR(T headE, T leftE, T rightE)
{
Node<T> h = head.get(headE);
h.setLeftChild(new Node<T>(leftE));
h.setRightChild(new Node<T>(rightE));
}
public void addL(T headE, T leftE)
{
Node<T> h = head.get(headE);
h.setLeftChild(new Node<T>(leftE));
}
public void addR(T headE, T rightE)
{
Node<T> h = head.get(headE);
h.setRightChild(new Node<T>(rightE));
}
public Node<T> get(T headE)
{
return head.get(headE);
}
public void prettyPrintTree()
{
//BTreePrinter.printNode(head);
}
public void printPreOrder()
{
head.printPreOrder();
}
public void printPostOrder()
{
head.printPostOrder();
}
public void printInOrder()
{
head.printInOrder();
}
}
class Node<T>
{
private Node<T> rightChild;
private Node<T> leftChild;
T self;
public Node(T self)
{
this.self = self;
}
public Node<T> get(T search)
{
if (self.equals(search))
return this;
if (rightChild == null && leftChild == null)
return null;
if (rightChild != null && leftChild == null)
return rightChild.get(search);
if (leftChild != null && rightChild == null)
return leftChild.get(search);
Node<T> rf = rightChild.get(search);
return (rf != null) ? rf : leftChild.get(search);
}
public Node<T> getRightChild()
{
return rightChild;
}
public void setRightChild(Node<T> rightChild)
{
this.rightChild = rightChild;
}
public Node<T> getLeftChild()
{
return leftChild;
}
public void setLeftChild(Node<T> leftChild)
{
this.leftChild = leftChild;
}
public void printPreOrder()
{
System.out.print(self + " ");
if (leftChild != null)
leftChild.printPreOrder();
if (rightChild != null)
rightChild.printPreOrder();
}
public void printPostOrder()
{
if (leftChild != null)
leftChild.printPostOrder();
if (rightChild != null)
rightChild.printPostOrder();
System.out.print(self + " ");
}
public void printInOrder()
{
if (leftChild != null)
leftChild.printInOrder();
System.out.print(self + " ");
if (rightChild != null)
rightChild.printInOrder();
}
public String toString()
{
return self + "";
}
}
</code></pre>
<p>As far as this is concerned, is it a bad idea to use the data stored in each node as a key (as I have done)? Obviously I can't have duplicate values, but is there any other way to do this whilst preserving the ability to link together trees (as is seen below)?</p>
<p>Part 2:</p>
<pre><code>class AmorphousBTreeCreator<T>
{
ArrayList<Node<T>> unassignedTrees = new ArrayList<Node<T>>();
boolean fNode = true;
private Node<T> head;
public void addLR(T headE, T leftE, T rightE) //when a node is added, it automatically attempts to connect it to the head.
{
if (fNode)
{
head = new Node<T>(headE);
fNode = false;
}
Node<T> h = head.get(headE);
if (h == null)
{
h = new Node<T>(headE);
unassignedTrees.add(h);
}
h.setLeftChild(new Node<T>(leftE));
h.setRightChild(new Node<T>(rightE));
}
public void addL(T headE, T leftE)
{
if (fNode)
{
head = new Node<T>(headE);
fNode = false;
}
Node<T> h = head.get(headE);
if (h == null)
{
h = new Node<T>(headE);
unassignedTrees.add(h);
}
h.setLeftChild(new Node<T>(leftE));
}
public void addR(T headE, T rightE)
{
if (fNode)
{
head = new Node<T>(headE);
fNode = false;
}
Node<T> h = head.get(headE);
if (h == null)
{
h = new Node<T>(headE);
unassignedTrees.add(h);
}
h.setRightChild(new Node<T>(rightE));
}
public BTree<T> createTree()
{
int x = unassignedTrees.size();
for (int i = 0; i < x && unassignedTrees.size() > 0; i++)
{
for (int j = 0; j < unassignedTrees.size(); j++)
{
Node<T> n = unassignedTrees.get(j);
Node<T> link = head.get(n.self);
if (link != null) // if n is a descendant of head
{
link.setLeftChild(n.getLeftChild());
link.setRightChild(n.getRightChild());
unassignedTrees.remove(n);
}
link = n.get(head.self);
if (link != null) // if head is descendant of n
{
link.setLeftChild(head.getLeftChild());
link.setRightChild(head.getRightChild());
head = n;
unassignedTrees.remove(n);
}
}
}
return new BTree<T>(head);
}
}
</code></pre>
<p>For this, is my method to create a Binary Tree in <code>AmorphousBTreeCreator</code> poorly implemented? It seems that the worst case runtime would be <code>O(n^2)</code>, where n is the length of <code>unassignedTrees</code>, and worst case being if no stored sub-trees share any nodes with the head. I'm not sure if this is unavoidable, or just bad code. </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:10:26.783",
"Id": "76462",
"Score": "0",
"body": "What is the purpose of BTree? This is not a heap, search is O(N), so it not better than a list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:15:25.163",
"Id": "76465",
"Score": "0",
"body": "@abra While each `Node<T>` is in fact a tree, `BTree` wraps `Node<T>` to provide some ease of use functions (i.e. setting a child by passing in the head vs. using get, then set on a node)."
}
] | [
{
"body": "<p>Review for <code>Node</code> and <code>BTree</code> classes. Stay tuned for more.</p>\n\n<p>I know that this is a religious question, but Java people really like OTBS.</p>\n\n<pre><code>class BTree<T>\n{\n private Node<T> head;\n\n public BTree(T head)\n {\n this.head = new Node<T>(head);\n }\n\n public BTree(Node<T> head)\n {\n this.head = head;\n }\n</code></pre>\n\n<p>Why is it called add? It sets children, not adds.</p>\n\n<pre><code> public void addLR(T headE, T leftE, T rightE)\n {\n Node<T> h = head.get(headE);\n h.setLeftChild(new Node<T>(leftE));\n h.setRightChild(new Node<T>(rightE));\n }\n\n public void addL(T headE, T leftE)\n {\n Node<T> h = head.get(headE);\n h.setLeftChild(new Node<T>(leftE));\n }\n\n public void addR(T headE, T rightE)\n {\n Node<T> h = head.get(headE);\n h.setRightChild(new Node<T>(rightE));\n }\n</code></pre>\n\n<p>This is unsafe. Your tree can be corrupted by calls to this Node. Consider making Node class immutable.</p>\n\n<pre><code> public Node<T> get(T headE)\n {\n return head.get(headE);\n }\n</code></pre>\n\n<p>You don't really need this method, do you?</p>\n\n<pre><code> public void prettyPrintTree()\n {\n //BTreePrinter.printNode(head);\n }\n\n public void printPreOrder()\n {\n head.printPreOrder();\n }\n\n public void printPostOrder()\n {\n head.printPostOrder();\n }\n\n public void printInOrder()\n {\n head.printInOrder();\n }\n}\n\nclass Node<T>\n{\n private Node<T> rightChild;\n private Node<T> leftChild;\n</code></pre>\n\n<p>This is not exactly self per se... Value maybe?</p>\n\n<pre><code> T self;\n\n public Node(T self)\n {\n this.self = self;\n }\n</code></pre>\n\n<p>A bad name for an argument, but an okay name for this very method.</p>\n\n<pre><code> public Node<T> get(T search)\n {\n if (self.equals(search))\n return this;\n\n if (rightChild == null && leftChild == null)\n return null;\n\n if (rightChild != null && leftChild == null)\n return rightChild.get(search);\n</code></pre>\n\n<p>At this point leftChild is always null.</p>\n\n<pre><code> if (leftChild != null && rightChild == null)\n return leftChild.get(search);\n</code></pre>\n\n<p>Consider this piece of code.</p>\n\n<pre><code>Node<T> result = null;\nif (leftChild != null) {\n result = leftChild.get(search);\n}\nif (result == null && rightChild != null) {\n result = rightChild.get(search);\n}\nreturn result;\n</code></pre>\n\n<p>Why do you go right first? It is conventional to traverse left (smaller) child first.</p>\n\n<pre><code> Node<T> rf = rightChild.get(search);\n\n return (rf != null) ? rf : leftChild.get(search);\n }\n</code></pre>\n\n<p>ditto mutability</p>\n\n<pre><code> public Node<T> getRightChild()\n {\n return rightChild;\n }\n\n public void setRightChild(Node<T> rightChild)\n {\n this.rightChild = rightChild;\n }\n\n public Node<T> getLeftChild()\n {\n return leftChild;\n }\n\n public void setLeftChild(Node<T> leftChild)\n {\n this.leftChild = leftChild;\n }\n\n public void printPreOrder()\n {\n System.out.print(self + \" \");\n if (leftChild != null)\n leftChild.printPreOrder();\n if (rightChild != null)\n rightChild.printPreOrder();\n }\n\n public void printPostOrder()\n {\n\n if (leftChild != null)\n leftChild.printPostOrder();\n if (rightChild != null)\n rightChild.printPostOrder();\n System.out.print(self + \" \");\n }\n\n public void printInOrder()\n {\n\n if (leftChild != null)\n leftChild.printInOrder();\n System.out.print(self + \" \");\n if (rightChild != null)\n rightChild.printInOrder();\n }\n\n public String toString()\n {\n</code></pre>\n\n<p>Bad practice. Use self.toString();</p>\n\n<pre><code> return self + \"\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T20:17:58.887",
"Id": "76574",
"Score": "0",
"body": "While I definitely agree with some of these, this answer doesn't really address any of my specific questions (or `AmorphousBTreeCreator`, obviously)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:31:36.627",
"Id": "44153",
"ParentId": "44139",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:41:07.003",
"Id": "44139",
"Score": "10",
"Tags": [
"java",
"optimization",
"tree"
],
"Title": "Binary Tree/ Amorphous Binary Tree Creator"
} | 44139 |
<p>I've made a function that takes an array of amounts owed by each user_id and works out the best way to square everyone up. The input array would look something like this, but may consist of 1 or more "users" who all owe (or are owed) money between each other:</p>
<pre><code>//the owings should sum to 0.
$owings = array(
1 => -1.72, //user 1 owes -1.72
2 => -5.78,
3 => 7.5,
);
</code></pre>
<p>And here is my function:</p>
<pre><code>/**
* Calculate the most efficient way to settle up a group of payments
*
* @param array $owings
*/
function settleUp($owings){
$reimbursments = array();
$payment = 0.11; $i = 1;
while ( $payment > 0.1 || $payment < -0.1 ){
$min = 0;
$max = 0;
foreach ($owings as $id => $owing){
if ($owing < $min) {
$min = $owing;
$min_id = $id;
}
if ($owing > $max) {
$max = $owing;
$max_id = $id;
}
}
$payment = -$min > $max ? -$max : $min;
if ($payment !== 0) {
$reimbursments[] = array(
'from' => $max_id,
'to' => $min_id,
'payment' => -$payment,
);
$owings[$max_id] += $payment;
$owings[$min_id] -= $payment;
}
$i++;
}
return $reimbursments;
}
</code></pre>
<p>The result looks like this:</p>
<pre><code>//print_r(settleUp($owings));
Array
(
[0] => Array
(
[from] => 3
[to] => 2
[payment] => 5.78
)
[1] => Array
(
[from] => 3
[to] => 1
[payment] => 1.72
)
)
</code></pre>
<p>Currently I use a while loop that iterates until the net balance owed is close to 0. Is there a better way of doing this? Perhaps using a recursive function?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:00:48.520",
"Id": "76449",
"Score": "0",
"body": "When you say the best way do you mean the least number of payments?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:06:50.427",
"Id": "76452",
"Score": "0",
"body": "Yes, the most efficient way for a group of people to all square up. E.g If Tim owes Sue £20 and Sue owes Tim £5 it would be better for Tim just to pay Sue £15 than for them both to pay each other the amount they owe. This is a simple example but gets more complicated with more people."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:35:07.287",
"Id": "76456",
"Score": "0",
"body": "I wasn't sure if you wanted to try all the possible combinations and see which results in the minimum number of payments or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T08:58:04.230",
"Id": "76668",
"Score": "0",
"body": "I'm pretty sure my method should always give the minimum number of payments but I wanted to verify this and see if there was a more efficient or elegant way of doing it. You suggestions are helpful though."
}
] | [
{
"body": "<p>Well if you want to split hairs, you could do a couple of minor changes (commented below)</p>\n\n<p>Honestly, I can't see any advantage in making it recursive, it works fine as it is</p>\n\n<pre><code>function settleUp($owings){\n $reimbursments = array();\n\n// $i is never used\n // $payment = 0.11; $i = 1;\n\n// by using a do/while loop you don't need to assign $payment to a random value to being the loop\n do {\n $min = 0;\n $max = 0;\n foreach ($owings as $id => $owing){\n if ($owing < $min) {\n $min = $owing;\n $min_id = $id;\n }\n if ($owing > $max) {\n $max = $owing;\n $max_id = $id;\n }\n }\n $payment = -$min > $max ? -$max : $min;\n\n if ($payment !== 0) {\n $reimbursments[] = array(\n 'from' => $max_id,\n 'to' => $min_id,\n 'payment' => -$payment,\n );\n\n $owings[$max_id] += $payment;\n $owings[$min_id] -= $payment;\n }\n // $i++;\n } while ( $payment > 0.1 || $payment < -0.1 );\n\n return $reimbursments;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:54:51.173",
"Id": "44143",
"ParentId": "44140",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44143",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:52:23.103",
"Id": "44140",
"Score": "3",
"Tags": [
"php"
],
"Title": "Can this PHP code to settle up payments be improved?"
} | 44140 |
<p>I have a program that gets 5 random dice throws from <a href="http://random.org/" rel="nofollow">random.org</a> over and over. In order to avoid doing <code>getaddrinfo()</code> over and over with the exact same data, I moved some of the code to an initialization function (and an unused finalization function).</p>
<p>My issues are:</p>
<ul>
<li>is this a bad idea?</li>
<li>can bad things happen to the program in some situations?</li>
<li>am I doing the socket thing correctly?</li>
</ul>
<p>Any other pointers, suggestions, criticisms are very welcome.</p>
<pre><code>#include <ctype.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
struct Data {
char datetime[20];
int die[5];
};
struct ConnData {
char cmd[200];
size_t cmdlen;
struct addrinfo *p;
int csock;
};
int initdata(struct ConnData *cd, const char *url);
int fetchpage(char *dst, size_t dstlen, struct ConnData *cd);
int killdata(struct ConnData *cd);
int process(struct Data *data, const char *html);
int save(const struct Data *data);
int gotenough(void);
int initdata(struct ConnData *cd, const char *url) {
struct addrinfo hints[1];
struct addrinfo *servinfo;
char host[100];
char resource[100];
char *phost, *presource;
const char *ptr;
int rv;
strcpy(host, "");
strcpy(resource, "");
memset(hints, 0, sizeof hints);
servinfo = NULL;
cd->p = NULL;
phost = host;
presource = resource;
ptr = url + 7; // skip over "http://"
while (*ptr != '/') *phost++ = *ptr++;
*phost = 0;
while (*ptr) *presource++ = *ptr++;
*presource = 0;
cd->cmdlen = (size_t)sprintf(cd->cmd, "GET %s HTTP/1.0\r\n\r\n", resource);
hints->ai_family = AF_UNSPEC;
hints->ai_socktype = SOCK_STREAM;
rv = getaddrinfo(host, "80", hints, &servinfo);
if (rv) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for (cd->p = servinfo; cd->p; cd->p = cd->p->ai_next) {
cd->csock = socket(cd->p->ai_family, cd->p->ai_socktype,
cd->p->ai_protocol);
if (cd->csock == -1) continue; // try next address
rv = connect(cd->csock, cd->p->ai_addr, cd->p->ai_addrlen);
close(cd->csock);
if (rv < 0) continue; // try next address
break; // successful connection
}
if (!cd->p) {
fprintf(stderr, "Unable to connect to HTTP server\n");
return 2;
}
freeaddrinfo(servinfo);
return 0;
}
int killdata(struct ConnData *cd) {
/* nothing to do */
(void)cd;
return 0;
}
int fetchpage(char *dst, size_t dstlen, struct ConnData *cd) {
ssize_t nbuff = 1;
size_t used = 0;
cd->csock = socket(cd->p->ai_family, cd->p->ai_socktype,
cd->p->ai_protocol);
connect(cd->csock, cd->p->ai_addr, cd->p->ai_addrlen);
send(cd->csock, cd->cmd, cd->cmdlen, 0);
do {
nbuff = recv(cd->csock, dst + used, dstlen - used - 1, 0);
if (nbuff < 0) {
fprintf(stderr, "error obtaining data\n");
return 3;
}
used += (size_t)nbuff;
if (used + 1 == dstlen) break; /* ignore stuff that doesn't fit */
} while (nbuff > 0);
dst[used] = 0;
close(cd->csock);
return 0;
}
int process(struct Data *data, const char *html) {
char *ptr = NULL;
ptr = strstr(html, "<p>You rolled 5 dice:</p>");
if (!ptr) return 1;
for (int k = 0; k < 5; k++) {
ptr = strstr(ptr, ".png\" alt=\"");
if (!ptr) return k + 2;
ptr += 11;
data->die[k] = atoi(ptr);
}
ptr = strstr(ptr, "<p>Timestamp: ");
if (!ptr) return 7;
strncpy(data->datetime, ptr + 14, 19);
data->datetime[19] = 0;
return 0;
}
int save(const struct Data *data) {
printf("%s:", data->datetime);
for (int k = 0; k < 5; k++) printf(" %d", data->die[k]);
printf("\n");
return 0;
}
int gotenough(void) {
static int n = 0;
n += 1;
return (n == 10);
}
int main(void) {
unsigned afewseconds = 3;
char html[100000];
char url[] = "http://www.random.org/dice/?num=5";
struct Data data[1] = {0};
struct ConnData cd[1] = {0};
if (initdata(cd, url)) goto LBL_INIT;
while (1) {
if (fetchpage(html, sizeof html, cd)) goto LBL_FETCH;
if (process(data, html)) goto LBL_PROCESS;
if (save(data)) goto LBL_SAVE;
if (gotenough()) break;
sleep(afewseconds);
}
if (killdata(cd)) goto LBL_KILL;
goto LBL_FINISH;
LBL_KILL:
fprintf(stderr, "Killing error (never happens)\n");
goto LBL_FINISH;
LBL_SAVE:
fprintf(stderr, "Saving error.\n");
goto LBL_FINISH;
LBL_PROCESS:
fprintf(stderr, "Processing error.\n");
goto LBL_FINISH;
LBL_FETCH:
fprintf(stderr, "Fetching page error.\n");
goto LBL_FINISH;
LBL_INIT:
fprintf(stderr, "Initializing data.\n");
goto LBL_FINISH;
LBL_FINISH:
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:59:30.830",
"Id": "76447",
"Score": "0",
"body": "If what you want is to get random numbers, there should be an easiest way ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:00:36.340",
"Id": "76448",
"Score": "0",
"body": "LOL -- that is just a working example of the real thing."
}
] | [
{
"body": "<h1>Things you could improve:</h1>\n\n<h3>Dependencies:</h3>\n\n<ul>\n<li><p>You are <strong><em>way</em></strong> overdoing this problem. By a lot. You can generate pseudo-random on your computer just fine. There is no reason to create a dependency on the internet for that. What if you don't have access to the internet? Right now your program fails to function, because of that <em>huge</em> and <em>unnecessary</em> dependency.</p></li>\n<li><p>If you absolutely <strong>must</strong> use the internet, use <a href=\"http://curl.haxx.se/libcurl/\" rel=\"nofollow noreferrer\"><code>libcurl</code></a> instead of your own DIY way of connecting to the internet. And make sure to support \"offline-mode\".</p>\n\n<blockquote>\n <p><code>libcurl</code> is a free and easy-to-use client-side URL transfer library,\n supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS,\n LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet\n and TFTP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP\n uploading, HTTP form based upload, proxies, cookies, user+password\n authentication (Basic, Digest, NTLM, Negotiate, Kerberos), file\n transfer resume, http proxy tunneling and more!</p>\n \n <p><code>libcurl</code> is highly portable, it builds and works identically on\n numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD,\n Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga,\n OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare,\n DOS and more...</p>\n</blockquote></li>\n</ul>\n\n<h3>Syntax/Styling:</h3>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/q/46586/1937270\"><strong>Never</strong> use <code>goto</code>.</a> </p>\n\n<p><img src=\"https://i.stack.imgur.com/kMDAj.png\" alt=\"Neal Stephenson thinks it's cute to name his labels 'dengo'\"></p>\n\n<p>Yes, there are some rare situations where you may find it necessary to use it. This is not one of them.</p>\n\n<blockquote>\n<pre><code> if (initdata(cd, url)) goto LBL_INIT;\n while (1) {\n if (fetchpage(html, sizeof html, cd)) goto LBL_FETCH;\n if (process(data, html)) goto LBL_PROCESS;\n if (save(data)) goto LBL_SAVE;\n if (gotenough()) break;\n sleep(afewseconds);\n }\n if (killdata(cd)) goto LBL_KILL;\n goto LBL_FINISH;\n\nLBL_KILL:\n fprintf(stderr, \"Killing error (never happens)\\n\");\n goto LBL_FINISH;\n\nLBL_SAVE:\n fprintf(stderr, \"Saving error.\\n\");\n goto LBL_FINISH;\n\nLBL_PROCESS:\n fprintf(stderr, \"Processing error.\\n\");\n goto LBL_FINISH;\n\nLBL_FETCH:\n fprintf(stderr, \"Fetching page error.\\n\");\n goto LBL_FINISH;\n\nLBL_INIT:\n fprintf(stderr, \"Initializing data.\\n\");\n goto LBL_FINISH;\n\nLBL_FINISH:\n return 0;\n</code></pre>\n</blockquote>\n\n<p>All you are doing is printing a simple unique error message for every <code>goto</code> label. And then you go to <code>LBL_FINISH</code>, where you indicate a successful return whether you have an error or not. Get rid of the <code>goto</code>s completely, and return <strong>unique</strong> error indicators.</p></li>\n<li><p><code>typedef</code> your <code>struct</code>s.</p>\n\n<blockquote>\n<pre><code>struct Data {\n char datetime[20];\n int die[5];\n};\n</code></pre>\n</blockquote>\n\n<p>The <code>typedef</code> means you no longer have to write <code>struct</code> all over the place. That not only saves some space, it also can make the code cleaner since it provides a bit more abstraction.</p>\n\n<pre><code>typedef struct\n{\n char datetime[20];\n int die[5];\n} Data;\n</code></pre></li>\n<li><p>Use parenthesis with <code>sizeof</code></p>\n\n<blockquote>\n<pre><code>sizeof hints\n</code></pre>\n</blockquote>\n\n<pre><code>sizeof(hints)\n</code></pre></li>\n<li><p>This isn't a standard way to do a counter.</p>\n\n<blockquote>\n<pre><code>int gotenough(void) {\n static int n = 0;\n n += 1;\n return (n == 10);\n}\n</code></pre>\n</blockquote></li>\n</ul>\n\n<h3>Memory/Data Handling:</h3>\n\n<ul>\n<li><p>Is your method <code>killdata()</code> trying to erase your <code>struct</code>?</p>\n\n<blockquote>\n<pre><code>int killdata(struct ConnData *cd) {\n /* nothing to do */\n (void)cd;\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>Throwing your data into a <code>void</code> container doesn't \"kill\" it. You need to go through each of the <code>struct</code> members and set them to <code>NULL</code>. </p></li>\n</ul>\n\n<h1>Final Code:</h1>\n\n<p>I've re-written your code completely into a more portable program, that accomplishes the basic functionality that your program does. As you can see from the length of my program to your program, this isn't a very hard task to accomplish without using the internet.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void)\n{\n srand((unsigned int) time(NULL));\n for (int i = 0; i < 100; i++)\n {\n printf(\"%d\\n\", (rand() % 6) + 1);\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:18:56.580",
"Id": "76474",
"Score": "0",
"body": "hmmm .. my issue is not with generation of (pseudo)random numbers, thank you anyway. My issue is with connecting to the internet repeatedly over and over again without wasting resources (the random dice is an example program that connects to the internet repeatedly over and over again)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:22:25.260",
"Id": "76475",
"Score": "0",
"body": "@pmg That is why I included the little thing about `libcurl` in there. It will reduce down your code a lot, and make things a bit more simple and easy to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:24:36.927",
"Id": "76476",
"Score": "1",
"body": "\"never use `gotos`\": ok; \"`typedef` your structs\": no thanks, writing an extra `struct` is no pain and I fail to see what you gain for including abstraction in a program in this way; \"use parenthesis with `sizeof`\": no thanks, I'd use parenthesis if I applied `sizeof` to a type (and even then the parenthesis would belong to the type, not to the operator). Thank you for your review. I appreciate it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:01:04.707",
"Id": "44156",
"ParentId": "44145",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:57:17.707",
"Id": "44145",
"Score": "6",
"Tags": [
"c",
"networking",
"socket",
"http"
],
"Title": "Checking web-page repeatedly"
} | 44145 |
<p>I am new to threading and I am a junior developer, so I guess there are many mistakes. My scenario is this:</p>
<ul>
<li>look into the database</li>
<li>if there are data which should be sent
<ul>
<li>add the data to the queue</li>
</ul></li>
<li>if queue is not empty
<ul>
<li>send the next message and remove it from the queue</li>
<li>sleep 10 seconds</li>
</ul></li>
<li>if a message from another thread arrived
<ul>
<li>stop waiting and go to next message in queue</li>
</ul></li>
<li>if no message from another thread arrived
<ul>
<li>go back to the first step, but do this only 2 times</li>
<li>if a message still hasn't arrived from another thread
<ul>
<li>pass to the next message until queue is empty</li>
</ul></li>
</ul></li>
<li>return to the first step</li>
</ul>
<p>I am trying to do this like this:</p>
<pre><code>private Thread ReceiveThread;
private Thread SendThread;
internal static Thread ServiceThread;
</code></pre>
<p>These 3 threads:</p>
<pre><code>ReceiveThread = new Thread(ReceiveTask);
ReceiveThread.Start();
ServiceThread = new Thread(SerAutoThread.SendServiceMsg);
ServiceThread.Start();
SendThread = new Thread(SendTask);
SendThread.Start();
</code></pre>
<p></p>
<pre><code>class SerAutoThread
{
internal static object[] NextService;
public static readonly object _locker = new object();
internal static Queue<object[]> Services;
internal static int sendingTime = 0;
private static DatabaseFirebird DB;
internal static void SendServiceMsg()
{
DB = new DatabaseFirebird();
DB.Open(ConnectionStr);
Services = new Queue<object[]>();
while (true)
{
if (Services.Count != 0)
{
SetNextSerAndSend();
}
else
{
CheckAndSetServices();
}
}
}
private static void SetNextSerAndSend()
{
NextService = Services.Dequeue();
for (int j = 0; j < 4; j++)
{
if (sendingTime == TRANSMITTED)
{
//pass to next msg
sendingTime = 0;
j = NEXTMSG;
}
else if (sendingTime < 3)
{
sendingTime++;
Byte[] data = SetNextPckage();
DeviceManager.MessageSendQueue.PostItem(new SendMessage("UDPCmd",
NextService[(int)NextMsg.DeviceId].ToString(),
data, data.Length));
MyDebug.WriteLine("Sended...");
lock (_locker)
{
Monitor.Wait(_locker, TimeSpan.FromSeconds(10));
}
}
else
{
// pass to next msg
j = NEXTMSG;
}
}
}
}
</code></pre>
<p></p>
<pre><code>private void ReceiveTask()
{
ReceiveMessage receiveMsg;
while (true)
{
receiveMsg = Com.MessageReceiveQueue.GetItem(-1);
SerAutoThread.sendingTime = SerAutoThread.TRANSMITTED;
lock (SerAutoThread._locker)
{
Monitor.Pulse(SerAutoThread._locker);
}
}
}
</code></pre>
<p></p>
<pre><code> private void SendTask()
{
SendMessage msg;
while (true)
{
msg = MessageSendQueue.GetItem(-1);
String rtrn = PushData(msg);
}
}
</code></pre>
<p>Is this thread-safe or not? I'm not sure if something is wrong with the design or I'm doing something wrong elsewhere.</p>
<p>And this is not my entire code (for understanding). When I actually run the app, this works fine. Yesterday just ones my Database management system (Firebird) locked. Then I stopped my app, stopped Firebird server then started again and ran my app again. Now it is ok again. I am not using threads with deep understanding. So I am worried about thread safety.</p>
<p>Is it possible for the thread-locked Firebird?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-30T08:34:16.890",
"Id": "104984",
"Score": "0",
"body": "You may opt for tasks, instead of threads. To me your code look like a self rolled message bus on a db , you may consider msmq for the same purpose if possible."
}
] | [
{
"body": "<p>This looks pretty good to me. I am not that good at threads myself, so I won't comment on the thread safety, but these are a few things I noticed.</p>\n\n<p>This is fine as it is, but you might want to consider making this a ternary:</p>\n\n<pre><code>if (Services.Count != 0)\n{\n SetNextSerAndSend();\n}\nelse\n{\n CheckAndSetServices();\n}\n</code></pre>\n\n<p>Here it is in ternary form:</p>\n\n<pre><code>Services.Count == 0 ? CheckAndSetServices() : SetNextSerAndSend();\n</code></pre>\n\n<p>I'm not sure how this would affect the performance of your code, or whether it is important that the variable stay the same, but it is good to always keep your variables in as tight a scope as possible:</p>\n\n<pre><code>private void SendTask()\n{\n SendMessage msg;\n while (true)\n {\n msg = MessageSendQueue.GetItem(-1);\n String rtrn = PushData(msg);\n }\n}\n</code></pre>\n\n<p>This could possibly become:</p>\n\n<pre><code>private void SendTask()\n{\n while (true)\n {\n SendMessage msg = MessageSendQueue.GetItem(-1);\n String rtrn = PushData(msg);\n }\n}\n</code></pre>\n\n<p>The same principle can be applied to <code>ReceiveTask</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-14T02:07:22.570",
"Id": "151202",
"Score": "1",
"body": "What advantage is there for the ternary? It just makes the code harder to maintain, if any other statements needed to be in the \"then\" or \"else\" parts. Also, in `SendTask()`, you haven't really changed the scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-14T02:08:57.733",
"Id": "151203",
"Score": "0",
"body": "@Snowbody In my version of `SendTask()`, you cannot use `msg` outside the loop. The ternary can make it more difficult to maintain, but that brings up the question of why should we ever use them; I feel this is as good a place for a ternary as any other."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-14T01:53:32.940",
"Id": "84060",
"ParentId": "44146",
"Score": "2"
}
},
{
"body": "<p>You have a classic situation where multiple threads can access the database and two operations (a read and an update) are required to do the work.</p>\n\n<p>It is possible to make such schemes work, but it is hard work - you will need a transaction around the read/update operation and your code will possibly need to handle deadlock exceptions. Debugging and testing the deadlock code is difficult, as it will seldom happen.</p>\n\n<p>If only one application is involved, then I suggest you delegate database operations to a singleton thread-safe class. Synchronizing its methods will ensure that only one thread accesses the database at any time.</p>\n\n<p>If you need the database to do implement thread safety, consider setting the transaction isolation level to SERIALIZED. This should fix the problem at the expense of performance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-14T06:03:19.200",
"Id": "84067",
"ParentId": "44146",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:59:40.213",
"Id": "44146",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"thread-safety"
],
"Title": "Database threading design"
} | 44146 |
<p>The Rapheal script seems to be too long. Is there any option to make it shorter ?</p>
<p>I think <code>loop</code> can make this script smaller. Does anyone have good suggestions or advice?</p>
<p><a href="http://jsfiddle.net/sweetmaanu/Ta8mR/5/" rel="nofollow">http://jsfiddle.net/sweetmaanu/Ta8mR/5/</a></p>
<p>Here is the long script :</p>
<pre><code>var barTitle = { "font-size": 9};
var svgWidth = 480;
var svgHeight = 300;
var safety02 = new Raphael('safety02-mobile', 'svgWidth', 'svgHeight');
safety02.setViewBox(-30, 0, svgWidth, svgHeight, false); //false
safety02.setSize('100%', '100%');
// Create options object that specifies the rectangle
var safetyBar1_1 = { width:30, height:150, x:60,y:50};
var safetyBar1_2 = { width:30, height:130, x:90,y:70};
var safetyBar2_1 = { width:30, height:165, x:140, y:35};
var safetyBar2_2 = { width:30, height:100, x:170, y:100};
var safetyBar3_1 = { width:30, height:130, x:220,y:70};
var safetyBar3_2 = { width:30, height:65, x:250,y:135};
var safetyBar4_1 = { width:30, height:120, x:300, y:80};
var safetyBar4_2 = { width:30, height:100, x:330, y:100};
var rect1_1 = safety02.rect(safetyBar1_1.x, 200, safetyBar1_1.width, 0).attr({fill: '#F6A01A', stroke:'#000'});
var rect1_2 = safety02.rect(safetyBar1_2.x, 200, safetyBar1_2.width, 0).attr({fill: '#CCC', stroke:'#000'});
var rect2_1 = safety02.rect(safetyBar2_1.x, 200, safetyBar2_1.width, 0).attr({fill: '#F6A01A', stroke:'#000'});
var rect2_2 = safety02.rect(safetyBar2_2.x, 200, safetyBar2_2.width, 0).attr({fill: '#CCC', stroke:'#000'});
var rect3_1 = safety02.rect(safetyBar3_1.x, 200, safetyBar3_1.width, 0).attr({fill: '#F6A01A', stroke:'#000'});
var rect3_2 = safety02.rect(safetyBar3_2.x, 200, safetyBar3_2.width, 0).attr({fill: '#CCC', stroke:'#000'});
var rect4_1 = safety02.rect(safetyBar4_1.x, 200, safetyBar4_1.width, 0).attr({fill: '#F6A01A', stroke:'#000'});
var rect4_2 = safety02.rect(safetyBar4_2.x, 200, safetyBar4_2.width, 0).attr({fill: '#CCC', stroke:'#000'});
var p1title = safety02.text(0, 110, "Percentage (%)").rotate(-90);
var unicorn = safety02.path("M400 200 H40 V10").attr({stroke: "#000","stroke-width": 1});
var s1firstBar = safety02.text(90, 210, "Headache").attr(barTitle);
var p1thirdBar = safety02.text(250, 210, "Nausea").attr(barTitle);
var p1firstBar = safety02.text(165, 210, "Diarrhoea").attr(barTitle);
var p1thirdBar = safety02.text(330, 215, "Abdminal \n pain").attr(barTitle);
var anim1_1 = Raphael.animation({y:safetyBar1_1.y,height:safetyBar1_1.height}, 2000);
var anim1_2 = Raphael.animation({y:safetyBar1_2.y,height:safetyBar1_2.height}, 2000);
var anim2_1 = Raphael.animation({y:safetyBar2_1.y,height:safetyBar2_1.height}, 1000);
var anim2_2 = Raphael.animation({y:safetyBar2_2.y,height:safetyBar2_2.height}, 1000);
var anim3_1 = Raphael.animation({y:safetyBar3_1.y,height:safetyBar3_1.height}, 2000);
var anim3_2 = Raphael.animation({y:safetyBar3_2.y,height:safetyBar3_2.height}, 2000);
var anim4_1 = Raphael.animation({y:safetyBar4_1.y,height:safetyBar4_1.height}, 1000);
var anim4_2 = Raphael.animation({y:safetyBar4_2.y,height:safetyBar4_2.height}, 1000);
rect1_1.animate(anim1_1);
rect1_2.animate(anim1_2.delay(300));
rect2_1.animate(anim2_1);
rect2_2.animate(anim2_2.delay(300));
rect3_1.animate(anim3_1);
rect3_2.animate(anim3_2.delay(300));
rect4_1.animate(anim4_1);
rect4_2.animate(anim4_2.delay(300));
$('#viewFreqFirst-big').click(function(){
rect1_1.animate({y:80,height:120}, 1500);
rect1_2.animate({y:100,height:100}, 1500);
rect2_1.animate({y:105,height:95}, 1500);
rect2_2.animate({y:115,height:85}, 1500);
rect3_1.animate({y:140,height:60}, 1500);
rect3_2.animate({y:160,height:40}, 1500);
rect4_1.animate({y:120,height:80}, 1500);
rect4_2.animate({y:140,height:60}, 1500);
});
$('#viewFreqSecond-big').click(function(){
rect1_1.animate({y:safetyBar1_1.y,height:safetyBar1_1.height}, 1500);
rect1_2.animate({y:safetyBar1_2.y,height:safetyBar1_2.height}, 1500);
rect2_1.animate({y:safetyBar2_1.y,height:safetyBar2_1.height}, 1500);
rect2_2.animate({y:safetyBar2_2.y,height:safetyBar2_2.height}, 1500);
rect3_1.animate({y:safetyBar3_1.y,height:safetyBar3_1.height}, 1500);
rect3_2.animate({y:safetyBar3_2.y,height:safetyBar3_2.height}, 1500);
rect4_1.animate({y:safetyBar4_1.y,height:safetyBar4_1.height}, 1500);
rect4_2.animate({y:safetyBar4_2.y,height:safetyBar4_2.height}, 1500);
});
</code></pre>
| [] | [
{
"body": "<p>A naming scheme like <code>foo3_2</code> suggests that you want a two-dimensional array instead:</p>\n\n<pre><code>var safetyBar1_1 = { width:30, height:150, x:60,y:50};\nvar safetyBar1_2 = { width:30, height:130, x:90,y:70};\nvar safetyBar2_1 = { width:30, height:165, x:140, y:35};\nvar safetyBar2_2 = { width:30, height:100, x:170, y:100};\nvar safetyBar3_1 = { width:30, height:130, x:220,y:70};\nvar safetyBar3_2 = { width:30, height:65, x:250,y:135};\nvar safetyBar4_1 = { width:30, height:120, x:300, y:80};\nvar safetyBar4_2 = { width:30, height:100, x:330, y:100};\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>var safetyBars = [\n [ { width: 30, height: 150, x: 60, y: 50},\n { width: 30, height: 130, x: 90, y: 70}],\n [ { width: 30, height: 165, x: 140, y: 35},\n { width: 30, height: 100, x: 170, y: 100}],\n [ { width: 30, height: 130, x: 220, y: 70},\n { width: 30, height: 65, x: 250, y: 135}],\n [ { width: 30, height: 120, x: 300, y: 80},\n { width: 30, height: 100, x: 330, y: 100}]\n ];\n</code></pre>\n\n<p>(note also how the indentation of numbers was improved to increase readability. You do not have to like this indention style, I'm using it here because it is fairly compact).</p>\n\n<p>Once we add further information like <code>fill</code> and `stroke to these records, we can change other parts of your code to loops:</p>\n\n<pre><code>var rects = []\nfor (var i = 0; i < safetyBars.length; i++) {\n rects[i] = [];\n for (var j = 0; j < safetyBars[i].length; j++) {\n var bar = safetyBars[i][j];\n rects[i][j] = safety02.rect(bar.x, 200, bar.width, 0).\n attr({fill: bar.fill, stroke: bar.stroke});\n }\n}\n</code></pre>\n\n<p>This iteration pattern is so frequent here that I would abstract it:</p>\n\n<pre><code>function map2d(in, fn) {\n var out = []\n for (var i = 0; i < in.length; i++) {\n out[i] = [];\n for (var j = 0; j < in[i].length; j++) {\n out[i][j] = fn(in[i][j]);\n }\n }\n return out;\n}\n\nvar rects = map2d(safetyBars, function (bar) {\n return safety02.rect(bar.x, 200, bar.width, 0).\n attr({fill: bar.fill, stroke: bar.stroke});\n});\n</code></pre>\n\n<p>… and similar for all the other blocks of related code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:54:07.047",
"Id": "44151",
"ParentId": "44148",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:26:10.187",
"Id": "44148",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"raphael.js"
],
"Title": "How to shorten the JavaScript in Raphaël?"
} | 44148 |
<p>I get a <code>map</code> from <code>DB</code> called <code>doc1</code> and I also have the <code>arrayList</code> called <code>someWord</code>. I will find the subscription of <code>doc1</code> and <code>someWord</code> and store it in <code>doc2</code>. I will also add the intersecting words with zero index in <code>doc2</code>.</p>
<p>This code consumes too much time:</p>
<pre><code>public void setDocuments() {
// Neighbor contain the arrayList of Documents
neighbors.add(new Neighbor<Integer>("sky"));
neighbors.add(new Neighbor<Integer>("earth"));
Map<Long, String> docInfo;
// Document is a Map
Document<String> doc1 = new Document<String>();
Document<Integer> doc2;
Map<Integer, Long> sorted;
ArrayList<String> intersectionWords;
HashSet<String> different;
try {
docInfo = dbDocMeta.getDocInfo();
String family;
int index = 0;
for (Long id : docInfo.keySet()) {
family = docInfo.get(id).contains("sky") ? "sky" : "earth";
for (Neighbor<Integer> neighbor : neighbors) {
// check if the document in the Neighbour family
if (neighbor.getFamily().equalsIgnoreCase(family)) {
different = new HashSet<String>();
different.addAll(someWord);
doc1 = dbWords.getNeighbors(id);
doc2 = new Document<Integer>();
intersectionWords = new ArrayList<String>();
for (String word : doc1.getMap().keySet()) {
index = dbWords.getIndex(word);
if (selectedFeatures.contains(word)) {
doc2.add(index, doc1.getAttributes().get(word));
intersectionWords.add(word);
}
}
if (!doc2.getMap().isEmpty()) {
different.removeAll(intersectionWords);
Iterator<String> iterator = different.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
index = dbWords.getIndex(s);
doc2.add(index, 0);
}
sorted = new TreeMap<Integer, Long>(doc2.getAttributes());
doc2.setMap(sorted);
neighbor.addDocument(doc2);
break;
}
}
}
}
} catch (InterruptedException e) {
logger.error("InterruptedException msg : {} \n {}", e.getMessage(), e.getStackTrace());
} catch (ClassNotFoundException e) {
logger.error("ClassNotFoundException msg : {} \n {}", e.getMessage(), e.getStackTrace());
}
}
</code></pre>
<p>Neighbour variables are:</p>
<pre><code>private ArrayList<Document<T>> documents;
private int docCount;
private String family;
</code></pre>
<p>It also contains some setters and getters, and <code>dbDocMeta</code> contains the <code>ID</code> of all Documents.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:03:32.620",
"Id": "76460",
"Score": "0",
"body": "Could post all the code? What is Neighbor class? What is dbDocMeta?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T13:33:05.087",
"Id": "76471",
"Score": "0",
"body": "Contains how exacly? Is it a map of Lists or Sets? We can't know the complexity without all the code."
}
] | [
{
"body": "<p>You should declare variables in the smallest possible scope. E.g. instead of</p>\n\n<pre><code>String family;\nfor (...) {\n family = ...;\n ...\n}\n</code></pre>\n\n<p>we could do</p>\n\n<pre><code>for (...) {\n String family = ...;\n ...\n}\n</code></pre>\n\n<p>The same applies to <code>docInfo</code>, <code>doc1</code>, <code>doc2</code>, <code>sorted</code>, <code>intersectionWords</code>, <code>different</code>, and <code>index</code>.</p>\n\n<p>You have this snippet:</p>\n\n<pre><code>Iterator<String> iterator = different.iterator();\nwhile (iterator.hasNext()) {\n String s = iterator.next();\n ...\n}\n</code></pre>\n\n<p>which could be abbreviated to <code>for (String s : different) { ... }</code>.</p>\n\n<p>If we clean up these two points, we end up with this:</p>\n\n<pre><code>public void setDocunents() {\n // Neighbor contain the arrayList of Documents\n neighbors.add(new Neighbor<Integer>(\"sky\"));\n neighbors.add(new Neighbor<Integer>(\"earth\"));\n\n try {\n Map<Long, String> docInfo = dbDocMeta.getDocInfo();\n for (Long id : docInfo.keySet()) {\n String family = docInfo.get(id).contains(\"sky\") ? \"sky\" : \"earth\";\n for (Neighbor<Integer> neighbor : neighbors) {\n // check if the document in the Neighbour family\n if (neighbor.getFamily().equalsIgnoreCase(family)) {\n HashSet<String> different = new HashSet<String>();\n different.addAll(someWord);\n Document<String> doc1 = dbWords.getNeighbors(id);\n Document<Integer> doc2 = new Document<Integer>();\n ArrayList<String> intersectionWords = new ArrayList<String>();\n for (String word : doc1.getMap().keySet()) {\n int index = dbWords.getIndex(word);\n if (selectedFeatures.contains(word)) {\n doc2.add(index, doc1.getAttributes().get(word));\n intersectionWords.add(word);\n }\n }\n if (!doc2.getMap().isEmpty()) {\n different.removeAll(intersectionWords);\n for (String s : different) {\n int index = dbWords.getIndex(s);\n doc2.add(index, 0);\n }\n Map<Integer, Long> sorted = new TreeMap<Integer, Long>(doc2.getAttributes());\n doc2.setMap(sorted);\n neighbor.addDocument(doc2);\n break;\n }\n }\n }\n }\n } catch (InterruptedException e) {\n logger.error(\"InterruptedException msg : {} \\n {}\", e.getMessage(), e.getStackTrace());\n } catch (ClassNotFoundException e) {\n logger.error(\"ClassNotFoundException msg : {} \\n {}\", e.getMessage(), e.getStackTrace());\n }\n}\n</code></pre>\n\n<p>In a next step, we remove calculations from inner loops that don't have to be recalculated each time. E.g. <code>doc1 = dbWords.getNeighbors(id)</code> depends only on <code>id</code>, and probably does not have to be called for each <code>neighbor</code>. On the other hand, <code>different</code> is only needed inside a specific <code>if</code> branch.</p>\n\n<p>Furthermore, <code>doc2</code> will be discarded unless that branch is entered, so we will build it only in that case (assuming <code>doc2.getMap().isEmpty()</code> is equivalent to <code>intersectionWords.isEmpty()</code>.</p>\n\n<p>We can further remove unnecessary variables – their types just add clutter to the code.</p>\n\n<p>A bare <code>break</code> inside nested loops can be a bit confusing, so we'll use the labelled for: <code>break neighbors</code>.</p>\n\n<p>The <code>HashSet</code> constructor can directly take a collection, there is no need to separately call <code>addAll</code>.</p>\n\n<p>If the whole body of a loop us subject to an <code>if (cond)</code>, it is often easier to read when at the beginning of a loop, we <code>if (!cond) continue</code>.</p>\n\n<p>Unrelated implementation details like calculating the intersection of two sets should be factored out into helper functions.</p>\n\n<pre><code>public void setDocunents() {\n // Neighbor contain the arrayList of Documents\n neighbors.add(new Neighbor<Integer>(\"sky\"));\n neighbors.add(new Neighbor<Integer>(\"earth\"));\n\n try {\n Map<Long, String> docInfo = dbDocMeta.getDocInfo();\n for (Long id : docInfo.keySet()) {\n String family = docInfo.get(id).contains(\"sky\") ? \"sky\" : \"earth\";\n Document<String> doc1 = dbWords.getNeighbors(id);\n\n neighbors:\n for (Neighbor<Integer> neighbor : neighbors) {\n // check if the document in the Neighbour family\n if (!neighbor.getFamily().equalsIgnoreCase(family)) {\n continue neighbors;\n }\n\n Set<String> intersectionWords = intersection<String>(doc1.getMap().keySet(), selectedFeatures);\n if (intersectionWords.isEmpty()) {\n continue neighbors;\n }\n\n HashSet<String> different = new HashSet<String>(someWord);\n Document<Integer> doc2 = new Document<Integer>();\n for (String s : intersectionWords) {\n doc2.add(dbWords.getIndex(word), doc1.getAttributes().get(word));\n different.remove(s);\n }\n for (String s : different) {\n doc2.add(dbWords.getIndex(s), 0);\n }\n // due to the choice of a TreeMap, the elements are sorted\n doc2.setMap(new TreeMap<Integer, Long>(doc2.getAttributes()));\n neighbor.addDocument(doc2);\n\n break neighbors;\n }\n }\n } catch (InterruptedException e) {\n logger.error(\"InterruptedException msg : {} \\n {}\", e.getMessage(), e.getStackTrace());\n } catch (ClassNotFoundException e) {\n logger.error(\"ClassNotFoundException msg : {} \\n {}\", e.getMessage(), e.getStackTrace());\n }\n}\n\nprivate static <A> Set<A> intersection(final Set<A> xs, final Set<A> ys) {\n // make sure that xs is the smaller set\n if (ys.size() < xs.size()) {\n return intersection<A>(ys, xs);\n }\n\n final HashSet<A> result = new HashSet<>();\n for (A x : xs) {\n if (ys.contains(x)) {\n result.add(x)\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>This could be optimized further, e.g. when <code>doc2.add(…)</code> has no side effects except setting the underlying map, or if the composition of <code>someWord</code> is known.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:44:21.663",
"Id": "44160",
"ParentId": "44150",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "44160",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:47:54.777",
"Id": "44150",
"Score": "3",
"Tags": [
"java",
"optimization",
"iteration"
],
"Title": "Intersection of words"
} | 44150 |
<p>I created an <code>enum</code> for a class and in the constructor I inserted all the <code>enum</code> values into a set. I am wondering if there is a better way anyone can recommend. I feel like there should be, but have been unable to think of one or find one online. I wrote the code in C++ and am using the Boost libraries.</p>
<p>Here is the <code>enum</code>:</p>
<pre><code>class CreateAndUseIniFile {
std::set<CreateAndUseIniFile::iniFileValues> m_modules;
enum iniFileValues {
FIXED_VOLTAGE1,
FIXED_VOLTAGE2,
FIXED_VOLTAGE3,
FIXED_VOLTAGE4
}
}
</code></pre>
<p>and this is the constructor where I add the values</p>
<pre><code>CreateAndUseIniFile::CreateAndUseIniFile() {
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE1);
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE2);
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE3);
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE4);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T02:17:33.247",
"Id": "76633",
"Score": "0",
"body": "Like the fellow asking http://codereview.stackexchange.com/q/35208/32004 it sounds like you might be looking for [n3815](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3815.html) to become real."
}
] | [
{
"body": "<p>You can iterate over the <code>enum</code> and insert each one individually.</p>\n\n<pre><code>for ( int i = FIXED_VOLTAGE1; i != FIXED_VOLTAGE4; i++ )\n{\n m_modules.insert(CreateAndUseIniFile::static_cast<iniFileValues>(i));\n}\n</code></pre>\n\n<p><strong>Note</strong>: This will work with your specific case... don't do this if you have <code>enums</code> with set values that contain gaps between <code>enum</code> values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T16:45:32.187",
"Id": "76514",
"Score": "0",
"body": "Thanks, for some reason I thought I couldn't iterate though an enum"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T16:53:44.847",
"Id": "76515",
"Score": "0",
"body": "@Aaron No problem. `enums` are basically just fancy `ints`. They should only be iterated through during controlled situations like yours."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:48:30.120",
"Id": "44163",
"ParentId": "44158",
"Score": "6"
}
},
{
"body": "<p>As an alternative, you can use <a href=\"http://www.boost.org/doc/libs/1_39_0/libs/assign/doc/index.html\" rel=\"nofollow\" title=\"Boost Assignment Library\">Boost Assignment Library</a>.\nThen you will get something like this:</p>\n\n<pre><code>#include <boost/assign/list_of.hpp>\n#include <set>\nclass CreateAndUseIniFile {\npublic:\n enum iniFileValues {\n FIXED_VOLTAGE1,\n FIXED_VOLTAGE2,\n FIXED_VOLTAGE3,\n FIXED_VOLTAGE4\n };\n CreateAndUseIniFile() {\n m_modules =\n boost::assign::list_of\n (FIXED_VOLTAGE1)\n (FIXED_VOLTAGE2)\n (FIXED_VOLTAGE2)\n (FIXED_VOLTAGE3)\n (FIXED_VOLTAGE4);\n }\n std::set<CreateAndUseIniFile::iniFileValues> m_modules;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T22:45:59.953",
"Id": "44477",
"ParentId": "44158",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "44163",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:28:26.260",
"Id": "44158",
"Score": "7",
"Tags": [
"c++",
"enum",
"set"
],
"Title": "Is there a better way to insert an enum into a set without macros?"
} | 44158 |
<p>Description of my code:</p>
<p>I am trying to maximize the number of nodes that could be reachable in a graph. Please do not consider my main algorithm, I want it to be like that. The only parts that I need to be boosted are the way of using data structures and reachability. I don't want to change my main algorithm.</p>
<p>I am looking for boosting the performance of my program. Here is the source code of that. Is there any part that could perform faster? Any little speed up would be great because of this algorithm should be run on a graph with more than 1m nodes.</p>
<pre><code>public LinkedHashSet<Customer> retentionSeedFinder(int budget,
HashSet<Customer> churnerNodes, int delay,
DirectedSparseGraph<Customer, Transaction> network) {
LinkedHashSet<Customer> seedSet = new LinkedHashSet<Customer>();
numberofNodes = network.getVertexCount();
churnNet = new HashSet<Customer>();
HashSet<Customer> tmpchurnNet = new HashSet<Customer>();
HashSet<Customer> availableNodes;
// at timestep 0
churnNet.addAll(churnerNodes);
churnNet.addAll(getNeighbors(churnerNodes, network));
availableNodes = getReachableNodes(churnNet, network);
// at timestep 1
int timestep = 1;
tmpchurnNet = churnNet;
while (timestep <= delay) {
Collection<Customer> neighbors;
System.out.println("***********************At timestep:" + timestep
+ "*************************");
for (Customer churner : churnNet) {
neighbors = network.getNeighbors(churner);
for (Customer specificNeighbor : neighbors) {
tmpchurnNet.add(specificNeighbor);
}
}
churnNet = tmpchurnNet;
timestep++;
}
PriorityQueue<Customer> marginalGainHeap = new PriorityQueue<Customer>(
1, new Comparator<Customer>() {
public int compare(Customer c1, Customer c2) {
if (c1.getMarginalGain() < c2.getMarginalGain())
return 1;
if (c1.getMarginalGain() > c2.getMarginalGain())
return -1;
if (c1.getMarginalGain() == c2.getMarginalGain()) {
if (c1.getRevenue() < c2.getRevenue())
return 1;
if (c1.getRevenue() > c2.getRevenue())
return -1;
}
return 0;
}
});
// set of all remains available nodes
availableNodes.removeAll(churnNet);
for (Customer avail : availableNodes) {
avail.setMarginalGain(0);
marginalGainHeap.add(avail);
}
int seedNum = 1;
while (seedSet.size() < budget) {
Collection<Customer> tmpAvailNodes = new HashSet<Customer>();
tmpAvailNodes.addAll(availableNodes);
for (Customer remainingNode : tmpAvailNodes) {
remainingNode.setMarginalGain(calculateMarginalGain(
remainingNode, seedSet, network, availableNodes,
churnNet));
// heapify bar asase mg
marginalGainHeap.remove(remainingNode);
marginalGainHeap.add(remainingNode);
}
availableNodes.remove(marginalGainHeap.peek());
System.out.println(marginalGainHeap.peek().getName());
seedSet.add(marginalGainHeap.poll());
System.out
.println("Target seed subscriber for short-term campaign has been found:"
+ seedNum++);
}
return seedSet;
}
private double calculateMarginalGain(Customer remainingNode,
HashSet<Customer> seedSet,
DirectedSparseGraph<Customer, Transaction> net,
HashSet<Customer> availableNodes, HashSet<Customer> churnNetwork) {
// Marginal gain for short-term campaign
HashSet<Customer> tmp = new HashSet<Customer>(); // seedset U
// {remainingNode}
tmp.addAll(seedSet);
tmp.add(remainingNode);
HashSet<Customer> tmpAvailableNodes = new HashSet<Customer>();
tmpAvailableNodes.addAll(availableNodes);
// sigma function for calculating the expected number of influenced
// customers- seedSettmp=seedset U {u}
tmpAvailableNodes.removeAll(churnNetwork);
HashSet<Customer> influencedNet = getNeighbors(tmp, net);
tmpAvailableNodes.retainAll(influencedNet);
return tmpAvailableNodes.size();
}
private HashSet<Customer> getNeighbors(HashSet<Customer> churnNetwork,
DirectedSparseGraph<Customer, Transaction> net) {
HashSet<Customer> churnNeighbors = new HashSet<Customer>();
churnNeighbors.addAll(churnNetwork);
Collection<Customer> neighbors = new HashSet<Customer>();
for (Customer node : churnNetwork) {
neighbors = net.getNeighbors(node);
for (Customer neighbor : neighbors) {
churnNeighbors.add(neighbor);
}
}
return churnNeighbors;
}
public HashSet<Customer> getReachableNodes(Collection<Customer> startNodes,
DirectedSparseGraph<Customer, Transaction> graph) {
Queue<Customer> queue = new LinkedList<Customer>();
HashSet<Customer> visited = new HashSet<Customer>();
queue.addAll(startNodes);
visited.addAll(startNodes);
while (!queue.isEmpty()) {
Customer v = queue.poll();
Collection<Customer> neighbors = graph.getNeighbors(v);
for (Customer n : neighbors) {
if (!visited.contains(n)) {
queue.offer(n);
visited.add(n);
}
}
}
return visited;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:50:11.770",
"Id": "76479",
"Score": "1",
"body": "Have you profiled your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:51:34.743",
"Id": "76480",
"Score": "0",
"body": "What are you trying to achieve. A quick look says that this is one of those shortest path solution. If yes what is the algorithm that you are using? Please elaborate a *little* about your problem and your solution to get a good review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:52:57.267",
"Id": "76481",
"Score": "1",
"body": "Please, oh please, at least describe what your code does. Including a description of your code makes things so much easier for us."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:02:20.143",
"Id": "76483",
"Score": "0",
"body": "I added some description. However I dont want to change my main algorithm. I am looking for changing the way of implementing this algorithm and the used data structures..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:15:59.473",
"Id": "76489",
"Score": "1",
"body": "Its a bit difficult to comment on optimizing the topping, if you got half of the cake wrong. Your code has the usual beginner issues: bad structure, bad formatting, strong lack of sub-methods, long \"spaghetti\" code-parts, no comments, and so much more... So yes it is possible to optimize this code, but you need to be more specific."
}
] | [
{
"body": "<p>Lots to think about, this is not a comprehensive evaluation</p>\n\n<h2>Use Java7</h2>\n\n<p>your code style indicates you are using Java6 (you are not using the <a href=\"http://www.javaworld.com/article/2074080/core-java/jdk-7--the-diamond-operator.html\" rel=\"nofollow\">diamond operator <code><></code></a>...).</p>\n\n<p>Java 7 and it's recent updates are faster than Java6.</p>\n\n<h2>Extract the comparator:</h2>\n\n<pre><code>private static final Comparator<Customer> PRIORITY_COMPARATOR = new Comparator<>() {\n public int compare(Customer c1, Customer c2) {\n if (c1.getMarginalGain() < c2.getMarginalGain())\n return 1;\n if (c1.getMarginalGain() > c2.getMarginalGain())\n return -1;\n if (c1.getMarginalGain() == c2.getMarginalGain()) {\n if (c1.getRevenue() < c2.getRevenue())\n return 1;\n if (c1.getRevenue() > c2.getRevenue())\n return -1;\n }\n return 0;\n }\n }\n</code></pre>\n\n<p>Then use it as:</p>\n\n<pre><code>PriorityQueue<Customer> marginalGainHeap = new PriorityQueue<>(1, PRIORITY_COMPARATOR);\n</code></pre>\n\n<h2>LinkedHashSet</h2>\n\n<p>Your method returns <code>LinkedHashSet<Customer></code>. This strikes me as odd.... To me this means:</p>\n\n<ul>\n<li>the order is important</li>\n<li>you don't know what your data does in terms of duplicates.</li>\n</ul>\n\n<p>Using a Set means you expect duplicate data, and you only discover it is a duplicate <strong>after</strong> you have done the work, and you add it to the set.</p>\n\n<p>You should adjust this to be a more natural structure, like a <code>List<Customer></code> and then ensure that you are not processing the same customer twice....</p>\n\n<h2>Dubious Queue Usage</h2>\n\n<blockquote>\n<pre><code> for (Customer remainingNode : tmpAvailNodes) {\n remainingNode.setMarginalGain(calculateMarginalGain(\n remainingNode, seedSet, network, availableNodes,\n churnNet));\n\n // heapify bar asase mg\n marginalGainHeap.remove(remainingNode);\n marginalGainHeap.add(remainingNode);\n }\n</code></pre>\n</blockquote>\n\n<p><code>marginalGainHeap</code> is a Priority queue. It is not a free data structure.</p>\n\n<p>Changing the priority of a value is dubious (I had to check that the <code>remove()</code> will actually succeed... It will, but it <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html\" rel=\"nofollow\">performs slowly ( <em>O(n)</em> performance )</a>. Because of the way you <code>remove()</code> and <code>add()</code> ( <em>O( log n)</em> ) the same values multiple times, you are running at essentially <em>O(n<sup>2</sup>log(n))</em> performance in that section.</p>\n\n<h2>System.out.println</h2>\n\n<p>You are doing this a lot.</p>\n\n<p>It is slow.</p>\n\n<p>Don't</p>\n\n<h2>calculateMarginalGain</h2>\n\n<p>This method looks horrendous for performance.</p>\n\n<ul>\n<li>2 new HashSets</li>\n<li>4 <em>O(n)</em> operations - addAll, addAll, retainAll, removeAll</li>\n</ul>\n\n<p>Call to getNeighbours adds:</p>\n\n<ul>\n<li>2 new HashSet</li>\n<li>1 addAll</li>\n<li><em>O(n * m)</em> loop system</li>\n</ul>\n\n<h2>Conclusion....</h2>\n\n<p>You have to change your code to <strong><em>NOT do things you have to Undo Later</em></strong></p>\n\n<ul>\n<li>Don't add things to a priority queue if you have to change the priority</li>\n<li>Don't add things to a HashSet if you have to remove them later.</li>\n<li>.....</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T10:12:11.853",
"Id": "77330",
"Score": "0",
"body": "I used LinkedHashSet because of I need an ordered set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T10:37:48.477",
"Id": "77332",
"Score": "0",
"body": "Without using System.out how can I figure out the progress of my program? About \"not do things you have to undo late\" you meant I should check before adding data? I my case it is impossible because of at the time of insertion I have no idea about this problem."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:52:42.323",
"Id": "44165",
"ParentId": "44159",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:43:59.717",
"Id": "44159",
"Score": "4",
"Tags": [
"java",
"performance",
"graph"
],
"Title": "Maximize the number of nodes that could be reachable in a graph"
} | 44159 |
<p>I have a working script that selects image fields in all tables and empty their values if the physical file doesnt exist.</p>
<pre><code> $query1 = "SELECT table_name,column_name
FROM information_schema.columns
WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";
$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);
while($row1 = mysql_fetch_row($result1)){
if (!strpos($row1[0],'backup') > 0){
$sql = "Select COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '".$row1[0]."' AND EXTRA = 'auto_increment'";
$resultcol = mysql_query($sql);
$rowcol = mysql_fetch_row($resultcol);
$query2 = "SELECT " . $row1[1] . ", " .$rowcol[0] . "
FROM " . $row1[0] . "
WHERE " . $row1[1] . " != '' AND " . $row1[1] . " IS NOT NULL
";
echo $query2 . "<br>";
$result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);
while ($rowdb = mysql_fetch_row($result2)){
if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0])){
$sql = "UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE " . $rowcol[0]. "= ".$rowdb[1];
echo $sql . "<br><br>";
$delete_count++;
//mysql_query("UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE id = ".$row1["id"]);
}
}
}
}
</code></pre>
<p>The script is working fine, but it takes time. I was wondering if there is a smarter (more optimized) way to get the same function.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:38:12.120",
"Id": "76496",
"Score": "2",
"body": "For the sake of ease (of writing, reading and thus maintaining) I would recommend using PDO instead of using the MySQL drivers like that. It's more secure too once you start working with data a user can send to your query. Here are [the Official PDO Documentation](http://be2.php.net/pdo) and a [nice blog post](http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059) that can get you started. PDO will also make it very easy to change from MySQL to something else later on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T19:50:17.407",
"Id": "76566",
"Score": "0",
"body": "There is probably not much you can do to get it to run any faster."
}
] | [
{
"body": "<p>The <a href=\"http://www.php.net/manual/en/intro.mysql.php\" rel=\"nofollow noreferrer\"><code>mysql_*</code> functions are deprecated</a>. Use <code>mysqli</code> or PDO instead.</p>\n\n<p>Each query that you issue has a rather large overhead: you have to communicate the query to the server; the server has to parse, plan, and execute the query; the results have to be returned to your application. Therefore, you want to avoid running any query in a loop. You're much better off executing fewer complex queries than many simple queries.</p>\n\n<p>First, note that your <code>$query1</code> has a bug: <a href=\"https://stackoverflow.com/a/1241158/1157100\"><code>AND</code> has higher precedence than <code>OR</code></a>, so you need parentheses. Also, you eventually ignore any column named <code>…backup</code>, so you might as well filter those out immediately.</p>\n\n<pre><code>SELECT TABLE_NAME AS table_name, COLUMN_NAME AS image_col\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE\n TABLE_SCHEMA = 'schemaname'\n AND TABLE_NAME NOT LIKE '%backup%'\n AND (COLUMN_NAME LIKE '%image%' OR COLUMN_NAME = 'video');\n</code></pre>\n\n<p>Let's clarify the naming.</p>\n\n<ul>\n<li>Your <code>$row1[0]</code> is what I call <code>table_name</code></li>\n<li>Your <code>$row1[1]</code> is what I call <code>image_col</code></li>\n</ul>\n\n<p>Notionally, you want to execute this query for each result returned by that <code>$schema</code> query.</p>\n\n<pre><code>UPDATE `$schema['table_name']`\n SET `$schema['image_col']` = ''\n WHERE\n `$schema['image_col']` != '' AND `$schema['image_col']` IS NOT NULL\n AND `$s['image_col']` NOT LIKE '%facebook%'\n AND NOT file_exists('$img_root/$schema['image_col']')\n</code></pre>\n\n<p>Of course, there are two problems with that idea:</p>\n\n<ol>\n<li>There is no <code>file_exists()</code> function in MySQL (and furthermore, if such a function existed, it would be wrong to run it on the database server rather than on the application server, since they could be on different machines with different filesystems).</li>\n<li><p>You have to execute many <code>UPDATE</code>s, not just one. Furthermore, the <code>UPDATE</code> queries are dynamic — the table and column names vary.</p>\n\n<p><strong>This is a strong indication that your database schema is poorly designed.</strong> There should not be a proliferation of tables! You should also not be doing version control or backups by creating tables named <code>…backup</code>. I encourage you to follow up with these issues on <a href=\"http://dba.stackexchange.com\">http://dba.stackexchange.com</a>.</p></li>\n</ol>\n\n<p>A solution to the first problem is to create a temporary table that <a href=\"https://stackoverflow.com/a/1860417/1157100\">lists all images on your website's filesystem</a>, then write the <code>UPDATE</code> with an anti-join.</p>\n\n<pre><code>$db = new mysqli(…);\n$db->query('CREATE TEMPORARY TABLE fs_images ( filename VARCHAR(128) PRIMARY KEY );');\n$ins = $db->prepare('INSERT INTO fs_images VALUES (?)');\n$file_it = new RecursiveDirectoryIterator($img_root);\nforeach (new RecursiveIteratorIterator($file_it) as $f) {\n $ins->bind_param('s', basename($f));\n $ins->execute();\n}\n$ins->close();\n</code></pre>\n\n<p>A solution to the second problem is to use a <a href=\"https://dba.stackexchange.com/a/48275/8230\">stored procedure with a loop that executes dynamically composed SQL queries</a> with a <a href=\"http://dev.mysql.com/doc/refman/5.0/en/cursors.html\" rel=\"nofollow noreferrer\">cursor</a>.</p>\n\n<pre><code>DELIMITER $$\nCREATE PROCEDURE clear_images()\nBEGIN\n DECLARE done INT DEFAULT FALSE;\n DECLARE table_name VARCHAR(64);\n DECLARE image_col VARCHAR(64);\n\n DECLARE schema_cursor CURSOR FOR\n SELECT TABLE_NAME AS table_name, COLUMN_NAME AS image_col\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE\n TABLE_SCHEMA = 'schemaname'\n AND TABLE_NAME NOT LIKE '%backup%'\n AND (COLUMN_NAME LIKE '%image%' OR COLUMN_NAME = 'video');\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;\n\n OPEN schema_cursor;\n schema_loop: LOOP\n FETCH schema_cursor INTO table_name, image_col;\n IF done THEN\n LEAVE schema_loop;\n END IF;\n\n PREPARE stmt FROM CONCAT(\n 'UPDATE `', @table_name, '`',\n ' SET `', @image_col, '` = ''''',\n ' WHERE',\n ' `', @image_col, '` != '''' AND `', @image_col, '` IS NOT NULL',\n ' AND `', @image_col, '` NOT LIKE ''%facebook%''',\n ' AND `', @image_col, '` NOT IN (SELECT filename FROM fs_images);'\n );\n EXECUTE stmt;\n DEALLOCATE PREPARE stmt;\n END LOOP;\nEND$$\nDELIMITER ;\n</code></pre>\n\n<p>Anyway, this solution is rather nasty (and untested!) — all as a result of your poor database schema design.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T21:38:55.257",
"Id": "44203",
"ParentId": "44161",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T14:44:36.997",
"Id": "44161",
"Score": "7",
"Tags": [
"php",
"optimization",
"mysql",
"sql"
],
"Title": "Removing image records if no physical file exists"
} | 44161 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.