body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have written a few <em>simple-to-be-used</em> methods in Java 8, and am wondering what could be improved upon those:</p>
<pre><code>public static <E, R, C extends Collection<? extends R>> C transform(final Collection<E> collection, final Function<? super E, ? extends R> mapper) {
try {
Objects.requireNonNull(collection);
Objects.requireNonNull(mapper);
Class<? extends Collection> clazz = collection.getClass();
@SuppressWarnings("unchecked") Collection<Object> returnCollection = clazz.newInstance();
collection.stream().map(mapper).forEach(returnCollection::add);
@SuppressWarnings("unchecked") C genericReturnCollection = (C)returnCollection;
return genericReturnCollection;
} catch (InstantiationException | IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
public static <E, R, C extends Collection<R>> C transform(final Collection<E> collection, final Function<? super E, ? extends R> mapper, final Supplier<C> collectionSupplier) {
Objects.requireNonNull(collection);
Objects.requireNonNull(mapper);
Objects.requireNonNull(collectionSupplier);
return collection.stream().map(mapper).collect(Collectors.toCollection(collectionSupplier));
}
</code></pre>
<p>Their purpose is to provide similar functionality as the <code>List.replaceAll()</code> method, but then allowing that the mapped type differs from the original type. Hence it is something that should be in a <code>static</code> factory class, as it will always need to create a new collection.</p>
<p>Some example code:</p>
<pre><code>LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(5);
linkedList.add(10);
linkedList.add(15);
LinkedList<String> resultList = transform(linkedList, i -> (i + 1) + "-" + i);
</code></pre>
<p>and</p>
<pre><code>LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(5);
linkedList.add(10);
linkedList.add(15);
LinkedList<String> resultList = transform(linkedList, i -> (i + 1) + "-" + i, LinkedList::new);
</code></pre>
<p>Both have as output:</p>
<blockquote>
<p>6-5<br>
11-10<br>
16-15</p>
</blockquote>
<p>I am aware that the <code>transform</code> with a <code>Supplier<C></code> as argument is obviously much nicer, however for convienience the single-argument version with only a function is much better.</p>
| [] | [
{
"body": "<p>I see the Supplier-less option as being a very broken one. Consider the following code:</p>\n\n<pre><code>transform(linkedList.sublist(0, linkedList.size() / 2), i -> (i + 1) + \"-\" + i);\n</code></pre>\n\n<p>Or, any of the other collections that do not have a meaningful default constructor:</p>\n\n<pre><code>transform(Arrays.asList(argv), a -> a.toLowerCase());\n</code></pre>\n\n<p>The code will cause more headaches than the small requirement to add the supplier will require.</p>\n\n<p>The Generics of the mapping are also broken when there is no supplier, because the actual type of the return list should be more specific....</p>\n\n<p>Lose the first static method.</p>\n\n<p>The second method looks fine, except for the ordering of the arguments. I would make the supplier the middle, not the last argument (and I would introduce some newlines to make it not-so-long-of-a-line):</p>\n\n<pre><code>public static <E, R, C extends Collection<R>> C transform(\n final Collection<E> collection,\n final Supplier<C> collectionSupplier,\n final Function<? super E, ? extends R> mapper) {\n ....\n}\n</code></pre>\n\n<p>The logical reading of that order is better, take this collection, map to that collection, and use this function to do it..... maybe it is not such a big deal...?</p>\n\n<p>The use-case seems to read better for me:</p>\n\n<pre><code>List<String> lcargs = transform(Arrays.asList(args), ArrayList::new, a -> a.toLowerCase());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:36:18.150",
"Id": "47971",
"ParentId": "47967",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47971",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:22:14.303",
"Id": "47967",
"Score": "10",
"Tags": [
"java",
"type-safety",
"factory-method"
],
"Title": "Methods creating transform functionality on Collections"
} | 47967 |
<p>Inspired by <a href="https://stackoverflow.com/questions/23213332/bash-shell-simulation-in-browser">this question on Stack Overflow</a>, I've attempted to code such animation, mostly to get some more practice with async, promises and Q.js:</p>
<p><a href="http://codepen.io/Kos/pen/ClqeJ?editors=001" rel="nofollow noreferrer">(Live demo)</a></p>
<pre><code>function addOutput(s) {
$('<div>').text(s).appendTo(wnd);
//return Q.defer().promise;
return Q.delay(100).then(function() { return addPrompt(); });
}
function addInput(s) {
var l = $('.prompt:last');
return addLettersRecursive(l, s);
}
function addPrompt() {
var prompt = "kos@codepen % ";
var l = $('<div>').text(prompt).addClass('prompt').appendTo(wnd);
return Q.delay(900);
}
function addLettersRecursive(container, s) {
container.append(s.charAt(0)); // dangerous :(
var row_complete = Q.defer();
Q.delay(100).then(function() {
if (s.length <= 1) {
Q.delay(300).then(function() {
row_complete.resolve();
});
}
addLettersRecursive(container, s.substr(1)).then(function() {
row_complete.resolve();
})
});
return row_complete.promise;
}
// Usage
addPrompt(">>> ")
.then(function() { return addInput("whoami"); })
.then(function() { return addOutput("kos"); })
.then(function() { return addInput("uname -a"); })
.then(function() { return addOutput("Javascript in codepen.io, powered by Q.js"); })
.then(function() { return addInput("raz dwa"); })
.then(function() { return addOutput("zsh: command not found: raz"); })
.then(function() { return addInput("trzy cztery"); })
.then(function() { return addOutput("zsh: command not found: trzy"); })
.done();
</code></pre>
<p>I'm not really satisfied by this implementation, though. How can I simplify it? Here are the specific concerns I have:</p>
<ol>
<li>I implemented <code>addInput</code> in terms of a recursive helper function <code>addLettersRecursive</code> which still is overly complicated according to my gut feeling.</li>
<li>There's this <code>.then(function() { return function_that_returns_promise(args); });</code> pattern all over, which seems like a very verbose way of chaining behaviour. </li>
</ol>
<p>What I have tried:</p>
<ol>
<li><p>I attempted to unwind the recursion by stacking the promises one on top of another in a loop, which was a bit tricky to implement because of the selective closure involved. There's some improvement but still looks messy:</p>
<pre><code>function addInput(s) {
var container = $('.prompt:last');
var d = Q.delay(0);
for (var i=0; i<s.length; ++i) {
d = d.then(function(i) { return function() { // pass i by value
container.append(s.charAt(i));
return Q.delay(100);
}}(i));
}
return d.then(function() { return Q.delay(300); });
}
</code></pre></li>
<li><p>I'm not sure if this kind of pattern is typical to promise-driven code, or I'm just doing something sub-optimally. One thing that came to my mind is this substitution:</p>
<pre><code> /* before */ .then(function() { return addInput("whoami"); })
/* after */ .then(addInput.bind(null, "whoami"))
/* before */ return d.then(function() { return Q.delay(300); });
/* after */ return d.then(Q.delay.bind(Q, 300));
</code></pre>
<p>Is it a good track?</p></li>
</ol>
<p>Generally I haven't seen much "real life" uses of promises yet except the book cases, so if anything else looks out of the ordinary or sub-optimal, please raise it.</p>
| [] | [
{
"body": "<p>This stuff is hard to get right, at this point good promise driven code seems more like an art than engineering.</p>\n\n<p>From a CodeReview perspective, your code is fairly easy to follow, except for one thing which got me stumped for a little while, <code>row_complete</code> should really be named <code>char_complete</code>, and then suddenly <code>addLettersRecursive</code> will make more sense.</p>\n\n<p>There are at least 3 additional ways you can deal with <code>.then(function() { return function_that_returns_promise(args); });</code></p>\n\n<ol>\n<li><p>Change your functions ( like <code>addInput</code> ) to return a function, like this:</p>\n\n<pre><code>function addInput(s) {\n return function addInputWrapper(){\n var l = $('.prompt:last');\n return addLettersRecursive(l, s);\n }\n}\n</code></pre>\n\n<p>Then you can call simply <code>.then( addInput( 'whoami' ) )</code></p></li>\n<li><p>Create a generic wrapper function like this:</p>\n\n<pre><code>function wrap( f ){\n var args = Array.prototype.slice.call(arguments,1);\n return function wrapper(){\n return f.apply( this, args );\n }\n}\n</code></pre>\n\n<p>Then you can call <code>.then( wrap( addInput, 'whoami' ) )</code></p></li>\n<li><p>Generate a <code>lambdafy</code> function like this : </p>\n\n<pre><code>function lambdafy( f )\n{\n var lambda = function(){\n var args = Array.prototype.slice.call(arguments);\n return function(){\n f.apply( this , args );\n }\n }\n return lambda;\n}\n</code></pre>\n\n<p>Then you can <code>addInput = lambdafy( addInput )</code> and <code>.then( addInput( 'whoami' ) )</code></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:38:47.007",
"Id": "84448",
"Score": "0",
"body": "Thanks! 1 crossed my mind but probably isn't conventional, for instance `Q.delay()` returns the promise immediately. 2 looks very similar to `Function.bind` in usage, and I think I'll stick with this approach for now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T12:53:49.427",
"Id": "47974",
"ParentId": "47970",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T11:32:41.153",
"Id": "47970",
"Score": "2",
"Tags": [
"javascript",
"asynchronous",
"promise",
"animation"
],
"Title": "Promise-driven animation"
} | 47970 |
<p>I have made an <code>any</code> class in C++, base loosely on <code>boost::any</code>, but written differently. I am checking to see if I have done it correctly and that there are no mistakes in it:</p>
<pre><code>class any
{
public:
any()
: dt(new data<void *>(0))
{
}
template<class T>
any(const T &value)
: dt(new data<T>(value))
{
}
any(any &rhs)
: dt(rhs.dt->duplicate())
{
}
~any()
{
delete dt;
}
template<class T>
T cast() const
{
if (type() == typeid(T))
{
return (reinterpret_cast<data<T> *>(dt)->val);
}
throw std::exception("invalid cast type");
}
template<class T>
operator T() const
{
return (cast<T>());
}
template<class T>
bool is() const
{
return (type() == typeid(T));
}
any &operator=(any &rhs)
{
if (this != &rhs)
{
delete dt;
dt = rhs.dt->duplicate();
}
return (*this);
}
template<class T>
any &operator=(const T &value)
{
delete dt;
dt = new data<T>(value);
return (*this);
}
any &swap(any &rhs)
{
std::swap(dt, rhs.dt);
return (*this);
}
template<class T>
bool operator==(const T &value) const
{
return (type() == typeid(T) &&
cast<T>() == value);
}
bool operator==(any &rhs) const
{
return (type() == rhs.type() &&
dt->cmp(rhs.dt));
}
template<class T>
bool operator!=(const T &value) const
{
return (!((*this) == value));
}
bool operator!=(any &rhs) const
{
return (!((*this) == rhs));
}
const std::type_info &type() const
{
return (dt->type());
}
protected:
struct dummy
{
public:
virtual const std::type_info &type() const = 0;
virtual bool cmp(dummy *rhs) const = 0;
virtual dummy *duplicate() = 0;
};
template<class T>
struct data
: public dummy
{
public:
data()
: val()
{
}
data(const T &value)
: val(value)
{
}
~data()
{
}
const std::type_info &type() const
{
return (typeid(T));
}
bool cmp(dummy *rhs) const
{
return (val == reinterpret_cast<data<T> *>(rhs)->val);
}
dummy *duplicate()
{
return (new data<T>(val));
}
T val;
};
dummy *dt;
};
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I am checking to see if I have done it correctly and that there are no mistakes in it:</p>\n</blockquote>\n\n<p>What have you done to test this class? You might want to write some unit-tests.</p>\n\n<hr>\n\n<p>I think I see at least one bug: the destructor ...</p>\n\n<pre><code> ~any()\n {\n delete dt;\n }\n</code></pre>\n\n<p>... calls <code>delete dt</code>.</p>\n\n<p><code>dt</code> seems to be of type <code>dummy*</code> ...</p>\n\n<pre><code>dummy *dt;\n</code></pre>\n\n<p>... but is actually of type <code>data<T></code> which derives from <code>dummy</code>.</p>\n\n<p><code>dummy</code> is defined without a virtual destructor: so when you call <code>delete dt</code> then the <code>dummy</code> destructor will be called but the <code>data</code> destructor won't be called, and therefore the <code>T</code> data member of the <code>data</code> destructor won't be called, which is a bug if <code>T</code> has a non-trivial (non-default) destructor.</p>\n\n<hr>\n\n<p>I don't see why you don't define <code>duplicate</code> as a <code>const</code> method, and define the <code>any(any &rhs)</code> constructor and the <code>any &operator=(any &rhs)</code> operator as taking <code>const</code> reference parameters.</p>\n\n<hr>\n\n<p>You defined the implementation details of <code>any</code> as <code>protected</code> instead of <code>private</code>, as if you expect <code>any</code> to be subclassed. If <code>any</code> will be subclassed then its methods (e.g. its destructor) should perhaps be <code>virtual</code>.</p>\n\n<hr>\n\n<p>You implemented <code>operator T() const</code> which is a conversion operator; but boost implements an explicit function i.e. <code>any_cast</code> for this purpose. I'm not sure why boost chose the latter but it may be better for some reason: perhaps it's safer because it's more explicit.</p>\n\n<p>boost define a custom exception type <code>bad_any_cast</code> if the cast fails; you're just using a <code>std::exception</code> which might be harder to catch accurately.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:47:10.623",
"Id": "84199",
"Score": "0",
"body": "boost uses the cast convention as they did not want automatic (compiler generated) conversion from an `Any<T>` to a `T`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T18:20:45.310",
"Id": "84205",
"Score": "0",
"body": "@LokiAstari Yes, but can you guess at why they didn't want automatic conversion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T22:17:11.120",
"Id": "84241",
"Score": "0",
"body": "At a guess: Auto conversion in general is a bad idea (obvious few exceptions)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T13:38:05.370",
"Id": "47977",
"ParentId": "47975",
"Score": "6"
}
},
{
"body": "<p>Your code is in pretty much good shape but there are still several issues apart from what mentioned by <a href=\"https://codereview.stackexchange.com/a/47977/39083\">ChrisW</a>:</p>\n\n<ul>\n<li>There are many cases in input arguments and return types of functions where you are not particularly careful about <code>const</code>/non-<code>const</code> and <em>value vs. reference</em>.</li>\n<li>This code won't work for <em>built-in arrays</em>, hence neither for C-style strings. One way is to <em>decay</em> the type of the input argument before storage; built-in arrays are decayed to pointers in this case (which means array elements are not really copied).</li>\n<li>The default constructor shouldn't allocate anything; initialize the data pointer to <code>nullptr</code> and provide member functions <code>empty()</code> and <code>clear()</code> to control the <em>state</em> of having/not having data.</li>\n<li>Your <em>assignment operators</em> are unnecessarily complex, inefficient (by self-tests) and not exception-safe (if <code>new</code> throws, the current object is already destroyed). The most elegant solution to all these issues is the <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">copy-swap idiom</a>, where all actual work is done by constructors alone.</li>\n<li>You don't need <code>typeid</code> to test for <em>type equality</em>; a lightweight (but low-level) solution <em>without RTTI</em> is <a href=\"https://codereview.stackexchange.com/a/45079/39083\">here</a>.</li>\n<li><em>Type identification</em> should be kept as an internal detail; the minimal required functionality is type equality by <code>is()</code>; don't expose <code>type()</code>, rather keep it as private as possible.</li>\n<li>Type checking is a good thing, but for performance you should also provide <em>unchecked access</em>.</li>\n<li><em>Casting</em> is from a base to a derived class, so need not (and should not) be done with <code>reinterpret_cast</code>; rather, <code>dynamic_cast</code> / <code>static_cast</code> for checked / unchecked access. <code>dynamic_cast</code> to a reference type will automatically throw an <code>std::bad_cast</code> if the object is not of the right type, so there is not need to manually check with <code>is()</code>. This does need RTTI but is more elegant.</li>\n<li>Storing <em>empty objects</em> (like function objects) is currently inefficient, as it does need extra space on top of the virtual function table. This can be solved by the <a href=\"http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Empty_Base_Optimization\" rel=\"nofollow noreferrer\">empty base optimization</a>, which is done automatically by using <code>std::tuple</code>.</li>\n<li>Implicit <em>conversion operators</em> are a possible source for ambiguities and confusion; you may keep them if you need their convenience, but use carefully (e.g. try to explicitly initialize an object of the right type).</li>\n<li><em>Comparison operators</em> are a clear overkill (if you have them, why not also have arithmetic operators, and so on?). If you still want them, define them as <em>non-member</em> functions, using public members <code>is</code> and <code>cast</code> to implement them.</li>\n<li>There are no <em>move semantics</em>.</li>\n<li>There is no specialized binary (non-member) function <code>swap</code>. Defaulting to <code>std::swap</code> is not as efficient as it involves three move operations; without move semantics, things are even worse as it involves three <em>copy</em> operations.</li>\n</ul>\n\n<p>I took the liberty to re-factor your code to a great extent, and here is the result, resolving all issues above:</p>\n\n<pre><code>class some\n{\n using id = size_t;\n\n template<typename T>\n struct type { static void id() { } };\n\n template<typename T>\n static id type_id() { return reinterpret_cast<id>(&type<T>::id); }\n\n template<typename T>\n using decay = typename std::decay<T>::type;\n\n template<typename T>\n using none = typename std::enable_if<!std::is_same<some, T>::value>::type;\n\n struct base\n {\n virtual ~base() { }\n virtual bool is(id) const = 0;\n virtual base *copy() const = 0;\n } *p = nullptr;\n\n template<typename T>\n struct data : base, std::tuple<T>\n {\n using std::tuple<T>::tuple;\n\n T &get() & { return std::get<0>(*this); }\n T const &get() const& { return std::get<0>(*this); }\n\n bool is(id i) const override { return i == type_id<T>(); }\n base *copy() const override { return new data{get()}; }\n };\n\n template<typename T>\n T &stat() { return static_cast<data<T>&>(*p).get(); }\n\n template<typename T>\n T const &stat() const { return static_cast<data<T> const&>(*p).get(); }\n\n template<typename T>\n T &dyn() { return dynamic_cast<data<T>&>(*p).get(); }\n\n template<typename T>\n T const &dyn() const { return dynamic_cast<data<T> const&>(*p).get(); }\n\npublic:\n some() { }\n ~some() { delete p; }\n\n some(some &&s) : p{s.p} { s.p = nullptr; }\n some(some const &s) : p{s.p->copy()} { }\n\n template<typename T, typename U = decay<T>, typename = none<U>>\n some(T &&x) : p{new data<U>{std::forward<T>(x)}} { }\n\n some &operator=(some s) { swap(*this, s); return *this; }\n\n friend void swap(some &s, some &r) { std::swap(s.p, r.p); }\n\n void clear() { delete p; p = nullptr; }\n\n bool empty() const { return p; }\n\n template<typename T>\n bool is() const { return p ? p->is(type_id<T>()) : false; }\n\n template<typename T> T &&_() && { return std::move(stat<T>()); }\n template<typename T> T &_() & { return stat<T>(); }\n template<typename T> T const &_() const& { return stat<T>(); }\n\n template<typename T> T &&cast() && { return std::move(dyn<T>()); }\n template<typename T> T &cast() & { return dyn<T>(); }\n template<typename T> T const &cast() const& { return dyn<T>(); }\n\n template<typename T> operator T &&() && { return std::move(_<T>()); }\n template<typename T> operator T &() & { return _<T>(); }\n template<typename T> operator T const&() const& { return _<T>(); }\n};\n</code></pre>\n\n<p>I call it <code>some</code> instead of <code>any</code> because I prefer to hold <code>some</code>thing rather than <code>any</code>thing :-) Plus, <code>any</code> is a common name for a function (like <code>all</code>), which is not the case for <code>some</code>.</p>\n\n<p>Members <code>cast()</code> provide type-checked access, while members <code>_()</code> (shortest notation) provide unchecked access. I have chosen to give conversion operators unchecked access for performance but you are free to change that or remove them altogether.</p>\n\n<p>I've also made a <a href=\"http://coliru.stacked-crooked.com/a/a5eab9499d50e829\" rel=\"nofollow noreferrer\">live example</a>, including an extensive series of tests to demonstrate (almost) all possible uses.</p>\n\n<p>Note that <code>base</code> (your <code>dummy</code>) now has a <code>virtual</code> destructor.</p>\n\n<p>There is one more issue: using the <em>free store</em> is serious performance bottleneck when it comes to small types. What you can do is define a particular size to be allocated on <em>stack</em>, and only use the free store for larger objects, similar to <a href=\"http://john-ahlgren.blogspot.gr/2012/03/small-string-optimization-and-move.html\" rel=\"nofollow noreferrer\">short (or small) string optimization</a>.</p>\n\n<p>More generally, it is a good idea to parametrize the implementation with respect to how memory management (allocation, deallocation) is done by providing a kind of <em>allocator</em> object. <code>any</code> is really a <em>container</em>, even if of at most one object.</p>\n\n<p>I have extended the implementation towards this direction but I will probably post this as a separate answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:39:08.540",
"Id": "84834",
"Score": "0",
"body": "I eventually completed what I had promised and I posted it as a new *question*: [Yet another 'any'](http://codereview.stackexchange.com/q/48344/39083)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:26:52.007",
"Id": "48250",
"ParentId": "47975",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T13:08:24.647",
"Id": "47975",
"Score": "11",
"Tags": [
"c++",
"reinventing-the-wheel"
],
"Title": "'any' class implementation"
} | 47975 |
<p>I have a long command that I am building with shovels (<code><<</code>), with the intention of eventually running <code>system(command)</code>. I'd like to log the command string, to make sure it is built properly, right before I execute the command. However, the command has to contain account credentials that I don't want to log. I'm looking for an elegant way to satisfy both requirements (1. log the meat of the command string, 2. don't log the auth credentials it contains).</p>
<p>This is what I have now:</p>
<pre><code>command = ""
public = ""
[command, public].each {|str| str << "command_name"}
[command, public].each {|str| str << " -a a"}
[command, public].each {|str| str << " -b b"}
[command, public].each {|str| str << " -c c"}
command << " -d d"
command << " -e e"
[command, public].each {|str| str << " -f f"}
command << " -g g"
[command, public].each {|str| str << " -h h"}
[command, public].each {|str| str << " -i i"}
puts command
=> command_name -a a -b b -c c -d d -e e -f f -g g -h h -i i
puts public
=> command_name -a a -b b -c c -f f -h h -i i
system(command)
</code></pre>
<p><a href="https://stackoverflow.com/questions/23229746/can-you-append-to-two-strings-in-the-same-line-in-ruby">Original question from Stack Overflow</a></p>
| [] | [
{
"body": "<p>You seem to be repeatedly performing a lot of operations on both 'command' and 'public' together. The way these variables are related make me think they should actually be part of the same object. For example:</p>\n\n<pre><code>class Command\n attr_reader :command, :loggable\n\n def initialize(command)\n @command = command\n @loggable = command\n end\n\n def concat(option)\n @command << ' ' + option\n @loggable << ' ' + option\n end\n alias_method :<<, :concat\n\n def concat_private(option)\n @command << ' ' + option\n end\n\n alias_method :to_s, :command\n alias_method :to_str, :command\nend\n\ncommand = Command.new('echo')\ncommand << '-a this'\ncommand << '-b that'\ncommand.concat_private '--password asdf'\n\nsystem(command)\n</code></pre>\n\n<p>This approach also makes your code more testable, gives you the flexibility of adding additional methods to <code>Command</code> should the need arise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:12:00.793",
"Id": "47993",
"ParentId": "47978",
"Score": "8"
}
},
{
"body": "<p>I see two more security issues with this code.</p>\n\n<ol>\n<li><p><strong>Executing a string rather than an array of command and parameters</strong></p>\n\n<p>When building a command line programmatically, it is dangerous to build it as a string, especially when any of the parameters comes from user input. When calling <a href=\"http://www.ruby-doc.org/core-trunk/Kernel.html#method-i-system\" rel=\"nofollow noreferrer\"><code>Kernel#system</code></a> with a string, a shell interprets the command line; when calling it with an array, the operating system kernel executes the command directly.</p>\n\n<p>In the benign failure case, the password might contain a <kbd>space</kbd>, in which case the shell would interpret it as two parameters, probably causing your command to be invoked incorrectly. In the worst case, the user could trigger an <strong>arbitrary command execution vulnerability.</strong></p>\n\n<p>As an illustration, the following code will do more than just set your password to <code>\"hello\"</code>:</p>\n\n<pre><code>password_file = '.htpasswd'\nusername = 'CHK'\npassword = 'hello; touch me; grep; unzip; strip; finger; fsck -y; more; yes; yes; yes; umount; sleep'\ncommand = \"htpasswd -b -c #{password_file} #{username} #{password}\"\nsystem(command)\n</code></pre>\n\n<p>Practice safer computing! This is not vulnerable to arbitrary command execution:</p>\n\n<pre><code>command = ['htpasswd', '-b', '-c', password_file, username, password]\nsystem(*command)\n</code></pre></li>\n<li><p><strong>Passing sensitive information on the command line</strong></p>\n\n<p>Even if you manage to censor the logger within Ruby, it's still considered dangerous practice to pass any sensitive information as a command-line parameter. Command lines are <a href=\"https://security.stackexchange.com/q/16072/27444\">visible to all users on a machine</a>.</p>\n\n<p>For that reason, all reasonable commands should offer an alternative mechanism to accept secret information. For example, <a href=\"http://httpd.apache.org/docs/current/programs/htpasswd.html#security\" rel=\"nofollow noreferrer\">the recommended way to use <code>htpasswd</code></a>, since Apache 2.4, is to read the password from standard input.</p>\n\n<pre><code>command = ['htpasswd', '-i', '-c', password_file, username]\nIO.popen(command, mode='w') do |htpasswd|\n htpasswd.puts(password)\nend\n</code></pre>\n\n<p>Similarly, here is an example of how to <a href=\"https://stackoverflow.com/a/11370662/1157100\">securely specify a passphrase to GnuPG (in Python)</a>.</p>\n\n<p>In summary, by <strong>passing the secret information through pipes instead of the command line,</strong> you solve both the log censorship problem <em>and</em> the machine-wide command-line visibility problem.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T22:22:07.890",
"Id": "84242",
"Score": "4",
"body": "I'd be lying if I said I didn't +1 this just because of the password."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T18:35:13.207",
"Id": "84357",
"Score": "0",
"body": "@200_success An idea how to avoid passing a password when using the VIX api's command line client (`vmrun`)? Question posted to SO here: http://stackoverflow.com/questions/21331525/is-possible-use-vix-api-without-type-password-in-plain-text"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T18:46:43.020",
"Id": "84358",
"Score": "0",
"body": "That's why we encourage you to ask questions on Code Review with real code, [not stripped-down hypothetical code](http://meta.codereview.stackexchange.com/q/1709/9357). Why use a command-line client at all? There's a [VIX API](https://www.vmware.com/support/developer/vix-api/), with at least four projects to provide Ruby bindings: [1](https://github.com/rhythmx/vixr) [2](https://github.com/jeffweiss/vixen) [3](https://labs.mwrinfosecurity.com/tools/vmware-vix-toolkit/) [4](http://rubyvmware.rubyforge.org/)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:35:24.937",
"Id": "48004",
"ParentId": "47978",
"Score": "18"
}
},
{
"body": "<p>I agree completely with everything @200_success said, but if you do want a sensitive info solution, I would suggest something more in the lines of <code>html_safe</code> - a specialized string which is makes by default, and only shown when explicitly requested:</p>\n\n<pre><code>class PrivateString < String\n alias to_private_s to_s\n\n def to_s\n '*******'\n end\n\n def concat(other)\n if other.respond_to?(:to_private_s)\n super(other.to_private_s)\n else\n super\n end\n end\n\n alias << concat\nend\n\nclass String\n def private\n PrivateString.new(self)\n end\n\n alias unsafe_concat concat\n\n def concat(other)\n if other.respond_to?(:to_private_s)\n unsafe_concat(other.to_s)\n else\n unsafe_concat(other)\n end\n end\n\n alias << concat\nend\n</code></pre>\n\n<p>Now your code will look like this:</p>\n\n<pre><code>command = \"\".private\npublic = \"\"\n\n[command, public].each {|str| str << \"command_name\"}\n[command, public].each {|str| str << \" -a a\"}\n[command, public].each {|str| str << \" -b b\"}\n[command, public].each {|str| str << \" -c c\"}\n[command, public].each {|str| str << \" -d d\".private}\n[command, public].each {|str| str << \" -e e\".private}\n[command, public].each {|str| str << \" -f f\"}\n[command, public].each {|str| str << \" -g g\".private}\n[command, public].each {|str| str << \" -h h\"}\n[command, public].each {|str| str << \" -i i\"}\n\nputs command\n=> command_name -a a -b b -c c -d d -e e -f f -g g -h h -i i\nputs public\n=> command_name -a a -b b -c c************** -f f******* -h h -i i\n\nsystem(command)\n</code></pre>\n\n<p>This is, of course, a bare bones implementation, and should probably be developed further (you can see <code>html_safe</code> implementation <a href=\"https://github.com/rails/rails/blob/7ce68406934c50a2ce3079bea4fd34936388c26a/activesupport/lib/active_support/core_ext/string/output_safety.rb#L123\" rel=\"nofollow\">here</a>), but it enables you to treat private strings like any other string, and only address it as private when needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T07:11:45.023",
"Id": "48029",
"ParentId": "47978",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:40:16.093",
"Id": "47978",
"Score": "11",
"Tags": [
"ruby",
"strings",
"security",
"logging",
"child-process"
],
"Title": "Pretty way of keeping sensitive info out of a logged command string in Ruby?"
} | 47978 |
<p>Which one is more verbose?</p>
<pre><code>private bool? _hasChangesToReconcile;
public bool HasChanges()
{
if (!_hasChangesToReconcile.HasValue)
{
if (Model != null)
{
using (var broker = _documentBrokerDelegateFactory())
{
return broker.Value.HasSectionChanges(Model.Id);
_hasChangesToReconcile = broker.Value.HasSectionChanges(Model.Id);
}
}
else
{
_hasChangesToReconcile = false;
}
}
return _hasChangesToReconcile.Value;
}
public void Handle(PageSectionVersionsCreated message)
{
if (!message.ChangesApplyTo(Model))
return;
_hasChangesToReconcile = null;
NotifyOfPropertyChange(() => ItemType);
}
</code></pre>
<p>or</p>
<pre><code>private State _pageStatus;
private enum PageStatus
{
HasChanges,
NoChanges,
}
private bool _hasChanges;
public bool HasChanges()
{
if (_pageStatus == PageStatus.HasChanges)
{
if (Model != null)
{
using (var broker = _documentBrokerDelegateFactory())
{
_hasChanges = broker.Value.HasSectionChanges(Model.Id);
}
}
}
return _hasChanges;
}
public void Handle(PageSectionVersionsCreated message)
{
if (!message.ChangesApplyTo(Model))
return;
_pageStatus = PageStatus.HasChanges;
NotifyOfPropertyChange(() => ItemType);
_pageStatus = PageStatus.NoChanges;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:54:13.487",
"Id": "84155",
"Score": "1",
"body": "Your nullable boolean can be null, obviously, which means it has three possible states, while your enum only has two. What was your intent?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:59:19.997",
"Id": "84159",
"Score": "0",
"body": "@Magus An enum can be null as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:00:50.793",
"Id": "84162",
"Score": "3",
"body": "@SimonAndréForsberg not in C#, it has to be declared as a `Nullable<MyEnumType>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:03:57.140",
"Id": "84164",
"Score": "0",
"body": "`private State _pageStatus` doesn't seem to be the same type as `PageStatus`. Shouldn't it be `private PageStatus _pageStatus;` or `private PageStatus? _pageStatus;`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:09:26.257",
"Id": "84167",
"Score": "0",
"body": "@Magus Exactly my question, what was the intent of the nullable if it will only end up with two states? I was proposing to my coworker an enum instead of using nullables"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:22:13.677",
"Id": "84169",
"Score": "0",
"body": "No, as @Mat'sMug said, both `bool` and `Enum` are value types. An enum with two states is equivalent to a boolean, except that it is integral. A flags enum would let you have more states, but it would not limit them. Currently, your nullable boolean has more possible values than your enum."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:30:50.927",
"Id": "84172",
"Score": "0",
"body": "@Magus The 2nd version has an enum *and* a non-nullable bool."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:36:35.813",
"Id": "84173",
"Score": "1",
"body": "That's downright horrific. There's a method named the same thing as an enum value right there. I'd just make an enum with three states..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:41:07.107",
"Id": "84174",
"Score": "1",
"body": "@Magus The 3 enum state names would be \"HasChanges\", \"NoChanges\", and \"DontKnowUntilItsRecalculated\"; so I prefer the `bool?`."
}
] | [
{
"body": "<p>in the first code block you have code that is unreachable</p>\n\n<pre><code>using (var broker = _documentBrokerDelegateFactory())\n{\n return broker.Value.HasSectionChanges(Model.Id);\n _hasChangesToReconcile = broker.Value.HasSectionChanges(Model.Id);\n}\n</code></pre>\n\n<p><code>hasChangesToReconcile</code> is never set to <code>broker.Value.HasSectionChanges(Model.Id)</code></p>\n\n<p>if you need that set, you should do it before the return.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:07:41.790",
"Id": "47980",
"ParentId": "47979",
"Score": "1"
}
},
{
"body": "<p>this code here can be simplified</p>\n\n<blockquote>\n<pre><code>if (!_hasChangesToReconcile.HasValue)\n{\n if (Model != null)\n {\n using (var broker = _documentBrokerDelegateFactory())\n {\n _hasChangesToReconcile = broker.Value.HasSectionChanges(Model.Id);\n }\n }\n else\n {\n _hasChangesToReconcile = false;\n }\n}\nreturn _hasChangesToReconcile.Value;\n</code></pre>\n</blockquote>\n\n<p>so that you return inside the if statement which is clearer to what is going on and performs less operations</p>\n\n<pre><code>if (!_hasChangesToReconcile.HasValue)\n{\n if (Model != null)\n {\n using (var broker = _documentBrokerDelegateFactory())\n {\n return broker.Value.HasSectionChanges(Model.Id);\n }\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n\n<p>if there was a loop here where there was more than one Change to reconcile I could see doing it the other way, but as is, this code is cleaner and more to the point.</p>\n\n<hr>\n\n<p>Same thing with this bit of code from the second set of code</p>\n\n<blockquote>\n<pre><code>if (_pageStatus == PageStatus.HasChanges)\n{\n if (Model != null)\n {\n using (var broker = _documentBrokerDelegateFactory())\n {\n _hasChanges = broker.Value.HasSectionChanges(Model.Id);\n }\n }\n}\nreturn _hasChanges;\n</code></pre>\n</blockquote>\n\n<p>you should just return <code>broker.Value.HasSectionChanges(Model.Id)</code> like this</p>\n\n<pre><code>if (_pageStatus == PageStatus.HasChanges)\n{\n if (Model != null)\n {\n using (var broker = _documentBrokerDelegateFactory())\n {\n return broker.Value.HasSectionChanges(Model.Id);\n }\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Something else that I noticed:</p>\n\n<p>both sets of code use a negative conditional inside the if statement of the Handle Method</p>\n\n<blockquote>\n<pre><code>public void Handle(PageSectionVersionsCreated message)\n{\n if (!message.ChangesApplyTo(Model))\n return;\n _pageStatus = PageStatus.HasChanges;\n NotifyOfPropertyChange(() => ItemType);\n _pageStatus = PageStatus.NoChanges;\n}\n</code></pre>\n</blockquote>\n\n<p>this should be rewritten to express this in terms of a positive.\nit should look like this:</p>\n\n<pre><code>public void Handle(PageSectionVersionsCreated message)\n{\n if (message.ChangesApplyTo(Model))\n {\n _pageStatus = PageStatus.HasChanges;\n NotifyOfPropertyChange(() => ItemType);\n _pageStatus = PageStatus.NoChanges;\n }\n}\n</code></pre>\n\n<p>since you aren't returning anything anyways, this is the more logical approach, and it looks way cleaner.</p>\n\n<hr>\n\n<p><strong>So I guess that you could say that they are both Verbose</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:21:54.863",
"Id": "47982",
"ParentId": "47979",
"Score": "2"
}
},
{
"body": "<p>The behaviour of the two fragments is slightly different:</p>\n\n<ul>\n<li>In the 2nd you <code>_pageStatus = PageStatus.NoChanges;</code> in the <code>Handle</code> method</li>\n<li>In the first you set a non-null value in the <code>HasChanges</code> method</li>\n</ul>\n\n<p>To make them equal the 2nd implementation should be like this:</p>\n\n<pre><code>public bool HasChanges()\n{\n if (_pageStatus == PageStatus.HasChanges)\n {\n _pageStatus = PageStatus.NoChanges;\n if (Model != null)\n {\n using (var broker = _documentBrokerDelegateFactory())\n {\n _hasChanges = broker.Value.HasSectionChanges(Model.Id);\n }\n }\n }\n return _hasChanges;\n} \n\npublic void Handle(PageSectionVersionsCreated message)\n{\n if (!message.ChangesApplyTo(Model))\n return;\n _pageStatus = PageStatus.HasChanges;\n NotifyOfPropertyChange(() => ItemType);\n}\n</code></pre>\n\n<hr>\n\n<p>Your two-state enum could be another boolean, e.g. <code>bool _resetHasChanges</code>.</p>\n\n<hr>\n\n<p>I find that having two related variables is more verbose than having a single <code>bool?</code> variable, especially when the 2nd enum variable is just tracking whether the first variable has an assigned value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:17:46.847",
"Id": "84192",
"Score": "0",
"body": "So you prefer enum more than the single bool?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:20:45.677",
"Id": "84194",
"Score": "0",
"body": "\"Verbose\" means \"too many words\" or \"saying something simple in a complicated way\". I prefer `bool?` because it's simpler, more expressive, and less likely to go wrong."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:39:20.937",
"Id": "47983",
"ParentId": "47979",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47983",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T14:48:38.950",
"Id": "47979",
"Score": "-7",
"Tags": [
"c#"
],
"Title": "Creating Enum vs Nullable bool for readability?"
} | 47979 |
<p>Here is my Python implementation of a simple fractions class:</p>
<pre class="lang-python prettyprint-override"><code>class frac:
def __init__(self, a,b):
self.a = a
self.b = b
def __add__(self, x):
return frac(self.a*x.b + self.b*x.a, self.b*x.b)
def __mul__(self, x):
return frac(self.a*x.a, self.b*x.b)
def __sub__(self, x):
return frac(self.a*x.b - self.b*x.a, self.b*x.b)
def __div__(self, x):
return frac(self.a*x.b, self.b*x.a)
def __repr__(self):
return "%s/%s"%(self.a,self.b)
</code></pre>
<p>It does addition OK:</p>
<pre><code>x = frac(1,3)
y = frac(1,2)
print x+ y
>> 5/6
</code></pre>
<p>However, it can miss the mark:</p>
<pre><code>x = frac(1,3)
y = frac(2,3)
print x+ y
>> 9/9
</code></pre>
<p>It seems if I run this library enough, the numerators and denominators will get very large. When should I start simplifying and where should I put that code?</p>
<p><hr>
There seems to be a fractions class already in Python, it this was instructive to put together. </p>
<p>My original goal was to allow for square roots of integers as well, but I will ask this in a separate question.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:54:20.767",
"Id": "85110",
"Score": "0",
"body": "You might consider [accepcting](http://codereview.stackexchange.com/help/someone-answers) the most helpful answer by clicking the check mark below the voting buttons."
}
] | [
{
"body": "<p>If you want to produce correct results, you should simplify after each operation. Euclid's algorithm is very fast in finding the GCD, and very simple to code. If you have a function like:</p>\n\n<pre><code>def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n</code></pre>\n\n<p>Then you could rewrite, e.g. you <code>__add__</code> method as:</p>\n\n<pre><code>def __add__(self, other):\n num = self.a * other.b + self.b * other.a\n den = self.b * other.b\n gcf = gcd(num, den)\n\n return frac(num // gcf, den // gcf)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T18:31:01.243",
"Id": "84208",
"Score": "1",
"body": "This simplification is needed in each function (and maybe even outside) so it should be a function of its own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T21:00:12.250",
"Id": "84235",
"Score": "0",
"body": "Euclid's algorithm may be fast compared with a naive approach, but if code reduces after every addition, subtraction, multiplication, or division, it will spend more time doing the reductions than it spends doing everything else combined."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T23:12:11.900",
"Id": "84246",
"Score": "1",
"body": "If you want correctness, you have to keep fractions in lowest terms. That the implementation in the standard Python library does exactly the same as @alexwlchan proposes, [see here](http://hg.python.org/cpython/file/2.7/Lib/fractions.py#l163), is a good indicator that this is the proper way of going about it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:23:11.807",
"Id": "47991",
"ParentId": "47984",
"Score": "4"
}
},
{
"body": "<p>I would probably put it right in your <code>__init__</code> method, which simplifies it every time a fraction is created (which includes after any operation).</p>\n\n<p>I disagree with Jaime's answer that you should do the simplification as part of the operation, as you'll have to copy/paste that code for every new operation.</p>\n\n<p>I’d write something like:</p>\n\n\n\n<pre><code>def gcd(x, y):\n while y:\n x, y = y, x % y\n return x\n\nclass Fraction(object):\n def __init__(self, numer, denom):\n cancel_factor = gcd(numer, denom)\n self.numer = numer / cancel_factor\n self.denom = denom / cancel_factor\n</code></pre>\n\n<p>A few other comments:</p>\n\n<ul>\n<li><p>Per <a href=\"http://legacy.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">PEP 8 on class names</a>, I'm using <code>Fraction</code> instead of <code>frac</code>.</p>\n\n<p>Also from PEP 8, I would put spaces around your multiplication operators.</p></li>\n<li><p>New style classes should inherit from <code>object</code> (as I've done above).</p></li>\n<li><p>I think <code>numer</code> and <code>denom</code> are better attribute names than <code>a</code> and <code>b</code>.</p></li>\n<li><p>The convention is to use <code>other</code> as the variable name in a method that takes two inputs, rather than <code>x</code>. For example:</p>\n\n\n\n<pre><code>def __add__(self, other):\n new_numer = self.numer * other.denom + self.denom * other.numer\n new_denom = self.denom * other.denom\n return Fraction(new_numer, new_denom)\n</code></pre></li>\n<li><p>I disagree with your use of <code>__repr__</code>. As a rule of thumb, <code>__repr__</code> should be something you can <code>eval()</code> to get back to that object; <code>__str__</code> is the human-readable object. See <a href=\"https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python\">difference between <code>__str__</code> and <code>__repr__</code></a> for more.</p>\n\n<p>Here's what I'd write:</p>\n\n\n\n<pre><code>def __repr__(self):\n return \"Fraction(%s, %s)\" % (self.numer, self.denom)\n\ndef __str__(self):\n return \"%s / %s\" % (self.numer, self.denom)\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:46:00.493",
"Id": "47995",
"ParentId": "47984",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "47995",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:48:14.380",
"Id": "47984",
"Score": "4",
"Tags": [
"python",
"integer"
],
"Title": "fractions data type -- when to reduce?"
} | 47984 |
<p>I want to print a lot of the same characters and I don't want to use a for loop and I'm also looking for a way to do it as less lines as possible. Even better I would like to be able to store that string in a static variable to use again and again.</p>
<p><strong>This is how I currently do it (ugly but at least no for loop):</strong></p>
<pre><code>System.out.println("----------------------------------------"
+ "----------------------------------------"
+ "----------------------------------------");
</code></pre>
<p>What's a better way (aesthetically wise)?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:05:12.990",
"Id": "84177",
"Score": "2",
"body": "SO dupe : http://stackoverflow.com/a/1235184/7602"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:08:54.823",
"Id": "84179",
"Score": "0",
"body": "@konijn didn't notice when I searched, sorry. Still though I think this is a more fitting question for this site now and it wouldn't be bad to have it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:14:06.800",
"Id": "84180",
"Score": "1",
"body": "Rolfl made the question viable, I learned something ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T01:34:02.787",
"Id": "84251",
"Score": "1",
"body": "In Python this is easily done with `'-'*80`, haha"
}
] | [
{
"body": "<p>I wouldn't call this ugly:</p>\n\n<blockquote>\n<pre><code>System.out.println(\"----------------------------------------\"\n + \"----------------------------------------\"\n + \"----------------------------------------\");\n</code></pre>\n</blockquote>\n\n<p>There's nothing wrong with it. It's perfectly clear what it does and it's efficient.</p>\n\n<p>If you print many lines like this then put the string in a variable so you can easily print as many times as you want:</p>\n\n<pre><code>private static final String DASHES = \"----------------------------------------\"\n + \"----------------------------------------\"\n + \"----------------------------------------\";\n</code></pre>\n\n<p>Maybe it's a hassle to create the string (for example, type \"-\" 10 times and copy and paste that 8 times) but you only have to do it once.</p>\n\n<p>If you <em>really</em> want to do it programmatically, then this seems a relatively nice way (without external libraries):</p>\n\n<pre><code>public static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\n</code></pre>\n\n<p>Or if you don't mind using <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#repeat%28java.lang.String,%20int%29\" rel=\"nofollow noreferrer\">StringUtils</a> (from commons-lang) then you might fancy this:</p>\n\n<pre><code>public static final String DASHES = StringUtils.repeat(\"-\", 80);\n</code></pre>\n\n<p>But like <a href=\"https://codereview.stackexchange.com/users/31503/rolfl\">@rolfl</a>, I don't think it's worth the effort to memorize such trickery. You can always just type the thing, there's nothing wrong with it. Also keep in mind <a href=\"http://en.wikipedia.org/wiki/Occam%27s_razor\" rel=\"nofollow noreferrer\">Occam's razor</a>: the simplest solution is often the best.</p>\n\n<p>See also this question on Stack Overflow:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string-in-java\">https://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string-in-java</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:12:28.490",
"Id": "84275",
"Score": "0",
"body": "I much prefer seeing `StringUtils.repeat(\"-\", 80)`, which more clearly and verifiably says: 80 hyphens/dashes. I've maintained projects with constants of 80 spaces that turned out *not* to be 80 spaces. Ne'er again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:06:54.907",
"Id": "47987",
"ParentId": "47986",
"Score": "11"
}
},
{
"body": "<p>Upvoted answers from <a href=\"https://stackoverflow.com/q/7107297/49942\">What is the easiest way to generate a String of n repeated characters?</a> are ...</p>\n\n<blockquote>\n<pre><code>int n = 80;\nchar[] chars = new char[n];\nArrays.fill(chars, '-');\nString result = new String(chars);\n</code></pre>\n</blockquote>\n\n<p>... and ...</p>\n\n<blockquote>\n <p>If you can, use <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html\" rel=\"nofollow noreferrer\">StringUtils</a> from Apache Commons <a href=\"http://commons.apache.org/lang/\" rel=\"nofollow noreferrer\">Lang</a>:</p>\n\n<pre><code>StringUtils.repeat(\"ab\", 3); //\"ababab\"\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:07:05.473",
"Id": "47989",
"ParentId": "47986",
"Score": "9"
}
},
{
"body": "<p>String constants in Java are very efficient. In practice, your code is very high-performing. The issue here is not about how fast the code runs, because, essentially, it cannot be run any faster than this.</p>\n\n<p>If you want to have more efficient code in terms of space, then the practical thing to do is to declare the value as a string constant, something like:</p>\n\n<pre><code>private static final String DASHES = \n \"----------------------------------------\"\n + \"----------------------------------------\"\n + \"----------------------------------------\";\n</code></pre>\n\n<p>And then, in your code, you just:</p>\n\n<pre><code>System.out.println(DASHES);\n</code></pre>\n\n<p>This will be just as fast, but the code is easier to read.</p>\n\n<p>If the one place where you declare the dashes is still unsightly, then you can compute the value using the other mechanisms shown in other answers... e.g. :</p>\n\n<pre><code>public static final String DASHES = new String(new char[80]).replace(\"\\0\", \"-\");\n</code></pre>\n\n<p>but that is overkill, and unnecessary.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>In your comments you raised the issue of having multiple different-length values. I would recommend that you create a constant for the longest one (whether you use the String-constant or some other generator method), and then do a <code>DASHES.substring(0, length)</code> on that to get the shorter constants...</p>\n\n<p>alternatively, I would consider a helper function as useful for this problem....</p>\n\n<pre><code>private static final String repeatChar(char c, int length) {\n char[] data = new char[length];\n Arrays.fill(data, c);\n return new String(data);\n}\n</code></pre>\n\n<p>and then your constants can be initialized with:</p>\n\n<pre><code>private static final String DASH80 = repeatChar('-', 80);\nprivate static final String SPACE40 = repeatChar(' ', 40);\n</code></pre>\n\n<p>etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:31:16.137",
"Id": "84183",
"Score": "0",
"body": "I would argue though that since performance is of no concern (initializing it just once is really no performance hit at all) the second way is better since it is literally one line (makes your code way more concise comparing to 4 lines) and also it is way easier to fine tune the number of characters one could want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:40:16.563",
"Id": "84184",
"Score": "3",
"body": "`new String(new char[80]).replace(\"\\0\", \"-\");` now if just something like that would exist in Brainf*ck..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:40:17.807",
"Id": "84185",
"Score": "0",
"body": "@SilliconTouch I would agree with the performance statement (the static initializer is not a performance problem). The real question is whether a string constant is easier to read than the alternatives. Importing a third-party library for a static initializer seems overkill, and the `new String(...).replace(...)` in itself is complicated too. I am on the fence. But, you should choose whichever is more readable to you. Given that you started with the constant string, it seems to me that is more maintainable for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:43:09.907",
"Id": "84186",
"Score": "1",
"body": "...and wish you were using C++, so the \"concise\" version could actually be somewhat concise, like: `std::string DASHES(80, '-');` :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:46:46.693",
"Id": "84187",
"Score": "0",
"body": "@rolfl It is true that it would not be worth to import a third-party library just for this reason but in my situation I am already using the library in that class so it is not an issue. I think I will prefer the second way because in my situation I am still fine tuning how many dashes I would need so it would be easier to use and for some reason it looks kinda easier to my eyes. Anyway though your answer was really helpful and made me realize things I did not see."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:47:29.367",
"Id": "84188",
"Score": "0",
"body": "@JerryCoffin I wish I was using C++ as well (I prefer it over Java) but unfortunately I am not.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:57:28.033",
"Id": "84189",
"Score": "0",
"body": "@SilliconTouch - I have added an edit, to show what I would typically do in my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T17:21:36.867",
"Id": "84195",
"Score": "0",
"body": "@rolfl I like the helper function now that I think about it. I will keep it in mind for the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T01:25:08.873",
"Id": "84250",
"Score": "0",
"body": "Why `repeatChar(char,int)` instead of `repeatStr(String,int)`? The latter is more general and if it's used in static initializers it's only going to be called once anyway"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T16:11:57.467",
"Id": "47990",
"ParentId": "47986",
"Score": "26"
}
},
{
"body": "<p>à la Java 8 :</p>\n\n<p>Say you have a </p>\n\n<pre><code>StringBuilder str = new StringBuilder(80);\nStream.generate(() -> '-').limit(80).forEach(str::append);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-06T14:36:37.637",
"Id": "292374",
"Score": "1",
"body": "OK, you've provided an alternative Code. Now, please add a Review, where you explain why your code is better than their code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-06T13:25:59.277",
"Id": "154583",
"ParentId": "47986",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47990",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T15:55:10.270",
"Id": "47986",
"Score": "17",
"Tags": [
"java"
],
"Title": "Printing 80 (or more) times the same character"
} | 47986 |
<p>Please help me to simplify the script below. It has a lot of variables and a lot of values are getting assigned to them. Can I make it simpler?</p>
<p>It has to calculate the percentage of 3 test forms: pre, post and final.</p>
<pre><code>DECLARE @tablefinal TABLE
(
RowID1 INT IDENTITY(1,1),
_CourseIDD int null,
_courseName varchar(1000) null,
_PRE INT NULL,
_POST int null,
_Feedback int null,
_final int NULL,
_Per decimal(18,2) null
)
DECLARE @rowCount INT,
@currentRow INT,
@@@CourseID INT,
@@@CourseName varchar (1000) --, @STUDENT_ID int = 1078
DECLARE @tableCourse TABLE
(
RowID INT IDENTITY(1,1),
_COURSE_ID INT NULL,
_COURSE_NAME varchar (1000) NULL
)
INSERT INTO @tableCourse (_COURSE_ID , _COURSE_NAME)
SELECT COURSE_ID,
COURSE_NAME
FROM DLC_COURSE C
WHERE COURSE_ID IN
(
SELECT CS.COURSESHD_COURSE_ID
FROM DLC_COURSE_SCHEDULE CS
INNER JOIN DLC_STUDENT_PAYMENT SP ON
CS.COURSESHD_ID = SP.STUDENT_PAYMENT_COURSESHD_ID
WHERE SP.STUDENT_PAYMENT_STUDENT_ID = @STUDENT_ID
AND CS.COURSESHD_STATUS=1
)
AND C.COURSE_STATUS=1
SELECT @rowCount = @@RowCount,
@currentRow = 1
WHILE @currentRow<=@rowCount
BEGIN
SELECT @@@CourseID = _COURSE_ID,
@@@CourseName = _COURSE_NAME
FROM @tableCourse
WHERE RowID = @currentRow
--do activity
--select @@@CourseID as CID, @@@CourseName as CN
SET @currentRow = @currentRow + 1
DECLARE @@Pre INT = 0,
@@Course INT = 0,
@@Post INT = 0,
@@Feedback INT = 0,
@@Final INT = 0
SELECT @@Pre = Count(*)
FROM DLC_ASSESSMENT_RESULT
WHERE RESULT_STUDENT_ID = @STUDENT_ID
AND RESULT_COURSE_ID = @@@CourseID
AND RESULT_STATUS='Pass'
AND RESULT_ASSESSMENT_TYPE=2
SELECT @@Course = ISNULL(COUNT(C.COURSE_ID),0)
FROM DLC_COURSE C
WHERE COURSE_ID IN
(
SELECT CS.COURSESHD_COURSE_ID
FROM DLC_COURSE_SCHEDULE CS
INNER JOIN DLC_STUDENT_PAYMENT SP
ON CS.COURSESHD_ID = SP.STUDENT_PAYMENT_COURSESHD_ID
WHERE SP.STUDENT_PAYMENT_STUDENT_ID = @STUDENT_ID
AND CS.COURSESHD_STATUS = 1
AND CS.COURSESHD_ENDDATE < GETDATE()
AND CS.COURSESHD_COURSE_ID = @@@CourseID
)
AND C.COURSE_STATUS=1
SELECT @@Post = Count(*)
FROM DLC_ASSESSMENT_RESULT
WHERE RESULT_STUDENT_ID = @STUDENT_ID
AND RESULT_COURSE_ID = @@@CourseID
AND RESULT_STATUS = 'Pass'
AND RESULT_ASSESSMENT_TYPE = 1
SELECT @@Feedback = Count(*)
FROM FEEDBACK_RESULTS
WHERE QUESTION_ID IN
(
SELECT QUESTION_ID
FROM FEEDBACK_QUESTIONS
WHERE QUESTION_COURSE = @@@CourseID
AND STATUS_ID = 1
)
AND EMP_ID = @STUDENT_ID
SELECT @@Final = COUNT(*)
FROM DLC_ASSESSMENT_RESULT
WHERE RESULT_STUDENT_ID = @STUDENT_ID
AND RESULT_COURSE_ID = @@@CourseID
AND RESULT_STATUS = 'Pass'
AND RESULT_ASSESSMENT_TYPE = 3
--declare @@Pre int= 0, @@Course int = 0 , @@Post int = 0, @@Feedback int = 0 , @@Final int = 0
DECLARE @per decimal (18,2)
--select isnull(@@Pre,0), isnull(@@Post,0) , isnull(@@Final,0)
SET @per = ((ISNULL(@@Pre,0) + ISNULL(@@Post,0) + ISNULL(@@Final,0) ) / 3.00 * 100)
INSERT INTO @tablefinal
SELECT ISNULL(@@Course,0) AS COURSE,
@@@CourseName,
ISNULL(@@Pre,0) AS PRE,
ISNULL(@@Post,0) AS Post,
ISNULL(@@Feedback,0) AS Feedback,
ISNULL(@@Final,0) AS Final,
@per
END
SELECT *
FROM @TABLEFINAL
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T01:16:56.413",
"Id": "88685",
"Score": "3",
"body": "Can you post your execution plan? This is a pretty complicated transaction and being we don't have access to the database it's a bit difficult to pinpoint where it could improve."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T15:13:07.173",
"Id": "88813",
"Score": "0",
"body": "is this going to be used in a report or application? I am sure that you are trying to do some of this stuff in the SQL that shouldn't be done in the SQL and should be done in the Report or Application."
}
] | [
{
"body": "<p>To sum up what this script does, just for the sake of simplicity:</p>\n\n<ol>\n<li><p>Declare a result set table variable <code>@tablefinal</code>.</p></li>\n<li><p>Declare variables for a counter, and for courses, and a commented out <code>@STUDENT_ID</code> (likely for testing purposes).</p></li>\n<li><p>Declare another result set table variable <code>@tableCourse</code> to hold course IDs and course names during the transaction. This seems to be to filter out courses with no students or not on the schedule. </p></li>\n<li><p>Set the counter start = 1 and end = total number of rows.</p></li>\n<li><p>Begin to cycle through <code>@tableCourse</code> at row 1 using <code>WHILE</code>. I noticed that <code>@student_id</code> is not declared or set (other than the instance which is commented out) even though it's being used in multiple <code>WHERE</code> clauses. May be worth your while to look into why it is that way. </p></li>\n<li><p>Count records for <code>@@pre</code> </p></li>\n<li><p>Count records for <code>@@courses</code></p></li>\n<li><p>Count records for <code>@@post</code></p></li>\n<li><p>Count records for <code>@@feedback</code></p></li>\n<li><p>Count records for <code>@@final</code></p></li>\n<li><p>Declare <code>@per</code> for precentage</p></li>\n<li><p>Calculate <code>@per</code> with a simple arithmetic operation</p></li>\n<li><p>Shove everything into your results table <code>@tablefinal</code> and then select from it to see the result set.</p></li>\n</ol>\n\n<p>To me this really seems like overkill, like a SQL programmer trying to show that he knows how to use variables. I think this could be much more simple, I won't rewrite the whole script but here are some ideas. If you decide to try that approach you will need to start from the ground up, you are welcome to post your new script in a new Code Review if you would like. </p>\n\n<pre><code>DECLARE @pre INT = (Count(*) FROM DLC_ASSESSMENT_RESULT WHERE RESULT_STATUS='Pass' AND RESULT_ASSESSMENT_TYPE=2); \n-- Repeat DECLARE (Count(*)) for @post, @feedback, @final \n\nSELECT \n C.COURSE_ID, \n C.COURSE_NAME, \n @pre AS 'Pre', \n @post AS 'Post', \n @feedback AS 'Feedback', \n @final AS 'Final', \n ((ISNULL(@Pre,0) + ISNULL(@@post,0) + ISNULL(@Final,0) ) / 3.00 * 100) AS 'Pre'\n\nFROM DLC_COURSE C \nWHERE COURSE_ID IN \n-- Taken from the script, seems to be the only important JOIN\n( \n SELECT CS.COURSESHD_COURSE_ID \n FROM DLC_COURSE_SCHEDULE CS \n INNER JOIN DLC_STUDENT_PAYMENT SP ON \n CS.COURSESHD_ID = SP.STUDENT_PAYMENT_COURSESHD_ID \n WHERE CS.COURSESHD_STATUS=1 \n) \nAND C.COURSE_STATUS=1 \n-- This will aggregate the result set by course\nGROUP BY C.COURSE_ID; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T17:07:54.763",
"Id": "51430",
"ParentId": "48001",
"Score": "3"
}
},
{
"body": "<p>You are working <em>way</em> too hard, because you are treating SQL like a programming language rather than the query language that it was meant to be. Describe the conditions you want, and let SQL Server's query optimizer figure out how to obtain the result set in the most efficient way possible.</p>\n\n<p>The whole thing should just be one query. Something like this, which probably contains some mistakes because there's no way for me to test, but you should get the idea.</p>\n\n<pre><code>WITH EndedCourses AS (\n SELECT CS.COURSESHD_COURSE_ID AS COURSE_ID\n FROM DLC_COURSE_SCHEDULE CS \n INNER JOIN DLC_STUDENT_PAYMENT AS SP\n ON CS.COURSESHD_ID = SP.STUDENT_PAYMENT_COURSESHD_ID\n WHERE\n CS.COURSESHD_STATUS=1\n AND CS.COURSESHD_ENDDATE < GETDATE()\n), Enrollment AS (\n SELECT SP.STUDENT_PAYMENT_STUDENT_ID AS STUDENT_ID\n , COURSE_ID\n , COURSE_NAME\n FROM DLC_COURSE C\n WHERE C.COURSE_STATUS = 1\n), PassCount AS (\n SELECT RESULT_STUDENT_ID AS STUDENT_ID\n , RESULT_COURSE_ID AS COURSE_ID\n , COUNT(CASE RESULT_ASSESSMENT_TYPE WHEN 2 THEN 1) AS PRE\n , COUNT(CASE RESULT_ASSESSMENT_TYPE WHEN 1 THEN 1) AS POST\n , COUNT(CASE RESULT_ASSESSMENT_TYPE WHEN 3 THEN 1) AS FINAL\n FROM DLC_ASSESSMENT_RESULT\n WHERE RESULT_STATUS = 'Pass' \n GROUP BY RESULT_STUDENT_ID, RESULT_COURSE_ID\n), Feedback AS (\n SELECT FEEDBACK_RESULTS.EMP_ID AS STUDENT_ID\n , FEEDBACK_QUESTIONS.QUESTION_COURSE AS COURSE_ID\n , COUNT(*) AS FEEDBACK_COUNT\n FROM FEEDBACK_RESULTS\n INNER JOIN FEEDBACK_QUESTIONS\n ON FEEDBACK_QUESTIONS.QUESTION_ID = FEEDBACK_RESULTS.QUESTION_ID\n WHERE FEEDBACK_QUESTIONS.STATUS_ID = 1\n GROUP BY FEEDBACK_RESULTS.EMP_ID, FEEDBACK_QUESTIONS.QUESTION_COURSE\n)\nSELECT EndedCourses.COURSE_ID AS COURSE_ID\n , COURSE_NAME\n , PRE\n , POST\n , FEEDBACK_COUNT\n , FINAL\n , CAST((PRE + POST + FINAL) / 3.00 * 100 AS DECIMAL(18, 2)) AS PER\n FROM EndedCourses\n INNER JOIN Enrollment\n ON Enrollment.COURSE_ID = EndedCourses.COURSE_ID\n INNER JOIN PassCount\n ON PassCount.STUDENT_ID = Enrollment.STUDENT_ID\n ON PassCount.COURSE_ID = Enrollment.COURSE_ID\n INNER JOIN Feedback\n ON Feedback.STUDENT_ID = Enrollment.STUDENT_ID\n ON Feedback.COURSE_ID = Enrollment.COURSE_ID\n WHERE Enrollment.STUDENT_ID = @STUDENT_ID;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T21:33:54.897",
"Id": "88870",
"Score": "0",
"body": "I think this should be marked as the best answer. Nice and clean, easy to understand and none of those nasty variables and `WHILE` loops."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T21:12:15.210",
"Id": "51446",
"ParentId": "48001",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T08:55:36.313",
"Id": "48001",
"Score": "3",
"Tags": [
"sql",
"sql-server"
],
"Title": "Calculating percentage of 3 test forms"
} | 48001 |
<p>I am building a new system that is using some tables from an old system.</p>
<p>For each user on this new system, I need to go to the old system and total up their sales. Currently it takes between 2-5 minutes to load.</p>
<pre><code>public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId)
{
string teamGoal = "";
List<ProPit_User> lstProPit_User = new List<ProPit_User>();
using (ProsPitEntities db = new ProsPitEntities())
{
// Find the team
Team team = db.Teams.Where(x => x.teamID == teamId).FirstOrDefault();
if (team != null)
{
// Grab team goal
teamGoal = Convert.ToString(team.goal);
}
// Make a list of all users who are on the team
lstProPit_User = db.ProPit_User.Where(x => x.teamID == teamId).ToList();
}
List<DailyTeamGoal> lstDailyTeamGoal = new List<DailyTeamGoal>();
using (TEntities db = new TEntities())
{
//have to get every day of the month
DateTime dt = DateTime.Now;
int days = DateTime.DaysInMonth(dt.Year, dt.Month);
decimal orderTotal = 0m;
for (int day = 1; day <= days; day++)
{
// For every day in the month total the sales
DailyTeamGoal dtg = new DailyTeamGoal();
dtg.Date = day.ToString(); //dt.Month + "/" + day; + "/" + dt.Year;
dtg.TeamGoal = teamGoal;
decimal orderTotalRep = 0m;
foreach (var propit_User in lstProPit_User)
{
DateTime dtStartDate = Convert.ToDateTime(dt.Month + "/" + day + "/" + dt.Year);
DateTime dtEndDate = dtStartDate.AddDays(1);
var lstorderTotalRep = (from o in db.Orders
where o.DateCompleted >= dtStartDate
where o.DateCompleted <= dtEndDate
where (o.Status == 1 || o.Status == 2)
where o.Kiosk != 0
where o.SalesRepID == propit_User.SalesRepID
orderby o.OrderTotal descending
select o.OrderTotal).ToList();
foreach (var item in lstorderTotalRep)
{
//orderTotalRep =+ item;
orderTotalRep += item;
}
}
orderTotal += orderTotalRep;
dtg.DailyTotal = orderTotal;
lstDailyTeamGoal.Add(dtg);
}
}
return lstDailyTeamGoal;
}
</code></pre>
<p>The above code will use my site to find the <code>teamID</code> the logged in person is on. It will then find all members who are on that team. For each member it finds it will calculate the total sales and then spit me back a list. Any way to speed this up?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:20:36.323",
"Id": "84219",
"Score": "2",
"body": "Is there an index on `Orders` including columns `DateCompleted`, `Status`, `Kiosk` and `SalesRepID`? How many rows are we talking about? Have you profiled anything to see where the bottleneck might be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T21:12:20.407",
"Id": "84237",
"Score": "0",
"body": "I have not profiles it yet. I found out the bottle neck, it isn't the query itself. The problem was for each day of the month I was running a single query to sum the total sales per user found on the team. Which came out to be around 900+ queries being ran. I've knocked it down to about 30 and is currently at least somewhat acceptable on speed around 30 seconds. Still trying to improve."
}
] | [
{
"body": "<p>I won't comment about the fact that this is a <code>static</code> method in what's possibly a <code>static</code> "helper" class and that it would be much prettier in a <em>service</em> class <em>instance</em>... but I just did.</p>\n<p>The method is doing way too many things.</p>\n<blockquote>\n<p><strong>Thing one</strong>:</p>\n<pre><code>// Make a list of all users who are on the team\n</code></pre>\n</blockquote>\n<p>That's one method. But there's a twist: you not only need all users on the team, but also the <code>teamGoal</code> figure. I'd encapsulate that in its own class:</p>\n<pre><code>public class TeamGoalAndUsersResult // todo: rename this class\n{\n public IEnumerable<ProPit_User> Users { get; private set; }\n public string Goal { get; private set; }\n\n public TeamGoalAndUsersResult(string goal, IEnumerable<ProPit_User> users)\n {\n Users = users;\n Goal = goal;\n }\n}\n</code></pre>\n<p>And then you can write a method/function that will return that type:</p>\n<pre><code>private TeamGoalAndUsersResult GetTeamGoalAndUsers(int teamId)\n{\n using (ProsPitEntities db = new ProsPitEntities())\n {\n var goal = string.Empty;\n var team = db.Teams.SingleOrDefault(x => x.teamID == teamId);\n if (team != null)\n {\n goal = Convert.ToString(team.goal);\n }\n\n var users = db.ProPit_User.Where(x => x.teamID == teamId).ToList();\n return new TeamGoalAndUsersResult(goal, users);\n }\n}\n</code></pre>\n<hr />\n<blockquote>\n<p><strong>Performance Issue</strong>:</p>\n<pre><code> var lstorderTotalRep = (from o in db.Orders\n where o.DateCompleted >= dtStartDate\n where o.DateCompleted <= dtEndDate\n where (o.Status == 1 || o.Status == 2)\n where o.Kiosk != 0\n where o.SalesRepID == propit_User.SalesRepID\n orderby o.OrderTotal descending\n select o.OrderTotal).ToList();\n\n foreach (var item in lstorderTotalRep)\n {\n //orderTotalRep =+ item;\n orderTotalRep += item;\n }\n</code></pre>\n</blockquote>\n<p>You're doing all the computation on the client. I'd take a wild guess and say that this is where your bottleneck is. Do you <em>really</em> need to <strong>select</strong>, <strong>sort</strong> and <strong>materialize</strong> all orders just to sum up <code>OrderTotal</code>?</p>\n<pre><code>var total = db.Orders.Where(o => o.DateCompleted >= dtStartDate\n && o.DateCompleted <= dtEndDate\n && (o.Status == 1 || o.Status == 2)\n && o.Kiosk != 0\n && o.SalesRepID == user.SalesRepID)\n .Sum(o => o.OrderTotal);\n\norderTotal += total;\ndtg.DailyTotal = orderTotal;\ndailyTeamGoals.Add(dtg);\n</code></pre>\n<p>The above doesn't sort anything, has the same criterion and performs everything on the server side, without materializing every order in the way. Also I believe if the table has all the fields used in the WHERE, in an index (guts tell me "especially <code>DateCompleted</code>"), that would further help the server-side processing, but that's something you're probably better off finding out with a profiler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:15:28.563",
"Id": "84227",
"Score": "1",
"body": "+1 I definitely consider the ordering and ToList() the first point of call for bottle necking here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:27:29.177",
"Id": "84308",
"Score": "0",
"body": "All that extra stuff was not necessary so I removed it and just summed it up now. I also just sum up the complete teams sales instead of each users sales. It also ran each day of the month, even if it was the first day of the month so I forced it to only run for the days that have passed + current day which sped it up to very fast speed still around 30 seconds toward the end of the month however."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:56:38.767",
"Id": "84313",
"Score": "0",
"body": "@JamesWilson feel free to post your updated code as a new question, I for one, would be happy to review it and see what else can be fine-tuned ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T19:58:33.940",
"Id": "84366",
"Score": "1",
"body": "@Mat'sMug I posted the new code under a new question for review if interested. http://codereview.stackexchange.com/questions/48082/looking-to-speed-up-this-method"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:45:52.910",
"Id": "48005",
"ParentId": "48002",
"Score": "3"
}
},
{
"body": "<p>I can't shake this feeling that you could use grouping to get the same result of totaling up the sales of the month hence effectively doing all of the hard work in SQL and limiting the amount of queries required.</p>\n\n<p>Utitlising <a href=\"https://codereview.stackexchange.com/users/23788/mats-mug\">Matt's</a> excellent answer here is something I've come up with. </p>\n\n<pre><code>public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId)\n{ \n // utitilising the method suggested by Mats Mug below\n var team = GetTeamGoalAndUsers(teamId); \n var dailySales = GetTeamDailySalesTotal(team.Users);\n\n return dailySales.Select(p => new DailyTeamGoal\n {\n Date = p.Key,\n TeamGogal = team.Goal,\n DailyTotal = p.Value\n });\n}\n\nprivate static Dictionary<int, int> GetTeamDailySalesTotal(IEnumerable<ProPit_User> teamMembers)\n{\n // Date ranges\n DateTime now = DateTime.Now;\n DateTime dtStartDate = new DateTime(now.Year,now.Month,1);\n int numberOfDaysInMonth = dtStartDate.DaysInMonth();\n DateTime dtEndDate = new DateTime(now.Year,now.Month,numberOfDaysInMonth); \n\n // ensure every day has at least an entry for it even if there are 0 sales on that day\n var sales = InitialiseSalesPerMonth(numberOfDaysInMonth);\n\n // Get the total sum of the daily sales for each rep\n var dailySalesTotal = (from o in orders\n where o.DateCompleted >= dtStartDate\n && o.DateCompleted <= dtEndDate\n && (o.Status == 1 || o.Status == 2)\n && o.Kiosk != 0\n && teamMemberIds.Any(m =>m == o.SalesRepID)\n group o by o.DateCompleted.Day into s\n select new {\n Day = s.Key,\n OrderTotal = s.Sum(p => p.OrderTotal)\n }).ToList();\n\n dailySalesTotal.Foreach(p => sales[p.Day] = p.OrderTotal); \n\n return sales;\n}\n\n private Dictionary<int, int> InitialiseSalesPerMonth(int numberOfDays)\n {\n var sales = new Dictionary<int, int>();\n\n for(int i = 1; i <= numberOfDays; i++)\n {\n sales.Add(i, 0);\n }\n\n return sales;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T22:38:13.743",
"Id": "48014",
"ParentId": "48002",
"Score": "2"
}
},
{
"body": "<p>As a rough rule of thumb, I assume that performance is as follows:</p>\n\n<ul>\n<li>Fastest: calling methods in my own process</li>\n<li>Fastish: calling methods in my run-time library (e.g. the .NET framework)</li>\n<li>Slowish: calling O/S methods for I/O</li>\n<li>Slowest: using the network to call methods on another machine</li>\n</ul>\n\n<p>I assume that your function is slow because you are making hundreds of SQL calls:</p>\n\n<ul>\n<li>For each team member</li>\n<li>For each day in the month</li>\n</ul>\n\n<p>There may be two ways to speed this up:</p>\n\n<ol>\n<li><p>For each day, select the orders for all team members.</p>\n\n<p>The culprit is the <code>where o.SalesRepID == propit_User.SalesRepID</code> clause which selects for one team member.</p>\n\n<p>I guess that translates to a SQL expression like <code>WHERE Orders.SalesRepID = 3</code>. </p>\n\n<p>Instead you want something which translates to a <code>WHERE ... IN</code> expression (where you pass in the IDs of all team members); or, do a <code>JOIN</code> against the teams table.</p></li>\n<li><p>The other thing you could try to do is select all data for the whole month (using one SQL SELECT statement) into a cache of the data in your own process.</p>\n\n<p>This is possible using e.g. the <code>DataSet</code> and <code>DataTable</code> classes in ADO.NET (I don't know whether/how you can do it using the Entity Framework).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T01:24:00.553",
"Id": "48019",
"ParentId": "48002",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48005",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:11:51.677",
"Id": "48002",
"Score": "5",
"Tags": [
"c#",
"performance",
"linq",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Calculating total sales from each member"
} | 48002 |
<p>I use 'GROUP_CONCAT' to get comma separated lists of a person's educational background. Included in those lists are the type of degree, major, issuing establishment, and year received. <code>degreeType</code> is a required field and cannot empty. Prior to looping, I split the lists into arrays, like so:</p>
<pre><code>$degreeType = explode(",", $degreeType);
$major = explode(",", $major);
$issuingEstablishment = explode(",", $issuingEstablishment);
$yearReceived = explode(",", $yearReceived);
</code></pre>
<p>I can then do a <code>foreach</code> loop and echo out the information returned. However, since <code>explode()</code> returns an array, even if it's empty, I have to check it first before starting the <code>foreach</code>. As shown below:</p>
<pre><code>$counter = 0;
//echo out education
if($degreeType[0]!=""){
foreach($degreeType as $dType) {
if($counter == 0) $info .= "<h2>Educational Background</h2><ul>";
$info .= "<li>$dType - ";
$info .= ($major[$counter]!="") ? "$major[$counter], " : "";
$info .= $issuingEstablishment[$counter];
$info .= ($yearReceived[$counter]!="") ? ", $yearReceived[$counter]" : "";
$info .= "</li>";
$counter++;
}
$info .= "</ul>";
}
</code></pre>
<p>Alternatively, I could run a check prior to separating the lists. Either solution seems inelegant. Is there a cleaner/faster/better way to split the lists and loop through them, but only if they actually contain information? Initially I was going to dabble with using an <code>object</code>, but <code>mysqli</code> doesn't support that with prepared statements. Any advice is much appreciated! </p>
| [] | [
{
"body": "<p>Your script is alright, there are just some minor issues:</p>\n\n<p>1.) If string is enclosed inside <code>\"\"</code> then PHP interpreter checks whether there are some variables or not, if string is enclosed inside <code>''</code> PHP interpreter does not check it. </p>\n\n<p>2.) You forgot to declare <code>$info</code> variable, it is always good to declare your variables before doing some operations on them like <code>.=</code>.</p>\n\n<p>3.) I don't like using this shorter syntax, because it can be source of bugs which are hard to find, in my opinion it is usually better to use <code>{}</code>:</p>\n\n<p><code>if($counter == 0) $info .= \"<h2>Educational Background</h2><ul>\";</code></p>\n\n<p>4.) You don't need to repeat <code>$info .=</code> on every line, it can be replaced by <code>.</code>.</p>\n\n<p>I rewrote the script in respect to previously mentioned points:</p>\n\n<pre><code>$degreeType = explode(',', $degreeType);\n$major = explode(',', $major);\n$issuingEstablishment = explode(',', $issuingEstablishment);\n$yearReceived = explode(',', $yearReceived);\n\n$counter = 0;\n$info = '';\nif($degreeType[0] != ''){\n foreach($degreeType as $dType) {\n if(!$counter) {\n $info .= '<h2>Educational Background</h2><ul>';\n }\n\n $info .= \"<li>$dType - \"\n . (($major[$counter] != '') ? \"$major[$counter], \" : '')\n . $issuingEstablishment[$counter]\n . (($yearReceived[$counter] != '') ? \", $yearReceived[$counter]\" : '')\n . '</li>'\n ;\n\n $counter++;\n }\n $info .= \"</ul>\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T20:04:57.370",
"Id": "84225",
"Score": "0",
"body": "Oops! I forgot to copy-n-paste the `info` initialization, but it was in the original. Thanks for the tips, incorporating them now!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:48:18.027",
"Id": "48006",
"ParentId": "48003",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48006",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T19:14:21.557",
"Id": "48003",
"Score": "3",
"Tags": [
"php",
"array"
],
"Title": "Is there a more elegant solution than this spaghetti code without completely revamping the whole page?"
} | 48003 |
<p>I wrote a Player package in Go. It builds correctly, but I would love a review on what I did and did not do "the Go way". I'm new to coding in the language, although I've gotten about halfway through Ivo Balbaert's "The Way To Go".</p>
<p>The code consists of a struct and a bunch of setters and getters for the struct. </p>
<pre><code>package Player
import (
"math/rand"
"time"
)
type Player struct {
name string
race string
id int64
pos Position
facing int64
health int64
wpn_id int64 // Weapon id
is_buf bool // Has buff
buf_mt float64 // Buff multiplier
}
type Position map[int64]int64
func (P *Player) SetPlayer(name string, race string) *Player {
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
P.name = name
P.race = race
P.id = rand.Int63()
P.pos = Position{0: 0}
P.facing = 0
P.health = 100
P.wpn_id = 0
P.is_buf = false
P.buf_mt = 0.0
return P
}
func (P *Player) GetPlayer() *Player {
return P
}
func (P *Player) SetPosition(x int64, y int64) {
P.pos = Position{x: y}
}
func (P *Player) GetPosition() Position {
return P.pos
}
func (P *Player) SetFacing(direction int64) {
P.facing = direction
}
func (P *Player) GetFacing() int64 {
return P.facing
}
func (P *Player) SetHealth(amount int64, direction string) {
if direction == "down" {
P.health = P.health - amount
} else {
P.health = P.health + amount
}
}
func (P *Player) GetHealth() int64 {
return P.health
}
func (P *Player) SetWeaponId(weapon_id int64) {
P.wpn_id = weapon_id
}
func (P *Player) GetWeaponId() int64 {
return P.wpn_id
}
func (P *Player) SetIsBuffed(is_buff bool) {
P.is_buf = is_buff
}
func (P *Player) GetIsBuffed() bool {
return P.is_buf
}
func (P *Player) SetBuffMultiplier(multiplier float64) {
P.buf_mt = multiplier
}
func (P *Player) GetBuffMultiplier() float64 {
return P.buf_mt
}
</code></pre>
| [] | [
{
"body": "<p>This is fairly bare-bones as far as packages go, but there are thing that can be improved here.</p>\n\n<p>Firstly, to create a player object, someone is going to need to do the equivalent of:</p>\n\n<pre><code>player := new(Player)\nplayer.SetPlayer(...)\n</code></pre>\n\n<p>This is a bit annoying. I'd much rather create a function that constructs a fully initialised <code>Player</code>:</p>\n\n<pre><code>func NewPlayer(name string, race string) *Player {\n ...\n}\n</code></pre>\n\n<p>We can also use some syntactic sugar to shorten the actual initialisation:</p>\n\n<pre><code>func NewPlayer(name_ string, race_ string) *Player {\n rand := rand.New(rand.NewSource(time.Now().UnixNano()))\n return &Player{name: name_, race: race_, id: rand.Int63(), pos: Position{0: 0}, \n facing: 0, health: 100, wpn_id: 0, is_buf: false, buf_mt: 0.0}\n}\n</code></pre>\n\n<p>I don't really understand what the point of the function:</p>\n\n<pre><code>func (P *Player) GetPlayer() *Player {\n return P\n}\n</code></pre>\n\n<p>is supposed to be. It takes a player, and returns the same player - a no-op.</p>\n\n<p>I'm also not sure why you use a <code>map</code> for position, when 2 integers will do:</p>\n\n<pre><code>type Position struct {\n x int64\n y int64\n}\n</code></pre>\n\n<p>In the following function:</p>\n\n<pre><code>func (P *Player) SetHealth(amount int64, direction string) {\n if direction == \"down\" {\n P.health = P.health - amount\n } else {\n P.health = P.health + amount\n }\n}\n</code></pre>\n\n<p><code>direction</code> could be an enum-like type:</p>\n\n<pre><code>type Direction uint8\n\nconst (\n DOWN Direction = iota,\n UP Direction = iota\n)\n\nfunc (P *Player) SetHealth(amount int64, direction Direction) {\n switch direction {\n case DOWN: P.health -= amount\n case UP: P.health += amount\n default: panic(\"Unknown direction type!\")\n }\n}\n</code></pre>\n\n<p>Although this is overkill here, and I'd go with @WinstonEwert's suggestion and just pass in either a positive or negative number that can be used to modify the player health.</p>\n\n<p>A type with a lot of getters and setters doesn't really fit with the Go \"mantra\". In fact, I'd consider this a bit of an anti-pattern in most languages - if you're going to write both <code>Get</code> and <code>Set</code> functions, without really checking arguments or enforcing constraints, you may as well just give direct access to the underlying variable. This is debatable, however, and I know some people will disagree, so I'll won't belabour the point. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:19:34.633",
"Id": "84673",
"Score": "1",
"body": "You think that health is going to do something beyond up and down? Personally, I'd have the caller pass negative numbers if they wanted to decrease health."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:14:13.723",
"Id": "84866",
"Score": "0",
"body": "Thank you Yuushi. I'm new to coding in Go, coming from Python/PHP/Java land, so I'm still learning to code the Go \"way\". This isn't a package ever meant to go into production code or whatnot, simply a learning exercise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T01:22:29.623",
"Id": "84907",
"Score": "0",
"body": "@WinstonEwert Heh, whoops, I really didn't read that closely enough - for some reason I read that as an actual setting of the player direction, not health."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:49:22.630",
"Id": "48243",
"ParentId": "48012",
"Score": "4"
}
},
{
"body": "<pre><code>func (P *Player) SetPlayer(name string, race string) *Player {\n rand := rand.New(rand.NewSource(time.Now().UnixNano()))\n</code></pre>\n\n<p>You should do this once at the beginning your program, and pass it around to where you need the random number generator. For almost all applications, you should only seed the random number generator once, not each time you use it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:18:25.887",
"Id": "48248",
"ParentId": "48012",
"Score": "3"
}
},
{
"body": "<p>Switch</p>\n\n<pre><code>package Player\n</code></pre>\n\n<p>to</p>\n\n<pre><code>package player\n</code></pre>\n\n<p>Effective Go's recommendations are: \"By convention, packages are given lower case, single-word names; there should be no need for underscores or mixedCaps\". <a href=\"http://golang.org/doc/effective_go.html#package-names\" rel=\"nofollow\">http://golang.org/doc/effective_go.html#package-names</a></p>\n\n<p>Switch</p>\n\n<pre><code>func NewPlayer(name string, race string) *Player \n</code></pre>\n\n<p>to</p>\n\n<pre><code>func New(name string, race string) *Player \n</code></pre>\n\n<p>Any code referencing your package already will be using player. in front, so having player.New(...) is a little tighter than player.NewPlayer(...). If your package had several constructors it would make sense to keep it NewPlayer, but for a single purpose package, switching to New is preferred. <a href=\"http://golang.org/doc/effective_go.html#package-names\" rel=\"nofollow\">http://golang.org/doc/effective_go.html#package-names</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T17:53:15.363",
"Id": "88843",
"Score": "0",
"body": "Thank you. I'm used to writing `class Player` for example in PHP so you could say I got used to that"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T14:33:17.887",
"Id": "51413",
"ParentId": "48012",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T21:04:57.593",
"Id": "48012",
"Score": "5",
"Tags": [
"beginner",
"game",
"go"
],
"Title": "Wrote a package in Go. What did I do wrong? What did I do right?"
} | 48012 |
<p>I'm pretty new to Go, and I do not know the best or idiomatic ways to do most of the stuff, so I'd appreciate feedback on how to make my code better, faster or more idiomatic.</p>
<p>My program is a set of methods/functions to parse an infix notation expression then convert it to reverse polish notation using Dijkstra's Shunting-Yard algorithm and then finally solve it, so far it supports basic operations "+ - / * ^", nested parentheses & basic trig functions.</p>
<p>File 1:</p>
<pre><code>package gocalc
import (
"strings"
"unicode"
)
type Token struct {
Type TokenType
Value string
}
type TokenType int
const (
Number TokenType = iota
Operator
LParen
RParen
fnction
)
// fnction Parse converts an expression into a stack of tokens
func Parse(input string) (tokens Stack) {
var cont string
var fn bool
for _, v := range input {
val := string(v)
if unicode.IsDigit(v) || val == "." {
cont += val
} else if unicode.IsLetter(v) || strings.Contains("[]", val) {
if val == "]" {
cont += val
fn = false
} else {
cont += val
fn = true
}
} else if strings.Contains("+-*/^", val) {
if fn {
cont += val
} else {
if cont != "" {
if unicode.IsLetter(rune(cont[0])) {
tokens.Push(Token{fnction, cont})
} else {
tokens.Push(Token{Number, cont})
}
cont = ""
}
tokens.Push(Token{Operator, val})
}
} else if strings.Contains("()", val) {
if fn {
cont += val
} else {
if cont != "" {
if unicode.IsLetter(rune(cont[0])) {
tokens.Push(Token{fnction, cont})
} else {
tokens.Push(Token{Number, cont})
}
cont = ""
}
if val == "(" {
tokens.Push(Token{LParen, val})
} else {
tokens.Push(Token{RParen, val})
}
}
}
}
if cont != "" {
if unicode.IsLetter(rune(cont[0])) {
tokens.Push(Token{fnction, cont})
} else {
tokens.Push(Token{Number, cont})
}
}
return tokens
}
</code></pre>
<p>File 2:</p>
<pre><code>package gocalc
import (
"math"
"strconv"
"strings"
)
var oprData = map[string]struct {
prec int
asoc bool // true = right // false = left
fx func(x, y float64) float64
}{
"^": {4, true, func(x, y float64) float64 { return math.Pow(x, y) }},
"*": {3, false, func(x, y float64) float64 { return x * y }},
"/": {3, false, func(x, y float64) float64 { return x / y }},
"+": {2, false, func(x, y float64) float64 { return x + y }},
"-": {2, false, func(x, y float64) float64 { return x - y }},
}
var fnData = map[string]func(x float64) float64{
"Cos": func(x float64) float64 { return math.Cos(x) },
"Sin": func(x float64) float64 { return math.Sin(x) },
"Tan": func(x float64) float64 { return math.Tan(x) },
"Acos": func(x float64) float64 { return math.Acos(x) },
"Asin": func(x float64) float64 { return math.Asin(x) },
"Atan": func(x float64) float64 { return math.Atan(x) },
}
// Function ToRPN converts a stack of tokens from infix notation to Reverse Polish Notation
func ToRPN(tokens Stack) Stack {
output := Stack{}
ops := Stack{}
for _, v := range tokens.Values {
switch {
case v.Type == Operator:
for !ops.IsEmpty() {
val := v.Value
top := ops.Peek().Value
if (oprData[val].prec <= oprData[top].prec && oprData[val].asoc == false) ||
(oprData[val].prec < oprData[top].prec && oprData[val].asoc == true) {
output.Push(ops.Pop())
continue
}
break
}
ops.Push(v)
case v.Type == LParen:
ops.Push(v)
case v.Type == RParen:
for i := ops.Length() - 1; i >= 0; i-- {
if ops.Values[i].Type != LParen {
output.Push(ops.Pop())
continue
} else {
ops.Pop()
break
}
}
default:
output.Push(v)
}
}
if !ops.IsEmpty() {
for i := ops.Length() - 1; i >= 0; i-- {
output.Push(ops.Pop())
}
}
return output
}
// Function SolveRPN returns the result of the Reverse Polish Notation expression
func SolveRPN(tokens Stack) float64 {
stack := Stack{}
for _, v := range tokens.Values {
if v.Type == Number {
stack.Push(v)
} else if v.Type == Function {
stack.Push(Token{Number, SolveFunction(v.Value)})
} else if v.Type == Operator {
f := oprData[v.Value].fx
var x, y float64
y, _ = strconv.ParseFloat(stack.Pop().Value, 64)
x, _ = strconv.ParseFloat(stack.Pop().Value, 64)
result := f(x, y)
stack.Push(Token{Number, strconv.FormatFloat(result, 'f', 12, 64)})
}
}
out, _ := strconv.ParseFloat(stack.Values[0].Value, 64)
return out
}
func SolveFunction(input string) string {
var fArg float64
fType := strings.TrimRight(input, "[.]0123456789+-/*^()")
args := strings.TrimLeft(strings.TrimRight(input, "]"), fType+"[")
if !strings.ContainsAny(args, "+ & * & - & / & ^") {
fArg, _ = strconv.ParseFloat(args, 64)
} else {
stack := Parse(args)
stack = ToRPN(stack)
fArg = SolveRPN(stack)
}
return strconv.FormatFloat(fnData[fType](fArg), 'f', 12, 64)
}
</code></pre>
<p>File 3:</p>
<pre><code>package gocalc
type Stack struct {
Values []Token
}
// Function Pop removes the top token of the stack and returns its value
func (stack *Stack) Pop() (i Token) {
if len(stack.Values) == 0 {
return
}
i = stack.Values[len(stack.Values)-1]
stack.Values = stack.Values[:len(stack.Values)-1]
return
}
// Fuction Push adds a token to the top of the stack
func (stack *Stack) Push(i ...Token) {
stack.Values = append(stack.Values, i...)
}
// Function Peek returns the token at the top of the stack
func (stack *Stack) Peek() Token {
return stack.Values[len(stack.Values)-1]
}
// Function IsEmpty check if there are any tokens in the stack
func (stack *Stack) IsEmpty() bool {
return len(stack.Values) == 0
}
// Function Length returns the amount of tokens in the stack
func (stack *Stack) Length() int {
return len(stack.Values)
}
</code></pre>
<p>The code can be found <a href="https://github.com/marcmak/gocalc" rel="nofollow">on GitHub</a>.</p>
<p>I plan to further develop the code and to eventually add equation solving and more advanced features.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T22:48:50.303",
"Id": "48015",
"Score": "4",
"Tags": [
"optimization",
"parsing",
"converting",
"go",
"math-expression-eval"
],
"Title": "Parsing an infix notation expression and converting to reverse polish notation"
} | 48015 |
<p>Here is my solution to Project Euler 23: Non Abundant Sums. I know I'm doing the <code>Divisors</code> function brute force, but I can't seem to get it to work any other way. Any improvements are welcome.</p>
<pre><code>#include <iostream>
#include <vector>
//Calculates divisors
void Divisors(unsigned number, std::vector<unsigned> &result){
for(unsigned a = 1; a < number; a++){
if(number % a == 0){
result.push_back(a);
}
}
}
//Calls for divisors and adds them
unsigned SumOfDivisors(unsigned number){
unsigned result = 0;
std::vector<unsigned> divisors;
Divisors(number, divisors);
for(unsigned a = 0; a < divisors.size(); a++){
if(divisors[a] < number)
result += divisors[a];
}
return result;
}
//Calls calculates the sum of divisors to see if it is Abundant
bool IsAbundant(unsigned number){
if(SumOfDivisors(number)> number){
return true;
}
else{
return false;
}
}
//pushes back abundant numbers
void Abundant(unsigned limit, std::vector<unsigned> &abunNumbers){
for(unsigned a = 1; a < limit; a++){
if(IsAbundant(a)){
abunNumbers.push_back(a);
}
}
}
//Find's all number's that are the sum of two abundant numbers
void SumOfAbundant(unsigned limit, std::vector<unsigned> const& abunNumbers, std::vector<bool> &sumAbun){
for(unsigned a = 0; a < abunNumbers.size(); a++){
for(unsigned b = a; b < abunNumbers.size(); b++){
if(abunNumbers[a]+abunNumbers[b] <= limit){
sumAbun[abunNumbers[a]+abunNumbers[b]] = true;
}
else{
break;
}
}
}
}
int main(){
const unsigned limit = 28123;
unsigned result = 0;
std::vector<unsigned>abunNumbers;
Abundant(limit, abunNumbers);
std::vector<bool>sumAbun(limit,false);
SumOfAbundant(limit, abunNumbers, sumAbun);
for(unsigned a = 0 ; a < sumAbun.size() ; a++){
if(!sumAbun[a]){
result += a;
}
}
std::cout << result;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T03:04:02.247",
"Id": "84252",
"Score": "0",
"body": "Clean and well structured code, but your `Divisors` code populates a `vector` that is thrown away by `SumOfDivisors`. Combining those, retaining only the sum would eliminate the `divisors` vector completely and save a small amount of time. The biggest gains will be algorithm changes, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T04:20:34.000",
"Id": "84253",
"Score": "0",
"body": "@Edward: Eliminating the vector would actually be a huge percentage of the time. I will bet more than 50%. Yes, an algorithmic change would be even better. But so what, it's already got to be under 1 second."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T06:31:26.807",
"Id": "84261",
"Score": "0",
"body": "if you look at the wikipedia page for abundant numbers, it states that the largest number that can't be made by summing two abundant numbers is 20161. 28123 and above is only the smallest number that can be **proven**. that may cut down your time a little"
}
] | [
{
"body": "<p>I would recommend the following changes:</p>\n\n<ul>\n<li><p>Math is your friend. Factorize the number into prime powers (a precalculated table of primes is of immence value for a lot of Project Euler problems), and use a formula from <a href=\"http://en.wikipedia.org/wiki/Divisor_function\">this</a> article.</p></li>\n<li><p>Memoize. As soon as you identify a single (prime) divisor of a number, and take the quotient, notice that the quotient was already inspected and factorized. A vector of tuples <code>(prime, power)</code> representing a factorization may also help a lot.</p></li>\n</ul>\n\n<p>There could be other optimizations, but these two seem to be enough.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T00:30:53.653",
"Id": "48018",
"ParentId": "48016",
"Score": "11"
}
},
{
"body": "<p>The problem states that all numbers greater than 28123 are out, so you only need to consider numbers up to that limit. That's not a lot of numbers.</p>\n\n<p>Having said that, each project Euler problem involves a new math skill. I'll provide some optimization hints.</p>\n\n<p>In this case, the math you need is factorization. You are dividing by every number from 1 to n-1 in order to factorize n. You don't have to do that.</p>\n\n<ol>\n<li><p>All numbers are divisible by 1, so don't even test it. You can start your count at 1 instead of zero.</p></li>\n<li><p>You are summing up the factors, so don't build a list, build a running total. That will reduce a lot of inefficiency. In fact, you overuse lists in several places: not only are you building a list of factors, but you are building a list of the numbers you want. Nothing in this problem said you had to build a list of anything, just sum the numbers you find. Granted, the only one that really affects the timing is the list of factors.</p></li>\n<li><p>You only need to go up to the square root of a number to factor. Consider 28: divide by 1, get 28 (which by the way doesn't count). Divide by 2, get 14. Divide by 4, get 7. You don't have to divide by 7, because you already got it by dividing by 4. That cuts the problem to \\$O(\\sqrt{n})\\$ rather than \\$O(n)\\$.</p></li>\n</ol>\n\n<p>The suggestion above is still a brute-force approach, but it's a more efficient brute-force solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:13:51.183",
"Id": "84551",
"Score": "1",
"body": "As evidenced by downvotes, the condescension in your original answer is disfavoured by the Code Review community. I've edited it to have a neutral tone. Remember, even expert programmers were once beginners too. You obviously have a lot of knowledge to contribute, but please remember to [be nice](http://codereview.stackexchange.com/help/behavior)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T04:15:53.513",
"Id": "48021",
"ParentId": "48016",
"Score": "-1"
}
},
{
"body": "<p>I was perplexed why you want a better answer if your current answer is able to solve this in seconds, but if you are interested in the math, there are definitely better ways to do it. They just don't matter much if the maximum number is on the order of 28000.</p>\n\n<p>If you eliminate the lists and go up to the square root, the code should get faster by a factor of 1000 or so, a rough estimate based on the difference between 28000 and the square root which is 167. Another factor of 2 due to only dividing by odd numbers after checking 2.</p>\n\n<p>But if you look at Wikipedia on abundant numbers: <a href=\"http://en.wikipedia.org/wiki/Abundant_number\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Abundant_number</a>\nYou will see that the first abundant number that is not divisible by 2 is 5391411025\nFirst of all, that's way more than 28000. So you can immediately ignore any number that is not even in your search for abundant numbers. Wikipedia says 2 or 3, which is confusing and seems wrong. Perhaps I misunderstood them but I was looking at their list of abundant numbers, and 20 is abundant, and it's not a multiple of 3 (it's a multiple of 5). 1+2+4+5+10 > 20</p>\n\n<p>Still, this means that any number that is abundant is going to be divisible by 2 and either 3 or 5 (or both). Think of it. How are you going to get factors that sum to a lot? You need factors that are an appreciable fraction of the whole number. The closest you can get to n is n / 2. The next closest is n / 3.</p>\n\n<p>The highest number you have to check is the square root, and since the square root of 28000 is about 170, that's the high end. But you can immediately terminate if you find that the number is already abundant, or if the sum is so low that it cannot possibly become abundant. So try only even numbers, and do the following:</p>\n\n<pre><code>int factors = 1 + 2 + n / 2;\nif (n % 3 == 0)\n factors += 3 + n/3 + 6 + n / 6;\nif (n % 5 == 0)\n factors += 5 + n / 5;\nif (factors > n)\n abundant.push_back(n);\n</code></pre>\n\n<p>Even if I'm not quite right, 99.9% of the abundant numbers will immediately be abundant with this test, so in constant time you will have detected them. You could check a few manually the rest of the way if you are \"close\" to abundant. I leave you to decide how close is close.</p>\n\n<p>A number that is not divisible by 2,3,4,5,6,7 is almost certainly not abundant. So you can find that critical value and then not test anything higher.\nStore the abundant numbers into a vector.</p>\n\n<p>Given the list of abundant numbers:</p>\n\n<pre><code>for (i = 0; i < abundant.size(); i++)\n for (int j = i+1; j < abundant.size(); j++) {\n int abundantSum = abundant[i] + abundant[j];\n if (abundantSum < 28123)\n numbers[abundantSum] = true;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T07:05:20.597",
"Id": "48304",
"ParentId": "48016",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48018",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T22:54:59.443",
"Id": "48016",
"Score": "8",
"Tags": [
"c++",
"c++11",
"programming-challenge"
],
"Title": "Project Euler 23: Non Abundant Sums"
} | 48016 |
<p>In an effort to rid my code of jQuery, I wrote a custom global event management/handling system. I was expecting this to be hard as, from what I've read, most people don't create their own. It's far simpler than most libraries I've seen. Is there a flaw in this method? What are the benefits of using something like <a href="https://github.com/Wolfy87/EventEmitter" rel="noreferrer">EventEmitter.js</a>?</p>
<pre><code>var EvtMgr = function() {
var events = {};
this.on = function(evtName, callback) {
if (!events[evtName]) events[evtName] = [];
events[evtName].push(callback);
}
this.trigger = function(evtName, evtObj) {
events[evtName].forEach(function(callback) {
callback(evtObj);
});
}
this.remove = function(evtName) {
delete events[evtName];
}
}
exports.evtMgr = new EvtMgr();
</code></pre>
<p>Then I can register listeners with <code>evtMgr.on('foo', function(evtObj) {…});</code></p>
| [] | [
{
"body": "<blockquote>\n <p>I was expecting this to be hard as, from what I've read, most people don't create their own</p>\n</blockquote>\n\n<p>Actually, there are <a href=\"https://www.google.com/search?q=js%20pub-sub%20libraries\">more people who create event emitters than you think</a>. I'm one of them, and <a href=\"https://github.com/fskreuz/MiniEvent\">here's my implementation</a>. Aside from Event Emitter, it's also called \"pub-sub\", and <a href=\"https://gist.github.com/cowboy/661855\">here's one of the same nature</a> under that label.</p>\n\n<p>It's a basic practice of the concept of managing async and decoupled code. It also makes for a good practice in code performance, coding style and sample code when learning GIT.</p>\n\n<blockquote>\n <p>It's far simpler than most libraries I've seen.</p>\n</blockquote>\n\n<p>Because it is very simple. Collect callbacks, and when triggered, you look for the right collection and fire. That's about it.</p>\n\n<blockquote>\n <p>Is there a flaw in this method?</p>\n</blockquote>\n\n<p>Yes, and that's what I haven't fixed in mine. The following code in <code>trigger</code> is the problem:</p>\n\n<pre><code>events[evtName].forEach(function(callback) {\n callback(evtObj);\n});\n</code></pre>\n\n<p>In your trigger, you fire the callbacks one after the other. That's fine for sequential code. But what if each of the callbacks contained operations that are synonymous to looping 100k times? And imagine if every callback listening to that fired event did that? That would freeze up the browser.</p>\n\n<p>A solution to that is using timers. Timers can be \"set aside\" when JS is busy. They don't \"block the thread\", as they usually call it. That way, you have these \"gaps\" when executing the callbacks, allowing the browser to breathe and do something else, like render the page perhaps.</p>\n\n<pre><code>var length = events[evtName].length;\nvar i = 0;\nvar timer = setInterval(function(){ // Execute whenever possible\n events[evtName][i].call(); // Nothing special about the call()\n if(++i == length) clearInterval(timer); // Clear when done\n},0);\n</code></pre>\n\n<blockquote>\n <p>What are the benefits of using something like EventEmitter.js?</p>\n</blockquote>\n\n<p>If you mean the concept of pub-sub, then you have decoupled of code which means it's easier to put in and pull out code without breaking the rest of the app. You also have a basic facility for managing asynchronous events.</p>\n\n<p>If you meant the library itself, then you just saved your time writing, testing and maintaining a pub-sub library. Not to mention, it's all free. All you need to do is grab and go (and maybe give credits where it's due).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T05:02:06.707",
"Id": "48025",
"ParentId": "48017",
"Score": "8"
}
},
{
"body": "<p>You are missing a key piece of functionality: Removing an event handler. You allow the removal of all event handlers, but not a single handler:</p>\n\n<pre><code>this.remove = function(evtName, callback) {\n if (!callback) {\n // clear all handlers for an event\n events[evtName] = [];\n }\n else if (events[evtName]) {\n // remove a single handler\n var i = 0, callbacks = events[evtName],\n length = callbacks.length;\n\n for (i; i < length; i++) {\n if (callbacks[i] === callback) {\n callbacks.splice(i, 1);\n break;\n }\n }\n }\n};\n</code></pre>\n\n<p>If you ever need to write object oriented code, you might consider accepting a <code>context</code> argument to the <code>on()</code> method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:49:06.980",
"Id": "48064",
"ParentId": "48017",
"Score": "2"
}
},
{
"body": "<p>Check out <a href=\"http://blog.ponyfoo.com/2014/03/07/a-less-convoluted-event-emitter-implementation\" rel=\"nofollow\">\"A Less Convoluted Event Emitter Implementation\" by Nicolas Bevacqua</a> that explains the benefits of having the event triggering functionality as a mixin instead of just a plain constructor or centralized object.</p>\n\n<p>Check out <a href=\"https://github.com/component/emitter\" rel=\"nofollow\">component/emitter</a> and <a href=\"https://github.com/bevacqua/contra/blob/b8e47113995b944b0ba5ed1936490eae48ad1bfa/src/contra.js#L136-179\" rel=\"nofollow\"><code>λ.emitter</code> from bevacqua/contra</a> for concrete examples.</p>\n\n<p>The pattern would allow you to make anything an event emitter!</p>\n\n<pre><code>var dog = {};\nEvtMgr(dog);\ndog.trigger('wroof');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:38:58.063",
"Id": "48107",
"ParentId": "48017",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48025",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T23:22:23.827",
"Id": "48017",
"Score": "13",
"Tags": [
"javascript",
"event-handling"
],
"Title": "Simple event management system"
} | 48017 |
<p>I'm implementing some basic algorithms in Go as an introductory exercise. Here are four different algorithms to find the Nth Fibonacci number.</p>
<p>I'm looking for general feedback, but I'm specially interested in the Go idiom. Are the algorithms implemented idiomatically? If not, how can I correctly use the Go idiom to implement them? </p>
<p>Any other feedback you can think of is also welcome.</p>
<pre><code>// Algorithms to calculate the nth fibonacci number
package main
import (
"fmt"
"math"
)
func main() {
for i := 0; i <= 20; i++ {
fmt.Println(fibonacci(i))
fmt.Println(fibonacciRecursive(i))
fmt.Println(fibonacciTail(i))
fmt.Println(fibonacciBinet(i))
println()
}
}
// Iterative
func fibonacci(n int) int {
current, prev := 0, 1
for i := 0; i < n; i++ {
current, prev = current + prev, current
}
return current
}
// Recursive
func fibonacciRecursive(n int) int {
if n < 2 {
return n
}
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2)
}
// Tail recursion
func fibonacciTail(n int) int {
return tailHelper(n, 1, 0)
}
func tailHelper(term, val, prev int) int {
if term == 0 {
return prev
}
if term == 1 {
return val
}
return tailHelper(term - 1, val + prev, val)
}
// Analytic (Binet's formula)
func fibonacciBinet(num int) int {
var n float64 = float64(num);
return int( ((math.Pow(((1 + math.Sqrt(5)) / 2), n) - math.Pow(1 - ((1 + math.Sqrt(5)) / 2), n)) / math.Sqrt(5)) + 0.5 )
}
</code></pre>
| [] | [
{
"body": "<p>For <code>tailHelper()</code>, the <code>term == 1</code> case is superfluous and should be eliminated.</p>\n\n<p>In <code>fibonacciBinet()</code>, the quantity \\$\\frac{1 + \\sqrt{5}}{2}\\$ appears twice. Since that quantity is known as the <a href=\"http://en.wikipedia.org/wiki/Golden_ratio\" rel=\"nofollow noreferrer\">Golden Ratio</a>, I would define an intermediate value</p>\n\n<pre><code>var phi = (1 + math.Sqrt(5)) / 2;\n</code></pre>\n\n<p>However, none of these four solutions is particularly idiomatic for Go. The most expressive way to write a Fibonacci sequence in Go is as an <a href=\"http://www.golangpatterns.info/object-oriented/iterators\" rel=\"nofollow noreferrer\">iterator</a>, such as <a href=\"https://codereview.stackexchange.com/a/28445/9357\">this one</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T18:35:46.013",
"Id": "48077",
"ParentId": "48020",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48077",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T02:28:32.067",
"Id": "48020",
"Score": "7",
"Tags": [
"algorithm",
"go",
"fibonacci-sequence"
],
"Title": "Four algorithms to find the Nth Fibonacci number"
} | 48020 |
<p>I have been teaching myself Python 3. I watched a video on YouTube entitled "stop writing classes". The Gtable class doesn't even have an init function, so I can't help but wonder if I should have done something different. Also as someone teaching themselves a language for the first time I would really appreciate any critique on how to write the code more efficiently, as well as any anti-idioms unintentionally used. Specifically I feel like there was probably a better way to generate the dictionaries, but especially with the first one I was having trouble writing a comprehension.</p>
<pre><code>##input file text
##|HAAS T|TARGET T|XGEOM|ZGEOM
##$T0101$T0101$X22.960$Z20.0$
##$T0202$T0606$X32.425$Z7.376$
##$T0303$T0404$X30.588$Z15.620$
##$T0404$T0202$X22.367$Z18.549$
##$T0505$T0808$X33.291$Z8.197$
class GeometryTable(dict):
"create a geometry table from a file for use in regexes"
def __init__(self):
self.d={}
def create(self,location):
f=open(location,'r')
tablestring=f.read()
f.close()
tablelist=[]
tablelist=tablestring.split('$')
#delete unecessary data from list
tablelist.pop(0)
tablelist=[item for item in tablelist if item!='\n']
#create a dictionary
count=0
keylist=[]
valuelist=[]
while count<len(tablelist):
keylist.append(tablelist[count])
valuelist.append([tablelist[count+1],tablelist[count+2],tablelist[count+3]])
count+=4
self.d=dict(zip(keylist,valuelist))
def xval(self,string):
if string in self.d:
return (self.d[string][1])
else:return(r"X20.0")
def zval(self,string):
if string in self.d:
return (self.d[string][2])
else:return(r"Z20.0")
def tval(self,string):
if string in self.d:
return (self.d[string][0])
else:return(r"T2020")
def report(self,string):
if string in self.d:
return (self.d[string])
else:return(r"(no value)")
class GTable(GeometryTable):
"""for replacing geometries that were given
default values before this program was created"""
def load(self,location):
GeometryTable.load(self,location)
b=self.__dict__["d"].values()
redict={x[0]:x for x in b}
self.d=redict
##output dictionaries for regular expressions
##>>> test.d
##{'T0101': ['T0101', 'X22.960', 'Z20.0'],
## 'T0202': ['T0606', 'X32.425', 'Z7.376'],
## 'T0303': ['T0404', 'X30.588', 'Z15.620'],
## 'T0404': ['T0202', 'X22.367', 'Z18.549'],
## 'T0505': ['T0808', 'X33.291', 'Z8.197']}
</code></pre>
| [] | [
{
"body": "<p>So there are a few improvements that I can see in your code, mainly in the <code>create</code> function.</p>\n\n<hr>\n\n<p>When reading a file, use the <code>with</code> keyword. This will open the file and, once the program leaves that scope, the file will automatically be closed.</p>\n\n<p>I would recommend changing how you read the file. From what I can tell, each line will be its own key in your <code>dict</code>. So instead of reading the <strong>entire</strong> file in one statement, I would recommend reading line-by-line.</p>\n\n<p>By making the changes mentioned above, when we split the input by <code>$</code>, we get unnecessary values in the first and last index of the resulting <code>list</code>. To fix this, we can use <a href=\"http://forums.udacity.com/questions/2017002/python-101-unit-1-understanding-indices-and-slicing\" rel=\"nofollow\">list slicing</a>. By using the notation <code>list[start:end]</code>, where <code>start</code> specifies the first index you want <strong>included</strong> and <code>stop</code> specifies the first index you want <strong>excluded</strong>, we can remove the first and last indices.</p>\n\n<p>Finally, when creating a <code>dict</code> you can assign a key-value pair simply by using the syntax:</p>\n\n<pre><code>dict[key] = value\n</code></pre>\n\n<p>Bringing all of these suggestions together, here is my version of your <code>create</code> function:</p>\n\n<pre><code>def create(self, location):\n # Once this block of code finishes, f will close.\n with open(location, 'r') as f:\n # Reads the file line-by-line\n for line in f:\n # Split the data and remove the first and last indices\n data = line.split('$')[1:-1]\n\n # Assign the key-value pair to the dict\n self.d[data[0]] = data[1:]\n</code></pre>\n\n<hr>\n\n<p>As a final aside, look over <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>. PEP8 is the official Python style guide. Following those conventions (especially underscores in variable names, so <code>table_string</code> instead of <code>tablestring</code>) will help your code look and feel more Pythonic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T06:37:03.283",
"Id": "84262",
"Score": "0",
"body": "That worked really well with one small tweak. Added: if len(data)>1:self.d[data[0]] = data[1:] to handle index out of range error. Thankyou"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T05:19:47.693",
"Id": "48026",
"ParentId": "48022",
"Score": "3"
}
},
{
"body": "<h3>Misnomer</h3>\n\n<p><code>GeometryTable.create()</code> is poorly named: it doesn't <em>create</em> a <code>GeometryTable</code>. Rather, it <em>loads</em> tabular geometry data from a file. Therefore, it should be called <code>load()</code> instead. With that simple renaming, the following code starts to make sense:</p>\n\n<pre><code>table = GeometryTable()\ntable.load('part1.dat') # Loads some data\ntable.load('part2.dat') # Loads more data into the same object\n</code></pre>\n\n<h3>Inappropriate inheritance, Part I</h3>\n\n<p><code>GeometryTable</code> inherits from <code>dict</code>. Why? Would you say that <code>GeometryTable</code> <em>is</em> a <code>dict</code>, or that <code>GeometryTable</code> <em>uses</em> a <code>dict</code>? The latter is clearly true: it uses a <code>dict</code> called <code>self.d</code>. The former isn't true: you couldn't meaningfully write code like</p>\n\n<pre><code>table = GeometryTable()\ntable.load('something.dat')\ntable['T0202'] # ← Produces a KeyError\n</code></pre>\n\n<p>Therefore, as you've designed it, <code>GeometryTable</code> should just be an <code>object</code>, not a <code>dict</code>.</p>\n\n<p>That said, you could change <code>GeometryTable</code> so that it <em>is</em> a <code>dict</code>, such that you can call <code>table['T0202'].x</code>. I don't really recommend doing so. \"Prefer composition over inheritance\" is a <a href=\"https://softwareengineering.stackexchange.com/q/134097/51698\">general</a> <a href=\"https://stackoverflow.com/q/49002/1157100\">maxim</a> of object-oriented design.</p>\n\n<h3>Meaningless array indices</h3>\n\n<p>Expressions like <code>tablelist[count+2]</code> and <code>self.d[string][1]</code> are mysterious and hard to understand. I recommend the use of <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a> so that you can have meaningful names like <code>self.d[string].x</code> instead.</p>\n\n<h3>Too much code</h3>\n\n<p>You're working too hard. <code>load()</code> could be written in five lines. Furthermore, for readability, efficiency, and scalability, it's better to work line by line rather than reading the entire file at once.</p>\n\n<pre><code>from collections import defaultdict, namedtuple\n\nclass GeometryTable(object):\n Row = namedtuple('Row', ['t', 'x', 'z'])\n default_row = lambda cls: cls.Row('T2020', 'X20.0', 'Z20.0')\n\n def __init__(self):\n self.d = defaultdict(self.default_row)\n\n def load(self, filename):\n \"\"\"\n Loads data in the following format from the named file:\n\n |HAAS T|TARGET T|XGEOM|ZGEOM\n $T0101$T0101$X22.960$Z20.0$\n $T0202$T0606$X32.425$Z7.376$\n $T0303$T0404$X30.588$Z15.620$\n $T0404$T0202$X22.367$Z18.549$\n $T0505$T0808$X33.291$Z8.197$\n \"\"\"\n with open(filename) as f:\n next(f) # Discard first line, which contains a header\n for line in f:\n cols = line.split('$')\n self.d[cols[1]] = self.Row(*cols[2:5])\n\n def tval(self, haas):\n return self.d[haas].t\n\n def xval(self, haas):\n return self.d[haas].x\n\n def zval(self, haas):\n return self.d[haas].z\n\n def report(self, haas):\n return self.d.get(haas, '(no value)')\n</code></pre>\n\n<p>Alternatively, use the <a href=\"https://docs.python.org/3/library/csv.html\" rel=\"nofollow noreferrer\"><code>csv</code></a> module:</p>\n\n<pre><code>import csv\n\nclass GeometryTable(object):\n …\n def load(self, filename):\n with open(filename) as f:\n next(f) # Discard first line, which contains a header\n rows = csv.reader(f, delimiter='$')\n for cols in rows:\n self.d[cols[1]] = self.Row(*cols[2:5])\n</code></pre>\n\n<p>One minor deviation from your original code is that <code>.report()</code> returns a <code>namedtuple</code> rather than a list. However, considering that it sometimes returns a string instead (which is weird), I assume that that is an inconsequential detail.</p>\n\n<h3>Inappropriate inheritance, Part II</h3>\n\n<p>Your <code>GTable</code> class doesn't actually work. For one thing, <code>Geometrytable</code> is mis-capitalized, so it's evidently untested code.</p>\n\n<p>The call to <code>Geometrytable.create(self,location)</code> would be better written as <code>super().load(filename)</code> (with the renaming suggested earlier).</p>\n\n<p>Instead of <code>self.__dict__[\"d\"]</code>, why not just write <code>self.d</code>?</p>\n\n<p>The biggest problem, though, is that a <code>GTable</code> simply isn't a <code>GeometryTable</code>. The methods <code>.tval()</code>, <code>.xval()</code>, and <code>.zval()</code> will all give wrong results, since their implementation is simply incompatible <code>GTable</code>'s data representation. I have no idea what you are trying to accomplish with <code>GTable</code>, but inheritance is not the right solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T19:38:48.680",
"Id": "84362",
"Score": "0",
"body": "Namedtuple feature as well as the use of defaults. This was very informative and helpful, thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T10:00:28.607",
"Id": "48032",
"ParentId": "48022",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48032",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T04:28:24.130",
"Id": "48022",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"hash-map"
],
"Title": "Geometry table for use in regexes"
} | 48022 |
<p>This is intended as something of a comparative study. I'm including not just one, but two separate implementations of code to implement the Project Euler problem to sum the even Fibonacci numbers up to 4,000,000. The first is a very C-like implementation. The second attempts to make much more use of modern C++. To do so, it includes a specialized iterator to generate Fibonacci numbers, and a generic algorithm for summing items from a range conditionally (and uses a lambda expression to specify the condition).</p>
<p>If we include that generic algorithm, the latter is (marginally) longer than the former (though I've also included some timing code in the former that's currently absent in the latter). I'm curious to know what people think of them--whether the latter is really an improvement, which style you'd prefer to see in your code base, and so on.</p>
<p>More specific questions:</p>
<ol>
<li>Do iterators and algorithms produce a net loss or gain for this particular code? </li>
<li>Is it problematic that the iterator's <code>operator !=</code> actually does a <code><</code> comparison internally, on the basis that it's looking for the end of a logical range, but doesn't expect you to necessarily know the exact value of the Fibonacci number at the end of the range you care about?</li>
</ol>
<p>Version 1:</p>
<pre><code>#include <iostream>
#include <time.h>
int main() {
clock_t start = clock();
unsigned long long total;
int max_reps = 10000;
for (int reps = 0; reps < max_reps; reps++) {
total = 0;
unsigned long long first = 1;
unsigned long long second = 1;
unsigned long long fib = first + second;
while (fib < 4000000) {
if ((fib % 2) == 0)
total += fib;
first = second;
second = fib;
fib = first + second;
}
}
clock_t stop = clock();
std::cout << total
<< "\ntime: "
<< (1000.0 * (stop - start)) / double(CLOCKS_PER_SEC * max_reps) << "ms\n";
}
</code></pre>
<p>...and version 2:</p>
<pre><code>#include <iostream>
template <class T=unsigned>
class fib_iterator {
T first, second;
public:
fib_iterator(T v1=1, T v2 = 1) : first(v1), second(v2) {}
int operator *() { return first + second; }
fib_iterator &operator++() {
int temp = first + second;
first = second;
second = temp;
return *this;
}
bool operator!=(fib_iterator const &r) { return first < r.first; }
};
template <class InIt, class F, class T>
T accumulate_if(InIt b, InIt e, T accum, F f) {
while (b != e) {
if (f(*b))
accum += *b;
++b;
}
return accum;
}
int main() {
std::cout << accumulate_if(fib_iterator<>(), fib_iterator<>(4000000),
0U, [](unsigned v) { return v % 2 == 0; });
}
</code></pre>
<p>Of course, the questions I've asked above are not intended to limit the scope of reviews--only to add to the normal review I'd hope for when posting any code here.</p>
| [] | [
{
"body": "<p>Sorry if I sound Fortranish. Project Euler is about math, not programming.</p>\n\n<p>A Fibonacci number is even if its index is \\$3n+2\\$. A Binet's formula reduces their sum to the sum of 2 geometric progressions. That, and some error estimation, is pretty much it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T13:09:30.767",
"Id": "84299",
"Score": "4",
"body": "Binet's formula is painful to use for anything other than the first few fibonnaci numbers, due to floating-point inaccuracy and, well, floating-point. It's possible to compute them efficiently while staying in the integers, e.g. via reduced matrix form (using the [matrix formula](http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) but cutting out some redundant work, and using square-and-multiply), though if you just need to generate all of them in sequence then nothing beats just doing it the naive way, obviously."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T13:24:14.133",
"Id": "84300",
"Score": "1",
"body": "@Thomas, you've missed the point. There's no need to compute any Fibonacci numbers. user58697 is proposing replacing the entire loop with a couple of calls to `pow`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T13:42:18.533",
"Id": "84302",
"Score": "4",
"body": "@PeterTaylor And that's exactly it. `pow` is not ideal as it requires moving to floating-point, staying in integers gets rid of plenty of problems you will encounter (and is pretty much as efficient as `pow` if you do it right, if not more). Project Euler is also about writing elegant code that scales - as is this Q/A site, I think - even though most of the simpler problems can be brute-forced :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T18:33:00.323",
"Id": "84356",
"Score": "1",
"body": "Sorry I was unclear. There is no need to *calculate* the result using Binet's. With Binet it is easy to see *what* the result is :it is a certain combination of a few (pretty large) Fibonacci numbers (is there LaTeX here?), which again can be calculated precisely and very fast."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T06:31:48.983",
"Id": "48028",
"ParentId": "48023",
"Score": "8"
}
},
{
"body": "<p>I only have a few remarks concerning the second version:</p>\n\n<ul>\n<li>Why does <code>fid_iterator::operator*</code> return an <code>int</code>? Shouldn't it return a <code>T</code> instead since the class is templated? You also declared <code>temp</code> as <code>int</code>. Since you are only adding numbers, you don't need it to be signed, so I don't understand why it is not <code>T</code>.</li>\n<li>You should add the public types <code>value_type</code>, <code>reference</code>, etc... to <code>fib_iterator</code> so that it is compatible with <code>std::iterator_traits</code> and generic algorithms using it. I believe that <code>iterator_category</code> would be <code>std::forward_iterator_tag</code>.</li>\n<li>To fully satisfy the <a href=\"http://en.cppreference.com/w/cpp/concept/ForwardIterator\" rel=\"nofollow\"><code>ForwardIterator</code></a> concept, <code>fib_iterator</code> needs to implement <code>operator++(int)</code>.</li>\n<li>You should rename <code>F</code> to <a href=\"http://en.cppreference.com/w/cpp/concept/Predicate\" rel=\"nofollow\"><code>Predicate</code></a> to clarify the intent of the function passed to <code>accumulate_if</code>.</li>\n</ul>\n\n<p>At first, computing mathematical formula thanks to iterators did not seem intuitive (to me). However, I totally do understand why you chose iterators instead of returning a collection; it's probably much more memory efficient and it is easy to create a wrapper function to return a container if one really wants to.</p>\n\n<p>I generally prefere code that looks like math formula when I have to write math-related code, but in this particular case, I find that the iterators and the modern C++ feel are rather suited :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T08:22:13.950",
"Id": "48030",
"ParentId": "48023",
"Score": "7"
}
},
{
"body": "<p>That's not a fair comparison of programming styles, as you haven't attempted to make everything else equal. If I were to translate Version 2 into a C-style loop, I would write:</p>\n\n<pre><code>#include <iostream>\n\nint main() {\n unsigned sum = 0;\n for ( unsigned first = 1, second = 1, temp;\n first < 4000000;\n temp = first + second, first = second, second = temp ) {\n if ((first + second) % 2 == 0) sum += (first + second);\n }\n std::cout << sum << std::endl;\n}\n</code></pre>\n\n<p>That's the entire program. The readability is so-so, but the conciseness could be considered a virtue.</p>\n\n<p>My translation makes it clear that the termination condition of your Version 2 is probably not what you intended. The last number you add could very well be over 4 million. You're lucky that 5702887 and 9227465 are both odd.</p>\n\n<hr>\n\n<p>In my opinion, the middle ground would be optimal.</p>\n\n<p>The Fibonacci sequence is an infinite stream of numbers. Expressing it as an iterator would be the most natural way to model the problem. The iterator class adds verbosity to the code, but I can see benefits.</p>\n\n<p>However, I'm not a fan of <code>accumulate_if()</code>. A conventional for-loop uses no advanced language features such as lambda. It doesn't even require <code>fib_iterator<T>::operator!=(…)</code>, which, as you pointed out, is misleading,<sup>1</sup> and as I pointed out, is buggy. Furthermore, to specify the condition to terminate iteration, you have to construct a <code>fib_iterator<>(4000000, 1)</code>. Even though the <code>1</code> is implicit rather than explicit, I still find it icky.</p>\n\n<p>A for-loop accomplishes the task with less code. Most importantly, the code is laid out in the most easily recognizable format possible to any C/C++ programmer: as a loop rather than a long line of parameters to some function I'm not familiar with. Since loop condition tests <code>*it</code>, the same number that we add to the sum, it's foolproof.</p>\n\n<pre><code>int main() {\n unsigned sum = 0;\n for (auto it = fib_iterator<>(); *it < 4000000; ++it) {\n if (*it % 2 == 0) sum += *it;\n }\n std::cout << sum << std::endl;\n}\n</code></pre>\n\n<p>I wouldn't say that the <code>accumulate_if()</code> concept has no merit, but I don't think that it is justified for this simple problem.</p>\n\n<hr>\n\n<p><sup>1</sup> By the way, why did you choose to implement and use <code>fib_iterator<T>::operator!=(…)</code> rather than <code>fib_iterator<T>::operator<(…)</code>? The latter doesn't require you to lie.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:36:14.893",
"Id": "84293",
"Score": "0",
"body": "Probably the habit of implementing `operator!=` in iterators. That's one of the functions I would always expect to exist for a given iterator."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:46:33.017",
"Id": "48043",
"ParentId": "48023",
"Score": "6"
}
},
{
"body": "<p>I think that the first version is somewhat more straightforward and would be understandable by those not familiar with the latest C++ constructs. </p>\n\n<p>However, I do rather like the idea of implementing the Fibonacci sequence as an iterator. It makes some sense, although I have some quibbles with how it's implemented:</p>\n\n<ol>\n<li>Every instance of <code>int</code> in the iterator should probably be <code>T</code></li>\n<li>I'd have avoided the use of <code>temp</code> in <code>operator++</code></li>\n<li><code>operator*</code> and <code>operator!=</code> should be declared <code>const</code></li>\n<li>using <code><</code> in definition of <code>!=</code> isn't necessarily bad, but odd</li>\n</ol>\n\n<p>I'd also eliminate <code>accumulate_if</code> entirely and use <code>std::accumulate</code> instead:</p>\n\n<pre><code>std::accumulate(fib_iterator<>(), fib_iterator<>(4000000U), 0U, \n [](unsigned accum, unsigned v) { return accum + (v & 1 ? 0 : v); })\n</code></pre>\n\n<p>To my eye, it's a little easier to understand, since you're using a lambda anyway.</p>\n\n<p>Also, I'd be at least slightly concerned about numerical overflow for both versions. Seems like it might be worth <code>throw</code>ing an exception rather than silently returning bad answers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T13:18:11.793",
"Id": "48048",
"ParentId": "48023",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48030",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T04:39:12.740",
"Id": "48023",
"Score": "8",
"Tags": [
"c++",
"fibonacci-sequence",
"comparative-review"
],
"Title": "Another even Fibonacci numbers implementation"
} | 48023 |
<p>I just made a working implementation of calculating a string's length, but I'm not exactly sure it's the most efficient way. I divide the string up in blocks of four bytes each (32 bits), and add 4 to EAX. Once I hit a completely NULL block, I roll back the count of EAX by 4 bytes, and then calculate the final block's size one byte at a time. It only works using ASCII characters, and is limited to 32 bit computing (though that can be easily upgraded to 64 bit soon). I'm using assembly on a Linux maching using NASM. Here's the code:</p>
<pre class="lang-none prettyprint-override"><code>; Function to compute the length of a string in blocks
; this only works in ASCII, or else it may give the wrong character count.
; input register: EAX - the string
section .data
BYTE_COUNT equ 4 ;4 bytes = 32 bits
NULL_TERMINATOR equ 0 ;\0, aka 0
section .text
global _strlen ;main entry point
_strlen:
push ebp ; c calling convention: preserve ebp
mov ebx, eax ; mov to ebx the string
jmp _NextBlock ; go to _NextChar
_NextBlock:
cmp word [eax], NULL_TERMINATOR ; Compare whether or not this block is completely null (e.g. 0)
jz _RollbackFinalBlock ; if it is, jump to _RollbackFinalBlock
; if not...
add eax, BYTE_COUNT ; Add to EAX the block size
jmp _NextBlock; repeat loop
_RollbackFinalBlock:
sub eax, BYTE_COUNT ;Subtract the block size from EAX, because it is null
jmp _FinalizeFinalBlock ; go to _FinalizeFinalBlock
_FinalizeFinalBlock:
cmp byte[eax], NULL_TERMINATOR ;Compare the characters of the final block to the null byte.
jz _Exit ;if this byte is null, proceed to _Exit
; if not...
inc eax ;increment EAX
jmp _FinalizeFinalBlock ;repeat loop
_Exit:
dec eax ; We will have a null terminator at the end. remove it.
sub eax, ebx ; compute difference to get answer, and store result in EAX
pop ebp ; load preserved EBP value from the stack
ret ; exit this function
</code></pre>
<p>You can test this function by linking it with a c program, and calling it from there.</p>
<p>The problem I have is that I have an extra jump to _RollbackFinalBlock and _FinalizeFinalBlock. Is there a way to make this implementation faster and more efficient?</p>
| [] | [
{
"body": "<p>I have a number of comments that I hope you find helpful. </p>\n\n<h2>Code comments</h2>\n\n<p>First, your code is generally well commented and I had little difficulty in understanding what the code was doing or why. That's a good thing. A few minor points, though. First, your comment for the overall function says</p>\n\n<pre><code>; input register: EAX - the string\n</code></pre>\n\n<p>however, it's probably useful to point out that EAX is actually a pointer to the string and isn't intended to contain a whole string.</p>\n\n<p>Also, comments should tell something not obvious about the code. So this:</p>\n\n<pre><code> jmp _NextBlock; repeat loop\n</code></pre>\n\n<p>is arguably OK, but this:</p>\n\n<pre><code> inc eax ;increment EAX\n</code></pre>\n\n<p>is not really helpful. Instead you should say <em>why</em> the code is incrementing <code>EAX</code> rather than simply repeating what the instruction does.</p>\n\n<h2>Structure</h2>\n\n<p>Overall, the structure was OK, but the line</p>\n\n<pre><code> jmp _NextBlock ; go to _NextChar\n</code></pre>\n\n<p>near the top of the function is not needed, since <code>_NextBlock</code> is the next instruction anyway. The same is true of the <code>jmp</code> just before <code>_FinalizeFinalBlock</code>. Generally speaking, you should strive to eliminate unconditional jumps. So for example, your code includes this:</p>\n\n<pre><code> _FinalizeFinalBlock:\n cmp byte[eax], NULL_TERMINATOR ;Compare the characters of the final block to the null byte.\n jz _Exit ;if this byte is null, proceed to _Exit\n ; if not...\n inc eax ;increment EAX\n jmp _FinalizeFinalBlock ;repeat loop\n\n _Exit:\n</code></pre>\n\n<p>But you could easily restructure that to eliminate the unconditional <code>jmp</code> like this:</p>\n\n<pre><code> dec eax ; \n _FinalizeFinalBlock:\n inc eax ;increment EAX\n cmp byte[eax], NULL_TERMINATOR ;Compare the characters of the final block to the null byte.\n jnz _FinalizeFinalBlock ; keep going until final block is NULL\n\n _Exit:\n</code></pre>\n\n<h2>Algorithm</h2>\n\n<p>The most significant problem I see with the code is the algorithm that relies on strings having multiple trailing NUL bytes. This may be true for code that calls this function, but it's not generally true of C strings which typically end with only a single NUL character. </p>\n\n<h2>Instruction set use</h2>\n\n<p>The <code>repnz scasb</code> instruction is probably going to be a lot more efficient that the loop you've constructed. I'd recommend reading about it and then incorporating that into your code.</p>\n\n<h2>Register use</h2>\n\n<p>The <code>ebx</code> register is destroyed and not saved by the function. This may be fine for your purposes, but it should be documented in comments at the top of the function.</p>\n\n<p>Also, the code doesn't actually alter <code>ebp</code> so there isn't any point to pushing it onto the stack and popping it off at the end of the routine. (Maybe you meant <code>ebx</code>?)</p>\n\n<h1>Update:</h1>\n\n<p>On my machine (quad core running 3.2GHz under 64-bit Linux) I found this version to be slightly (15%) faster than the corresponding <code>repnz scasb</code> version:</p>\n\n<pre><code>strlen2:\n mov edx, [esp + 4]\n xor eax,eax ; count = 0\n jmp overit\nlooptop:\n inc edx\n inc eax\noverit:\n cmp byte[edx],0\n jnz looptop\n ret\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T17:13:33.740",
"Id": "84350",
"Score": "1",
"body": "Thanks for the review. I still have to brush up on the REPNZ SCASB instruction sets, but from what I can tell it can compare the string, byte for byte, for the null character until it is found. I implemented something similar which compares it byte for byte, but it took about 43 microseconds to complete. With this version of the code, it took 29-30 microseconds to complete. Let's see if REPNZ SCASB is able to do better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:27:06.240",
"Id": "48052",
"ParentId": "48034",
"Score": "6"
}
},
{
"body": "<blockquote>\n <p>I'm using assembly on a Linux maching using NASM.</p>\n</blockquote>\n\n<p>In that case, the parameter passed to <code>_strlen</code> is pushed on the stack, not passed in the eax register.</p>\n\n<hr>\n\n<pre><code> cmp word [eax], NULL_TERMINATOR ; Compare whether or not this block is completely null (e.g. 0)\n jz _RollbackFinalBlock ; if it is, jump to _RollbackFinalBlock\n ; if not...\n add eax, BYTE_COUNT ; Add to EAX the block size\n</code></pre>\n\n<p>This is wrong: because you can't assume that a string has more than one zero-byte. Your implementation detects end-of-string only if all the <code>word [eax]</code> bytes are 0; whereas it should detect end-of-string if any of the <code>word [eax]</code> bytes are 0.</p>\n\n<p>Also, is <code>word</code> what you wanted to say: or should you have written <code>dword</code>?</p>\n\n<hr>\n\n<blockquote>\n <p>Is there a way to make this implementation faster and more efficient?</p>\n</blockquote>\n\n<p><a href=\"http://tsunanet.net/~tsuna/strlen.c.html\" rel=\"nofollow\">An algorithm like this</a> might be faster than a naive implementation (not necessarily faster than an incorrect implementation like yours) because it tests 4 bytes at a time.</p>\n\n<p>Alternatively on some processors there are <a href=\"https://www.google.com/search?q=strchr+se2#q=strchr+sse2\" rel=\"nofollow\">SSE2 instructions which can be used for strlen</a>.</p>\n\n<p>Or, the simplest solution (and fast on some CPUs) is <code>repnz scasb</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T01:29:26.907",
"Id": "84403",
"Score": "0",
"body": "Regarding repnz scasb, it requires that ECX be loaded with the counter. Where am I going to get the value for ECX, and if I did get the value already for ECX, wouldn't that already have been the string length?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T01:46:02.157",
"Id": "84404",
"Score": "1",
"body": "@pacoalphonso https://www.google.com/search?q=strlen+ecx suggests using `sub ecx, ecx` followed by `not ecx` to set it to `0xffffffff`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T22:38:05.090",
"Id": "48087",
"ParentId": "48034",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:09:06.430",
"Id": "48034",
"Score": "7",
"Tags": [
"strings",
"assembly"
],
"Title": "String length calculation implementation in Assembly (NASM)"
} | 48034 |
<p>Please review this code.</p>
<pre><code>import java.util.Scanner;
import java.util.* ;
public class LMComplex {
Scanner name = new Scanner(System.in);
Scanner age = new Scanner(System.in);
Scanner gender = new Scanner(System.in);
Scanner height = new Scanner(System.in);
String usrname;
String usrage;
String usrgender;
Double usrheight;
public void main(){
System.out.println("Enter your name: ");
usrname = name.nextLine();
System.out.println("Enter your age(Numbers): ");
usrage = age.nextLine();
System.out.println("Enter your gender(male/female): ");
usrgender = gender.nextLine();
System.out.println("Enter your height(feet.inches . 5 feet 5 inches = 5.5): ");
usrheight = height.nextDouble();
Double rusrheight = Math.ceil(usrheight);
if(rusrheight > usrheight)
{
rusrheight = rusrheight - 1;
}
else
{
}
Double rusrheightininches = usrheight - rusrheight;
if(rusrheightininches >= 0.10 && rusrheightininches < 0.12)
{
rusrheightininches = rusrheightininches * 100;
} else {
rusrheightininches = rusrheightininches * 10;
}
Double rusrheightinincheschecker = rusrheightininches;
rusrheightininches = Math.ceil(rusrheightininches);
if(rusrheightininches > rusrheightinincheschecker)
{
rusrheightininches = rusrheightininches - 1;
}
else
{
}
System.out.println("Hii " + usrname + ". I am Cartic, a basic textual virtual personal assistant. I do know that you are " + usrage +" years old. You are a " + usrgender + " and are " + rusrheight + " feet " + rusrheightininches + " inch(es) tall");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:35:35.770",
"Id": "84280",
"Score": "6",
"body": "Format your code (indent blocks) for easy reading."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:37:12.803",
"Id": "84282",
"Score": "1",
"body": "@MrSmith42 that's a review... If rolfl hadn't already posted an answer almost solely about formatting, I'd have suggested you do, but rolfl was the fastest reviewer in the west here ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:00:43.113",
"Id": "84315",
"Score": "2",
"body": "*\"just 14 years old and have been learning java\"* That's great! Stick with it, Java is going to be around a long time. The world needs good programmers, and the best ones are those who start young. (I started programming at 12, and started Java at 14. At the time, I didn't have the benefit of StackOverflow & StackExchange.) :)"
}
] | [
{
"body": "<p>Indenting is the first part of common practice that you should consider when sharing your code with anyone. Here is your code, which I have put though the 'standard' indenting function of Eclipse:</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class LMComplex {\n Scanner name = new Scanner(System.in);\n Scanner age = new Scanner(System.in);\n Scanner gender = new Scanner(System.in);\n Scanner height = new Scanner(System.in);\n String usrname;\n String usrage;\n String usrgender;\n Double usrheight;\n\n public void main() {\n System.out.println(\"Enter your name: \");\n usrname = name.nextLine();\n System.out.println(\"Enter your age(Numbers): \");\n usrage = age.nextLine();\n System.out.println(\"Enter your gender(male/female): \");\n usrgender = gender.nextLine();\n System.out.println(\"Enter your height(feet.inches . 5 feet 5 inches = 5.5): \");\n usrheight = height.nextDouble();\n Double rusrheight = Math.ceil(usrheight);\n if (rusrheight > usrheight)\n {\n rusrheight = rusrheight - 1;\n }\n else\n {\n\n }\n Double rusrheightininches = usrheight - rusrheight;\n if (rusrheightininches >= 0.10 && rusrheightininches < 0.12)\n {\n rusrheightininches = rusrheightininches * 100;\n } else {\n rusrheightininches = rusrheightininches * 10;\n }\n Double rusrheightinincheschecker = rusrheightininches;\n rusrheightininches = Math.ceil(rusrheightininches);\n if (rusrheightininches > rusrheightinincheschecker)\n {\n rusrheightininches = rusrheightininches - 1;\n }\n else\n {\n\n }\n System.out.println(\"Hii \" + usrname + \". I am Cartic, a basic textual virtual personal assistant. I do know that you are \" + usrage\n + \" years old. You are a \" + usrgender + \" and are \" + rusrheight + \" feet \" + rusrheightininches + \" inch(es) tall\");\n }\n}\n</code></pre>\n\n<p>Now, it is much easier to see the structure.</p>\n\n<p>Java code-style guidelines put the <code>{</code> opening brace on the same line as the control statement, so, for example, the code:</p>\n\n<blockquote>\n<pre><code> if (rusrheightininches >= 0.10 && rusrheightininches < 0.12)\n {\n rusrheightininches = rusrheightininches * 100;\n } else {\n rusrheightininches = rusrheightininches * 10;\n }\n</code></pre>\n</blockquote>\n\n<p>should be:</p>\n\n<pre><code> if (rusrheightininches >= 0.10 && rusrheightininches < 0.12) {\n rusrheightininches = rusrheightininches * 100;\n } else {\n rusrheightininches = rusrheightininches * 10;\n }\n</code></pre>\n\n<p>Also, in the previous <code>if</code> statement you have an empty else block.... you can just remove it:</p>\n\n<blockquote>\n<pre><code> if (rusrheight > usrheight)\n {\n rusrheight = rusrheight - 1;\n }\n else\n {\n\n }\n</code></pre>\n</blockquote>\n\n<p>becomes:</p>\n\n<pre><code> if (rusrheight > usrheight) {\n rusrheight = rusrheight - 1;\n }\n</code></pre>\n\n<p>As for your variables, they are nice descriptive names, but, in Java, it is common to use what is called 'camelCase', where the first letter is lower-case, and the subsequent first-word-letters are Capitalized.</p>\n\n<p>Also, while it is often convenient to shorten long parts of variables, the abbreviation of 'user' to 'usr' is not saving you much.....</p>\n\n<p>So, for example, your variables :</p>\n\n<blockquote>\n<pre><code>String usrname;\nString usrage;\nString usrgender;\nDouble usrheight;\n</code></pre>\n</blockquote>\n\n<p>would be</p>\n\n<pre><code>String userName;\nString userAge;\nString userGender;\nDouble userHeight;\n</code></pre>\n\n<p>I would recommend that you use an IDE (Eclipse/IntelliJ/Netbeans) to help you get these things right. There is some debate about whether new programmers should use an IDE or not, because they make some things really easy and you may miss understanding some of the basic requirements of the language.... but, I believe that the IDE's allow you to focus on the stuff that is more important, like the code content.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:14:41.490",
"Id": "84318",
"Score": "0",
"body": "admittedly i fall into the group that recommends against new developers using advanced IDEs. Eclipse is a great IDE, but features like intellisense and the numerous editor plugins, allow for bad practices.\n\nIts important for any programmer to learn how to read and understand a JavaDoc, instead of just letting intellisense tell you the methods.\n\nIt also requires you to pay more attention to the Models you're building. my recommendation would be http://www.jgrasp.org/schools.html it's no frills it has the JVM, but it was developed by Auburn University and is an excellent platform to learn on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:17:00.697",
"Id": "84319",
"Score": "0",
"body": "@Madullah I understand both perspectives, and agree with a lot of the arguments on both sides... ;-) In my opinion, the 'balance' falls in favour of using an IDE (for me the tipping-factor is the ease-of-debugging running programs)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:21:22.117",
"Id": "84320",
"Score": "0",
"body": "I agree, my software recommendation, has an excellent visual debugger. http://www.jgrasp.org/debugger.html and is used by many HS and Universities becuase of what it does and doesn't provide."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:26:44.457",
"Id": "48038",
"ParentId": "48035",
"Score": "16"
}
},
{
"body": "<pre><code>Scanner name = new Scanner(System.in);\nScanner age = new Scanner(System.in);\nScanner gender = new Scanner(System.in);\nScanner height = new Scanner(System.in);\n</code></pre>\n\n<p>There is absolutely no reason to have four scanner variables. It does not matter which one you use, it would be better to just have one: <code>Scanner scanner = new Scanner(System.in);</code></p>\n\n<p>Also, you should close the <code>Scanner</code> once your done with it by calling <code>scanner.close();</code> (or use try-with-resources statement)</p>\n\n<hr>\n\n<pre><code>Double usrheight;\n</code></pre>\n\n<p>You don't need to use <code>Double</code>, use <code>double</code> instead. The difference is that <code>double</code> is a <em>primitive</em> type, which means that among other things it cannot be set to <code>null</code>.</p>\n\n<hr>\n\n<pre><code>else \n{\n\n}\n</code></pre>\n\n<p>There's no reason in including an <code>else</code> if you don't do anything in it. Remove that part.</p>\n\n<hr>\n\n<p>A variable name such as <code>rusrheightininches</code> is easier to read by using \"camelCase\", I would name it <code>realUserHeightInches</code></p>\n\n<p>Instead of using <code>rusrheightininches = rusrheightininches * 100;</code> you can do <code>rusrheightininches *= 100;</code> which is just a shorter way of writing it.</p>\n\n<hr>\n\n<p><strong>Variable Scope</strong>. Your variables are currently declared as <em>fields</em> in the class. They only need to be accessible inside one method, so you can declare them within that method as <em>local variables</em>.</p>\n\n<hr>\n\n<p><strong>Taking it further</strong></p>\n\n<p>Java is an Object Oriented language. Write your own classes, use objects, add more methods. Everything does not need to be done inside one method. I suggest you read Oracle's tutorial at <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/\">http://docs.oracle.com/javase/tutorial/java/javaOO/</a> . You could use a <code>Person</code> class for example with the properties name, age, gender height.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:30:38.600",
"Id": "48040",
"ParentId": "48035",
"Score": "11"
}
},
{
"body": "<p>This code does not work.</p>\n\n<p>When you try to run your program, Java will complain because it can't find the <code>main</code> method. Isn't there a <code>main</code> method right there? Yes, but it has the wrong <em>signature</em>. Java looks for a <code>public static void main (String[] argv)</code> – both the <code>static</code> and the <code>String[]</code> argument are important.</p>\n\n<p>The simplest way to add that is</p>\n\n<pre><code>public static void main(String[] argv) {\n new LMComplex().main();\n}\n</code></pre>\n\n<p>The next big problem is that you are creating multiple <code>Scanner</code>s around the same input stream <code>System.in</code>. Due to buffering, lines will get lost. Instead, create only one <code>Scanner</code>, and request multiple <code>nextLine</code>s from it:</p>\n\n<pre><code>Scanner in = new Scanner(System.in);\nSystem.out.println(\"Enter your name: \");\nusrname = in.nextLine();\nSystem.out.println(\"Enter your age(Numbers): \");\nusrage = in.nextLine();\n...\n</code></pre>\n\n<p>Once these issues are fixed, the program will actually start to work correctly, and there are many style issues to improve (see rolfl's answer for a good summary).</p>\n\n<p>Another bug: The <code>nextDouble</code> method of a <code>Scanner</code> is locale dependent. When I enter <code>5.5</code> as the height, I will get an exception because the decimal separator in my German locale is the comma – <code>5,5</code> works perfectly. To avoid this, we need to set a locale that works independently of the system locale:</p>\n\n<pre><code>Scanner in = new Scanner(System.in);\nin.useLocale(new Locale(\"en\", \"US\"));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:38:44.413",
"Id": "84284",
"Score": "1",
"body": "I think saying \"This code does not work.\" just because it's lacking a main method is a bit overkill. Besides lacking a main method, the code itself runs perfectly fine. I did not encounter any problem with lines getting lost, any way to reproduce that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:41:18.273",
"Id": "84285",
"Score": "0",
"body": "@SimonAndréForsberg I thought the same thing, but then I [ran the code](http://ideone.com/Pqm6Ax). Apparently creating multiple scanners somehow exhausts the lines (?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:45:44.770",
"Id": "84287",
"Score": "0",
"body": "I also ran the code (in Eclipse), and I did not encounter that problem. Strange. Ideone bug?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:52:52.173",
"Id": "84289",
"Score": "0",
"body": "@SimonAndréForsberg I can reproduce the failure on my machine, by piping the input through STDIN. My `java -version` output: *java version \"1.7.0_51\"\nOpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.12.04.2)\nOpenJDK Server VM (build 24.45-b08, mixed mode, sharing)*"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:31:40.403",
"Id": "48041",
"ParentId": "48035",
"Score": "11"
}
},
{
"body": "<h2>Naming:</h2>\n<p>You should use <strong>readable</strong> names for your variables. Furthermore the convention for Java-naming is <code>camelCase</code>. Your fieldnames should start with a lower-case letter and each new "word" inside of these names, should start with a single upper-case letter.</p>\n<p>readable here means, you shouldn't have to do some crazy tounge-exercise when reading variable names out loud. <code>usr</code> and similar is not good, there is no need to save characters in the wrong place:</p>\n<pre><code>usrname --> userName\nusrage --> userAge\n//repeat with all other variables\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:33:35.363",
"Id": "48042",
"ParentId": "48035",
"Score": "7"
}
},
{
"body": "<p>Most has been said already but I'll add that you can contract these statements</p>\n\n<pre><code>rusrheightininches = rusrheightininches * 100; \nrusrheightininches = rusrheightininches - 1;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>rusrheightininches *= 100;\nrusrheightininches -= 1;\n</code></pre>\n\n<p>I'll restate the importance of naming conventions: this is unreadable</p>\n\n<pre><code>rusrheightinincheschecker \n</code></pre>\n\n<p>but this isn't:</p>\n\n<pre><code>rUserHeightInInchesChecker\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T13:55:35.387",
"Id": "48049",
"ParentId": "48035",
"Score": "5"
}
},
{
"body": "<p>Your height input routine is broken, because you have used a floating-point number to represent two numbers that just happen to be separated by a dot. The fundamental flaw is that 5 ft. 1 in. is indistinguishable from 5 ft. 10 in.</p>\n\n<pre><code>System.out.println(\"Enter your height(feet.inches . 5 feet 5 inches = 5.5): \");\nusrheight = height.nextDouble();\nDouble rusrheight = Math.ceil(usrheight);\nif(rusrheight > usrheight)\n{\nrusrheight = rusrheight - 1;\n}\nelse \n{\n\n}\nDouble rusrheightininches = usrheight - rusrheight;\nif(rusrheightininches >= 0.10 && rusrheightininches < 0.12)\n{\nrusrheightininches = rusrheightininches * 100;\n} else {\nrusrheightininches = rusrheightininches * 10;\n}\nDouble rusrheightinincheschecker = rusrheightininches;\nrusrheightininches = Math.ceil(rusrheightininches);\nif(rusrheightininches > rusrheightinincheschecker)\n{\nrusrheightininches = rusrheightininches - 1;\n}\nelse \n{\n\n}\n</code></pre>\n\n<p>There are a lot of puzzling moments as I read through that code.</p>\n\n<ul>\n<li>Why are there empty <code>else</code> clauses? Just leave them out.</li>\n<li>Why do you declare <code>rusrheight</code>, <code>rusrheightininches</code>, and <code>rusrheightinincheschecker</code> as <code>Double</code> objects? That will cause much unnecessary autoboxing and unboxing.</li>\n<li>What does <code>rusrheight</code> mean? Isn't it just <code>Math.floor(usrheight)</code>?</li>\n<li>What is the point of <code>rusrheightinincheschecker</code>? It just helps to compute <code>Math.floor(rusrheightininches)</code> the hard way.</li>\n</ul>\n\n<p>In the end, though, those concerns are irrelevant since the parsing strategy is fundamentally flawed. You really ought to write a custom parsing routine. For example:</p>\n\n<pre><code>/**\n * Reads a height in feet and inches, in the format fff.ii.\n * The input must be at the end of a line.\n *\n * @return The height as inches (i.e., \"4.3\" is interpreted as 4 * 12 + 3 = 51).\n */\npublic static double readHeightAsInches(Scanner scan)\n throws InputMismatchException {\n scan.next(Pattern.compile(\"([+-]?\\\\d+)(?:\\\\.(\\\\d*\\\\.?\\\\d*))?$\"));\n MatchResult match = scan.match();\n int feet = Integer.parseInt(match.group(1));\n double inches = (match.group(2) != null && !match.group(2).isEmpty()) ?\n Double.parseDouble(match.group(2)) : 0.0;\n return 12 * feet + (feet >= 0 ? inches : -inches);\n}\n</code></pre>\n\n<p>It's easier to return a single number representing the number of inches rather than a pair of numbers representing feet and inches.</p>\n\n<p>That would be paired with a formatting routine:</p>\n\n<pre><code>public static String formatHeight(double inches) {\n StringBuffer sb = new StringBuffer(20);\n if (inches < 0) {\n sb.append('-');\n inches = -inches;\n }\n if (inches >= 24) {\n sb.append((int)inches / 12).append(\" feet \");\n } else if (inches >= 12) {\n sb.append((int)inches / 12).append(\" foot \");\n }\n sb.append(inches %= 12);\n sb.append(inches >= 1 && inches < 2 ? \" inch\" : \" inches\");\n return sb.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T12:46:21.207",
"Id": "84479",
"Score": "0",
"body": "Agreed on all points, but the replacement code looks rather daunting, especially the use of a regex. To read in feet and inches, it'd be simpler just to read them in using two separate questions, or alternatively to read in one line and [split it](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java), parsing each element of the result. For formatting, I'd use `int feet = (int)inches / 12; int extraInches = inches % 12;`, and then the pluralization checks become clearer. Support for fractional inches and negative height seems unnecessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T16:34:16.607",
"Id": "84525",
"Score": "0",
"body": "@deltab Agreed, that the code could be much simpler if you don't need to implement the originally intended behaviour."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T17:46:12.303",
"Id": "48074",
"ParentId": "48035",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:15:20.787",
"Id": "48035",
"Score": "14",
"Tags": [
"java",
"beginner"
],
"Title": "Questions & Responses: Let me tell you about you"
} | 48035 |
<p>I have code below which is set to check the date of <code>DateToComplete</code>, and if the date is 2 weeks or more ago, change the status of Complete from 3 to 2.</p>
<p>Is this the best way?</p>
<pre><code>USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[spChanger]
AS
BEGIN
Execute ('UPDATE [TblActions] SET Complete = 2 WHERE DateToComplete < Date.Now.AddDays(14) AND Complete = 3' )
END
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:51:27.003",
"Id": "84329",
"Score": "1",
"body": "I removed the .net tag because this looks like a T-SQL CREATE PROCEDURE script, but the presence of `Date.Now.AddDays(14)` makes me wonder... is this working as it should?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:28:36.137",
"Id": "84337",
"Score": "0",
"body": "If this is called from VB.NET code, I think it would be better to use an ORM (Entity Framework?) and *code* that logic, rather than stuffing *business logic* in a stored procedure."
}
] | [
{
"body": "<blockquote>\n<pre><code>Create PROCEDURE [dbo].[spChanger] \n\nAS\nBEGIN\n\nExecute ('UPDATE [TblActions] SET Complete = 2 WHERE DateToComplete < Date.Now.AddDays(14) AND Complete = 3' )\n\nEND\n</code></pre>\n</blockquote>\n\n<p>Your casing is inconsistent. If you prefer UPPERCASE keywords, stick to uppercase :)</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[spChanger] \n\nAS\nBEGIN\n\nEXECUTE ('UPDATE [TblActions] SET Complete = 2 WHERE DateToComplete < Date.Now.AddDays(14) AND Complete = 3' )\n\nEND\n</code></pre>\n\n<p>The name of the procedure is potentially problematic. \"Changer\" says nothing about what's changing, and as your database grows you'll certainly end up wondering why you didn't call it something along the lines of <code>spUpdateTblActionsCompleteStatusCode</code>.</p>\n\n<hr>\n\n<p>Why are you executing a string? Why not just do this?</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[spChanger] \n\nAS\nBEGIN\n\n UPDATE TblActions\n SET Complete = 2 \n WHERE DateToComplete < Date.Now.AddDays(14) \n AND Complete = 3\n\nEND\n</code></pre>\n\n<p>Now you get IntelliSense in SSMS (assuming SQL Server) and it's much harder to make a typo on a column name.</p>\n\n<hr>\n\n<p>I don't think this <code>CREATE PROCEDURE</code> script can run though. <code>Date.Now.AddDays(14)</code> isn't valid T-SQL.</p>\n\n<p>That said I think you're missing opportunity for some parameters. I'd do it like this:</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[spUpdateTblActionsCompleteStatusCode] \n @completeStatusValue INT = 2,\n @daysDiff INT = 14,\n @completeStatusFilter INT = 3\nAS\nBEGIN\n\n UPDATE TblActions\n SET Complete = @completeStatusValue\n WHERE DATEDIFF(d, DateToComplete, DATEADD(d, @daysDiff, GETDATE())) < @daysDiff\n AND Complete = @completeStatusFilter\n\nEND\n</code></pre>\n\n<p>When your code runs this stored procedure, if no parameters are passed it will just use the default values, and you have the flexibility to pass different parameters if/when you need to.</p>\n\n<p>Also I'd recommend scripting your T-SQL as a <code>DROP+CREATE</code>, so the full script would look like this:</p>\n\n<pre><code>USE [DB]\nGO\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n\nIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateTblActionsCompleteStatusCode]') AND type IN (N'P', N'PC'))\nDROP PROCEDURE [dbo].[spUpdateTblActionsCompleteStatusCode]\nGO\n\nCREATE PROCEDURE [dbo].[spUpdateTblActionsCompleteStatusCode] \n @completeStatusValue INT = 2,\n @daysDiff INT = 14,\n @completeStatusFilter INT = 3\nAS\nBEGIN\n\n UPDATE TblActions\n SET Complete = @completeStatusValue\n WHERE DATEDIFF(d, DateToComplete, DATEADD(d, @daysDiff, GETDATE())) < @daysDiff\n AND Complete = @completeStatusFilter\n\nEND\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:31:20.637",
"Id": "84338",
"Score": "0",
"body": "The reason for DROP+CREATE is that you want to be able to run the script *n* times, and always produce the same result; if you just CREATE, then the 2nd time you run it it will run into an error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:33:36.813",
"Id": "84340",
"Score": "0",
"body": "if you already have a SPROC with this name you can run an `ALTER` on it. rather than drop a procedure to create it again. all you have to do is change the `CREATE` to `ALTER` after you create the SPROC the first time. I think it would be a little nicer on the query. then when it is the way you want it, you run the SPROC to do the stuff inside of the SPROC"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:39:05.983",
"Id": "84341",
"Score": "0",
"body": "If there are permissions to be scripted, I'd rather have them explicitly scripted alongside the CREATE part, for explicitness."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:45:08.607",
"Id": "84343",
"Score": "0",
"body": "what is the difference between an `ALTER` and a `CREATE` the Stored Procedures that I have created and altered the only thing that changed when I needed to alter them was the Keyword?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:49:38.850",
"Id": "84345",
"Score": "0",
"body": "If there are permissions involved, ALTER wouldn't affect them; I'd prefer having the script explicitly having them, and put the .sql file under source control in the .net project. Actually it's just because I was taught to script drop+create over alter ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:53:51.743",
"Id": "84347",
"Score": "0",
"body": "I Learned from `Trial and Error and Google`. I like the Source Control idea though."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:18:20.053",
"Id": "48068",
"ParentId": "48044",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48068",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:13:37.863",
"Id": "48044",
"Score": "2",
"Tags": [
"sql",
"stored-procedure"
],
"Title": "Execute edit in a stored procedure based on database value"
} | 48044 |
<p>I am learning PDO. I have a class - User...</p>
<pre><code>class User {
protected static $table_name="users";
public $id;
public $first_name;
public $last_name;
public function pdo_create() {
global $handler;
$sql = " INSERT INTO users (first_name, last_name)";
$sql .= " VALUES (?, ?)";
$query = $handler->prepare($sql);;
$query->execute(array($this->first_name ,$this->last_name));
}
}
</code></pre>
<p>When I run this...</p>
<pre><code>$user= new User();
$user->first_name = "test";
$user->last_name = "test";
$user->pdo_create();
</code></pre>
<p>It works fine. I know it's a bit odd posting when things are working, but I have suspicions that this is not the best approach. I am still learning PDO and about the convert my MySQLi site over to PDO. I want to make sure the PDO veterans think this is a reasonable approach.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:23:58.130",
"Id": "84290",
"Score": "1",
"body": "Welcome to Code Review! Working code is exactly what we're about!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:30:55.507",
"Id": "84291",
"Score": "0",
"body": "@SimonAndréForsberg basically critic his code because he is new to PDO. Read my rebuttal for him"
}
] | [
{
"body": "<p>Your design is flawed in the following way:</p>\n\n<p><strong>DO NOT USE GLOBAL.</strong></p>\n\n<p>It is not OO programming and you shouldn't be calling it if you are using PDO - pass your PDO through your function or as part of your user constructors. (see <strong>SOLID</strong> design patterns)</p>\n\n<pre><code>class User \n{\n //private attributes\n private $_db;\n public function __construct(PDO $pdo)\n {\n $this->_db = $pdo;\n }\n}\n</code></pre>\n\n<p><strong>your function pdo_create</strong>\nis too couple with pdo - if you decide to switch off from pdo - you will need to re-write that function call to reflect what you change to - use convention a bit more general: <code>creatingUser(PDO $pdo)</code> for example or even better <code>creatingUser(DBInterface $db)</code> (as part of <strong>SOLID</strong></p>\n\n<p>Now as for the function itself:</p>\n\n<p>+1 for using prepare statement however ? is more used for mysqli - it better to use place handler instead. such as VALUES(:first_name, :last_name). When you pass the array you can then use the place handler to effectively assign to which variable its value. It is best for readability later.</p>\n\n<p>Finally: you defeat the purpose of the class if your attributes are PUBLIC. Ideally functions receives parameters by the function itself OR by the constructor of the class which initializes the attributes of the class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:36:09.123",
"Id": "84292",
"Score": "1",
"body": "azngunit81 - forgive my ingnorance, but could you give me an example using this case of \"pass your PDO through your function or as part of your user constructors\". I'd be really grateful.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:42:05.480",
"Id": "84296",
"Score": "0",
"body": "@GhostRider I added a bit of code - but fill out the rest on your own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:54:29.140",
"Id": "84297",
"Score": "0",
"body": "many thanks I can see what way to go now..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:29:57.890",
"Id": "48046",
"ParentId": "48045",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48046",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T12:15:35.620",
"Id": "48045",
"Score": "4",
"Tags": [
"php",
"pdo"
],
"Title": "Evaluation of insert method from within a class using PDO"
} | 48045 |
<p>I wrote this script as a way to backup and/or download quickly a set of repos or gists from a user. I don't have any major concerns but I'm a noob at bash scripting, and I've been scouring the internet putting these pieces together. I would love for someone to take a look and let me know best practices or problems there may be.</p>
<pre><code>#!/usr/bin/env bash
# Check if git is installed, if not bail
if [[ ! "$(type -P 'git')" ]]; then
printf "$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\n" "Git is required to use $(basename "$0")"
printf "\n"
printf "Download it at http://git-scm.com"
exit 2
fi
# Check if jq is installed, if not bail
if [[ ! "$(type -P 'jq')" ]]; then
printf "$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\n" "jq is required to parse JSON."
printf "\n"
printf "Download it at http://stedolan.github.io/jq"
exit 2
fi
# variables
feed="repos"
path="${HOME}/Downloads"
usage="$(basename "$0"): usage: $(basename "$0") [-h|--help] [-v|--version] [-f|--feed <value>] <github_username> [<path>]"
# Test for known flags
for opt in "$@"
do
case "$opt" in
-f | --feed) # choose feed type
if [[ "$2" == "repos" || "$2" == "gists" ]]; then
feed="$2"
else
printf "%s\n" "-bash: $(basename "$0"): $1: invalid feed type [repos|gists]"
printf "%s" "$usage"
exit 1
fi
shift 2
;;
-h | --help) # Help text
printf "\n"
printf "%s\n" "Options:"
printf "\n"
printf "\t%s\n" "-h, --help Print this help text"
printf "\t%s\n" "-f, --feed [<value>] <value> can be either gists or repos, default is repos"
printf "\t%s\n" "-v, --version Print out the version"
printf "\n"
printf "%s\n" "Documentation can be found at https://github.com/chriopedia/clone-all"
exit 0
;;
--test) # test suite using roundup
roundup="$(type -P 'roundup')"
[[ ! -z $roundup ]] || {
printf "$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\n" "Roundup is required to run tests"
printf "\n"
printf "Download it at https://github.com/bmizerany/roundup"
exit 2;
}
$roundup ./tests/*.sh
exit 0
;;
-v | --version) # Version of software
printf "%s\n" "Version $(git describe --tags)"
exit 0
;;
--) # End of all options
printf "%s\n" "-bash: $(basename "$0"): $1: invalid option"
printf "%s" "$usage"
exit 1
;;
-*)
printf "%s\n" "-bash: $(basename "$0"): $1: invalid option"
printf "%s" "$usage"
exit 1
;;
*) # No more options
break
;;
esac
done
# Check if username is passed in, if not bail
if [[ -z "$1" ]]; then
printf "$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\n" "A valid Github user is required"
exit 3
fi
# check if directory is not blank and exists
if [[ ! -z "$2" && -d "$2" ]]; then
# http://www.linuxforums.org/forum/programming-scripting/solved-delete-trailing-slashes-using-bash-board-means-print-172714.html
# This matches from the start of the source string, any
# string ending with a non-slash.
pattern="^.*[^/]"
# Apply regex
[[ ${2} =~ $pattern ]]
# Print the portion of the source string which matched the regex.
path="${BASH_REMATCH[0]}"
fi
# set some variables
user="$1"
api_url="https://api.github.com/users/${user}/${feed}"
current_page=1
per_page=100
printf "%s" "Checking status of user '${user}'"
# http://stackoverflow.com/questions/238073/how-to-add-a-progress-bar-to-a-shell-script
# start progress bar
while :;do echo -n .;sleep 1;done &
# check response header from github user passed in
# http://stackoverflow.com/a/10724976/1536779
response="$(curl --write-out %{http_code} --silent --output /dev/null "${api_url}")"
# kill the progress bar
kill $!; trap 'kill $!' SIGTERM
# if reponse is greater than or equal to 400 somethings wrong
if [[ "${response}" -ge 400 ]]; then
printf "%s\n" "-bash: $(basename "$0"): $1: user doesn't exist"
#debug statement
printf "%s\n" "Github HTTP Response code: ${response}"
exit 3
fi
# grab the total number of pages there are
# https://gist.github.com/michfield/4525251
total_pages="$(curl -sI "${api_url}?page=1&per_page=${per_page}" | sed -nE "s/^Link:.*page=([0-9]+)&per_page=${per_page}>; rel=\"last\".*/\1/p")"
if [[ -z ${total_pages} ]]; then
total_pages=1
fi
# grab a list of repos or gists
# @params $1: page number
# example: get_repos_list 1
get_repos_list() {
# get a json list of all repos and story as array
if [[ ${feed} != 'gists' ]]; then
repos=$(curl -fsSL "${api_url}?page=${1}&per_page=${per_page}" | jq '.[] | .name')
else
repos=$(curl -fsSL "${api_url}?page=${1}&per_page=${per_page}" | jq '.[] | .id')
fi
echo "$repos"
}
# loop through list of repos at the current page
clone_shit() {
printf "%s" "Grabbing list of ${feed} for ${user}"
# http://stackoverflow.com/questions/238073/how-to-add-a-progress-bar-to-a-shell-script
# start progress bar
while :;do echo -n .;sleep 1;done &
# get the list of repos for user
repos_list=($(get_repos_list "${current_page}"))
# kill the progress bar
kill $!; trap 'kill $!' SIGTERM
printf "\n"
# loop through all repos in array
for index in ${!repos_list[*]}
do
# variable assignment
repo="${repos_list[$index]}"
# Strip quotes from string
repo="${repo:1:${#repo}-2}"
if [[ ${feed} != "gists" ]]; then
printf "%s\n" "Cloning https://github.com/${user}/${repo} to ${path}/repos/${repo}"
#git clone "https://github.com/${user}/${repo}" "${path}/repos/${repo}"
else
printf "%s\n" "Cloning https://gist.github.com/${repo}.git to ${path}/gists/${repo}"
#git clone "https://gist.github.com/${repo}.git" "${path}/gists/${repo}"
fi
done
}
printf "\n"
clone_shit
if [[ ${total_pages} -gt 1 && ${current_page} -lt ${total_pages} ]]; then
current_page=$((current_page + 1))
clone_shit
fi
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T22:37:12.807",
"Id": "84391",
"Score": "0",
"body": "Only glanced for a second but `if [[ \"$(some command)\" ]]; then` is very redundant when you want to depend on the commands return value. `if some command; then` works just fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T22:44:28.303",
"Id": "84392",
"Score": "0",
"body": "@EtanReisner, would you point to a specific example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T23:18:32.503",
"Id": "84393",
"Score": "1",
"body": "`if [[ ! \"$(type -P 'git')\" ]]; then` can be replaced with `if ! type -P 'git' >/dev/null; then` for example. Which works because type returns true if it finds its argument and false otherwise and avoids the subshell and string comparison (against the empty string)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:03:15.863",
"Id": "84405",
"Score": "1",
"body": "Your use of `printf` is a bit odd. You give it a format specifier of `%s` and then interpolate variables into its only argument and have it print that. It would be better to give it the actual string you want the variables interpolated into using its formatting specifiers and then giving it the variables as arguments. `printf 'Grabbing ... %s for %s' \"${feed}\" \"${user}\"` instead of `printf '%s' \"Grabbing .. ${feed} for ${user}\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:14:16.843",
"Id": "84421",
"Score": "0",
"body": "Is the single quote necessary in the first part of the print statement or is that just preference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:31:36.190",
"Id": "84423",
"Score": "0",
"body": "Either quote will work. The difference is what gets evaluated inside the quotes and since, in general, you want the argument to printf to be a static string using '' forces a better habit (at least as far as I'm concerned). My general rule is use single quotes in all situations that don't require double quotes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:58:33.473",
"Id": "84425",
"Score": "0",
"body": "Cool, but how do you deal with situations like such... `printf \"$(tput setaf 1)⊘ Error:$(tput sgr0) Git is required to use %s. Aborting!\\n\" \"$(basename \"$0\")\"`. How do you deal with the `tput` interpolation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T05:02:31.320",
"Id": "84426",
"Score": "1",
"body": "`printf '%s⊘ Error:%s Git is required to use %s. Aborting!\\n' \"$(tput setaf 1)\" \"$(tput sgr0)\" \"$(basename \"$0\")\"` the output from tput is just characters like anything else (not to mention that your double quote version doesn't work in an interactive shell with history expansion on because the shell tries to expand the `!` and explodes."
}
] | [
{
"body": "<p>It's not a bad attempt, though full of duplicated code and some bad practices.</p>\n\n<h3>Checking if a program exists</h3>\n\n<p>You do this kind of thing several times:</p>\n\n<blockquote>\n<pre><code># Check if git is installed, if not bail\nif [[ ! \"$(type -P 'git')\" ]]; then\n printf \"$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\\n\" \"Git is required to use $(basename \"$0\")\"\n printf \"\\n\"\n printf \"Download it at http://git-scm.com\"\n exit 2\nfi\n</code></pre>\n</blockquote>\n\n<p>First of all, the <code>if</code> condition can be simplified to this:</p>\n\n<pre><code>if ! type -P git >/dev/null; then\n</code></pre>\n\n<p>If <code>git</code> is not on <code>$PATH</code>, the <code>type</code> command will fail, making the condition evaluate to true and execute the <code>then</code> block. This is a lot more efficient than doing a process substitution with <code>$(...)</code> followed by a string evaluation. I also removed the quotes from <code>'git'</code>, you don't need to escape bare words like \"git\", \"jq\", \"round\". So the same goes for those.</p>\n\n<p>However, as you notice now you have to redirect the output of the <code>type</code> command to <code>/dev/null</code>. Before, this output was captured by the <code>$(...)</code> process substitution. Since we're not using that anymore, we need to get rid of it ourselves. It's still much cleaner this way.</p>\n\n<p>Another thing in this method, you are using a second <code>printf</code> just to print a blank line:</p>\n\n<blockquote>\n<pre><code>printf \"$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\\n\" \"Git is required to use $(basename \"$0\")\"\nprintf \"\\n\"\n</code></pre>\n</blockquote>\n\n<p>It would be better to make that <code>\\n</code> part of the first <code>printf</code>:</p>\n\n<blockquote>\n<pre><code>printf \"$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\\n\\n\" \"Git is required to use $(basename \"$0\")\"\n</code></pre>\n</blockquote>\n\n<h3>Reducing duplication</h3>\n\n<p>You have a lot of duplication throughout. For example <code>$(basename \"$0\")</code> appears almost 10 times. It would be better to save it in a constant early in the script, for example:</p>\n\n<pre><code>me=$(basename \"$0\")\n</code></pre>\n\n<p>Error reporting also happens way too often, and since you're doing it in a fancy way, it's kind of complicated, so you probably copy-pasted it every time. Copy-pasting is never good, because if you need to change something later, you have to synchronize your changes. It would be better to create a helper method for reporting errors:</p>\n\n<pre><code>print_error() {\n printf \"$(tput setaf 1)⊘ Error:$(tput sgr0) %s. Aborting!\\n\\n\" \"$1\"\n}\n</code></pre>\n\n<p>You don't need to copy-paste this fancy <code>printf</code> anymore, you can just do:</p>\n\n<pre><code>print_error \"jq is required to parse JSON.\"\n</code></pre>\n\n<p>Similarly, you check if git, jq, roundup exist, and you always use the same pattern for this logic. This is another ideal candidate for a helper function:</p>\n\n<pre><code>require_prog() {\n prog=$1\n msg=$2\n url=$3\n type -P \"$prog\" >/dev/null || {\n print_error \"$msg\"\n echo \"Download it at $url\"\n exit 2\n }\n}\n</code></pre>\n\n<p>Now your checks become simply:</p>\n\n<pre><code>require_prog git \"Git is required to use $me\" http://git-scm.com\nrequire_prog jq \"jq is required to parse JSON.\" http://stedolan.github.io/jq\n</code></pre>\n\n<h3>Looping over <code>$@</code></h3>\n\n<p>A nice trick that instead of <code>for i in \"$@\"; do ...; done</code>, you can shorten as:</p>\n\n<pre><code>for i; do ...; done\n</code></pre>\n\n<h3>Using <code>case</code> instead of multiple OR conditions in <code>[[ ... ]]</code></h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>if [[ \"$2\" == \"repos\" || \"$2\" == \"gists\" ]]; then\n feed=\"$2\"\nelse\n printf \"%s\\n\" \"-bash: $(basename \"$0\"): $1: invalid feed type [repos|gists]\"\n printf \"%s\" \"$usage\"\n exit 1\nfi\nshift 2\n</code></pre>\n</blockquote>\n\n<p>I find this way neater:</p>\n\n<pre><code>case \"$2\" in\n repos | gists) feed=\"$2\" ;;\n *)\n echo \"-bash: $me: $1: invalid feed type [repos|gists]\"\n echo \"$usage\"\n exit 1\nesac\nshift 2\n</code></pre>\n\n<p>They are both fine. However, if you prefer to use <code>[[ ... ]]</code> then note that you don't need all those quotes you have there, you could write like this:</p>\n\n<pre><code>if [[ $2 == repos || $2 == gists ]]; then\n</code></pre>\n\n<p>Maybe you're thinking it's better to be safe than sorry with quotes, but I think it's better to understand how they work. Quotes are very \"noisy\", I find it a lot easier to read without quotes.</p>\n\n<h3>Tedious <code>printf</code></h3>\n\n<p>This is really tedious:</p>\n\n<blockquote>\n<pre><code>printf \"\\n\"\nprintf \"%s\\n\" \"Options:\"\nprintf \"\\n\"\n</code></pre>\n</blockquote>\n\n<p>You could do the same thing a lot easier with simple <code>echo</code> statements:</p>\n\n<pre><code>echo\necho Options:\necho\n</code></pre>\n\n<h3>The above are just examples...</h3>\n\n<p>Your script is quite long, and full of the kind of mistakes I pointed out above. Apply the same logic as above everywhere, and your script will become cleaner and better.</p>\n\n<h3>shellcheck.net</h3>\n\n<p>There is this awesome site that can spot many common shell scripting errors and bugs:</p>\n\n<pre><code>http://www.shellcheck.net/#\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-16T05:48:59.827",
"Id": "60212",
"ParentId": "48050",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "60212",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:11:21.143",
"Id": "48050",
"Score": "8",
"Tags": [
"bash",
"console",
"git",
"curl"
],
"Title": "Bash script to clone all public repos or gists for a specified user, optionally to a directory of choice"
} | 48050 |
<p>I have written some code to track buffs as a side addition to the popular game <a href="http://leagueoflegends.wikia.com/wiki/Buff" rel="noreferrer">League of Legends</a>.</p>
<p>My code is incredibly repetitive and I also have the issue of not being able to track multiple buffs, although that might not be on topic for the question so feel free to not consider this when answering.</p>
<pre><code>import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Jungle Timers v1.0");
System.out.println("\nSelect a buff to time:");
System.out.println("\n1. Blue");
System.out.println("2. Enemy Blue");
System.out.println("3. Red");
System.out.println("4. Enemy Red");
System.out.println("5. Dragon");
System.out.println("6. Baron");
System.out.print("\n> ");
int timerChoice = keyboard.nextInt();
keyboard.close();
switch (timerChoice) {
case 1:
friendlyBlue();
case 2:
enemyBlue();
case 3:
friendlyRed();
case 4:
enemyRed();
case 5:
Dragon();
case 6:
Baron();
}
}
public static void friendlyBlue() {
System.out.println("\nTracking your blue...");
System.out.println("5 Minutes left");
int friendlyBlue = 300;
long startTime = System.currentTimeMillis() / 1000;
long endTime = startTime + friendlyBlue;
while (System.currentTimeMillis() / 1000 < endTime) {
while (startTime != System.currentTimeMillis() / 1000) {
startTime += 1;
if (endTime - startTime > 1)
if (endTime - startTime == 240)
System.out.println("4 Minutes left");
if (endTime - startTime == 180)
System.out.println("3 Minutes left");
if (endTime - startTime == 120)
System.out.println("2 Minutes left");
if (endTime - startTime == 60)
System.out.println("1 Minute left");
if (endTime - startTime == 30)
System.out.println("30 Seconds left");
if (endTime - startTime == 15)
System.out.println("15 Seconds left");
if (endTime - startTime == 5)
System.out.println("5 Seconds left");
else if (endTime - startTime == 1) {
System.out.println("Blue Buff is up!");
}
}
}
}
public static void enemyBlue() {
System.out.println("\nTracking enemy blue...");
System.out.println("5 Minutes left");
int enemyBlue = 300;
long startTime = System.currentTimeMillis() / 1000;
long endTime = startTime + enemyBlue;
while (System.currentTimeMillis() / 1000 < endTime) {
while (startTime != System.currentTimeMillis() / 1000) {
startTime += 1;
if (endTime - startTime > 1)
if (endTime - startTime == 240)
System.out.println("4 Minutes left");
if (endTime - startTime == 180)
System.out.println("3 Minutes left");
if (endTime - startTime == 120)
System.out.println("2 Minutes left");
if (endTime - startTime == 60)
System.out.println("1 Minute left");
if (endTime - startTime == 30)
System.out.println("30 Seconds left");
if (endTime - startTime == 15)
System.out.println("15 Seconds left");
if (endTime - startTime == 5)
System.out.println("5 Seconds left");
else if (endTime - startTime == 1) {
System.out.println("Enemy Blue Buff is up!");
}
}
}
}
public static void friendlyRed() {
System.out.println("\nTracking your red...");
System.out.println("5 Minutes left");
int friendlyRed = 300;
long startTime = System.currentTimeMillis() / 1000;
long endTime = startTime + friendlyRed;
while (System.currentTimeMillis() / 1000 < endTime) {
while (startTime != System.currentTimeMillis() / 1000) {
startTime += 1;
if (endTime - startTime > 1)
if (endTime - startTime == 240)
System.out.println("4 Minutes left");
if (endTime - startTime == 180)
System.out.println("3 Minutes left");
if (endTime - startTime == 120)
System.out.println("2 Minutes left");
if (endTime - startTime == 60)
System.out.println("1 Minute left");
if (endTime - startTime == 30)
System.out.println("30 Seconds left");
if (endTime - startTime == 15)
System.out.println("15 Seconds left");
if (endTime - startTime == 5)
System.out.println("5 Seconds left");
else if (endTime - startTime == 1) {
System.out.println("Red Buff is up!");
}
}
}
}
public static void enemyRed() {
System.out.println("\nTracking enemy red...");
System.out.println("5 Minutes left");
int enemyRed = 300;
long startTime = System.currentTimeMillis() / 1000;
long endTime = startTime + enemyRed;
while (System.currentTimeMillis() / 1000 < endTime) {
while (startTime != System.currentTimeMillis() / 1000) {
startTime += 1;
if (endTime - startTime > 1)
if (endTime - startTime == 240)
System.out.println("4 Minutes left");
if (endTime - startTime == 180)
System.out.println("3 Minutes left");
if (endTime - startTime == 120)
System.out.println("2 Minutes left");
if (endTime - startTime == 60)
System.out.println("1 Minute left");
if (endTime - startTime == 30)
System.out.println("30 Seconds left");
if (endTime - startTime == 15)
System.out.println("15 Seconds left");
if (endTime - startTime == 5)
System.out.println("5 Seconds left");
else if (endTime - startTime == 1) {
System.out.println("Enemy Red Buff is up!");
}
}
}
}
public static void Dragon() {
System.out.println("\nTracking dragon...");
System.out.println("6 Minutes left");
int dragon = 360;
long startTime = System.currentTimeMillis() / 1000;
long endTime = startTime + dragon;
while (System.currentTimeMillis() / 1000 < endTime) {
while (startTime != System.currentTimeMillis() / 1000) {
startTime += 1;
if (endTime - startTime > 1)
if (endTime - startTime == 300)
System.out.println("5 Minutes left");
if (endTime - startTime == 240)
System.out.println("4 Minutes left");
if (endTime - startTime == 180)
System.out.println("3 Minutes left");
if (endTime - startTime == 120)
System.out.println("2 Minutes left");
if (endTime - startTime == 60)
System.out.println("1 Minute left");
if (endTime - startTime == 30)
System.out.println("30 Seconds left");
if (endTime - startTime == 15)
System.out.println("15 Seconds left");
if (endTime - startTime == 5)
System.out.println("5 Seconds left");
else if (endTime - startTime == 1) {
System.out.println("Dragon is up!");
}
}
}
}
public static void Baron() {
System.out.println("\nTracking baron...");
System.out.println("7 Minutes left");
int baron = 420;
long startTime = System.currentTimeMillis() / 1000;
long endTime = startTime + baron;
while (System.currentTimeMillis() / 1000 < endTime) {
while (startTime != System.currentTimeMillis() / 1000) {
startTime += 1;
if (endTime - startTime > 1)
if (endTime - startTime == 360)
System.out.println("6 Minutes left");
if (endTime - startTime == 300)
System.out.println("5 Minutes left");
if (endTime - startTime == 240)
System.out.println("4 Minutes left");
if (endTime - startTime == 180)
System.out.println("3 Minutes left");
if (endTime - startTime == 120)
System.out.println("2 Minutes left");
if (endTime - startTime == 60)
System.out.println("1 Minute left");
if (endTime - startTime == 30)
System.out.println("30 Seconds left");
if (endTime - startTime == 15)
System.out.println("15 Seconds left");
if (endTime - startTime == 5)
System.out.println("5 Seconds left");
else if (endTime - startTime == 1) {
System.out.println("Baron is up!");
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:45:11.353",
"Id": "84310",
"Score": "2",
"body": "You do know, something like that already exists? http://blog.overwolf.com/releases/overwolf-version-0-33-199-released"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:56:32.310",
"Id": "84312",
"Score": "15",
"body": "@Vogel612 I do, but this seemed interesting to me for learning purposes :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T20:12:59.480",
"Id": "84368",
"Score": "3",
"body": "@Vogel612 Many things actually. Including countless apps. That being said, `hello world` exists 100584902 times, and someone new codes it every day. OP surely learned something valuable about methods/functions here."
}
] | [
{
"body": "<p>You could pull out the <code>while</code> loop of each function and make it its own function. Something like this</p>\n\n<pre><code>private static void Countdown(long startTime, long endTime, string finalMsg){\n while (System.currentTimeMillis() / 1000 < endTime) {\n while (startTime != System.currentTimeMillis() / 1000) {\n startTime += 1;\n if (endTime - startTime > 1) {\n if (endTime - startTime == 240)\n System.out.println(\"4 Minutes left\");\n if (endTime - startTime == 180)\n System.out.println(\"3 Minutes left\");\n if (endTime - startTime == 120)\n System.out.println(\"2 Minutes left\");\n if (endTime - startTime == 60)\n System.out.println(\"1 Minute left\");\n if (endTime - startTime == 30)\n System.out.println(\"30 Seconds left\");\n if (endTime - startTime == 15)\n System.out.println(\"15 Seconds left\");\n if (endTime - startTime == 5)\n System.out.println(\"5 Seconds left\");\n } else if (endTime - startTime == 1) {\n System.out.println(finalMsg);\n }\n }\n}\n</code></pre>\n\n<p>Then from each function, call the Countdown function. I think it will look a little cleaner and less repetitive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:42:39.543",
"Id": "84309",
"Score": "6",
"body": "I'd also precalculate `endTime - startTime` to improve performance. If done correctly, you can even shorten the parameter list then..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T19:38:26.913",
"Id": "84361",
"Score": "2",
"body": "@Vogel612 A decent compiler would make that optimisation for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:32:54.990",
"Id": "84415",
"Score": "2",
"body": "A perfect example of why you should _always_ write explicit braces. Also, the repetitive `if` statements should be chained using `else if`. Better yet, use a `switch` block. (I see @JerryCoffin has already addressed the issue.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:39:23.483",
"Id": "48053",
"ParentId": "48051",
"Score": "12"
}
},
{
"body": "<h1>Concept:</h1>\n<p>Your concept is not suited to be used on multiple countdowns, instead you might want to try something like the following:</p>\n<p>Beware, this is a raw draft!</p>\n<pre><code>public class Buff{\n private int respawnSeconds;\n private String name;\n private int respawnsAtSecond;\n //constructor + getters and setters\n\n public void kill(int currentGameSeconds){\n this.respawnsAtSecond = currentGameSeconds + respawnSeconds;\n }\n}\n\npublic class Game{\n private int elapsedSeconds;\n private Set<Buff> buffs;\n\n public void start(){\n elapsedSeconds = 0;\n buffs.add(new Buff("friendlyBlue", 300));\n //Add the other buffs\n }\n\n //You need some ticking mechanism, maybe you could use something like a while(true)\n}\n</code></pre>\n<hr>\n<h1>Sidenotes:</h1>\n<h2>Naming:</h2>\n<p>Your method names are inconsistent.. the blue and red methods are <code>camelCase</code>, but your larger objectives are <code>PascalCased</code> (<code>Dragon</code>, <code>Baron</code>) aside from that, you are very consistent with very clear and understandable camelcased local variables.</p>\n<h2>Method Responsibilites:</h2>\n<p>You make your methods do too much. They are doing the counting, the printing and the calculations all at once... Extract sub-methods and add parameters for the different objective names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:41:41.670",
"Id": "48054",
"ParentId": "48051",
"Score": "10"
}
},
{
"body": "<p>First: I think the point @DFord makes is quite good.</p>\n\n<p>Second, I think you should work on indenting your code better. In particular, the indentation of your main <code>if</code>/<code>then</code>/<code>else</code> chain is misleading:</p>\n\n<pre><code> if (endTime - startTime > 1)\n if (endTime - startTime == 360)\n System.out.println(\"6 Minutes left\");\n if (endTime - startTime == 300)\n System.out.println(\"5 Minutes left\");\n if (endTime - startTime == 240)\n System.out.println(\"4 Minutes left\");\n if (endTime - startTime == 180)\n System.out.println(\"3 Minutes left\");\n if (endTime - startTime == 120)\n System.out.println(\"2 Minutes left\");\n if (endTime - startTime == 60)\n System.out.println(\"1 Minute left\");\n if (endTime - startTime == 30)\n System.out.println(\"30 Seconds left\");\n if (endTime - startTime == 15)\n System.out.println(\"15 Seconds left\");\n if (endTime - startTime == 5)\n System.out.println(\"5 Seconds left\");\n else if (endTime - startTime == 1) {\n System.out.println(\"Foo is up!\");\n</code></pre>\n\n<p>When an <code>else</code> follows a chain of <code>if</code> statements like this, it attaches to the most recent <code>if</code> that doesn't already have an else. An <code>if</code> statement controls exactly one following statement (which needs to be a compound statement if you want it to control more than one syntactical statement). In other words, the code really works like:</p>\n\n<pre><code>if (endTime - startTime > 1)\n if (endTime - startTime == 360)\n System.out.println(\"6 Minutes left\");\n\n// The following are evaluated regardless of whether the `> 1` condition was met\nif (endTime - startTime == 300)\n System.out.println(\"5 Minutes left\");\nif (endTime - startTime == 240)\n System.out.println(\"4 Minutes left\");\nif (endTime - startTime == 180)\n System.out.println(\"3 Minutes left\");\nif (endTime - startTime == 120)\n System.out.println(\"2 Minutes left\");\nif (endTime - startTime == 60)\n System.out.println(\"1 Minute left\");\nif (endTime - startTime == 30)\n System.out.println(\"30 Seconds left\");\nif (endTime - startTime == 15)\n System.out.println(\"15 Seconds left\");\nif (endTime - startTime == 5)\n System.out.println(\"5 Seconds left\");\nelse if (endTime - startTime == 1) {\n System.out.println(\"Foo is up!\");\n</code></pre>\n\n<p>Based on your indentation, you apparently wanted it to be more like this:</p>\n\n<pre><code>if (endTime - startTime > 1) {\n if (endTime - startTime == 360)\n System.out.println(\"6 Minutes left\");\n if (endTime - startTime == 300)\n System.out.println(\"5 Minutes left\");\n if (endTime - startTime == 240)\n System.out.println(\"4 Minutes left\");\n if (endTime - startTime == 180)\n System.out.println(\"3 Minutes left\");\n if (endTime - startTime == 120)\n System.out.println(\"2 Minutes left\");\n if (endTime - startTime == 60)\n System.out.println(\"1 Minute left\");\n if (endTime - startTime == 30)\n System.out.println(\"30 Seconds left\");\n if (endTime - startTime == 15)\n System.out.println(\"15 Seconds left\");\n if (endTime - startTime == 5)\n System.out.println(\"5 Seconds left\");\n}\nelse if (endTime - startTime == 1) {\n System.out.println(\"Foo is up!\");\n</code></pre>\n\n<p>In this case, the braces prevent the <code>else</code> from attaching to the immediately previous <code>if</code>, forcing it to attach to the <code>if</code> you apparently intended instead.</p>\n\n<p>Although it might initially seem (or even be) somewhat wasteful, I'd tend to avoid the issue entirely: instead of a cascade of <code>if</code> statements, I'd probably put the statements to be printed out into some kind of Map, then just do a lookup in the map and print out the associated value (if it has one) for a given time.</p>\n\n<pre><code>// In real code, you'll need to pick some class that implements the Map interface,\n// but for the moment, I'm not really concerned with which one you pick.\nMap<Integer, string> names;\n\nnames.put(360, \"6 minutes left\");\nnames.put(300, \"5 minutes left\");\n//...\nnames.put(5, \"5 seconds left\");\n</code></pre>\n\n<p>Then the code just looks up the current time in <code>names</code> and prints out a string if there is one for a particular value. Aside: while I've used <code>names</code> here, it's probably not a good example to emulate--when naming the real variable, you should almost certainly pick a name that better reflects its intended function; something like <code>timeToString</code>, for example.</p>\n\n<p>Also note that this makes it fairly easy to export the values and strings to an configuration file instead of them being embedded in the code. If, for example, you ended up wanting to translate the program to Russian or French (or whatever) translating these strings wouldn't (in and of itself) force re-compiling the associated code. Likewise, if you decided to add or remove some of the messages, moving them to an external data file makes this trivial to do.</p>\n\n<p>That said, I should probably add that I doubt you could localize any significant program without re-compiling at all (or without rewriting at least a little of the code). Nonetheless, keeping strings like this external to the code does help keep the task a little more manageable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:04:52.287",
"Id": "48057",
"ParentId": "48051",
"Score": "11"
}
},
{
"body": "<p>I have never touched java, so this may not compile, but to make your code somewhat shorter, you could use, in addition to DFords answer (inside the loop):</p>\n\n<pre><code>long seconds = endTime - startTime;\nif (seconds == 1)\n System.out.println(finalMsg);\nelse if (seconds == 5)\n System.out.println(\"5 Seconds left\");\nelse if (seconds == 15)\n System.out.println(\"15 Seconds left\");\nelse if (seconds == 30)\n System.out.println(\"30 Seconds left\");\nelse if (seconds <= 240 && seconds % 60 == 0)\n System.out.println(seconds/60 + \" minutes left\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T19:48:26.657",
"Id": "84363",
"Score": "0",
"body": "Beat me to it. That should be 360 though, not 240."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:03:46.893",
"Id": "84373",
"Score": "0",
"body": "@Pharap Hm. Seems like OP starts counting from multiple points (240s, 300s and 360s)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:13:10.063",
"Id": "48067",
"ParentId": "48051",
"Score": "6"
}
},
{
"body": "<p><em>(relatively critical review ... apologies in advance)</em></p>\n<p>The two issues I feel are most incorrect about your code is the buggy switch statement, and the poor choice of timing mechanism. The decision to use these mechanisms has lead to a poor OOP design.</p>\n<h2>Switch</h2>\n<p>First, though, the switch bug:</p>\n<blockquote>\n<pre><code>switch (timerChoice) {\ncase 1:\n friendlyBlue();\ncase 2:\n enemyBlue();\ncase 3:\n friendlyRed();\ncase 4:\n enemyRed();\ncase 5:\n Dragon();\ncase 6:\n Baron();\n }\n</code></pre>\n</blockquote>\n<p>If the user chooses 1, they will do <em>everything</em>!!! Your switch cases should 'break':</p>\n<pre><code>switch (timerChoice) {\ncase 1:\n friendlyBlue();\n break;\ncase 2:\n enemyBlue();\n break;\ncase 3:\n friendlyRed();\n break;\ncase 4:\n enemyRed();\n break;\ncase 5:\n Dragon();\n break;\ncase 6:\n Baron();\n break;\n }\n</code></pre>\n<p>Other problems related to code-conventions (like the upper-case B in <code>Baron</code>, and D in <code>Dragon</code> are not as significant).</p>\n<p>Case statements in Java are 'fall-through', and you need to break unless you want the following statements to execute as well.</p>\n<h2>Timer</h2>\n<p>In Java, the right solution for any timing problem, is to use the library timer functions. In recent Java versions, the right tool is the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newScheduledThreadPool(int)\" rel=\"noreferrer\"><code>ScheduledExecutorService</code></a>. This service allows you to schedule tasks in the future.</p>\n<p>I would build it something like:</p>\n<pre><code>private final class TimedEvent {\n private final long preTarget;\n private final String message;\n TimedEvent(long millis, String message) {\n this.preTarget = millis;\n this.message = message;\n }\n private long delayTo(final long target) {\n return target - preTarget;\n }\n}\n\n.....\n\npublic static final TimedEvent[] EVENTS = {\n new TimedEvent(240000, "4 Minutes left"),\n new TimedEvent(180000, "3 Minutes left"),\n new TimedEvent(120000, "2 Minutes left"),\n new TimedEvent(60000, "1 Minute left"),\n new TimedEvent(30000, "30 Seconds left"),\n new TimedEvent(15000, "15 Seconds left"),\n new TimedEvent(5000, "5 Seconds left"),\n new TimedEvent(1000, "1 Second left")\n};\n\n....\n</code></pre>\n<p>Then, with the TimedEvents set up, you can schedule them in a loop, counting down to the target time.....</p>\n<pre><code>final long now = System.currentTimeMillis();\nfinal long target = now + sometime; /// whatever you are counting down to....\nfor (final TimedEvent te : EVENTS) {\n long delay = te.delayTo(target);\n if (delay >= 0) {\n Callable<Object> torun = new Callable<Void>() {\n public void call() {\n System.out.println(te.getMessage());\n return null;\n }\n }\n scheduler.schedule(torun, delay, TimeUnit.MILLISECONDS);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:42:33.123",
"Id": "48072",
"ParentId": "48051",
"Score": "21"
}
},
{
"body": "<p>@Dford is completly right with putting the time event to an seperatly method.</p>\n\n<p>I still find it more readable when you use the switch in combinations with readable final's</p>\n\n<pre><code>private static final int MINUTES_4 = 240;\nprivate static final int MINUTES_3 = 180;\nprivate static final int MINUTES_2 = 120;\nprivate static final int MINUTES_1 = 60;\nprivate static final int SECONDS_30 = 30;\nprivate static final int SECONDS_15 = 15;\nprivate static final int SECONDS_5 = 5;\nprivate static final int SECONDS_1 = 1;\n\nprivate static void Countdown(long startTime, long endTime, string finalMsg){\n while (System.currentTimeMillis() / 1000 < endTime) {\n while (startTime != System.currentTimeMillis() / 1000) {\n String message;\n startTime++;\n switch (endTime - startTime) {\n case MINUTES_4 : message = \"4 Minutes left\";\n break;\n case MINUTES_3 : message = \"3 Minutes left\";\n break;\n case MINUTES_2 : message = \"2 Minutes left\";\n break;\n case MINUTES_1 : message = \"1 Minutes left\";\n break;\n case SECONDS_30 : message = \"30 seconds left\";\n break;\n case SECONDS_15 : message = \"15 seconds left\";\n break;\n case SECONDS_5 : message = \"5 seconds left\";\n break;\n case SECONDS_1 : message = finalMsg;\n default : break;\n }\n if (null != message) {\n System.out.println(message);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T18:47:33.357",
"Id": "48079",
"ParentId": "48051",
"Score": "5"
}
},
{
"body": "<p>If we're talking proper class encapsulation or whatever, here's my way over-engineered version of what you could do. </p>\n\n<p>Also, I'm a C# programmer, so some of the syntax may be a little off, but I've made some effort at least to use correct Java.</p>\n\n<ul>\n<li>Keep your console prompts in the Main method </li>\n<li>Create an enum that represents your different types of timers</li>\n<li>Create what is essentially just a data repository class that holds your strings (like \"Tracking enemy blue...\") and other constant values (like your 300 that gets added to the timer).\n<ul>\n<li>Use meaningful names. Everything is static final. Something like @chillworld's answer.</li>\n<li>Call it something like GlobalConstants, or whatever is meaningful to you.</li>\n</ul></li>\n<li>Create a class that is responsible for managing your timer (call it Tracker or something. whatever.). This class would include:\n<ul>\n<li>A constructor that takes the above mentioned enum as a parameter</li>\n<li>A private field to locally store said enum</li>\n<li>Countdown method (from @DFord's answer) mixed with the optimization from @Lennart_96's answer</li>\n<li>An initialize method to set your timer values and such based on the local enum value, and call a separate method to display your initial countdown message, also based on the enum value.</li>\n</ul></li>\n</ul>\n\n<p>In the end you'd end up with something like:</p>\n\n<pre><code>public enum TimerType {\n FriendlyBlue, EnemyBlue...\n}\n\npublic class MainProgram {\n private TimerType tType;\n public static void main(String[] args) {\n // Do your console prompts\n\n // Assign the timer type\n switch (timerChoice) {\n case 1: tType = TimerType.FriendlyBlue; break;\n case 2: ...\n }\n\n // Create the tracker object and kick off the timer\n new Tracker(tType);\n }\n}\n\npublic class Tracker {\n private TimerType tType;\n private string initialTrackingMessage;\n ...\n\n public Tracker(TimerType timerType) {\n tType = timerType;\n InitializeTracker();\n CountDown();\n }\n\n private void InitializeTracker() {\n initialTrackingMessage = GetInitialTrackingMessageForTrackingType();\n // Initialize any other variables\n\n DisplayMessage(initialTrackingMessage);\n }\n\n private string GetInitialTrackingMessageForTrackingType() {\n string returnMessage;\n switch (tType) {\n case FriendlyBlue: returnMessage = GlobalConstants.TRACKING_BLUE; break;\n ...\n }\n return returnMessage;\n }\n\n private void DisplayMessage(string message) {\n System.out.println(message);\n // Any other logic you want to do\n }\n\n private void CountDown() {\n // Your countdown logic here\n }\n}\n\npublic static class GlobalConstants() {\n // Messages\n public static final string TRACKING_BLUE = \"Tracking your blue...\"\n ...\n\n // Values\n public static final int INITIAL_TIMER_LENGTH = 300;\n}\n</code></pre>\n\n<p>I'm sure you noticed that I like to use whole words in my coding. It's really nice for people who have to maintain your code when you're gone. You could also easily add a <code>Start()</code> method or something that takes care of the initialization and countdown, if you don't like the idea of doing it all from the constructor.</p>\n\n<p>If you end up adding more details to each type of timer, this approach makes it much easier to convert your core class into an abstract class, or even an interface, as appropriate. Maybe even both. The <code>Countdown</code> method would be appropriate for an abstract class, but the <code>InitializeTracker</code> method might be more appropriate for an interface, unless you need a default implementation. Also, the methods and types (classes, enums) each perform only one function, which is an important pillar of good OO design.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>As an additional benefit (and to address your secondary issue), you can easily track multiple buffs with this approach, by keeping a collection of Tracker objects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T22:12:51.123",
"Id": "48086",
"ParentId": "48051",
"Score": "3"
}
},
{
"body": "<p>I modified your code a bit to work with several countdowns now:</p>\n\n<ol>\n<li>create an entity for your buffs </li>\n<li>create an map with buffs</li>\n<li>used the map to remove the switch statement in main function</li>\n<li>used the map to make the menu dynamic</li>\n<li>start a new thread for every timer to start more than one timer</li>\n</ol>\n\n<p></p>\n\n<pre><code>package test;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Scanner;\n\n\npublic class LolTimer \n{ \n /**List with running countdowns*/\n private static List<String> countdowns = new ArrayList<String>();\n\n /**Main function*/\n public static void main(String[] args) \n {\n //variable instantiation\n Scanner myScanner = new Scanner(System.in); \n HashMap<Integer, Buff> BuffMap = creatBuffs();\n int numberBuffs = BuffMap.size();\n int buffID = 0;\n\n //Print the menue with buffs etc.\n System.out.println(\"Jungle Timers v1.0\");\n System.out.println(\"\\nSelect a buff to time:\\n\");\n for(int i = 1; i <= numberBuffs; i++)\n System.out.println(i + \". \" + BuffMap.get(i).m_sName);\n System.out.println(numberBuffs+1 + \". EXIT\");\n System.out.print(\"\\n> \");\n\n //loop to track as many buffs as the user want\n while(buffID != numberBuffs+1)\n {\n buffID = myScanner.nextInt();\n if(buffID > 0 && buffID <= numberBuffs)\n {\n Buff buff = BuffMap.get(buffID);\n trackBuff(buff.m_nRespawnTime, buff.m_sName);\n }\n }\n\n //if exit is choosen -> close scanner and exit the programm\n myScanner.close();\n System.exit(0);\n }\n\n /**Decide if a Buff is still running or not.*/\n public static void trackBuff(int nRespawnTime, String sName)\n {\n if(countdowns.contains(sName))\n System.out.println(\"This Countdown is still running.\");\n else \n {\n System.out.println(\"\\nTracking \" + sName + \"...\");\n startThread(nRespawnTime, sName);\n }\n }\n\n /**Starts new Thread with a new Countdowntimer.*/\n public static void startThread(int nRespawnTime, final String sName)\n {\n countdowns.add(sName);\n\n final int m_nStartTime = (int) (System.currentTimeMillis() / 1000);\n final int m_nEndTime = m_nStartTime + nRespawnTime;\n\n Thread updateThread = new Thread() \n {\n @Override\n public void run() \n {\n int curTime = m_nStartTime;\n int m_nTimeDiff = 0;\n\n while (System.currentTimeMillis() / 1000 < m_nEndTime) \n {\n while (curTime != System.currentTimeMillis() / 1000) \n {\n m_nTimeDiff = m_nEndTime - curTime;\n curTime += 1;\n if (m_nTimeDiff == 420)\n System.out.println(sName + \": 7 Minutes left\");\n if (m_nTimeDiff == 360)\n System.out.println(sName + \": 6 Minutes left\");\n if (m_nTimeDiff == 300)\n System.out.println(sName + \": 5 Minutes left\");\n if (m_nTimeDiff == 240)\n System.out.println(sName + \": 4 Minutes left\");\n if (m_nTimeDiff == 180)\n System.out.println(sName + \": 3 Minutes left\");\n if (m_nTimeDiff == 120)\n System.out.println(sName + \": 2 Minutes left\");\n if (m_nTimeDiff == 60)\n System.out.println(sName + \": 1 Minute left\");\n if (m_nTimeDiff == 30)\n System.out.println(sName + \": 30 Seconds left\");\n if (m_nTimeDiff == 15)\n System.out.println(sName + \": 15 Seconds left\");\n if (m_nTimeDiff == 5)\n System.out.println(sName + \": 5 Seconds left\");\n }\n }\n\n System.out.println(sName + \" is up!\");\n countdowns.remove(sName);\n Thread.currentThread().interrupt();\n }\n };\n updateThread.start(); \n }\n\n /**Creat all the Buffs you want. You fastly can add some Buffs(wolves, ghosts) here.*/\n public static HashMap<Integer, Buff> creatBuffs()\n {\n HashMap<Integer, Buff> BuffMap = new HashMap<>();\n BuffMap.put(1, new Buff(300, \"your Blue\"));\n BuffMap.put(2, new Buff(300, \"enemy Blue\"));\n BuffMap.put(3, new Buff(300, \"your Red\"));\n BuffMap.put(4, new Buff(300, \"enemy Blue\"));\n BuffMap.put(5, new Buff(300, \"Dragon\"));\n BuffMap.put(6, new Buff(300, \"Baron\"));\n return BuffMap;\n }\n}\n\n/**Entity for your Buffs*/\nclass Buff\n{\n public int m_nRespawnTime;\n public String m_sName;\n\n public Buff(int time, String name)\n {\n m_nRespawnTime = time;\n m_sName = name;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T09:59:36.370",
"Id": "48136",
"ParentId": "48051",
"Score": "4"
}
},
{
"body": "<p>Let me just address your \"repetitive\" segment where you check how many minutes are left.. some simple math can trim down the size of those blocks:</p>\n\n<pre><code>int secLeft = endTime - startTime;\nint minsLeft = secLeft/60;\nif( secLeft % 60 == 0 ) // only happens at multiples of 60, eg 0,60,120,180..\n{\n // Message of form \"2 minutes left\"\n String msg = Integer.toString(minsLeft) + \" Minutes left\";\n}\nelse if( secLeft == 30 )\n{\n // need special cases for the smaller values\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:38:53.803",
"Id": "48319",
"ParentId": "48051",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48072",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:26:42.947",
"Id": "48051",
"Score": "26",
"Tags": [
"java",
"game",
"timer"
],
"Title": "Countdown Code: 'League of Legends'"
} | 48051 |
<p>I'm pretty new to Perl (<em>and multithreading</em>), so I was wondering if someone would be willing to take a look at my script and give me any tips on increasing performance.</p>
<h2>Motivation</h2>
<p>The script is designed to build several hundred C++ components, using multiple threads (one per component)</p>
<h2>Design</h2>
<p>At a high level, the script should follow this flow:</p>
<ul>
<li>Get parameters</li>
<li>Default the number of compilation and linking threads to use</li>
<li>Read in a list of components
<ul>
<li>The format here would be something like, if you pass in 'SERVER', we have a file that maps that component name to ~40 directories that need built</li>
</ul></li>
<li>Launch 16 threads in 'listening' state</li>
<li>Que up the work to be performed
<ul>
<li>Dependent on the actions passed in</li>
</ul></li>
</ul>
<h2>Code</h2>
<p>Commented throughout to clarify what <em>I expect to be happening</em></p>
<pre><code>use warnings;
use strict;
use POSIX qw(ceil floor strftime);
use Perl::OSType ':all';
use Getopt::Long;
use Pod::Usage;
use List::Util qw(min max);
use Log::Message::Simple qw(msg error debug);
use File;
use threads;
use threads::shared;
use Thread::Semaphore;
use Thread::Queue 3.01 qw( );
my $q = Thread::Queue->new();
my @procs;
my @comps;
my @compsCopy;
my @retCodes;
share(@retCodes);
my @failedComponents;
share(@failedComponents);
my $maxThreadsSem = Thread::Semaphore->new(0);
my $compStr = "";
my $MAKE_INVOCATION_PATH;
my $MAKE;
## Parse options and print usage if there is a syntax error,
## or if usage was explicitly requested.
GetOptions('help|?' => \my $help, man => \my $man, 'verbose' => \my $verbose, 'comps:s{,}' => \my @compList, 'COMPLIST:s' => \my $legacyCOMPLIST, 'action:s{1,3}' => \my @actionList,
'clthreads:i' => \my $clthreads, 'linkthreads:i' => \my $linkthreads) or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-verbose => 2) if $man;
#set silent flag for make
$ENV{SL} = '@' unless $verbose;
@compList = qw(SERVER TOOLS) if !@compList;
@actionList = qw(clean depend build link) if !@actionList;
#default thread counts
### --> The assumption here is that compile consumes less resources than link,
### so I default to the number of cores for compile, and slightly lower for linking
my $numCores;
if(is_os_type('Windows'))
{
$numCores = `grep -c '^processor' \/proc\/cpuinfo`;
}
elsif(is_os_type('Unix'))
{
my $numCoresText = `lsconf | grep Processors`;
$numCoresText =~ m/(\d+)/;
$numCores = $1;
}
$clthreads = $numCores if !$clthreads;
$linkthreads = ceil($numCores * .75) if !$linkthreads;
SetMake();
my $startTime = (strftime "%m-%d-%Y %H:%M:%S", gmtime);
#the work
BuildInit(@ARGV);
print "Started At: \t$startTime\n";
print "Ended At: \t" . (strftime "%m-%d-%Y %H:%M:%S", gmtime) ."\n";
my $maxReturnCode = max @retCodes;
print "Highest Error Code: $maxReturnCode\n";
print "Components with failures: @failedComponents\n" if @failedComponents;
exit($maxReturnCode);
#----------------------------------------------------------
sub SetMake
{
if ( $ENV{MAKECMD} ) {
$MAKE=$ENV{MAKECMD}
} else {
# -k option tells make to continue its attempt to build a component after failures.
# make no longer quits compiling an entire directory after 1 compilation error.
$MAKE="make -k -C";
}
$MAKE_INVOCATION_PATH = $ENV{PATH_CYGDRIVE} || $ENV{PATH};
}
sub BuildInit {
my $actionStr = "";
my $compStr = "";
### --> Gets the list of directories for each 'component'
my @component_dirs;
foreach my $comp (@compList){
@component_dirs = (@component_dirs, GetDirs($comp));
}
### --> Limit the number of threads that can work at one time
my $maxThreadsSem = Thread::Semaphore->new($clthreads);
print "Action List: @actionList\n";
print "Component List: @compList\n";
print "Component Dir List: @component_dirs\n";
print "Compile Threads: $clthreads\n";
print "Link Threads: $linkthreads\n";
#---------------------------------------
#---- Setup Worker Threads ----------
for (1..16) {
async {
while (defined(my $job = $q->dequeue())) {
worker($job);
}
};
}
#-----------------------------------
#---- Enqueue The Work ----------
for my $action (@actionList){
my $sem = Thread::Semaphore->new(0); ## used to lock execution between 'actions'
#manage our resources while linking
if ($action eq 'link'){
$maxThreadsSem = Thread::Semaphore->new($linkthreads);
}
elsif ($action eq 'build'){
$maxThreadsSem = Thread::Semaphore->new($clthreads);
}
if($action eq 'depend'){
$ENV{PATH} = "$ENV{BUILD_PATH}/makedepend/bin;" . $ENV{PATH};
system("rm dependlist") == 0 or die "Failed on attempt to remove dependlist";
(system("$MAKE $MAKE_INVOCATION_PATH/makedepend")) == 0 or die "Could not build 'makedepend' - killing process";
}
### --> perform 'action' on each 'component directory'
$q->enqueue([$_, $action, $sem, $maxThreadsSem]) for @component_dirs;
### --> we don't want to move on to the next action before this action finishes
### --> e.g., we don't want to start linking prior to compiling finishing
$sem->down(scalar @component_dirs);
print "\n------>> Waiting for prior actions to finish up... <<------\n";
}
# Nothing more to do - notify the Queue that we're not adding anything else
$q->end();
for my $thread (threads->list())
{ $thread->join(); }
return 0;
}
sub worker {
my ($job) = @_;
my ($component, $action, $sem, $maxThreadsSem) = @$job;
#used to throttle the build / link process according the to specified threads
$maxThreadsSem->down() if $action eq 'link' or $action eq 'build';
Build($component, $action);
$sem->up();
$maxThreadsSem->up() if $action eq 'link' or $action eq 'build';
}
sub Build {
my ($comp, $action) = @_;
my $cmd = "$MAKE $MAKE_INVOCATION_PATH/$comp ";
my $retCode = -1;
#lack of reliable switch support in perl
if($action eq "depend")
{$cmd .= "$action >nul 2>&1"} #suppress output
elsif($action eq "clean")
{$cmd .= $action}
elsif($action eq "build")
{$cmd .= 'l1'}
elsif($action eq "link")
{$cmd .= ''} #add nothing; default is to link
else {die "Action: $action is unknown to me."}
print "\n\t\t*** Performing Action: \'$cmd\' on >>> $comp <<< ***" if ($verbose || $action eq 'depend');
if ($action eq "link"){
# hack around potential race conditions -- will only be an issue during linking
my $tries = 4;
until ($retCode == 0 or $tries == 0){
last if ($retCode = system($cmd)) == 2; #compile error; stop trying
$tries--;
};
}
else{
$retCode = system($cmd);
}
return $retCode if $action eq "depend"; #stop here for dependlist building
lock(@retCodes); #lock to keep thread-safe
push(@retCodes, ($retCode>>8));
#testing
if($retCode != 0){
if($verbose){
print "\n\t\t*** ERROR IN $comp: $@ !! ***\n";
print "\t\t*** Action: $cmd -->> Error Level: " . ($retCode >>8) . "\n";
}
lock(@failedComponents); #lock to keep thread-safe
push(@failedComponents, $comp);
}
return $retCode;
}
# searches the $strDataFile for the given $strComponentName, then
# fills the @dir_array with the appropriate directories for that component
sub GetDirs {
# ... <SNIP> ...
# mostly irrelevant
return @dir_array;
}
#-----------------------------------------------------------------
#---------------- Documentation / Usage / Help ------------------
=head1 NAME
sample - Using GetOpt::Long and Pod::Usage
=head1 SYNOPSIS
buildmom.pl [options]
options:
-help Brief help message
-man Full documentation
-comp s The list of components to perform actions on (from your comps.dat) | space delimited
-COMPLIST Legacy support for old build script
-action A list of actions to perform on each component; executed in the order given | space delimited
Available actions include clean, depend, build, link
-clthreads Number of threads used during compiling
-linkthreads Number of threads used during linking
-verbose Enables addition build output - may increase build time
=head1 DESCRIPTION
B<buildmom.pl> is used to perform various actions on your Momentum C++ project.
Parameters worth note:
-comps | [optional: defaulted to ALL] The list of components from your comps.dat file on which to have the
specified actions performed. Example usage: buildmom.pl -comps FOUNDATION COMMON TRANSPORT SERVER
-COMPLIST | [optional: legacy support] This is the same as the `-comps` parameter, with the exception that it allows
legacy support for older parameter passing (e.g., -COMPLIST=FOUNDATION:COMMON:TRANSPORT:SERVER)
-action | [optional: defaulted to `clean depend build link`] The set of actions, in order, which you want performed
on the comps list. Available actions include:
clean: Executes `make clean` for each component specified(excluding ffsfld)
depend: Builds the make depend list for each component specified
build: Builds each component specified (formerly 'the first pass')
link: Links each component specified (formerly 'the second pass')
-clthreads | [optional: defaulted to 100%] Specifies the number of threads to use during compilation
-linkthreads | [optional: defaulted to 75%] Specifies the number of threads to use during linking
{ For certain actions, specifically clean and depend, <buildmom.pl> will assume 100% thread usage every time.
These actions are lightweight, and the performance loss from these actions is minimal. If you specify multiple actions
e.g., buildmom.pl -actions clean depend build link, the script will consume 100% CPU for a couple of minutes while performing
the `clean` and `depend` steps, and then throttle back to the specified number of threads.
Another example: buildmom.pl -actions clean depend build link -clthreads 2 -linkthreads 2
On a 4 core non-HT system, you would see your CPU usage jump to 100% for a few minutes while
we perform the `clean` and `depend` steps. Once compilation begins, your CPU usage will throttle
back down to ~50% due to the number of threads specified. }
=cut
</code></pre>
<h2>Assumptions</h2>
<p>Like I said, I'm pretty new to both Perl and multithreading. The primary assumption I've made here that I'm really not sure about is the number of threads to use. I've throttled it based on the number of cores available on the machine - is that the correct way to go about it? I assumed that anything >#cores would just cause some thrashing and competition of resources; is that accurate?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:54:40.007",
"Id": "84311",
"Score": "2",
"body": "It appears you may be using GNU `make`. What advantage are you're hoping to get beyond that obtained from using something like `make -j16`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:58:59.017",
"Id": "84314",
"Score": "0",
"body": "Nothing extraordinary - a couple of things that come to mind are `exe` directories can't be threaded, so there's little benefit to using `make -j#` over building multiple `exe`s together. Also, logging was an issue - but with make V4, that's no longer a problem. This kind of spiraled from a fix to a rewrite of what we already had."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:09:21.660",
"Id": "84316",
"Score": "0",
"body": "\"What advantage are you're hoping to get beyond that obtained from using something like make -j16?\" -- also, where's the fun in that :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T15:37:32.653",
"Id": "84326",
"Score": "0",
"body": "@MrDuk: I deleted the comment because your description seems to contradict itself on this, and I'd need to read through the code to be sure which is accurate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:17:35.053",
"Id": "84334",
"Score": "0",
"body": "Why not experimenting with number of threads and taking notes? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T16:18:45.607",
"Id": "84335",
"Score": "0",
"body": "@mpapec Hah, good idea :) Unfortunately though, a full run of the build can be upwards of 60-70 minutes long .. so that gets tedious heh"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T14:44:21.753",
"Id": "48055",
"Score": "4",
"Tags": [
"performance",
"beginner",
"multithreading",
"perl"
],
"Title": "Building hundreds of C++ components using multiple threads"
} | 48055 |
<p>I am receiving the JSON from WebService and populating <code>ExpandoObject</code> from this one:</p>
<pre><code> var converter = new ExpandoObjectConverter();
var jsonObject = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
</code></pre>
<p>The JSON object is quite complex and in order to find the value I am doing this spaghetti code:</p>
<pre><code>KeyValuePair<string, object> CountPair = new KeyValuePair<string, object>();
var currentCountPair = jsonObject.FirstOrDefault(x => x.Key == "data").Value;
if (currentCountPair != null)
{
currentCountPair = ((ExpandoObject)currentCountPair).FirstOrDefault(x => x.Key == "children");
if (currentCountPair != null)
{
currentCountPair = ((IList<object>)((KeyValuePair<string, object>)currentCountPair).Value).FirstOrDefault();
if (currentCountPair != null)
{
currentCountPair = ((ExpandoObject)currentCountPair).FirstOrDefault(x => x.Key == "data").Value;
if (currentCountPair != null)
{
CountPair = ((ExpandoObject)currentCountPair).FirstOrDefault(x => x.Key == "score");
result.Score = CountPair.Value == null ? null : CountPair.Value.ToString();
}
}
}
}
</code></pre>
<p>What do you think? Is there any better way of getting that value from <code>ExpandoObject</code>?
Or at least to reduce the number of <code>if</code> statements and code complexity...</p>
| [] | [
{
"body": "<p>First, I don't see any reason for using <code>ExpandoObject</code> in your code. The same result could be achieved with cleaner code using <code>JObject</code>s.</p>\n\n<p>Second, what would help if you could express your query using “LINQ to null”. Basically, treat <code>null</code> as an empty collection and any other value as a collection containing just that value. (The technical term for this is <a href=\"https://en.wikipedia.org/wiki/Monad_%28functional_programming%29#The_Maybe_monad\" rel=\"nofollow\">the Maybe monad</a>.)</p>\n\n<p>With both of these changes, your code could look something like this:</p>\n\n<pre><code>var jsonObject = JsonConvert.DeserializeObject<JObject>(json);\n\nstring result =\n from o in jsonObject.ToNullWrapper()\n from data in o[\"data\"]\n from children in data[\"children\"]\n from child in children.FirstOrDefault()\n from data2 in child[\"data\"]\n from score in data2[\"score\"]\n select score.ToString();\n</code></pre>\n\n<p>Note that (ab)using LINQ like this is not idiomatic and probably very confusing. But I think it results in very clean code.</p>\n\n<p>To make this work, you need the implementation of LINQ to null:</p>\n\n<pre><code>public struct NullWrapper<T>\n where T : class\n{\n public T Value { get; private set; }\n\n public NullWrapper(T value)\n : this()\n {\n Value = value;\n }\n\n public static implicit operator T(NullWrapper<T> wrapper)\n {\n return wrapper.Value;\n }\n}\n\npublic static class NullExtensions\n{\n public static NullWrapper<T> ToNullWrapper<T>(this T value)\n where T : class\n {\n return new NullWrapper<T>(value);\n }\n\n public static NullWrapper<TResult>\n SelectMany<TSource, TIntermediary, TResult>(\n this NullWrapper<TSource> source,\n Func<TSource, TIntermediary> intermediarySelector,\n Func<TSource, TIntermediary, TResult> resultSelector)\n where TSource : class\n where TIntermediary : class\n where TResult : class\n {\n if (source.Value == null)\n return new NullWrapper<TResult>();\n\n var intermediary = intermediarySelector(source.Value);\n\n if (intermediary == null)\n return new NullWrapper<TResult>();\n\n return resultSelector(source.Value, intermediary).ToNullWrapper();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:36:20.717",
"Id": "84321",
"Score": "0",
"body": "Note that I think that the `SelectToken()` approach from my other answer is a much better solution in this case. But I thought I'll leave this here anyway."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:30:49.357",
"Id": "48060",
"ParentId": "48059",
"Score": "3"
}
},
{
"body": "<p>Instead of <code>ExpandoObject</code>, you can use <code>JObject</code> together with its <code>SelectToken()</code> method:</p>\n\n<pre><code>var jsonObject = JsonConvert.DeserializeObject<JObject>(json);\n\nvar scoreToken = jsonObject.SelectToken(\"data.children[0].data.score\");\n\nstring score = scoreToken == null ? null : scoreToken.ToString();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T16:35:14.617",
"Id": "48061",
"ParentId": "48059",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T11:26:16.463",
"Id": "48059",
"Score": "2",
"Tags": [
"c#",
"json"
],
"Title": "Is there a proper way to query ExpandoObject?"
} | 48059 |
<p>I am currently developing a touchless lightswitch via a Raspberry Pi, an ultrasonic module and a nice radio module.</p>
<p>However, I am quite a beginner in Python and it was a hard time (at least for me) to accomplish my goal. Whenever the measured distance is falling below the limit the switch is triggered "on" (1) and after that if the distance is falling short again the switch is triggered "off" (0).</p>
<pre><code>#!/usr/bin/env python
import os
import sys
import time
import RPi.GPIO as GPIO
GPIOTrigger = 23
GPIOEcho = 24
def wait(sec):
while sec > 0:
sys.stdout.write(str(sec) + ' \r')
sec -= 1
time.sleep(1)
def MeasureDistance():
GPIO.output(GPIOTrigger, True)
time.sleep(0.00001)
GPIO.output(GPIOTrigger, False)
StartTime = time.time()
while GPIO.input(GPIOEcho) == 0:
StartTime = time.time()
while GPIO.input(GPIOEcho) == 1:
StopTime = time.time()
TimeElapsed = StopTime - StartTime
Distance = (TimeElapsed * 34300) / 2
return Distance
def main():
STATUS = 0
try:
while True:
Distance = MeasureDistance()
if Distance > 10.0:
time.sleep(0.01)
else:
if STATUS != 1:
print("Passing by (%.1f cm)" % Distance)
import subprocess
subprocess.call(["/root/rcswitch-pi/send", "10000", "1", "1"])
wait(5)
STATUS = 1
else:
subprocess.call(["/root/rcswitch-pi/send", "10000", "1", "0"])
wait(5)
STATUS = 0
except KeyboardInterrupt:
print("Stopped by user")
GPIO.cleanup()
if __name__ == '__main__':
# use GPIO pin numbering convention
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIOTrigger, GPIO.OUT)
GPIO.setup(GPIOEcho, GPIO.IN)
GPIO.output(GPIOTrigger, False)
main()
</code></pre>
<p>This works but I am unsure whether there is a nicer way of determining the last status of <code>STATUS</code> or if there are some pitfalls I might not see.</p>
| [] | [
{
"body": "<p><code>MeasureDistance</code>. The way it is written, sometimes it measures the duration of the signal, sometimes the (desired) time for the echo to arrive (consider what happens if you enter the first <code>while</code> loop). Suggestion:</p>\n\n<pre><code>def MeasureDistance():\n StartTime = time.time()\n GPIO.output(GPIOTrigger, True)\n while GPIO.input(GPIOEcho) == 0:\n pass\n # Found the raising front\n StopTime = time.time()\n GPIO.output(GPIOTrigger, False)\n</code></pre>\n\n<p>Of course, if the echo arrives faster than the code executes (and Python is slow), you'd get the elapsed time 0. I suppose there's nothing you can do about that, other than resorting to interrupts. Also, you may want to put some safeguards (a timer maybe) in case the raising front never arrives.</p>\n\n<p><code>main</code>. I don't see the need to <code>import subprocess</code> in the middle of the code. Also, state variables tend to create an unmaintainable code. Suggestion:</p>\n\n<pre><code> try:\n Distance = MeasureDistance()\n while True:\n while Distance > 10.0:\n Distance = MeasureDistance()\n wait(5)\n switch_on()\n while Distance < 10.0:\n Distance = MeasureDistance()\n wait(5)\n switch_off()\n except KeyboardInterrupt:\n</code></pre>\n\n<p>PS: a magic <code>34300</code> constant must go. Give it a nice symbolic name (yes we all know it has something to do with the speed of sound).</p>\n\n<p>Update.\nUsually in the situations like yours you may have a funny behaviour at the breaking distance. Due to random factors (like the code execution time, and many more others) the distance is measured with a certain error, and the switch will go on and off unpredictably. To deal with it, allow for a hysteresis:</p>\n\n<pre><code> while Distance > breaking_distance - tolerance:\n Distance = MeasureDistance()\n wait(5)\n switch_on()\n while Distance < breaking_distance + tolerance:\n Distance = MeasureDistance()\n wait(5)\n switch_off()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T23:58:59.447",
"Id": "48089",
"ParentId": "48081",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48089",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T19:22:34.787",
"Id": "48081",
"Score": "10",
"Tags": [
"python",
"beginner",
"timer",
"raspberry-pi"
],
"Title": "Touchless lightswitch with Raspberry Pi"
} | 48081 |
<p>The old code I had before was atrociously slow but after some advice and research I was able to take a 2-5 minutes run time down to about 5-30 seconds. That is acceptable, but still looking to have it run as quickly as possible.</p>
<p>I'm still cleaning it up, like there shouldn't be two seperate PP entities calls.</p>
<pre><code>public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId)
{
string teamGoal = "";
List<ProPit_User> lstProPit_User = new List<ProPit_User>();
using (PPEntities db = new PPEntities())
{
Team team = db.Teams.Where(x => x.teamID == teamId).FirstOrDefault();
if (team != null)
{
teamGoal = Convert.ToString(team.goal);
}
lstProPit_User = db.ProPit_User.Where(x => x.teamID == teamId).ToList();
}
List<DailyTeamGoal> lstDailyTeamGoal = new List<DailyTeamGoal>();
using (TEntities db = new TEntities())
using (PPEntities ppdb = new PPEntities())
{
//have to get every day of the month
DateTime dt = DateTime.Now;
int days = DateTime.DaysInMonth(dt.Year, dt.Month);
decimal orderTotal = 0m;
for (int day = 1; day <= DateTime.Now.Day; day++)
{
DailyTeamGoal dtg = new DailyTeamGoal();
dtg.Date = day.ToString(); //dt.Month + "/" + day; + "/" + dt.Year;
dtg.TeamGoal = teamGoal;
//decimal orderTotalRep = 0m;
DateTime dtStartDate = Convert.ToDateTime(dt.Month + "/" + day + "/" + dt.Year);
DateTime dtEndDate = dtStartDate.AddDays(1);
var ordersQuery = db.Orders.Where(o => o.DateCompleted >= dtStartDate
&& o.DateCompleted <= dtEndDate
&& (o.Status == 1 || o.Status == 2)
&& o.Kiosk != 0).ToList();
var lstSalesRepIDs = ppdb.ProPit_User
.Where(x => x.teamID == teamId).Select(v => v.SalesRepID).ToList();
var total = (from o in ordersQuery
where lstSalesRepIDs.Contains(o.SalesRepID)
select o.OrderTotal).Sum();
orderTotal += total;
dtg.DailyTotal = orderTotal;
lstDailyTeamGoal.Add(dtg);
}
}
return lstDailyTeamGoal;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T23:13:05.717",
"Id": "84394",
"Score": "0",
"body": "Is this faster? `abs( o.DateCompleted - (dtStartDate + 0.5) ) < 0.5`"
}
] | [
{
"body": "<p>You are calling queries in a for-loop for each day. Database queries are slow compared to C# code execution. Send only one query to the DB for the whole range of days.</p>\n\n<p>You can do the grouping by day either as DB query or query the ungrouped records and group using LINQ-to-Objects later.</p>\n\n<p>Also you are querying the <code>lstSalesRepIDs</code> within the loop. Why? The <code>teamId</code> seems not to change between the loop iterations. Query it before the loop.</p>\n\n<p>Also your where-clause tests the days like this: <code>o => o.DateCompleted >= dtStartDate && o.DateCompleted <= dtEndDate</code>. Where <code>dtEndDate</code> is one day more than <code>dtStartDate</code>. It looks to me as if you were taking two days at a time. Is this intended? If you want to include all times of a single day, change the comparison to <code>o.DateCompleted >= dtStartDate && o.DateCompleted < dtEndDate</code>. (Note: I used <code><</code> instead of <code><=</code> for the upper bound.)</p>\n\n<p>Don't make date calculations by converting from <code>DateTime</code> to <code>string</code> and back! <code>DateTime</code> contains all the functionality you need, without using any dirty tricks.</p>\n\n<hr>\n\n<pre><code>var salesRepIDs = new HashSet<int>(ppdb.ProPit_User\n .Where(ppu => ppu.teamID == teamId)\n .Select(ppu => ppu.SalesRepID)\n .AsEnumerable()); // HashSet.Contains is faster than List.Contains.\n\nDateTime today = DateTime.Today;\nDateTime startDate = new DateTime(today.Year, today.Month, 1);\nDateTime endDate = today.AddDays(1);\n\n// Note: If the DB contains no entries with future dates, \n// you can drop the test for the upper date!\nvar orders = db.Orders\n .Where(o => o.DateCompleted >= startDate\n && o.DateCompleted < endDate\n && (o.Status == 1 || o.Status == 2)\n && o.Kiosk != 0)\n .AsEnumerable();\n\n// Because of AsEnumerable() we are working with LINQ-to-Objects now.\nvar ordersByCompletionDate = orders\n .Where(o => salesRepIDs.Contains(o.SalesRepID))\n .GroupBy(o => o.DateCompleted.Date); // .Date in order to drop the time part.\nforeach (var dayGroup in ordersByCompletionDate) {\n decimal daylyTotal = dayGroup.Sum(o => o.OrderTotal);\n // ...\n}\n</code></pre>\n\n<p><code>.AsEnumerable()</code> has the advantage over <code>.ToList()</code> that the source is consumed on the fly, item by item. No in-memory list needs to be created.</p>\n\n<p>The <code>salesRepIDs.Contains(..)</code> part requires special attention. It could be performed as part of the DB query; however depending on the implementation and the number of <code>salesRepIDs</code> this could create queries with long <code>IN</code> lists: <code>WHERE id IN (1, 2, 3, ..)</code>. There is a limit for the length of these lists. This can lead to \"Query too complex\" exceptions. If this is not the case, i.e., if you know that you will always have a reasonable number of ID's, could can simplify the whole code and do everything (filtering, grouping and summing) with only one single DB query.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:38:38.787",
"Id": "84377",
"Score": "0",
"body": "I'm definitely interested in simplifying the query calls and have adopted a lot of the suggestions here. The .contains() portion could 'technically' be unlimited. But realistically it's around 30 users per team. Still working on changing my method over to these suggestions and then will begin to test it. Thanks for the advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:44:45.793",
"Id": "84380",
"Score": "0",
"body": "o.DateCompleted.Date returns an error for me. System.Nullable<System.DateTime> does not contain a definition for 'Date' and no extension method 'Date' accepting a first argument of type 'System.Nullable<Sustem.DateTime>' could be found."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:46:57.203",
"Id": "84381",
"Score": "0",
"body": "If `DateCompleted` is a `Nullable<DateTime>` then change the expression to `o.DateCompleted.Value.Date`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T20:17:40.137",
"Id": "48083",
"ParentId": "48082",
"Score": "8"
}
},
{
"body": "<p>I agree with Olivier Jacot-Descombes on the functional aspects of this code, but it also lacks organization, meaningful naming, and consistency, which will make it harder for other readers (or yourself in future years) to follow. Some examples:</p>\n\n<pre><code>public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId)\n...\nList<DailyTeamGoal> lstDailyTeamGoal = new List<DailyTeamGoal>();\n...\nDateTime dt = DateTime.Now;\n...\nint days = DateTime.DaysInMonth(dt.Year, dt.Month);\n</code></pre>\n\n<p>With modern strongly typed languages like C#, adding the <code>Type</code> to a method or variable name is considered unnecessary clutter. Furthermore, variables with unclear names get lost in translation when used elsewhere. In the last example above, what does <code>dt</code> mean other than the <code>Type</code> of the variable? Consider these improvements:</p>\n\n<pre><code>public static IEnumerable<DailyTeamGoal> GetDailyTeamGoals(int teamId)\n...\nList<DailyTeamGoal> dailyTeamGoals = new List<DailyTeamGoal>();\n...\nDateTime today = DateTime.Now.Date;\n...\nint daysThisMonth = DateTime.DaysInMonth(today.Year, today.Month);\n</code></pre>\n\n<p>There's also a lot going on in this one method. Separating it out into several methods with clear names will make the code easier to understand and can break logic out into distinct testable pieces. Right now, your single method about getting the Daily Team Goals encompasses a lot of business logic that will be hard to split out when the time comes (and it will).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:16:52.857",
"Id": "84374",
"Score": "0",
"body": "These are good points. I changed my identifiers accordingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:38:58.103",
"Id": "84378",
"Score": "0",
"body": "Yeah I've began renaming them, think hard habits to break with the type naming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T21:35:35.700",
"Id": "86090",
"Score": "0",
"body": "The number of public types in the .NET Framework 3.5 was over 10,000! And this number is growing with each release. This makes it impractical to find an appropriate type prefix for each type."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:10:21.170",
"Id": "48085",
"ParentId": "48082",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T19:58:03.330",
"Id": "48082",
"Score": "5",
"Tags": [
"c#",
"performance",
"linq",
"entity-framework",
"asp.net-mvc"
],
"Title": "Getting list of daily team goals"
} | 48082 |
<p>I have a data structure that uses a <code>Dictionary<ID,TimeSeries></code> to hold time series for different products. <code>TimeSeries</code> is implemented as something holding an array of <code>Point</code>, which contain a <code>DateTime</code> and a <code>double</code>.</p>
<p>Its interface is:</p>
<pre><code>TimeSeries{
int Length{ get; }
Point ElementAt(int index);
DateTime StartTime { get; }
DateTime EndTime { get; }
}
</code></pre>
<p>Given a pair of elements of such data structure I need to find the first time instant where they diverge. For my definition of divergence, if a dictionary contains an element and the other doesn't I need to return the time of the first point of the <code>TimeSeries</code> I have.</p>
<p>This is the code I'm using to compute the difference and that I'd like you to review and comment:</p>
<pre><code>bool TryFindFirstDivergenceTime(Dictionary<ID, TimeSeries> baseline, Dictionary<ID, TimeSeries> other, out DateTime firstDivergenceTime)
{
firstDivergenceTime = default(DateTime);
foreach(var baselineIDSeriesPair in baseline)
{
if(other.ContainsKey(baselineIDSeriesPair.Key))
{
firstDivergenceTime = Min(FindFirstDivergenceTime(baselineIDSeriesPair.Value, other[baselineIDSeriesPair.Key]), firstDivergenceTime);
}
else
{
firstDivergenceTime = Min(baselineIDSeriesPair.Value.Start, firstDivergenceTime);
}
}
foreach(var otherIDSeriesPair in other)
{
if(!baseline.ContainsKey(otherIDSeriesPair.Key))
{
firstDivergenceTime = Min(otherIDSeriesPair.Value.Start, firstDivergenceTime);
}
}
return firstDivergenceTime != default(DateTime);
}
public DateTime Min(DateTime first, DateTime second)
{
if(first == default(DateTime))
return second;
if(second == default(DateTime))
return first;
return new DateTime(Math.Min(first.Ticks, second.Ticks));
}
DateTime FindFirstDivergenceTime(TimeSeries first, TimeSeries second)
{
if(first.Length != second.Length)
{
throw new ArgumentException();
}
for(var i=0; i < first.Length; i++)
{
if(! first.ElementAt(i).Equals(second.ElementAt(i)))
{
return Min(first.ElementAt(i).Time, second.ElementAt(i).Time);
}
}
return default(DateTime);
}
</code></pre>
<p>I have the feeling that I am not approaching the problem in the right way as the code contains the repetition of the logic to find the time of the first difference when I don't have the same product in both the dictionaries.</p>
<p>The other think that I don't particularly like is that I find myself breaking th symmetry and using for on dictionary <code>Key</code> and <code>Value</code> from its <code>IEnumerable</code>, while from the other I need to perform a lookup.</p>
<p>How would you address those issues?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:36:12.750",
"Id": "84376",
"Score": "0",
"body": "I'm having a hard time telling what this is supposed to do without `Min` and `FindFirstDivergenceTime`, so IMO they are quite relevant. Also, this doesn't look like it would compile (see duplicate `StartTime` definitions in `TimeSeries` and first use of `otherIDSeriesPair` in the `TryFindFirstDivergenceTime` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:56:00.140",
"Id": "84384",
"Score": "0",
"body": "I fixed the compilation issues and I added the `Min` and `FindFirstDivergenceTime` method implementations"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T00:20:28.193",
"Id": "84397",
"Score": "0",
"body": "I'd probably try to use a `first.Zip(second, (a, b) => { . . . })` of some kind instead of the foreaches. That does require the order to be the same, though."
}
] | [
{
"body": "<p>Before getting to your question about reducing the duplication, there's another issue I'd like to point out first. The use of <code>default(DateTime)</code> as a check for the absence of a value is incorrect and misleading. <code>default(DateTime)</code> is a <em>valid</em> date. However unlikely it is that you will have a date that equals that value, it is misleading to use because anyone looking at your code that sees a <code>DateTime</code> variable will assume that it holds a proper date value because it <em>has to</em>. As a struct, it can't be represented as <code>null</code>, so it always holds a value. Enter <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/2cf62fcy%28v=vs.100%29.aspx\" rel=\"nofollow noreferrer\">nullable types</a>. <code>DateTime?</code> clearly expresses that the variable can be in a state where it doesn't hold a date value.</p>\n\n<p>That said, it appears you're trying to join the two dictionary and compare in these ways:</p>\n\n<ol>\n<li>When there are matching keys.</li>\n<li>When only one of the dictionaries holds a key.</li>\n</ol>\n\n<p>Sounds like a <a href=\"http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/\" rel=\"nofollow noreferrer\">Full Outer Join</a>, which someone has kindly shared a Linq-esque extension method for over on <a href=\"https://stackoverflow.com/questions/5489987/linq-full-outer-join/13503860#13503860\">Stack Overflow</a>. Using this, you can concisely and expressively rewrite your methods like so to avoid duplication (note the use of <code>DateTime?</code>):</p>\n\n<pre><code>// Note: I think this is a bad method name (it's the same as the one below,\n// which I think is better suited for the name). It should probably express\n// the comparison between these Dictionary maps.\npublic static DateTime? GetEarliestDivergenceTime(Dictionary<int, TimeSeries> baseline, Dictionary<int, TimeSeries> other, DateTime? defaultEarliestDivergenceTime = null)\n{\n // Omitting 'FullOuterJoin' code in StackOverflow link:\n var earliestDivergenceTimes = baseline.FullOuterJoin(\n other,\n b => b.Key,\n o => o.Key,\n (b,o) => GetEarliestDivergenceTimeOrDefault(b, o));\n\n return earliestDivergenceTimes.Min() ?? defaultEarliestDivergenceTime;\n}\n\npublic static DateTime? GetEarliestDivergenceTime(TimeSeries ts1, TimeSeries ts2, DateTime? defaultEarliestDivergenceTime)\n{\n DateTime? earliestDivergenceTime = null;\n\n if(ts1 != null && ts2 != null)\n {\n // Compare.\n }\n else if(ts1 != null && ts2 == null)\n {\n // Use ts1.\n }\n else if(ts1 == null && ts2 != null)\n {\n // Use ts2.\n }\n\n // earliestDivergenceTime will be null if both t1 and t2 are null.\n return earliestDivergenceTime ?? defaultEarliestDivergenceTime;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:22:35.863",
"Id": "84491",
"Score": "1",
"body": "I agree, although as you can see in my code comment I had a hard time with method/argument names since I'm still not 100% on how this would get used. Suggestions for improvement are welcome."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:07:26.500",
"Id": "48153",
"ParentId": "48084",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48153",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:07:34.757",
"Id": "48084",
"Score": "3",
"Tags": [
"c#",
"datetime"
],
"Title": "Matching items in different arrays and performing operations on them"
} | 48084 |
<p>I asked a math question and was hoping someone could have a look at the code for me as well. Unfortunately you might have to go look at the original question <a href="https://math.stackexchange.com/questions/767888/math-for-future-value-of-growing-annuity">here</a>.</p>
<pre><code>protected void ButtonCalRetire_Click(object sender, EventArgs e)
{
double FVc = 0;
double FVd = 0;
double PV = double.Parse(TextBoxCurrentSave.Text);
double i = double.Parse(TextBoxRoR.Text) / 100;
double b = (double)(int.Parse(TextBoxRetireAge.Text) - int.Parse(TextBoxCurrentAge.Text));
double R1 = double.Parse(TextBoxCurrentMonthlyContribution.Text);
double g2 = double.Parse(TextBoxAnnuityGrowthRetire.Text) / 100;
FVc = PV * Math.Pow((1 + i / 12), (b * 12));
FVd = R1 * (Math.Pow((1 + i / 12), (b * 12)) - Math.Pow((1 + g2 / 12), (b * 12))) / ((i / 12) - (g2 / 12));
double totSaved = FVc + FVd;
double R2 = double.Parse(TextBoxCurrentMonthlyContribution.Text);
double n = (double)(int.Parse(TextBoxDeathAge.Text) - int.Parse(TextBoxRetireAge.Text));
double PVg = R2 * Math.Pow((1 + g2 / 12), (b * 12)) / (i / 12 - g2 / 12) * (1 - ((Math.Pow((1 + g2 / 12), (n * 12))) / (Math.Pow((1 + i / 12), (n * 12)))));
double diff = FVc + FVd - PVg;
double R3 = diff / (Math.Pow((1 + i / 12), (b * 12)) - Math.Pow((1 + g2 / 12), (b * 12))) / ((i / 12) - (g2 / 12));
LabelTotControNeeded.Text = (R3 + R2).ToString("R ### ##0.00");
LabelControNeeded.Text = R3.ToString("R ### ##0.00");
}
</code></pre>
<p>Edit: </p>
<p>If I debug correctly, the PVg above (line repeated below) returns 0</p>
<pre><code>double PVg = R2 * Math.Pow((1 + g2 / 12), (b * 12)) / (i / 12 - g2 / 12) * (1 - ((Math.Pow((1 + g2 / 12), (n * 12))) / (Math.Pow((1 + i / 12), (n * 12)))));
</code></pre>
<p>Edit:</p>
<p>Here is the calculator: <a href="http://exceed.myib.co.za/calc" rel="nofollow noreferrer">http://exceed.myib.co.za/calc</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T01:12:17.287",
"Id": "84400",
"Score": "2",
"body": "Separate the formulaic bits into its own method from the bits which react to and update the UI. Your concerns are then separated and easier to maintain."
}
] | [
{
"body": "<h1>Naming conventions</h1>\n\n<p>As you will have noticed from the coloring: you're not following naming conventions. Variables inside a method are lowerCamelCase which means this</p>\n\n<pre><code>FVc\n</code></pre>\n\n<p>becomes this</p>\n\n<pre><code>fvC\n</code></pre>\n\n<h1>Naming</h1>\n\n<p>Your variables have very unclear names. From the context I know that this is part of a math formula, but you might be able to clarify them. If possible, consider using full words that clearly explain what that variable means.</p>\n\n<p>In that regard I would definitely change this</p>\n\n<pre><code>totSaved \n</code></pre>\n\n<p>into this</p>\n\n<pre><code>totalSaved\n</code></pre>\n\n<p>\"Saving\" 2 characters is nothing, but it lowers readability.</p>\n\n<h1>Parsing</h1>\n\n<p>You parse the same textbox fields many times. Instead, parse it once and put it a variable. Now you can reference that variable every time and it will be a lot easier to work with.</p>\n\n<h1>Formula clarity</h1>\n\n<p>You should also consider splitting up your long formulas (insofar a portion of a formula would make sense) to help you in case something needs to be debugged. It will be easier to check intermediate values and to keep the overview over what your formula represents.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:44:50.127",
"Id": "84417",
"Score": "0",
"body": "Looks like the `12` is the number of months in a year. Do you really think that should be a variable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T09:21:50.817",
"Id": "84458",
"Score": "0",
"body": "You can keep 12 as a constant. That will improve code readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:36:56.737",
"Id": "84473",
"Score": "1",
"body": "I tried to keep my phrasing general: no, I probably wouldn't change it into a variable. In retrospect, I shouldn't have brought it up since it isn't really appropriate here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T00:51:25.653",
"Id": "48093",
"ParentId": "48091",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T00:33:26.920",
"Id": "48091",
"Score": "3",
"Tags": [
"c#",
".net"
],
"Title": "Retirement-saving calculator"
} | 48091 |
<p>I am trying to process an audio library file which is about 350 KB. My application processes each song on the file gets its meta-data and displays it in a List Box.</p>
<p>The problem is that it takes too much time (about 1-2 mins). I need to make it faster like in the Windows Media Player. I tried to make it faster by saving meta data for each song in the library file. Now it takes about 30-50 secs. The application works fine; no performance issues.</p>
<p>If I use this method then it takes 1 min to load and process:</p>
<pre><code> public void m3uplaylist()
{
try
{
song.Clear();
}
catch (Exception)
{
}
string fileName = null;
FileStream fStream = null;
StreamReader sReader = null;
if (File.Exists(filename))
{
fStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
sReader = new StreamReader(fStream);
while ((fileName = sReader.ReadLine()) != null)
{
if (fileName.Length > 0 && fileName.Substring(0, 1) != "#" && fileName.Substring(0, 1) != "\n") //Checks whether the first character of the line is not # or Enter
{
try
{
string[] row1 = { fileName.Substring(0, fileName.LastIndexOf("\\")) + "\\" + fileName.Substring(fileName.LastIndexOf("\\") + 1) }; //Stores the song details in string array so that it can be added to the Grid
for (int i = 0; i < row1.Length; i++)
{
Songss sing = new Songss(row1[i]);
song.Add(sing);
progress++;
workers.ReportProgress(progress, bar1);
}
TotalSongs = File.ReadAllText(filename).Length / 100;
}
catch (FileNotFoundException ex)
{
}
}
}
fStream.Close();
sReader.Close();
}
}
</code></pre>
<hr>
<p>If I use this method the library loads in about 15 seconds:</p>
<pre><code> public void mplplaylistload(string filename)
{
if (File.Exists(filename))
{
TotalSongs = File.ReadAllText(filename).Length / 100 - 500;
string file = System.IO.Path.GetFileNameWithoutExtension(filename);
// Create the query
var rowsFromFile = from c in XDocument.Load(
filename).Elements(
"playlist").Elements("abc123").Elements("Song")
select c;
// Execute the query
foreach (var row in rowsFromFile)
{
Songss sing = new Songss(row.Element("Path").Value);
sing.title = row.Element("Title").Value;
if (GetFullInfo == true)
{
sing.album = row.Element("Album").Value;
sing.artist = row.Element("Artist").Value;
sing.length = row.Element("Length").Value;
sing.size = row.Element("Size").Value;
if (File.Exists(row.Element("Image").Value))
{
BitmapImage img = new BitmapImage(new Uri(row.Element("Image").Value));
img.CacheOption = BitmapCacheOption.None;
sing.source = img;
}
}
song.Add(sing);
progress++;
workers.ReportProgress(progress);
}
}
}
</code></pre>
<hr>
<p>The file from which it reads is like this:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<playlist>
<abc123>
<Song>
<Title>9</Title>
<Path>D:\MuziK\Music\9.mp3</Path>
<Album>Unkown Album</Album>
<Artist>Unknown Artist</Artist>
<Size>2,960KB</Size>
<Length>NA</Length>
<Image>C:\Users\The GaMeR\AppData\Local\Macalifa\albumarts\Unkown Album\9\art.jpg</Image>
</Song>
<Song>
<Title>Aa Bhi Ja Sanam</Title>
<Path>D:\MuziK\Music\Aa Bhi Ja Sanam.mp3</Path>
<Album></Album>
<Artist></Artist>
<Size>2,941KB</Size>
<Length>3:08</Length>
<Image>C:\Users\The GaMeR\AppData\Local\Macalifa\albumarts\\Aa Bhi Ja Sanam\art.jpg</Image>
</Song>
</abc123>
</code></pre>
<p></p>
<hr>
<p>What I need is to optimize the time-taken by the library to load.</p>
<p><strong>Note:</strong> I am using background worker to load the library. Is there any better approach than this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T00:58:11.617",
"Id": "84399",
"Score": "1",
"body": "Can you clarify a little about your two \"approaches\"? From a first glance they don't seem to do the same, why exactly are they considered an alternative? And since you know one of them is 4 times faster than the other, why do you want a codereview from that slower one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:07:41.207",
"Id": "84468",
"Score": "0",
"body": "@JeroenVannevel The first approach is slow, because i think it fetches meta-data for each song. The second however, is more faster because meta-data for each song is saved in the library file. I don't want codereview from slower one, i want code review of the faster one, to make it even more faster. As i have mentioned in my question, that i want it to be just like WMP, When user opens the application the library should already be loaded.....\n\n\nThe Don't look the same of-course.. The first one only reads the \"Song Paths\" but the second one reads everything."
}
] | [
{
"body": "<p>Instead of loading the entire XML file, you can use XStreamingElement and xmlReader to reduce the memory foot print. As your playlist grows, large xml file will become a problem. The following MSDN link describes it <a href=\"http://msdn.microsoft.com/en-us/library/bb387013.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb387013.aspx</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:08:56.900",
"Id": "84469",
"Score": "0",
"body": "Thanks!! i will look into it & inform you if it solves my problem"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:34:43.857",
"Id": "48127",
"ParentId": "48092",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T00:37:10.340",
"Id": "48092",
"Score": "2",
"Tags": [
"c#",
"performance",
"xml",
"wpf",
"audio"
],
"Title": "Optimizing playlist processing"
} | 48092 |
<p>At the moment is my code secure for SQL injections and so forth? I still need to hash passwords and make sure fields are valid and so forth. </p>
<pre><code><?php
try{
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
die();
}
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "INSERT INTO userinfo (name ,username, email, password) VALUES (:name,:username,:email,:password)";
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password
));
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T05:09:08.570",
"Id": "84427",
"Score": "2",
"body": "SQL attack has been over asked both here and on stackoverflow: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php, and http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php/60496#60496 both articles are applicable to what you are asking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T05:11:53.660",
"Id": "84428",
"Score": "1",
"body": "possible duplicate of [Is this code safe from SQL injection?](http://codereview.stackexchange.com/questions/24296/is-this-code-safe-from-sql-injection)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:14:29.667",
"Id": "84434",
"Score": "2",
"body": "@azngunit81 Same topic, different code. I don't see how this is a duplicate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:56:14.397",
"Id": "84442",
"Score": "0",
"body": "@200_success same PDO setup with similar code. Its an insert with PDO setup so the same response will be yield: the post needs to be sanitize, prepare statement is already use so that is fine but everything that is said in the articles mentioned is a repetition of similar response that would be drafted up - hence duplication of question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:03:19.460",
"Id": "84443",
"Score": "3",
"body": "@azngunit81 Remember that [all aspects of the code are reviewable](http://codereview.stackexchange.com/help/on-topic), not just the SQL injection issue that the OP raised. Questions submitted by two different users are almost never duplicates of each other."
}
] | [
{
"body": "<p>It is safe.</p>\n\n<p>You can improve your code like this:</p>\n\n<ul>\n<li>no need to use closing <code>?></code> in case that you are not outputting any HTML / or something else after your PHP code</li>\n<li>no need to use <code>\"\"</code> to wrap strings in case that you don't have any variables inside a string, you can use <code>''</code> instead, PHP interpreter does not need to check in that case whether there are any variables in the string or not</li>\n<li>you can replace <code>echo $e->getMessage; die()</code> by simplier <code>exit($e->getMessage());</code></li>\n<li>I added salt generation to your code <code>$salt = md5(uniqid(null, true));</code></li>\n<li>I added password hashing to your code by <code>$password = hash('sha256', $password . $salt);</code></li>\n</ul>\n\n<p>The whole code hereunder:</p>\n\n<pre><code><?php\n\ntry {\n $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');\n $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n} catch (PDOException $e){\n exit($e->getMessage());\n}\n\n$name = $_POST['name'];\n$username = $_POST['username'];\n$email = $_POST['email'];\n$password = $_POST['password'];\n\n$salt = md5(uniqid(null, true));\n$password = hash('sha256', $password . $salt);\n\n$sql = '\n INSERT INTO userinfo \n (name ,username, email, password, salt) \n VALUES \n (:name,:username,:email,:password, :salt)\n';\n\n$query = $handler->prepare($sql);\n\n$query->execute(array(\n ':name' => $name,\n ':username' => $username,\n ':email' => $email,\n ':password' => $password,\n ':salt' => $salt\n));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T16:31:28.440",
"Id": "84522",
"Score": "1",
"body": "Excellent observation, that salting and hashing are essential, you have made."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:21:45.500",
"Id": "84566",
"Score": "0",
"body": "Excellent answer. But isn't `password_hash` safer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:34:40.027",
"Id": "84576",
"Score": "0",
"body": "@user2981256 You can use `password_hash` as well, safety depends on used hashing algorithm. You can choose these values in both methods so the safety is about the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-22T16:17:25.007",
"Id": "148009",
"Score": "0",
"body": "Don't use sha256 for passwords. It's much too fast and therefore easy to attack. Use bcrypt, scrypt or PBKDF2."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:05:47.547",
"Id": "48139",
"ParentId": "48095",
"Score": "5"
}
},
{
"body": "<p>Yoda has some good points, and I agree with it being safe. I noticed you mentioned validating, but I figured I'd add my 2 cents for future readers that may come across this question. A few things jump out at me from the following:</p>\n\n<pre><code>$name = $_POST['name'];\n$username = $_POST['username'];\n$email = $_POST['email'];\n$password = $_POST['password'];\n</code></pre>\n\n<p>You should check that all fields have been posted, and stop processing if there is information missing. An example of this would be:</p>\n\n<pre><code>$name = isset($_POST['name']) ? $_POST['name'] : null;\nif($name==null) { \n exit(); \n}\n</code></pre>\n\n<p>This information is being entered into the database without any checks, which can lead to bad data being stored. I'm assuming that there may be checks client side (browser), but those checks are by no means fool-proof. Javascript could be disabled, rending those checks useless. There is <code>required</code> for HTML5, and some browsers have implemented that functionality. However, not all have, and many users will inevitably be using the older versions that haven't. What if the name and username are blank, or the name is <code>31&^5</code>. Checking the length and content should be done both on the client and the server.</p>\n\n<p>+1 for prepared statements!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T19:28:49.240",
"Id": "49365",
"ParentId": "48095",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48139",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T01:52:54.630",
"Id": "48095",
"Score": "6",
"Tags": [
"php",
"mysql",
"security",
"pdo",
"authentication"
],
"Title": "Preventing SQL Injection in user registration routine"
} | 48095 |
<p>I am not sure if I should be using recursion or not or if it even helps in increasing the performance of my algorithm. I feel as though I am creating and replacing too many arrays by calling my inner <code>rotate()</code> function.</p>
<p>Should I add a check to convert rotation <code>-270</code> to <code>90</code> and vice-versa so that I am rotating less often?</p>
<p>Please refer to the JSFiddle I have provided for details and clarification on the functions involved in the code below: <a href="http://jsfiddle.net/MrPolywhirl/PaCv8/" rel="nofollow">JSFiddle Demo</a></p>
<pre><code>var rotateMatrix = function (matrix, n, direction) {
var ret = matrix.slice();
var rotate = function(direction, matrix) {
var r = zeroArr(n, n);
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
if (direction < 0) {
r[i][j] = matrix[n - j - 1][i];
} else {
r[i][j] = matrix[j][n - i - 1];
}
}
}
return r;
};
for (var turn = Math.abs(direction); turn > 0; turn -= 90) {
ret = rotate(direction, ret);
}
return ret;
};
var tile = [
['A', 'B', 'C'],
['D', 'E', 'F'],
['G', 'H', 'I']
];
trace2('Rotate +180', printMatrix(rotateMatrix(tile, 3, 180)));
trace2('Rotate +90', printMatrix(rotateMatrix(tile, 3, 90)));
trace2('Orginal', printMatrix(tile));
trace2('Rotate -90', printMatrix(rotateMatrix(tile, 3, -90)));
trace2('Rotate -180', printMatrix(rotateMatrix(tile, 3, -180)));
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>Rotate +180:
I| H| G
--+--+--
F| E| D
--+--+--
C| B| A
Rotate +90:
C| F| I
--+--+--
B| E| H
--+--+--
A| D| G
Orginal:
A| B| C
--+--+--
D| E| F
--+--+--
G| H| I
Rotate -90:
G| D| A
--+--+--
H| E| B
--+--+--
I| F| C
Rotate -180:
I| H| G
--+--+--
F| E| D
--+--+--
C| B| A
</code></pre>
| [] | [
{
"body": "<p>The <code>n</code> parameter is redundant, as it should be possible to deduce the matrix dimensions from <code>matrix</code> itself, using <code>matrix.length</code> and <code>matrix[0].length</code>. You seem to have made the assumption that <code>matrix</code> is square — you should either document or relax the restriction.</p>\n\n<p>I suggest writing three separate inner functions for the three possible rotations. One code-reuse technique you could use for the ±90° rotations is to combine <a href=\"https://codereview.stackexchange.com/a/40372/9357\">transpose and row-swap operations</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T10:37:30.320",
"Id": "84464",
"Score": "0",
"body": "Wow, that question was insightful. I have come up with the ollowing: [Updated JSFiddle](http://jsfiddle.net/MrPolywhirl/NH42z/). Should I append these changes to my question for others to view? Is there any other way to optimize this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T16:51:21.990",
"Id": "84527",
"Score": "0",
"body": "@Mr.Polywhirl Concerning changes to reviewed code, you might want to read [this meta-post](http://meta.codereview.stackexchange.com/questions/1763/can-i-edit-my-own-question-to-include-revised-code-also-how-to-handle-iterativ)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:23:52.177",
"Id": "48111",
"ParentId": "48097",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:08:40.777",
"Id": "48097",
"Score": "4",
"Tags": [
"javascript",
"optimization",
"matrix"
],
"Title": "Matrix rotation efficiency"
} | 48097 |
<p>I understand that account details should be stored using a much more secure method, but this is only a demonstration script I've made to store login credentials and remember a user wishes to remain logged in using <code>localStorage</code> rather than <code>sessionStorage</code>.</p>
<p>Could anyone show me how I might write this more efficiently please? My main concern is code repetition, so I'd love to move toward a much more object oriented structure.</p>
<pre><code>var bic = bic || {};
bic.checkLogin = function() {
var loginUser = document.getElementById("loginUser").value;
var loginPass = document.getElementById("loginPass").value;
var storedUser = localStorage.Username;
var storedUser2 = storedUser.replace(/"/g,''); // remove " for plain text display in loginForm
var storedPass = localStorage.Password;
var checked = document.getElementById("rememberLogin").checked;
if(checked == true) {
localStorage.setItem("loggedIn", "yes");
} else {
localStorage.setItem("loggedIn", "no");
}
// if Username key exists, and user/pass values match storage entries
if(localStorage.Username) {
if(storedUser.match(loginUser) && storedPass.match(loginPass)) {
bic.notify("loginForm", "Logged in as: " + storedUser2 + "<br /><br /><a id='logout' href=''>Log out?</a>");
document.getElementById("logout").onclick = function(e){e.preventDefault();bic.logout();};
console.log("Logged in as: " + localStorage.Username);
} else {
bic.loginFailed();
bic.notify("loginStatus", "Login failed. Please try again.");
console.log("Failed logins: " + localStorage.failedLogins);
}
}
}
// localStorage equiv of cookie
bic.isLoggedIn = function() {
var a = localStorage.loggedIn;
var storedUser = localStorage.Username;
var storedUser2 = storedUser.replace(/"/g,''); // removing " as above
// does a exactly equal "yes"?
if(a === "yes") {
bic.notify("loginForm", "Logged in as: " + storedUser2 + "<br /><br /><a id='logout' href=''>Log out?</a>");
document.getElementById("logout").onclick = function(e){e.preventDefault();bic.logout();};
console.log("Logged in as: " + localStorage.Username);
}
}
// logout and remove localStorage key
bic.logout = function() {
document.getElementById("loginForm").innerHTML = "<input type='text' id='loginUser' placeholder='Username'><br /><br /><input type='password' id='loginPass' placeholder='Password'><br /><br /><button type='button' id='login'>Login</button> <button type='button' id='loginReg'>Register</button><br /><br /><input type='checkbox' id='rememberLogin' /> Stay logged in?<br /><span id='loginStatus'></span>";
bic.loginPrefill();
bic.delete("loggedIn");
console.log("Logged out");
}
</code></pre>
| [] | [
{
"body": "<h1>Separate UI from logic</h1>\n\n<p>You might want to keep the logic for localStorage handling separate from the DOM fetching logic. That way, your system for handling the local storage can easily be detached and reused elsewhere without that extra baggage. Also works the other way around, when you replace your UI.</p>\n\n<h1>Basic login API</h1>\n\n<p>In continuation with the previous paragraph, you could model it to have this API:</p>\n\n<pre><code>bic.login(username,password); // Return true if logged in, false if not\nbic.isLoggedIn(); // Return true if someone is logged in, else false\nbic.getUserId(); // Gets the current user's ID\nbic.logout(); // Logout current user\n\nbic.register(username,password) // Registration\nbic.destroyCurrentUser(); // Just for fun. Only a logged in user can delete himself\n</code></pre>\n\n<p>The UI logic is separate. It consumes this API rather than being one with it.</p>\n\n<h1>LocalStorage is synchronous</h1>\n\n<p>Note that localStorage is a <em>synchronous</em> operation. Doing heavy IO against localStorage could mean an unresponsive experience. This has an amplified effect on mobile devices, since they are times slower. Don't pull out or put in huge data. Do it by chunks. Use multiple small keys rather than one big key to house everything your system needs.</p>\n\n<h1>JSON.parse() and JSON.stringify()</h1>\n\n<p>localStorage is a string-based, key-value storage. But that's it. You need some form of format to structure highly complex data, like user data. Something that may look like:</p>\n\n<pre><code>[\n {id:1,name:\"foo\",password:\"***\"},\n {id:1,name:\"bar\",password:\"***\"},\n {id:1,name:\"baz\",password:\"***\"}\n]\n</code></pre>\n\n<p>To store data like a JS object, you need <code>JSON.stringify()</code> to turn it into a string. Then you can store it to localStorage. To get it, retrieve it from localStorage and then use <code>JSON.parse()</code> to convert from string.</p>\n\n<h1>Storage routine</h1>\n\n<p>What I typically do when using localStorage is to create an in-memory object of the data. On every save, I serialize the data with <code>JSON.stringify</code> and store it to the localStorage. If ever there are other code that modifies that same data, there are <a href=\"http://html5demos.com/storage-events\" rel=\"noreferrer\">localStorage events</a> to tell you if the data is modified in the storage.</p>\n\n<h1>Code refinements</h1>\n\n<p>Since I advertised array-based storage, then Array filter, splice, push would be your best friends here. In addition, I believe I introduced you to JSON stringify and parse already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T10:29:50.847",
"Id": "84463",
"Score": "0",
"body": "This gives me lots to think about moving forward. I'd used JSON.stringify a few times in the remainder of the code. But after your description, I think I've probably used it ineffectively. Many thanks, Josepsh!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:44:40.360",
"Id": "48108",
"ParentId": "48098",
"Score": "6"
}
},
{
"body": "<pre><code>if(storedUser.match(loginUser) && storedPass.match(loginPass))\n</code></pre>\n\n<p>Something like this is a really bad practice. Calling storedUser.match(loginUser) will do a regex evaluation of the value which can provide unexpected results. You should always do something like this:</p>\n\n<pre><code>if(storedUser === loginUser && storedPass === loginPass)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:43:01.057",
"Id": "48310",
"ParentId": "48098",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48108",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:15:07.390",
"Id": "48098",
"Score": "5",
"Tags": [
"javascript",
"html5",
"authentication"
],
"Title": "Can this localStorage login script be written more efficiently?"
} | 48098 |
<p>Recently I had someone describe a "Time Machine" service to me; that is, a service that could be used to change how a chunk of code perceives time.</p>
<p>Normally through calls to DateTime.Now and other DateTime statics, time is directly tied to the system clock. A Time Machine service is used instead of the static DateTime calls, and allows external code to change the time it reports. This is especially useful when writing unit tests for services that behave different as time passed due to timers, triggers, etc.</p>
<p>I liked the idea, and decided to implement my own version. Here are the relevant interfaces:</p>
<pre><code>// A service that can travel through time
public interface ITimeTraveler
{
ITimeMachine TimeMachine { get; set; }
}
// Interface for a Time Machine
public interface ITimeMachine
{
DateTime Now();
DateTime UtcNow();
DateTime Today();
DateTime UtcToday();
void TimeTravel(TimeSpan adjustment);
void TimeTravelTo(DateTime newDateTime);
void FreezeTime();
void UnfreezeTime();
void RevertAllTimeTravel();
bool IsCurrentlyTimeTraveling();
}
</code></pre>
<p>Here is the <a href="https://gist.github.com/jmblack/11275845" rel="nofollow">Time Machine Gist</a> with the full implementation.</p>
<hr>
<p>This includes two revisions. The first revision was the code I linked to originally, and additional revisions take the feedback here into consideration.</p>
<p>I'm looking for any feedback or suggestions on both the concept of this service and my current implementation.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:58:29.087",
"Id": "84411",
"Score": "9",
"body": "Just clicked the link. 137 lines of code, too long? Meh, we review twice as much for breakfast! Feel free to put it all in and have the *implementation* reviewed as well!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T12:27:35.243",
"Id": "84476",
"Score": "0",
"body": "@Mat'sMug I have added the full implementation as you requested! I'm not yet familiar with what is acceptable to paste in versus link to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:26:17.907",
"Id": "84482",
"Score": "2",
"body": "Awesome! It's nice that you kept the original reviewed code in place; please see [these guidelines](http://meta.codereview.stackexchange.com/a/1765/23788) for everything this community agrees makes sense in such situations ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:26:38.187",
"Id": "84492",
"Score": "0",
"body": "@Mat'sMug Doh, I shouldn't have edited the OP, but there's always next time. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:00:21.907",
"Id": "84498",
"Score": "4",
"body": "As @Mat'sMug noted, the question should not be updated with new code. Fortunately, Code Review has a time machine service! I have rolled back Rev 4 to Rev 2. Please follow the advice in the guidelines instead. Thanks for your cooperation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:02:30.130",
"Id": "84499",
"Score": "2",
"body": "Thanks, I'll update the text/links in this version to explain what's what without changing the code, and as mentioned before I'll follow those guides now that I've seen them!"
}
] | [
{
"body": "<p>I like it.</p>\n\n<p>For some <em>very specific cases</em> where a class needs to be tested and <em>its functionality depends on what <code>System.DateTime.Now</code> returns</em>, then you need an <em>abstraction</em> to wrap the static method calls, if you want to be able to write unit tests that have full control over that dependency.</p>\n\n<p>Your <code>ITimeMachine</code> does that nicely. While a meaningful name, <code>IDateTimeService</code> seems more appropriately generic though. <code>ITimeTraveler</code> might be superfluous.</p>\n\n<p>The dependent code would look like this:</p>\n\n<pre><code>public class MyClass\n{\n private readonly IDateTimeService _service;\n\n public MyClass(IDateTimeService service)\n {\n _service = service;\n }\n\n public void DoSomething()\n {\n var now = _service.Now(); // instead of DateTime.Now;\n //...\n }\n}\n</code></pre>\n\n<p>I also like that you made <code>Now()</code> a method. It abstracts away the fact that <code>DateTime.Now</code> is really a method in a property suit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:20:26.697",
"Id": "84414",
"Score": "1",
"body": "Perhaps a use case could be testing [particularly weird date issues](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result) very deeply into an instance, before determining the exact cause?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T12:30:13.860",
"Id": "84478",
"Score": "1",
"body": "Once I incorporated ChrisW's feedback, the naming you suggested works perfectly with the new interface/classes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:55:27.190",
"Id": "48102",
"ParentId": "48100",
"Score": "4"
}
},
{
"body": "<p>My guess is that:</p>\n\n<ul>\n<li><p>These methods are used by the code being tested:</p>\n\n<pre><code>DateTime Now();\nDateTime UtcNow();\nDateTime Today();\nDateTime UtcToday();\n</code></pre></li>\n<li><p>These methods are not called by the code being tested, and are instead called by the unit-test code (to set the 'now' experienced by the code being tested)</p>\n\n<pre><code>void TimeTravel(TimeSpan adjustment);\nvoid TimeTravelTo(DateTime newDateTime);\nvoid FreezeTime();\nvoid UnfreezeTime();\nvoid RevertAllTimeTravel();\nbool IsCurrentlyTimeTraveling();\n</code></pre></li>\n</ul>\n\n<p>The latter methods therefore needn't be in this interface (which is passed to the code being tested). These methods could instead be in a separate interface (known only to the unit-test code), or they could simply be methods of the <code>TimeMachine</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T12:29:00.453",
"Id": "84477",
"Score": "0",
"body": "This separation seems natural and it also prevents the extra logic and work from the Time Machine methods from being called in non-test code. I have incorporated this change into my OP. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:32:49.440",
"Id": "48112",
"ParentId": "48100",
"Score": "4"
}
},
{
"body": "<h3>Implementation</h3>\n<p>My other answer only covered the original interface(s). This one highlights a point I've noticed in the implementation.</p>\n<pre><code>/// <summary>\n/// Retrieve the current date and time.\n/// </summary>\npublic DateTime Now()\n{\n return FrozenDateTime != null \n ? FrozenDateTime.Value \n : DateTime.Now.Add(Offset);\n}\n\n/// <summary>\n/// Move to the specific point in time provided.\n/// </summary>\n/// <param name="newDateTime">The point in time to move to.</param>\npublic void TimeTravelTo(DateTime newDateTime)\n{\n Offset = newDateTime.Subtract(DateTime.Now);\n}\n</code></pre>\n<p>I was curious to see it in action, so I wrote this little test:</p>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var service = new TimeMachine();\n Console.WriteLine("Current time is: {0} (system time is: {1})", service.Now(), DateTime.Now);\n\n //service.FreezeTime();\n //Console.WriteLine("Time frozen at: {0}", service.Now());\n\n Thread.Sleep(2000);\n Console.WriteLine("Slept for 2000ms.");\n\n Console.WriteLine("Current time is: {0} (system time is: {1})", service.Now(), DateTime.Now);\n\n service.TimeTravelTo(DateTime.Now.AddHours(1));\n Console.WriteLine("Time-traveled 1 hour into the future.");\n\n Console.WriteLine("Current time is: {0} (system time is: {1})", service.Now(), DateTime.Now);\n\n service.UnfreezeTime();\n Console.WriteLine("Time unfrozen.");\n\n Console.WriteLine("Current time is: {0} (system time is: {1})", service.Now(), DateTime.Now);\n Console.ReadLine();\n }\n}\n</code></pre>\n<p>Output:</p>\n<p><img src=\"https://i.stack.imgur.com/y1iKR.png\" alt=\"enter image description here\" /></p>\n<p>If I uncomment the <code>FreezeTime()</code> call, I get this:</p>\n<p><img src=\"https://i.stack.imgur.com/bgkOh.png\" alt=\"enter image description here\" /></p>\n<p>This looks like a bug to me, because it's as if the <code>Sleep(2000)</code> never happened.</p>\n<p>If I change the implementation of <code>TimeTravelTo()</code> to use the class' own abstraction of <code>Now</code>:</p>\n<pre><code>/// <summary>\n/// Move to the specific point in time provided.\n/// </summary>\n/// <param name="newDateTime">The point in time to move to.</param>\npublic void TimeTravelTo(DateTime newDateTime)\n{\n Offset = newDateTime.Subtract(Now());\n}\n</code></pre>\n<p>I get this:</p>\n<p><img src=\"https://i.stack.imgur.com/SS7ZB.png\" alt=\"enter image description here\" /></p>\n<p>Which makes more sense to me (as long as time is frozen, <code>Sleep(2000)</code> has no impact, but when you unfreeze time the offset gets back on track) - but I might be wrong and your implementation could very well be doing exactly what it's supposed to be doing. Hence, my point isn't necessarily that there's a bug in your code, but that your XML documentation should be clearer about this behavior: is <em>unfreezing time</em> supposed to catch up with the actual date/time?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:28:46.747",
"Id": "84493",
"Score": "1",
"body": "The XML is a bit unclear here. Unfreezing is meant to only let the passage of time resume; there is RevertAllTimeTravel() for reverting to the actual present. I wanted to keep these separate functions so that the user has options."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:06:49.537",
"Id": "48152",
"ParentId": "48100",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48102",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:22:05.073",
"Id": "48100",
"Score": "6",
"Tags": [
"c#",
".net",
"datetime"
],
"Title": "Time Machine service"
} | 48100 |
<p>I've implemented the following <code>nub'</code> or "give distinct elements of list" function:</p>
<pre><code>nub' :: (Eq a) => [a] -> [a]
nub' [] = []
nub' xs = nubHelper xs []
nubHelper :: (Eq a) => [a] -> [a] -> [a]
nubHelper [] acc = acc
nubHelper (y:ys) acc = if(contains y acc)
then nubHelper ys acc
else nubHelper ys (acc ++ [y])
where contains match acc =
foldl (\as x -> if(y == x) then True else as) False acc
</code></pre>
<p>Example:</p>
<pre><code>*Main> nub' [1,2,1,1,1,1,3,4,3,1]
[1,2,3,4]
</code></pre>
<p>Surely there must be a cleaner way?</p>
| [] | [
{
"body": "<p>For the \"official\" answer, you can go straight to the <a href=\"http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/src/Data-List.html#nub\">GHC source for <code>nub</code></a>:</p>\n\n<pre><code>nub :: (Eq a) => [a] -> [a]\nnub l = nub' l []\n where\n nub' [] _ = []\n nub' (x:xs) ls\n | x `elem` ls = nub' xs ls\n | otherwise = x : nub' xs (x:ls)\n</code></pre>\n\n<p>Some of the differences that stand out are:</p>\n\n<ul>\n<li>Use a <code>where</code> clause to scope your helper function, and name it with a \"prime\" symbol. In your case, I guess the helper would be <code>nub''</code>. The helper's type can then be automatically inferred.</li>\n<li>Use pattern matching instead of if-then-else.</li>\n<li>Your <code>contains</code> helper is just the <code>elem</code> builtin. They chose to write <code>x `elem` ls</code> instead of <code>elem x ls</code>, probably to read more smoothly.</li>\n<li>It's more natural / efficient to prepend than to append elements to a list. Instead of building <code>acc</code> as the result as a list of wanted elements, they build <code>ls</code> as the list of elements to exclude in future encounters.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:33:54.833",
"Id": "84555",
"Score": "0",
"body": "Thanks for this answer, @200_success. Could you please say more to `It's more natural / efficient to prepend than to append elements to a list`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:42:26.293",
"Id": "84558",
"Score": "0",
"body": "Think of them as singly linked lists: manipulating the head is guaranteed to be trivial; operations on the tail might not be. (We don't know _exactly_ how the lists are implemented. There might be optimizations that make operations on the tail efficient, but you shouldn't rely on the existence of such optimizations.) With that in mind, see [How to work on lists](http://www.haskell.org/haskellwiki/How_to_work_on_lists#Notes_about_speed). Prepend (`:`) is guaranteed to be a fast operation, but Concatenate (`++`) isn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:00:09.300",
"Id": "84606",
"Score": "0",
"body": "thanks. From a style point of view, is the padding, required for each `=` to align, considered best practice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T06:49:15.073",
"Id": "84619",
"Score": "0",
"body": "I can't really say. The [Haskell style guide](http://www.haskell.org/haskellwiki/Programming_guidelines) stays silent on the issue."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:19:54.430",
"Id": "48104",
"ParentId": "48101",
"Score": "11"
}
},
{
"body": "<p>3 lines using <code>filter</code>.</p>\n\n<pre><code>nub' :: (Eq a) => [a] -> [a]\nnub' [] = []\nnub' (x:xs) = x : nub' (filter (/=x) xs)\n</code></pre>\n\n<h2>Explanation</h2>\n\n<p>What I'm doing here can be explained in the following: </p>\n\n<ol>\n<li>Separate the input as <code>x:xs</code> using pattern matching. So, <code>x</code> is the first lement of the list and <code>xs</code> will be rest of the list. </li>\n<li>Concat the first element <code>x</code> with a <code>nub</code> of filtered list of <code>xs</code> that \ndo not contain <code>x</code>. </li>\n</ol>\n\n<h3>Performance</h3>\n\n<p>In terms of performance, I'm not sure if this is the same as the one implemented in the GHC source code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-20T13:46:28.080",
"Id": "369910",
"Score": "1",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-20T13:31:15.807",
"Id": "192562",
"ParentId": "48101",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48104",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:43:19.493",
"Id": "48101",
"Score": "9",
"Tags": [
"haskell",
"reinventing-the-wheel"
],
"Title": "Implementing nub (distinct)"
} | 48101 |
<p>This code basically saves an uploaded file to the server. I am wondering if there is anything that I can do to tighten this code up. I am very new to F# so I'm still having trouble breaking away from the C# way of doing things.</p>
<pre><code>/// Create file paths
/// Returns a tuple (server path * link path * file number)
let createPath (file : HttpPostedFileBase) =
// server directory path
let serverDirPath =
HttpContext.Current.Server.MapPath(@"~/Uploads")
// get the file name
let origFileName = file.FileName
// get the extension
let extension = Path.GetExtension(origFileName)
// get the file size in bytes
let fileSize = file.ContentLength
// directory check
let pathExists() = Directory.Exists(serverDirPath)
// create directory
let createDir() =
if not (pathExists()) then
Directory.CreateDirectory(serverDirPath) |> ignore
createDir()
// find current file name
let findCurrentFileName() =
// check if row exist
let rowCount =
query{
for row in db.Uploads do
select row
count
}
// get file number
let fileNumber =
if rowCount < 1
then
1
else
query{
for row in db.Uploads do
select (row.FileNumber + 1)
head
}
// final path
let finalServPath =
serverDirPath + @"\" + fileNumber.ToString() + extension
// download link
let linkPath =
finalServPath.Replace(serverDirPath + @"\", @"~/Uploads/")
finalServPath, linkPath, fileNumber
findCurrentFileName()
/// Save file to server and path to db.
let SaveUpload (file: HttpPostedFileBase) (title : string) =
// create the path including filename
let servPath, linkPath, fileNumber = createPath file
// save file to server
file.SaveAs(servPath)
// create new row for db table
let newUpload =
new dbSchema.ServiceTypes.Uploads(Title = title,
FilePath = servPath,
Size = file.ContentLength.ToString(),
FileNumber = fileNumber,
LinkPath = linkPath)
// insert new row
insertRowIn db.Uploads newUpload
// save to db
saveToDb()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:08:58.563",
"Id": "84486",
"Score": "1",
"body": "It looks fine to me. I'd probably define a type for `createPath`'s return value instead of using a 3-tuple. The only other observation is it's unnecessary to check if a directory exists before calling `CreateDirectory`. It already does that check for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:23:52.683",
"Id": "84507",
"Score": "0",
"body": "Thanks for the comment, Daniel. Can you provide an example of the type to return."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:25:15.253",
"Id": "84509",
"Score": "0",
"body": "A record would work: `type PathInfo = { ServerPath: string; LinkPath: string; FileNumber: int }`"
}
] | [
{
"body": "<p>I think that you're using comments unnecessarily. If you set a variable called <code>fileNumber</code>, the comment <code>// get file number</code> doesn't tell the reader anything new and only clutters the code.</p>\n\n<hr>\n\n<pre><code>// directory check\nlet pathExists() = Directory.Exists(serverDirPath)\n\n// create directory\nlet createDir() = \n if not (pathExists()) then\n Directory.CreateDirectory(serverDirPath) |> ignore\ncreateDir()\n</code></pre>\n\n<p>I don't see any reason to have <code>createDir</code> or <code>pathExists</code> as separate functions, since they're short and not reusable.</p>\n\n<p>And as Daniel mentioned in a comment, the check is not actually necessary. So, I would simplify this code to just:</p>\n\n<pre><code>Directory.CreateDirectory(serverDirPath) |> ignore\n</code></pre>\n\n<hr>\n\n<pre><code>// check if row exist\nlet rowCount = \n query{\n for row in db.Uploads do\n select row\n count\n }\n\n// get file number\nlet fileNumber = \n if rowCount < 1\n then\n 1\n else\n query{\n for row in db.Uploads do\n select (row.FileNumber + 1)\n head\n }\n</code></pre>\n\n<p>You can use <code>headOrDefault</code> here, to get rid of the first query:</p>\n\n<pre><code>// get file number\nlet fileNumber = \n query {\n for row in db.Uploads do\n select row.FileNumber\n headOrDefault\n } + 1\n</code></pre>\n\n<p>Also, you're not using any ordering in the query, are you sure the largest <code>FileNumber</code> is always going to be the first one?</p>\n\n<hr>\n\n<pre><code>let finalServPath = \n serverDirPath + @\"\\\" + fileNumber.ToString() + extension\n</code></pre>\n\n<p>You can use <code>Path.Combine()</code> to concatenate parts of a path:</p>\n\n<pre><code>let finalServPath = \n Path.Combine(serverDirPath, fileNumber.ToString() + extension)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:54:08.973",
"Id": "48245",
"ParentId": "48106",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48245",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:32:30.317",
"Id": "48106",
"Score": "4",
"Tags": [
"beginner",
"f#",
"http"
],
"Title": "Server code to save uploaded files"
} | 48106 |
<p>I was a TA for a first-year Java programming course this year. As a very simple example of iterables/iterators, I wrote the following code for the students. I am curious if any styling or other improvements can be made.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.NoSuchElementException;
import java.util.Iterator;
public class Range implements Iterable<Integer> {
private int start, end;
public Range(int start, int end) {
this.start = start;
this.end = end;
}
public Iterator<Integer> iterator() {
return new RangeIterator();
}
// Inner class example
private class RangeIterator implements
Iterator<Integer> {
private int cursor;
public RangeIterator() {
this.cursor = Range.this.start;
}
public boolean hasNext() {
return this.cursor < Range.this.end;
}
public Integer next() {
if(this.hasNext()) {
int current = cursor;
cursor ++;
return current;
}
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public static void main(String[] args) {
Range range = new Range(1, 10);
// Long way
Iterator<Integer> it = range.iterator();
while(it.hasNext()) {
int cur = it.next();
System.out.println(cur);
}
// Shorter, nicer way:
// Read ":" as "in"
for(Integer cur : range) {
System.out.println(cur);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:20:10.063",
"Id": "84422",
"Score": "6",
"body": "how 'bout `@Override` annotations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-01T21:00:41.513",
"Id": "160396",
"Score": "0",
"body": "this article may be helpful: http://www.yegor256.com/2015/04/30/iterating-adapter.html"
}
] | [
{
"body": "<h2>Variables</h2>\n\n<p>I understand why you have the <code>Range.this.end</code> and <code>Range.this.start</code> to avoid confusion about where those variables come from... If you need the <code>Range.this</code> as part of the teaching exercise, then sure. Otherwise, I would recommend three things....</p>\n\n<ol>\n<li>add <code>range</code> as a prefix, even though it is slightly redundant</li>\n<li>Make them final...</li>\n<li>one variable per line... (it makes revision-control diffs/patches easier to read)</li>\n</ol>\n\n<p>The code would look like:</p>\n\n<pre><code>private final int rangeStart;\nprivate final int rangeEnd;\n</code></pre>\n\n<p>Then, all the <code>Range.this.start</code> would be just <code>rangeStart</code>, etc.</p>\n\n<h2>Nested classes</h2>\n\n<p>Your iterator class is a non-static class, so it can reference the outer class's range start/end.</p>\n\n<p>In this case, the nested class can be changed to a static class very easily. This has the potential of simplifying memory management because the iterator does not need a reference to the enclosing Range.</p>\n\n<p>Consider a private-static Iterator instance:</p>\n\n<pre><code>// Inner class example\nprivate static final class RangeIterator implements\n Iterator<Integer> {\n private int cursor;\n private final int end;\n\n public RangeIterator(int start, int end) {\n this.cursor = start;\n this.end = end;\n }\n\n public boolean hasNext() {\n return this.cursor < end;\n }\n\n public Integer next() {\n if(this.hasNext()) {\n int current = cursor;\n cursor ++;\n return current;\n }\n throw new NoSuchElementException();\n }\n\n public void remove() {\n throw new UnsupportedOperationException();\n }\n}\n</code></pre>\n\n<p>This static class removes the need for the back-references to <code>Range.this</code> entirely....</p>\n\n<p>The new iterator is called simply with:</p>\n\n<pre><code>public Iterator<Integer> iterator() {\n return new RangeIterator(start, end);\n}\n</code></pre>\n\n<h2>Pre-Validate</h2>\n\n<p>It is better to pre-validate state, than to fall-through to an error... This code:</p>\n\n<blockquote>\n<pre><code> public Integer next() {\n if(this.hasNext()) {\n int current = cursor;\n cursor ++;\n return current;\n }\n throw new NoSuchElementException();\n }\n</code></pre>\n</blockquote>\n\n<p>would be better as:</p>\n\n<pre><code> public Integer next() {\n if(!this.hasNext()) {\n throw new NoSuchElementException();\n }\n int current = cursor;\n cursor ++;\n return current;\n }\n</code></pre>\n\n<h2>Post-Increment</h2>\n\n<p>This block can be simplified:</p>\n\n<blockquote>\n<pre><code> int current = cursor;\n cursor ++;\n return current;\n</code></pre>\n</blockquote>\n\n<p>to just:</p>\n\n<pre><code>return cursor++;\n</code></pre>\n\n<p>although I imagine this is done as an education ploy.</p>\n\n<h2>Integer as the example</h2>\n\n<p>Because of the int auto-bocxing I worry that Integer may not be the right choice for data type. You may want to consider a non-primitive as the data.</p>\n\n<p>Autoboxing is the sort of thing that will confuse.</p>\n\n<h2>Conclusion</h2>\n\n<p>Otherwise, I don't see much in the way of problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T05:55:31.910",
"Id": "84429",
"Score": "0",
"body": "Thank you. I didn't think of using ``final``, it's a great idea. I also agree that a private static class would be better than an inner class, but I forgot to mention that the code was meant to provide them with an example of an inner class as well, for further exposure. The post-increment was done the longer way to avoid confusion, as students find it oddly confusing. Interesting point about using a non-primitive type. I wanted to provide an example of an iterable that was not a container (say linked list, hash set, etc.) for simplicity. Can you think of one that would not use a primitive?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:20:14.370",
"Id": "84435",
"Score": "4",
"body": "good points, about the \"Pre-Validate\", to throw in some wording: this idiom is known as \"guard clause\" (http://c2.com/cgi/wiki?GuardClause), it checks pre-conditions"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:51:34.123",
"Id": "48114",
"ParentId": "48109",
"Score": "36"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/users/31503/rolfl\">@rolfl</a> totally nailed it. Only a few nitpicks left behind:</p>\n\n<ul>\n<li>I'd drop all pointless comments, unless they serve a purpose when you teach this</li>\n<li>Add the <code>@Override</code> annotations for clarity when reading not in an IDE</li>\n<li>Whenever you can drop <code>this.</code> from <code>this.cursor</code>, I'd drop it</li>\n<li>The way you use spacing around brackets does not follow well the standard. Use the reformat function of your IDE (equivalent of <code>Control-Shift-f</code> in Eclipse)</li>\n</ul>\n\n<p>I think it's a great idea asking here before presenting to your class!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:27:57.610",
"Id": "84436",
"Score": "0",
"body": "commenting here because you mention ... the comments: I personally prefer multi-line comments to multiple // — and in my codebase I insist on at least a class level javadoc (what's this Range concept anyway?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:29:00.043",
"Id": "84437",
"Score": "2",
"body": "and @Override does not only serve readability because it secures correct overrides with compile errors"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T05:10:48.007",
"Id": "48115",
"ParentId": "48109",
"Score": "7"
}
},
{
"body": "<p>Overall, it's pretty good code to learn from.</p>\n\n<h3>Functionality</h3>\n\n<p>I like that you've used the inclusive-exclusive convention for the lower and upper bounds, respectively. The rationale for that design would be an interesting discussion topic.</p>\n\n<p>I suggest adding a second constructor for convenience:</p>\n\n<pre><code>public Range(int end) {\n this(0, end);\n}\n</code></pre>\n\n<p>There should probably be getters for <code>start()</code> and <code>end()</code>. Technically, you should override <code>.equals()</code> and <code>.hashCode()</code> as well, but maybe it's OK to leave them out for simplicity.</p>\n\n<h3>Style</h3>\n\n<p>As @rpg711 <a href=\"https://codereview.stackexchange.com/questions/48109/simple-example-of-an-iterable-and-an-iterator-in-java#comment84422_48109\">noted</a>, putting the <code>@Override</code> annotation everywhere would be good practice. It would also help students see which methods are mandatory parts of the interface (well, practically all of them).</p>\n\n<p>JavaDoc would be a good habit to teach. At the least, document the outer class and inner class, and probably their constructors as well.</p>\n\n<p>It would be more <a href=\"http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.6.2-horizontal-whitespace\" rel=\"noreferrer\">conventional</a> to put a space after the <code>if</code>, <code>for</code>, and <code>while</code> keywords. They look less like function calls that way.</p>\n\n<p>Declaring <code>start</code> and <code>end</code> as <code>final</code> could help emphasize to students that the <code>Range</code> is immutable, and only the <code>RangeIterator</code> changes state. Perhaps adding <code>final</code> would alleviate some of @rolfl's concerns about the inner class referring to <code>Range.this.start</code> and <code>Range.this.end</code>.</p>\n\n<p>In agreement with @rolfl, I would also personally prefer</p>\n\n<pre><code> @Override\n public Integer next() {\n if (!this.hasNext()) {\n throw new NoSuchElementException();\n }\n // The post-increment magically takes effect _after_\n // returning. This is equivalent to\n //\n // int value = this.cursor++;\n // return value;\n //\n return this.cursor++;\n }\n</code></pre>\n\n<p>… though I can understand if you choose not to burden the students with that trivia.</p>\n\n<h3>Test case</h3>\n\n<p>It would be useful to illustrate that two <code>RangeIterators</code> keep state independently. Perhaps this might make a good example?</p>\n\n<pre><code>Range digits = new Range(0, 10);\nfor (Integer tensDigit : digits) {\n for (Integer onesDigit : digits) {\n System.out.format(\"%s%s \", tensDigit, onesDigit);\n }\n System.out.println();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T05:37:17.420",
"Id": "48116",
"ParentId": "48109",
"Score": "13"
}
},
{
"body": "<p>I think some students would appreciate an example without inner classes: </p>\n\n<p>Range can implement the Iterator without an inner class. You just need to reset the cursor to the start value. Here I reset cursor in the Iterator method and in the next method, once it has finished iterating through the range. It works for the examples proposed. Of course, the Iterator is not keeping the states independently, and won't work for more complex examples, but I don't need to be passing constructor arguments to an inner class.</p>\n\n<pre><code>import java.util.NoSuchElementException;\nimport java.util.Iterator;\n\npublic class Range implements Iterable<Integer>, Iterator<Integer> {\n private int start, end, cursor;\n\n public Range(int start, int end) {\n this.start = start;\n this.end = end;\n }\n\n public Iterator<Integer> iterator() {\n cursor = start;\n return this;\n }\n\n public boolean hasNext() {\n return cursor < end;\n }\n\n public Integer next() {\n if(!hasNext()) {\n cursor = start;\n throw new NoSuchElementException();\n }\n return cursor++;\n }\n\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n public static void main(String[] args) {\n Range range = new Range(1, 10);\n\n // Long way\n Iterator<Integer> it = range.iterator();\n while(it.hasNext()) {\n int cur = it.next();\n System.out.println(cur);\n }\n\n // Shorter, nicer way:\n // Read \":\" as \"in\"\n for(Integer cur : range) {\n System.out.println(cur);\n }\n\n Range digits = new Range(0, 10);\n for (Integer tensDigit : digits) {\n for (Integer onesDigit : digits) {\n System.out.format(\"%s%s \", tensDigit, onesDigit);\n }\n System.out.println();\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-18T14:47:28.940",
"Id": "107944",
"ParentId": "48109",
"Score": "3"
}
},
{
"body": "<p>The <code>iterator</code> method can be written using an anonymous class, which directly accesses to the attributes it needs for its job.</p>\n\n<pre><code>@Override\npublic Iterator<Integer> iterator() {\n return new Iterator<Integer>() {\n private int cursor = start;\n\n @Override\n public boolean hasNext() {\n return cursor < end;\n }\n\n @Override\n public Integer next() {\n if (! hasNext()) {\n throw new NoSuchElementException();\n }\n return cursor++; \n }\n };\n</code></pre>\n\n<p>with the usual tradeoffs of using anonymous/inner/separate classes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T15:22:50.250",
"Id": "236299",
"ParentId": "48109",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48114",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:17:32.457",
"Id": "48109",
"Score": "45",
"Tags": [
"java",
"iterator",
"interval"
],
"Title": "Simple Example of an Iterable and an Iterator in Java"
} | 48109 |
<p>I'm trying to implement a template that takes a container as parameter. The template has a <code>getnext</code> method that cycles through the elements in the parameter. Take note that I'm not using C++11.</p>
<p>Header:</p>
<pre><code>#pragma once
template<template<class, class> class TContainer, class TObject>
class cycle
{
public:
explicit cycle( TContainer<TObject, std::allocator<TObject>> & container )
: mContainer( container ), index(0) {}
TObject getNext(int numObjectsToCycle)
{ return mContainer[index++ % numObjectsToCycle]; }
private:
TContainer<TObject, std::allocator<TObject>> & mContainer;
int index;
};
</code></pre>
<p>Implementation:</p>
<pre><code>#include <iostream>
#include <vector>
#include "cycle.h"
using namespace std;
class Processor
{
int mIndex;
vector<int> numbers;
public:
cycle<vector, int> cycler;
// Is it safe to pass numbers since it is declared first??
Processor() : mIndex(0), cycler(numbers) {}
void update() { cout << numbers[mIndex++ % numbers.size()] << std::endl;}
void addNumber(int x) { numbers.push_back(x); }
};
int main()
{
Processor S;
for (int i = 0; i < 5; ++i)
{
S.addNumber(i+1);
}
cout << "using update" << endl;
for (int c = 0; c < 10; ++c)
{
S.update();
}
cout << "using cycle" << endl;
for (int c = 0; c < 10; ++c)
{
cout << S.cycler.getNext(5) << endl;
}
std::cin.get();
}
</code></pre>
<p>Any improvement or potential issues to the code?</p>
| [] | [
{
"body": "<p>A few remarks:</p>\n\n<ul>\n<li><p>Try to avoid <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a>.</p></li>\n<li><p>In <code>Processor</code>, you should also explicitly call the constructor of the vector.</p></li>\n<li><p>Your cycle class could be templated on the container type only, and use <code>TContainer::value_type</code> instead.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:47:23.407",
"Id": "48124",
"ParentId": "48110",
"Score": "2"
}
},
{
"body": "<p>A few things about <code>update()</code>:</p>\n\n<ul>\n<li><p>It's less readable and maintainable to cram the functionality into one line. Just declare it within the class and define it outside. If the compiler decides that it should be inlined, it will do that for you.</p></li>\n<li><p>Prefer <code>\"\\n\"</code> over <code>std::endl</code> when just outputting a newline. The latter also flushes the buffer, which is slower and unneeded here. See <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">this</a> for more information.</p></li>\n<li><p><code>update</code> is not a very accurate name. What exactly does it update?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T08:28:06.590",
"Id": "84452",
"Score": "0",
"body": "It's actually a stripped down code so the contents of update is not just that. And the couts are really just to output them on the screen."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:57:37.193",
"Id": "48125",
"ParentId": "48110",
"Score": "2"
}
},
{
"body": "<p>Here is how I would write it:</p>\n\n<pre><code>template<typename C>\nclass cycle\n{\n C& mContainer;\n size_t index;\n using ref = decltype(mContainer[0]);\n\npublic:\n explicit cycle(C& container) :\n mContainer(container), index(0) {}\n\n ref getNext()\n {\n return mContainer[index++ % mContainer.size()];\n }\n};\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li><p>The template parameter is the container, <code>C</code>. This not only simplifies code, but also works for containers that do not follow a specific pattern, e.g. have more parameters than just a value type and an allocator type.</p></li>\n<li><p>The return type of <code>getNext</code> is automatically inferred from <code>C</code>. This is not just <code>C</code>'s <code>value_type</code> but a (non-<code>const</code>) reference to it.</p></li>\n<li><p>If I understand correctly from the title, <code>C</code> is supposed to be a <em>sequence of containers</em>? If so, the <code>value_type</code> is a container itself so it is even more important that a reference is returned from <code>getNext</code>.</p></li>\n<li><p>Why pass a parameter to <code>getNext</code>? To cycle correctly, you should use <code>mContainer.size()</code>, exactly as you do in <code>Processor::update</code>, right?</p></li>\n<li><p><code>index</code> is of type <code>size_t</code></p></li>\n</ul>\n\n<p>With only a few changes, here is <code>Processor</code>:</p>\n\n<pre><code>class Processor\n{\n size_t mIndex;\n std::vector<int> numbers;\n\npublic:\n cycle<std::vector<int>> cycler;\n Processor() : mIndex(0), numbers(), cycler(numbers) {}\n void update() { std::cout << numbers[mIndex++ % numbers.size()] << std::endl;}\n void addNumber(int x) { numbers.push_back(x); }\n};\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>again, <code>mIndex</code> is a <code>size_t</code></li>\n<li><code>cycler</code> is a <code>cycle<std::vector<int>></code></li>\n<li><code>numbers</code> is default-initialized</li>\n<li><code>cycler</code> is safely constructed after <code>numbers</code></li>\n</ul>\n\n<p>Also, whenever you want to</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>for convenience, only do it inside another (your own) namespace, never globally.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I just noticed you're not using C++11. In this case, just use</p>\n\n<pre><code> typedef typename C::value_type& ref;\n</code></pre>\n\n<p>instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T08:59:00.703",
"Id": "84455",
"Score": "0",
"body": "The parameter to getNext allows me to limit the cycling to the first 5 out of 10 elements for example. So if I want only the 10 elements all the time, then I won't need a parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T09:03:12.500",
"Id": "84456",
"Score": "0",
"body": "@kunkka_71 Ok, then maybe you could have two versions if you also need the automatic one. In this case, one overload could call the other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:09:21.403",
"Id": "84470",
"Score": "0",
"body": "after using typedef as you've mentioned, using ref = decltype(mContainer[0]); does not compile. decltype is C++11 only?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:17:22.140",
"Id": "84480",
"Score": "0",
"body": "@kunkka_71 Yes, the last `typedef ...` line is a *replacement* for `using ref = ...`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T08:53:52.123",
"Id": "48133",
"ParentId": "48110",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T04:18:13.157",
"Id": "48110",
"Score": "4",
"Tags": [
"c++",
"template",
"c++03"
],
"Title": "Using a template to cycle through a sequence of containers"
} | 48110 |
<p>If I have a number of different classes which manage certain tests. At the moment I have to launch each test individually which results in a lot of <code>if</code> statements.</p>
<p>I wonder if there is a way of putting all of these in a loop to manage the launching of each test and retrieving of results more cleanly. Does anyone have any advice? Can anyone improve on this? Is this use of classes optimal (I'm not a professional programmer)?</p>
<pre><code>class Engine(object):
"""Class that holds information about the
tests relevant to the engine"""
def __init__(self):
self.run = True # Flag to run the test or not
self.kg = 20.5 # Some information required by this test
self.ok = 'Not run' # Final result to say if the test was passed
class Wheels(object):
"""Class that holds information about the
tests relevant to the wheels"""
def __init__(self):
self.run = True
self.number = 4
self.ok = 'Not run'
class Door(object):
"""Class that holds information about the
tests relevant to the doors"""
def __init__(self):
self.run = True
self.colour = 'red'
self.ok = 'Not run'
class Car(object):
"""Class that holds information about the
different tests available"""
def __init__(self):
self.engine = Engine()
self.wheels = Wheels()
self.door = Door()
motor = Car()
if motor.engine.on is True:
import engine_tests # An external file containing everything about engine tests
motor.engine.ok = engine_tests.launch(weight=motor.engine.kg) # Return success/failure of tests
if motor.wheels.on is True:
import wheel_tests
motor.wheels.ok = wheel_tests.launch(nwheels=motor.wheels.number)
if motor.door.on is True:
import door_tests
motor.door.ok = door_tests.launch(shading=motor.door.colour)
print 'Tests completed'
print 'Engine: ', motor.engine.ok
print 'Wheels: ', motor.wheels.ok
print 'Door: ', motor.door.ok
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:26:42.523",
"Id": "84445",
"Score": "2",
"body": "Could you give some more context? Are you testing software or an actual car? Why would you not run every test always?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T08:23:33.780",
"Id": "84451",
"Score": "0",
"body": "Janne, thanks for the comment. All tests would not be run every time, perhaps because computational resources are insufficient for certain tests at certain times, or one of the tests may have failed so I need to re-run that test without running all tests again. The \"car\" is only a representative example of a series of tests on an object, defined in classes like this. Does this make it clearer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T09:22:29.137",
"Id": "84459",
"Score": "0",
"body": "If you want to use loops to avoid duplicated code, you could store the car parts in a dictionnary : `components = { 'Engine' : Engine(), 'Door' : Door(), }`"
}
] | [
{
"body": "<p>The params for testing are different from each object, so I think this part should be put in the classes and present a uniform interface, this is what classes are about.</p>\n\n<p>I suggest 2 versions: either you only put the params needed for test in the classes, or (better in my opinion), you put the entire call to the test in the classes. With some syntactic sugar, this leads to</p>\n\n<h2>Only the test data in the classes</h2>\n\n<pre><code>class Engine(object):\n \"\"\"Class that holds information about the\ntests relevant to the engine\"\"\"\n\n def __init__(self):\n self.run = True # Flag to run the test or not\n self.kg = 20.5 # Some information required by this test\n self.ok = 'Not run' # Final result to say if the test was passed\n\n def get_test_params(self):\n return { 'weight': self.kg }\n\nclass Wheels(object):\n \"\"\"Class that holds information about the\ntests relevant to the wheels\"\"\"\n\n def __init__(self):\n self.run = True\n self.number = 4\n self.ok = 'Not run'\n\n def get_test_params(self):\n return { 'nwheels': self.number }\n\nclass Door(object):\n \"\"\"Class that holds information about the\ntests relevant to the doors\"\"\"\n\n def __init__(self):\n self.run = True\n self.colour = 'red'\n self.ok = 'Not run'\n\n def get_test_params(self):\n return { 'shading': self.colour }\n\nclass Car(object):\n \"\"\"Class that holds information about the\ndifferent tests available\"\"\"\n\n def __init__(self):\n self.engine = Engine()\n self.wheels = Wheels()\n self.door = Door()\n\nmotor = Car()\n\nfor partName in 'engine wheels door'.split():\n part = getattr(motor, partName)\n part.on = True # So the test is run (everything is off in your example)\n if part.on: # No need to write \"is True\", this is what \"if\" is about\n test_module = __import__(partName + '_tests')\n part.ok = test_module.launch(**part.get_test_params())\n\nprint 'Tests completed'\nprint 'Engine: ', motor.engine.ok\nprint 'Wheels: ', motor.wheels.ok\nprint 'Door: ', motor.door.ok\n</code></pre>\n\n<h2>Running the test from the classes</h2>\n\n<pre><code>class Engine(object):\n \"\"\"Class that holds information about the\ntests relevant to the engine\"\"\"\n\n def __init__(self):\n self.run = True # Flag to run the test or not\n self.kg = 20.5 # Some information required by this test\n self.ok = 'Not run' # Final result to say if the test was passed\n\n def run_test(self):\n import engine_tests\n return engine_tests.launch(weight=self.kg)\n\nclass Wheels(object):\n \"\"\"Class that holds information about the\ntests relevant to the wheels\"\"\"\n\n def __init__(self):\n self.run = True\n self.number = 4\n self.ok = 'Not run'\n\n def run_test(self):\n import wheels_tests\n return wheels_tests.launch(nwheels=self.number)\n\nclass Door(object):\n \"\"\"Class that holds information about the\ntests relevant to the doors\"\"\"\n\n def __init__(self):\n self.run = True\n self.colour = 'red'\n self.ok = 'Not run'\n\n def run_test(self):\n import door_tests\n return door_tests.launch(shading=self.colour)\n\nclass Car(object):\n \"\"\"Class that holds information about the\ndifferent tests available\"\"\"\n\n def __init__(self):\n self.engine = Engine()\n self.wheels = Wheels()\n self.door = Door()\n\nmotor = Car()\n\nfor partName in 'engine wheels door'.split():\n part = getattr(motor, partName)\n part.on = True # So the test is run (everything is off in your example)\n if part.on: # No need to write \"is True\", this is what \"if\" is about\n part.ok = part.run_test()\n\nprint 'Tests completed'\nprint 'Engine: ', motor.engine.ok\nprint 'Wheels: ', motor.wheels.ok\nprint 'Door: ', motor.door.ok\n</code></pre>\n\n<p>If there's only one car, the last part can become:</p>\n\n<pre><code>for part in (motor.engine, motor.wheels, motor.door):\n part.on = True # So the test is run (everything is off in your example)\n if part.on: # No need to write \"is True\", this is what \"if\" is about\n part.ok = part.run_test()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:53:58.930",
"Id": "85015",
"Score": "0",
"body": "Thank you! These are two very elegant ways to do this, and this is very helpful. Thank you for taking the time to help improve my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T09:54:05.377",
"Id": "48135",
"ParentId": "48118",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48135",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:07:54.753",
"Id": "48118",
"Score": "3",
"Tags": [
"python",
"classes",
"unit-testing",
"python-2.x"
],
"Title": "Loop cleanly through different classes"
} | 48118 |
<p>I have written a Java class to replace text in file. The file contains database configurations and is as follows:</p>
<pre><code>test.properties
#local
db.url=jdbc:oracle:thin:@localhost:test
#db.user=testa
#db.password=testa
db.user=testb
db.password=testb
#db.user=testc
#db.password=testc
</code></pre>
<p><code>#</code> is a comment character. Now db schema <code>testb</code> is in use.</p>
<p>Here is my Java class to switch between schemas</p>
<pre><code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SwitchTo
{
public static void main(String[] args)
{
Map<String, String> schemaMap = new HashMap<String, String>();
schemaMap.put("a", "testa");
schemaMap.put("b", "testb");
schemaMap.put("c", "testc");
String newText = "";
for (int i = 0; i < args.length; i++)
{
newText = args[i];
}
String newdb = "";
newdb = schemaMap.get(newText);
if (newdb == null || (newdb != null && newdb.length() <= 0))
{
System.out.println("Schema not available, please select : ");
for (Map.Entry<String, String> entry : schemaMap.entrySet())
{
System.out.println(entry.getKey() + " for " + entry.getValue());
}
return;
}
try
{
BufferedReader file = new BufferedReader(new FileReader("test.properties"));
String total = "";
String line = "";
while ((line = file.readLine()) != null)
{
if (!line.startsWith("#") && line.contains("db.user"))
{
line = "#" + line;
}
if (!line.startsWith("#") && line.contains("db.password"))
{
line = "#" + line;
}
if (line.startsWith("#") && line.contains(newdb))
{
line = line.substring(1);
}
total = total + line + "\n";
}
FileOutputStream File = new FileOutputStream("test.properties");
File.write(total.getBytes());
System.out.println("Switched to schema " + schemaMap.get(newText));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
</code></pre>
<p>and I have created a batch file to run this program from command line which is as follows :</p>
<pre><code>switch.bat
java SwitchTo %1
</code></pre>
<p>Now when write at command line</p>
<pre><code>c:\> switch a
</code></pre>
<p>Then it will comment <code>testb</code> in the file and <code>testa</code> will be uncommented.</p>
<p>Please suggest other improvement for this code.</p>
<ol>
<li>Is using map for storing schemas is a good choice?</li>
<li>How can I make it generic to accommodate newly added schemas without need to compile this class again?</li>
<li>Is there any better algorithm for solving this?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:08:49.330",
"Id": "84444",
"Score": "4",
"body": "Rather than editing a file programmatically, consider keeping several configuration files, and copying the appropriate one into place to activate it. It's much simpler that way!"
}
] | [
{
"body": "<p>Actually, this can be more generic.</p>\n\n<p>Instead of hard-coding your map; fill it from your properties file.<br>\nSo change your prop file to : </p>\n\n<pre><code>#db.id=a\n#db.user=testa\n#db.password=testa\n\ndb.id=b\ndb.user=testb\ndb.password=testb\n</code></pre>\n\n<p>Fill your map like this :</p>\n\n<pre><code>private Map<String, String> schemaMap = new HashMap<String, String>();\n\npublic void fillMap() throws FileNotFoundException, IOException {\n String line;\n String key = null;\n String value = null;\n try (BufferedReader file = new BufferedReader(new FileReader(\"test.properties\"))){\n while ((line = file.readLine()) != null) {\n\n if (line.contains(\"db.id\")) {\n key = line.substring(line.indexOf('='));// could be you have to do an + 1\n }\n if (line.contains(\"db.user\")) {\n value = line.substring(line.indexOf('='));\n }\n if (key!=null && value != null) {\n schemaMap.put(key, value);\n key = null;\n value = null;\n }\n }\n } catch (IOException ex) {\n // report with Logger or System.out what happend.\n }\n}\n</code></pre>\n\n<p><strong>Secondly :</strong> In your main you use the args.<br>\nYou do <strong>not</strong> check for how many args you have, you just take the last arg.<br>\nMaybe a check for how many args you have is appropriate here, and make the program do what you want then. (like quitting with error message or taking default arg).</p>\n\n<p><strong>Third :</strong> Always close your resources(reader/writer in this case).<br>\nHere it is done with a Try-with-resources available from java 7, otherwise you will need a finally block where you close it in.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:13:25.677",
"Id": "48126",
"ParentId": "48122",
"Score": "12"
}
},
{
"body": "<p><strong>Naming</strong><br>\nYou should give your classes and variable <em>meaningful</em> names. </p>\n\n<p>Class names should not be verbs, but rather nouns - <code>SwitchTo</code> also doesn't really convey what the class does - <code>DatabaseConfigurationSwitcher</code> will do a better job. </p>\n\n<p>Variable names like <code>file</code>, <code>total</code> and <code>newText</code> might be technically accurate, but they don't help the reader know what they mean - <code>currentPropertiesFileContents</code>, <code>newPropertiesFileContents</code> and <code>selectedUser</code> would better convey meaning, and will make your code a lot easier to read.</p>\n\n<p>You should <em>always</em> abide by the <a href=\"http://en.wikipedia.org/wiki/Naming_convention_%28programming%29#Java\">naming conventions</a> of you language of choice - camelCase for java variables - <code>newdb</code> is a bad variable name. <code>File</code> is worse.</p>\n\n<p>There is no need to repeat the type of the container in its name: <code>schemas</code> is better than <code>schemaMap</code>.</p>\n\n<p><strong>Redundant code</strong><br>\nYou found a very curious way to assign the <code>newText</code> variable - you are actually assigning it <code><num of args> + 1</code> times! There is no need to assign it with <code>\"\"</code>, and definitely no need to override it <code>arg.length</code> times a simple:</p>\n\n<pre><code>String newText = args[args.length - 1];\n</code></pre>\n\n<p>would do. The only reason I can think of which might have driven you to this strange code is your fear that <code>args</code> will be empty, in which case you can add:</p>\n\n<pre><code>String newText = (args == null || args.length == 0) ? \"\" : args[args.length - 1];\n</code></pre>\n\n<p>Of course, as @chillworld suggested, both are wrong, as you should check that there is exactly one argument so:</p>\n\n<pre><code>if (args.length != 1) throw new Exception(\"Give only one argument\");\nString newText = args[0];\n</code></pre>\n\n<p><strong>Assumptions</strong><br>\nFor some reason, you assume that the username and password are always equal, and known at compile time. If that is the case, you could have made you life easier and instead of commenting and un-commenting lines in your code you could simply re-write the section, since you know its values:</p>\n\n<pre><code>test.properties\n\n#local\ndb.url=jdbc:oracle:thin:@localhost:test\n\n#### overwrite everything below this line with db.user=user;db.password=user ####\ndb.user=testa\ndb.password=testa\n</code></pre>\n\n<p>Of course, a better solution would be not to assume that you know either the username <em>or</em> the password at compile time, and use an external repository to hold this information (even the properties file itself could be it, as @chillworld suggested).</p>\n\n<p><strong>String concatenation</strong><br>\nUsing a <code>String</code> variable to collect all the lines in your code is not a good idea, as it results in a lot of new objects being built. A <a href=\"http://docs.oracle.com/javase/tutorial/java/data/buffers.html\"><code>StringBuilder</code></a> is a better type to do that, but in your situation.</p>\n\n<p><strong>Close your resources</strong><br>\nYou open a file reader, and then a file writer, but you never <code>close</code> them! This is very problematic, since you leave open file handles which may result in a serious memory leak. It is true that java will close all open handles when the process exits, but you should never count on that!</p>\n\n<p><strong>Don't catch what you can't handle</strong><br>\nYou have a <code>try</code> block, and two <code>catch</code> clauses, which do nothing but output the exception to the console.<br>\nA better way would be to declare <code>main(String[] args) throws FileNotFoundException, IOException</code>, and not even write the <code>try</code> block.<br>\nThis way, in case of an error, not only will its stack trace be printed in the console (via the error stream), but the console will also be notifies that the command ended abnormally, and the command users will be able to refer to that (looking at the <code>errorlevel</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:16:59.970",
"Id": "48141",
"ParentId": "48122",
"Score": "7"
}
},
{
"body": "<p>I suggest to add some meta-information in comments as follows:</p>\n\n<pre><code>#local\ndb.url=jdbc:oracle:thin:@localhost:test\n\n#begin_schema: a\n#db.user=testa\n#db.password=testa\n#end_schema\n\n#other unchangeable properties\nsome.property.a=value1\nsome.property.b=value2\n\n#begin_schema: b\ndb.user=testb\ndb.password=testb\n#end_schema\n</code></pre>\n\n<p>so, the comments #begin_schema/#end_schema will demarcates the boundary of blocks for facilitation of parse and process.</p>\n\n<p>here is my solution:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class SchemaSwitcher {\n\n static final Pattern BEGIN_PATTERN = Pattern.compile(\"^#*\\\\s*begin_schema:\\\\s*(.+)\\\\s*$\");\n static final Pattern END_PATTERN = Pattern.compile(\"^#*\\\\s*end_schema.*$\");\n\n static enum State {NO_OP, ADD_COMMENT, REM_COMMENT}\n\n public static void main(String[] args) throws Exception {\n String fileName = args[0];\n String schema = args[1];\n Path path = Paths.get(fileName);\n Files.write(path, switchSchema(Files.readAllLines(path), schema));\n }\n\n static List<String> switchSchema(List<String> lines, String schema) {\n State state = State.NO_OP;\n for (int i = 0; i < lines.size(); i++) {\n String line = lines.get(i);\n switch (state) {\n case NO_OP:\n Matcher matcher = BEGIN_PATTERN.matcher(line);\n if (matcher.matches()) {\n state = schema.equals(matcher.group(1)) ? State.REM_COMMENT : State.ADD_COMMENT;\n }\n break;\n case ADD_COMMENT:\n if (END_PATTERN.matcher(line).matches()) {\n state = State.NO_OP;\n } else {\n if (!line.startsWith(\"#\")) line = \"#\" + line;\n }\n break;\n case REM_COMMENT:\n if (END_PATTERN.matcher(line).matches()) {\n state = State.NO_OP;\n } else {\n while (line.startsWith(\"#\")) line = line.substring(1);\n }\n break;\n }\n lines.set(i, line);\n }\n return lines;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:24:30.393",
"Id": "84508",
"Score": "0",
"body": "Adding a `#begin section` and `#end section` are a bit overkill for 2 properties, that are \"always correctly formatted\". If it were a more complex config-file, I'd really love your suggestions. btw. `#end section` is unneccesary, if you assume, that a section cannot contain subsections... Still +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:07:15.607",
"Id": "84585",
"Score": "0",
"body": "closing tag (end_schema) allows to have unchangable block between two shcemas. if you think that this is redundant, it's very easy to change the code to consider the closing tag as optional"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:07:17.417",
"Id": "48145",
"ParentId": "48122",
"Score": "3"
}
},
{
"body": "<p>Addition to the answer of @chillworld and @Jamal</p>\n\n<p>use <code>java.nio</code> instead of <code>java.io</code></p>\n\n<pre><code>private Map<String, String> schemaMap = new HashMap<>();\n\npublic void fillMap() throws IOException {\n\n String key = null;\n String value = null;\n\n Path path = Paths.get(\"test.properties\");\n try {\n List<String> lines = Files.readAllLines(path, Charset.defaultCharset());\n\n for (String line : lines) {\n\n if (line.contains(\"db.id\")) {\n key = line.substring(line.indexOf('='));// could be you have to do an + 1\n }\n\n if (line.contains(\"db.user\")) {\n value = line.substring(line.indexOf('='));\n }\n\n if (key != null && value != null) {\n schemaMap.put(key, value);\n key = null;\n value = null;\n }\n }\n } catch (IOException e) {\n // report with Logger or System.out what happend.\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T09:50:52.650",
"Id": "48469",
"ParentId": "48122",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48126",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:36:45.910",
"Id": "48122",
"Score": "11",
"Tags": [
"java",
"file",
"io"
],
"Title": "File editing program"
} | 48122 |
<p>I wrote this code to handle logged in users. The session IDs will be stored in cookies. I would like to know if it's usable or if there are security problems.</p>
<p>It uses a 64bit id and another 64bit validation ID. Perhaps this is a bad idea, but here's what I thought: if someone tries to carry a brute force attack and happens to find the first value, he will most likely not have found the second value, so I can destroy that session before it's compromised. Would using a single huge id be better? What size would be considered safe?</p>
<p>I know the ideal would be to write a custom tree to avoid calling <code>bt_find()</code> and <code>bt_remove()</code> in some places and I plan to do that next.</p>
<p><strong>session.h</strong></p>
<pre><code>#ifndef SESSION_H
#define SESSION_H
#include <stdlib.h>
#include <time.h>
#define ID_SIZE 8
typedef struct Session_Manager Session_Manager;
typedef struct {
char id0[ID_SIZE];
char id1[ID_SIZE];
} Session;
//Every manager has its own set of sessions
Session_Manager *session_manager_new(void);
void session_manager_delete(Session_Manager *sm);
//Expiry is how long it takes for a session to be deleted
void session_manager_set_expiry(Session_Manager *sm, time_t seconds);
time_t session_manager_get_expiry(Session_Manager *sm);
//It's possible to execute a custom function to clean up user_data
void session_manager_set_on_delete(Session_Manager *sm, void (*delete_cb)(void *));
void (*session_manager_get_on_delete(Session_Manager *sm))(void *);
//Delete all expired sessions
void sess_clean_old_sessions(Session_Manager *sm);
//Create new session and associate user_data to it
Session *sess_new_session(Session_Manager *sm, void *user_data);
//Validate session, increase expiry time and return user_data
void *sess_get_data(Session_Manager *sm, Session *session);
//Delete session
void sess_delete_session(Session_Manager *sm, Session *session);
#endif
</code></pre>
<p><strong>session.c</strong></p>
<pre><code>#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include "session.h"
#include "binary_tree.h"
#define EXPIRY_DEFAULT 3600
#define allocate malloc
#define deallocate free
char *table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789";
struct Session_Manager {
Binary_Tree sessions;
time_t expiry;
void (*on_delete)(void *);
};
/* If id0 is correct but id1 is wrong it will fail and the session will be
deleted in order to make bruteforce unlikely to work. id1 is completely ignored
until a session with id0 is found */
typedef struct {
uint64_t id0;
uint64_t id1;
time_t expiry;
void *user_data;
} _Session;
//Callback to compare two sessions
static int compare_sessions(const void *s0_ptr, const void *s1_ptr)
{
const _Session *s0 = s0_ptr;
const _Session *s1 = s1_ptr;
return s0->id0 - s1->id0;
}
//Callback to clean old sessions
static void clean_sessions(void *s_ptr, void *sm_ptr)
{
_Session *s = s_ptr;
Session_Manager *sm = sm_ptr;
if(s->expiry <= time(NULL)){
if(sm->on_delete != NULL)
sm->on_delete(s->user_data);
bt_remove(&sm->sessions, s);
deallocate(s);
}
}
static void delete_all_content(void *s_ptr, void *sm_ptr)
{
_Session *s = s_ptr;
Session_Manager *sm = sm_ptr;
if(sm->on_delete != NULL)
sm->on_delete(s->user_data);
deallocate(s);
}
//Every manager has its own set of sessions
Session_Manager *session_manager_new(void)
{
Session_Manager *sm = allocate(sizeof(Session_Manager));
if(sm == NULL)
return NULL;
bt_init(&sm->sessions, compare_sessions);
sm->expiry = EXPIRY_DEFAULT;
sm->on_delete = NULL;
return sm;
}
void session_manager_delete(Session_Manager *sm)
{
bt_iterate_arg(&sm->sessions, delete_all_content, sm);
bt_free(&sm->sessions);
deallocate(sm);
}
//Expiry is how long it takes for a session to be deleted
void session_manager_set_expiry(Session_Manager *sm, time_t seconds)
{
sm->expiry = seconds;
}
time_t session_manager_get_expiry(Session_Manager *sm)
{
return sm->expiry;
}
void session_manager_set_on_delete(Session_Manager *sm, void (*delete_cb)(void *))
{
sm->on_delete = delete_cb;
}
void (*session_manager_get_on_delete(Session_Manager *sm))(void *)
{
return sm->on_delete;
}
//Delete all expired sessions
void sess_clean_old_sessions(Session_Manager *sm)
{
bt_iterate_arg(&sm->sessions, clean_sessions, sm);
}
//Create new session
Session *sess_new_session(Session_Manager *sm, void *user_data)
{
int file_descriptor, ret;
_Session *new_session = allocate(sizeof(_Session));
unsigned int random;
unsigned char *ids = (unsigned char *)new_session;
if(new_session == NULL)
return NULL;
if((file_descriptor = open("/dev/urandom", O_RDONLY)) == -1){
deallocate(new_session);
return NULL;
}
generate_random:
for(size_t i = 0; i < ID_SIZE * 2; ++i){
if(read(file_descriptor, &random, sizeof(int)) == -1){
deallocate(new_session);
close(file_descriptor);
return NULL;
}
random = random % 62;
ids[i] = table[random];
}
if((ret = bt_insert(&sm->sessions, new_session)) != BT_SUCCESS){
if(ret == BT_DUPLICATE)
goto generate_random;
deallocate(new_session);
close(file_descriptor);
return NULL;
}
close(file_descriptor);
new_session->expiry = time(NULL) + sm->expiry;
new_session->user_data = user_data;
return (Session *) new_session;
}
//Validate session, increase expiry time and return user_data
void *sess_get_data(Session_Manager *sm, Session *session)
{
_Session *real_session = bt_find(&sm->sessions, session);
if(real_session == NULL)
return NULL;
//Check id1
if(real_session->id1 != *(uint64_t *)session->id1){
if(sm->on_delete != NULL)
sm->on_delete(real_session->user_data);
bt_remove(&sm->sessions, real_session);
deallocate(real_session);
return NULL;
}
real_session->expiry = time(NULL) + sm->expiry;
return real_session->user_data;
}
//Delete session
void sess_delete_session(Session_Manager *sm, Session *session)
{
_Session *real_session = bt_find(&sm->sessions, session);
//There's no session with this id
if(real_session == NULL)
return;
if(sm->on_delete != NULL)
sm->on_delete(real_session->user_data);
bt_remove(&sm->sessions, real_session);
deallocate(real_session);
}
</code></pre>
| [] | [
{
"body": "<p>I am going to be very urandom here.</p>\n\n<ol>\n<li><p><code>ids[i] = table[random]</code> badly decreases the entropy. Instead of 64 random bits, your ID has less than 48.</p></li>\n<li><p>Can you elaborate on a use case, especially how the validation ID is used.</p></li>\n<li><p>As much as I am against global variables here is one exception I am ready to accept: <code>/dev/urandom</code> can well be opened once when the process starts. There's no real difference between a global file descriptor and a global literal. Besides, its randomness doesn't degrade.</p></li>\n<li><p>sess_new_session is overcomplicated. Factor out getting random number; reuse same <code>new_session</code> in case of <code>BT_DUPLICATE</code>. See also note 2.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:57:45.957",
"Id": "84450",
"Score": "0",
"body": "Thank you for answering. I'm using that table because I need to set cookies with the id and just copying the random bytes directly produces invalid characters. The id1 is used in `sess_get_data()`, if id1 does not match, it will destroy the session. I don't understand how to reuse same `new_session` since the id is already associated with another session? What length would you consider safe?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T07:47:49.673",
"Id": "48128",
"ParentId": "48123",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T06:44:26.597",
"Id": "48123",
"Score": "4",
"Tags": [
"c",
"security",
"session"
],
"Title": "Session manager for logged in users"
} | 48123 |
<p>I had a rather large method in one public class that I refactored into 2 helper classes. The thing is though, that those 2 helper classes have dependencies. I refactored them into helper classes so I could mock and test them easily, which worked out perfectly.</p>
<p>However, the thing is I don't want to have to register my helper classes in the DI container, because I know the public class will always be using those specific implementations.</p>
<p>This is how I implemented the public class' constructors:</p>
<pre><code> /// <summary>
/// Internal constructor used by tests for mocking.
/// </summary>
internal TranslationCompiler(ITranslationCatalogTransformer translationCatalogTransformer, ICompiledCatalogTransformer compiledCatalogTransformer)
{
if (compiledCatalogTransformer == null) throw new ArgumentNullException("compiledCatalogTransformer");
if (translationCatalogTransformer == null) throw new ArgumentNullException("translationCatalogTransformer");
_translationCatalogTransformer = translationCatalogTransformer;
_compiledCatalogTransformer = compiledCatalogTransformer;
}
/// <summary>
/// Public constructor that passes dependencies to concrete implementations of helper classes.
/// </summary>
public TranslationCompiler(IResourceService resourceService, ITranslationSerializer serializer)
{
if (resourceService == null) throw new ArgumentNullException("resourceService");
if (serializer == null) throw new ArgumentNullException("serializer");
_translationCatalogTransformer = new TranslationCatalogTransformer(resourceService);
_compiledCatalogTransformer = new CompiledCatalogTransformer(serializer);
}
</code></pre>
<p>Is this an acceptable use for poor man's DI? This way, the DI container only has to know the actual dependencies for the public class to work, while still being very testable.</p>
| [] | [
{
"body": "<p>I don't see anything wrong with your implementation - if it works for you, and does not interfere with the system - go for it!</p>\n\n<p>I will even go further and claim that the guard conditions in your internal constructor are redundant because the constructor will only be used by the single public constructor, or by a test which:</p>\n\n<ol>\n<li>Either counts on the helper - in which case a <code>NullPointerException</code> will occur and fail the test, or</li>\n<li>Does not need the helper, in which case there is no need to mock it...</li>\n</ol>\n\n<p>Final note: I guess that the public constructor actually <em>uses</em> <code>resourceService</code> and <code>serializer</code> in some code you deleted from it, otherwise, the guard conditions there are also redundant...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T11:43:12.527",
"Id": "84474",
"Score": "0",
"body": "The public constructor just passes the dependencies along. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:29:58.777",
"Id": "84494",
"Score": "1",
"body": "With regards to your first point, such guards are considered best practice because they throw the exception as early as possible, thereby decreasing the number of opportunities for confusion. The problem is immediately indicated without debugging. This may be less important if the library is not reused, but that is *never* the right assumption."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T10:31:19.490",
"Id": "48138",
"ParentId": "48129",
"Score": "3"
}
},
{
"body": "<p>Couple of things..</p>\n\n<p>First, having nearly identical code in both constructors is a maintenance pain. It may be okay every so often, but if you do it a lot it will cause a bug one day when you change one and not the other.</p>\n\n<p>You could change the public constructor to call the internal constructor like this:</p>\n\n<pre><code>public TranslationCompiler(IResourceService resourceService, ITranslationSerializer serializer)\n : this(new TranslationCatalogTransformer(resourceService), new CompiledCatalogTransformer(serializer))\n{\n}\n</code></pre>\n\n<p>Second, it's not really ideal to be creating different constructors (or any other code) just for tests. You really should be mocking the interfaces of the public API instead. \nIn this case the IResourceService and the ITranslationSerializer.</p>\n\n<p>If you are having trouble mocking those interfaces it's probably an indicator of some other issue with your design. Perhaps those interfaces can be broken up into a few smaller interfaces, or maybe your unit tests are making the wrong assumptions.</p>\n\n<p>Maybe posting one of your unit tests would help.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T23:01:13.967",
"Id": "48627",
"ParentId": "48129",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p><em>However, [...] I don't want to have to register my helper classes in the DI container, because <strong>I know</strong> the public class will <strong>always</strong> be using those specific implementations.</em></p>\n</blockquote>\n\n<p>That is a very strong assumption you're making here. Are you sure you'll <strong>never</strong> want to inject a <em>decorator</em> that will, say, report execution time to the debug output? Or one that catches and logs (with email notification if you want it) whatever uncaught exceptions that this other code could throw?</p>\n\n<p>This is what proper DI allows you to do, when you inject dependencies as <em>abstractions</em> - the class has no clue of the <em>actual</em> implementing type, and <em>doesn't care about it</em>, because as long as the implementing type in question implements the specified interface, <em>how it's implemented is not a concern of that class</em>. It's actually <em>none of its business</em>.</p>\n\n<blockquote>\n<pre><code>/// <summary>\n/// Public constructor that passes dependencies to concrete implementations of helper classes.\n/// </summary>\npublic TranslationCompiler(IResourceService resourceService, ITranslationSerializer serializer)\n{\n if (resourceService == null) throw new ArgumentNullException(\"resourceService\");\n if (serializer == null) throw new ArgumentNullException(\"serializer\");\n _translationCatalogTransformer = new TranslationCatalogTransformer(resourceService);\n _compiledCatalogTransformer = new CompiledCatalogTransformer(serializer);\n}\n</code></pre>\n</blockquote>\n\n<p>The key to a successful <a href=\"/questions/tagged/dependency-injection\" class=\"post-tag\" title=\"show questions tagged 'dependency-injection'\" rel=\"tag\">dependency-injection</a> implementation, is <em>going all the way through</em>.</p>\n\n<p>You haven't listed your class, but I'm expecting to see this somewhere like right above these constructors you've listed:</p>\n\n<pre><code>private readonly ITranslationCatalogTransformer _translationCatalogTransformer;\nprivate readonly ICompiledCatalogTransformer _compiledCatalogTransformer;\n</code></pre>\n\n<p><em>These <strong>are</strong> your class' dependencies</em>. <em>Inversion of Control</em> specifically implies giving away that control you're keeping all for yourself - the control over the specific types that implement the abstractions you're depending on.</p>\n\n<p><em>Just let go, embrace DI in its full glory.</em></p>\n\n<p>If there aren't any other dependencies (are you <code>new</code>ing up anything else anywhere else?), then at the end this should be the only constructor you need:</p>\n\n<pre><code>public TranslationCompiler(ITranslationCatalogTransformer translationCatalogTransformer,\n ICompiledCatalogTransformer compiledCatalogTransformer)\n{\n if (compiledCatalogTransformer == null) \n throw new ArgumentNullException(\"compiledCatalogTransformer\");\n\n if (translationCatalogTransformer == null) \n throw new ArgumentNullException(\"translationCatalogTransformer\");\n\n _translationCatalogTransformer = translationCatalogTransformer;\n _compiledCatalogTransformer = compiledCatalogTransformer;\n}\n</code></pre>\n\n<p>Even if you <em>actually</em> end up using a specific implementation forever, that's not a reason to introduce <em>tight coupling</em> in your architecture.</p>\n\n<hr>\n\n<p>What you have here isn't <em>Poor Man's DI</em>. It's not DI.</p>\n\n<p>You depend on two classes that each have their own dependencies, that you're able to provide via an IoC container: there's no reason to <code>new</code> them up yourself, unless there's lack of context in your post or, more likely, unless there's something I missed.</p>\n\n<p>The public constructor you have, doesn't take the constructed type's dependencies, and this only uselessly blurs things up. <em>Poor Man's DI</em> is a <em>replacement</em> for an IoC container, not a reason to introduce tight coupling.</p>\n\n<p>You're injecting your dependencies' dependencies: this means your client code must <code>new</code> up things that the object being created doesn't even need. Doesn't it smell?</p>\n\n<p>Even if you <em>are</em> going to <em>always</em> be using those specific implementations, by <code>new</code>ing them up yourself you have ruled out all the advantages of doing DI in the first place, and you have made your constructors much more ambiguous and complex than they need to be, at least from a DI standpoint, where a type's constructor signature is expected to <em>tell</em> us what <em>that type</em>'s dependencies are.</p>\n\n<p>...which brings us to <em>tell, don't ask.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T06:20:30.363",
"Id": "85393",
"Score": "0",
"body": "The reason I did it like this was to not have everyone know about my helper classes which are only there to avoid having a huge method in my class. The alternative was to refactor them into methods instead of helper classes, and make them `internal virtual` so I could mock them. But good point."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T02:12:25.507",
"Id": "48637",
"ParentId": "48129",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T08:05:33.873",
"Id": "48129",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"dependency-injection"
],
"Title": "Using Poor Man's DI to inject helper class dependencies"
} | 48129 |
<p>Resharper complain if you have code like this:</p>
<pre><code>border-width: 0px 1px 1px 0px;
</code></pre>
<p>and insists that units should be removed from zeroes as they are redundant. They are redundant, that is absolutely true, but I don't like inconsistency that is introduced by removal of units. You get code like this</p>
<pre><code>border-width: 0 1px 1px 0;
</code></pre>
<p>which is pretty hideous in my opinion. So, what do you guys think? Should I remove redundant units, or should I disable this warning?</p>
| [] | [
{
"body": "<p>0cm, 0px or 0x corresponding to 0, it doesn't need unit if it's of the same order of magnitude. 0px * 10cm is the same than 0 * 10cm.\nIn this case border-width corresponding to length's order of magnitude it's not necessary to precise the units.</p>\n\n<p>Moreover, for my part, I never specifies the things which are default. Whatever the language. I think it's more readable and elegant. It's my opinion because some people I met prefers specify everything.</p>\n\n<p>I hope my english is not so bad .</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T09:15:08.950",
"Id": "48134",
"ParentId": "48132",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T08:52:04.667",
"Id": "48132",
"Score": "1",
"Tags": [
"css",
"visual-studio"
],
"Title": "Resharper: Unit of measure is redundant"
} | 48132 |
<blockquote>
<p><strong>Problem:</strong></p>
<p>The fraction \$(\dfrac{49}{98})\$ is a curious fraction, as an inexperienced
mathematician in attempting to simplify it may incorrectly believe
that \$(\dfrac{49}{98}) = (\dfrac{4}{8})\$, which is correct, is obtained by cancelling the 9s.</p>
<p>We shall consider fractions like, \$(\dfrac{30}{50}) = (\dfrac{3}{5})\$, to be trivial examples.</p>
<p>There are exactly four non-trivial examples of this type of fraction,
less than one in value, and containing two digits in the numerator and
denominator.</p>
<p>If the product of these four fractions is given in its lowest common
terms, find the value of the denominator.</p>
</blockquote>
<p>This is some rough code -- this one was a lot harder than I expected it to be. Please help me optimize.</p>
<pre><code>from timeit import default_timer as timer
start = timer()
fractions_that_work = []
def a_common_element(list_a, list_b):
count = 0
common = 0
for m in list_a:
for n in list_b:
if m == n:
count += 1
common = m
if count == 1:
return common
return False
for numerator in range(10, 100):
for denominator in range(numerator + 1, 100): # denom must be > num
n_digits = sorted([int(x) for x in str(numerator)])
d_digits = sorted([int(x) for x in str(denominator)])
common = a_common_element(n_digits, d_digits)
if common:
n_digits.remove(common)
d_digits.remove(common)
n_rem = n_digits[0]
d_rem = d_digits[0]
if 0 not in n_digits and 0 not in d_digits:
if float(numerator) / denominator == float(n_rem) / d_rem:
fractions_that_work.append([numerator, denominator])
product_of_fractions = [1, 1]
for frac in fractions_that_work:
product_of_fractions[0] *= frac[0]
product_of_fractions[1] *= frac[1]
start = timer()
ans = product_of_fractions[1] / product_of_fractions[0]
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:22:39.733",
"Id": "84481",
"Score": "0",
"body": "Note for reviewers : the `start = timer()` is a mistake. Keeping the code in the answer as it is unless a mod thinks it's better to change it."
}
] | [
{
"body": "<p>Firstly, you set <code>start</code> at the top of the script (which is OK). However, you <strong>reset</strong> <code>start</code> right before your final calulation:</p>\n\n<pre><code># This will only time the execution of one statement!\nstart = timer()\nans = product_of_fractions[1] / product_of_fractions[0]\nelapsed_time = (timer() - start) * 1000 # s --> ms\n</code></pre>\n\n<p>Remove the above <code>start = timer()</code> to get a more accurate timing. Also, I would recommend moving the first <code>start</code> declaration to just before the nested <code>for</code> loops. That was the start time is more <em>spatially</em> related to what you are actually timing.</p>\n\n<hr>\n\n<p>Secondly, your <code>a_common_element</code> function's name is a little misleading. Currently, it insinuates it will return positively if the two <code>lists</code> have <em>any number</em> of common elements. Changing the function name to something like <code>has_single_common_element</code> gives a better description of what the function actually does.</p>\n\n<p>Also, <code>a_common_element</code> can be simplified a tad. By using <a href=\"https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\">list comprehension</a> we can combine the nested <code>for</code> loops into one comprehension:</p>\n\n<pre><code>def a_common_element(list_a, list_b):\n common_list = [value for value in list_a if value in list_b]\n\n if len(common_list) == 1:\n return common_list[0]\n return False\n</code></pre>\n\n<hr>\n\n<p>Your next section is actually quite interesting: you used a neat way to separate the digits. However, the downfall (I believe) to your method is the back-and-forth casting that it requires. I would, instead, recommend doing to calculations to get your digits:</p>\n\n<pre><code>for numerator in range(10, 100):\n for denomerator in range(numerator+1, 100):\n # Division will strip off the first digit\n # Modulus will strip off the 0th digit\n n_digits = sorted([int(numerator/10), numerator % 10]) \n d_digits = sorted([int(denomerator/10), denomerator % 10])\n</code></pre>\n\n<p>NOTE: This recommendation is based on the project description you provided, that is all numbers will have exactly 2 digits. If you wanted to extend this to greater sets of numbers (3-digits, 4-digits, etc) I would keep your current implementation.</p>\n\n<hr>\n\n<p>This next recommendation, like the previous, is based off of 2-digit numbers only.</p>\n\n<p>Once you remove the common digit from the <code>lists</code>, you assign the remaining digits to variables; which is good. However, you then go check if the <code>lists</code> contain <code>0</code> instead of comparing the variables:</p>\n\n<pre><code># I imagine this is what Python does in the backgroud when you say:\n# if 0 not in list\nif n_rem != 0 and d_rem != 0:\n</code></pre>\n\n<hr>\n\n<p>Your next section is nice. Its simple and intuitive. If you wanted to make the code more Pythonic, you could instead do it this way:</p>\n\n<pre><code>product_of_fractions = [1, 1]\nfor frac in fractions_that_work:\n product_of_fractions = [i*j for i, j in zip(product_of_fractions, frac)]\n</code></pre>\n\n<p>If you wanted to go a bit more towards functional programming you could use this single line of code:</p>\n\n<pre><code>from functools import reduce # Needed for Python 3, works in Python 2.6+\nimport operator\n\nproduct_of_fractions = [reduce(operator.mul, value) for value in zip(*fractions_that_work)]\n</code></pre>\n\n<p>Even though it may be more complex (and thus slightly less readable), I prefer this last way because of its brevity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:54:18.843",
"Id": "48147",
"ParentId": "48137",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48147",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T10:22:46.873",
"Id": "48137",
"Score": "8",
"Tags": [
"python",
"optimization",
"programming-challenge"
],
"Title": "Project Euler Problem 33 - digit canceling fractions"
} | 48137 |
<p>When it come to security I try to be to better as possible but I don't have the knowledge.</p>
<p>According to what I read on-line my following code should be good but I could use some of your comment/critic/fixes</p>
<p>Here is a simple class just to example how I would do a login. Does it look secure enough?</p>
<pre><code>class UserClass
{
private $dbCon = null;
public $Error = '';
public function __construct(PDO $dbCon)
{
$this->dbCon = $dbCon;
}
public function login($Email,$Password,$RegisterCustomerSession = FALSE)
{
$GetSalt = $this->dbCon->prepare('SELECT id,salt,hashPass FROM `customer` WHERE `email` = :Email');
$GetSalt -> bindValue(':Email',$Email);
$GetSalt -> execute();
if($GetSalt -> rowCount() == 0)
{
$this->Error = "No customer is registered with that email";
return false;
}
elseif($GetSalt->rowCount()>0)
{
$CustomerInfo = $GetSalt->fetch(PDO::FETCH_ASSOC);
if(sha1($Password.$CustomerInfo['salt'])==$CustomerInfo['hashPass'])
{
if($RegisterCustomerSession)
self::RegisterAllCustomerSession($CustomerInfo['id']);
return true;
}
else
{
$this->Error = "Invalid Password";
return false;
}
}
}
public function SetPassword($CustomerId,$Password)
{
$Salt = self::CreateSalt(16);
$HashPass = sha1($Password.$Salt);
$SetPasswordAndSalt = $this->dbCon->prepare('UPDATE `customer` SET `hashPass` = :HashPass,`salt` = :Salt WHERE `id` = :CustomerId;');
$SetPasswordAndSalt -> bindValue(':CustomerId',$CustomerId);
$SetPasswordAndSalt -> bindValue(':Salt',$Salt);
$SetPasswordAndSalt -> bindValue(':HashPass',$HashPass);
try{
$SetPasswordAndSalt ->execute();
return true;
}catch(PDOException $e){echo $e->getMessage(); return false; }
}
private function CreateSalt($HowLong = 16)
{
$CharStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-=+_<>';
$ReturnStr = '';
for($i = 0;$i<$HowLong;$i++)
{
$ReturnStr .= $CharStr{mt_rand(0,77)};
}
return $ReturnStr;
}
private function RegisterAllCustomerSession($CustomerId)
{
// some code.
}
}
</code></pre>
| [] | [
{
"body": "<p>I'm not sufficiently familiar with PDO to say more on your database access than that you don't seem to have any injection vulnerabilities. However, there are a few things which I would do differently.</p>\n\n<h3>Salt entropy</h3>\n\n<p>There are two things which strike me as odd about your salt generation. Firstly, using a base-77 encoding. If you configure your database correctly then you can use the full 8 bits of each byte of salt. That's more efficient, avoids possible bugs with generating a number in the wrong range (how sure are you that <code>strlen($CharStr) === 78</code>?), and is closer to the assumptions made when analysing salted hashing.</p>\n\n<p>Secondly, while <code>mt_rand</code> is better than <code>rand</code> it's not a cryptographic PRNG. The best portable secure PRNG in PHP is <code>openssl_random_pseudo_bytes</code>; if you're not planning to deploy to Windows then you could also get good entropy from <code>/dev/random</code>.</p>\n\n<h3>Hash</h3>\n\n<p>SHA is not generally recommended as a hash for passwords. The current conventional wisdom is that you want password hashing to be slow, and should use either bcrypt or scrypt. If you insist on SHA then you should use it as a component of PBKDF2.</p>\n\n<h3>Account existence oracle</h3>\n\n<p>There are two schools of thought on telling people \"That username doesn't exist\". The usability argument is that it's preferable to tell someone that they got their username wrong. The security argument is that you should always say \"Either your username doesn't exist or you got your password wrong\" to prevent people identifying accounts which do exist and then trying to brute-force their passwords. (Anti-brute-forcing techniques is a separate issue which I'm not going to address in detail).</p>\n\n<p>If you favour the security argument over the usability argument then you need to avoid telling people <em>indirectly</em> that the username doesn't exist. That means that if <code>$GetSalt -> rowCount() === 0</code> you should still do a hashing operation to avoid a quicker page load which leaks information.</p>\n\n<h3>Minor style points</h3>\n\n<pre><code>if($GetSalt -> rowCount() == 0)\n ...\nelseif($GetSalt->rowCount()>0)\n</code></pre>\n\n<p>I see three things wrong here:</p>\n\n<ol>\n<li>What other possibilities are there? Shouldn't that <code>elseif</code> just be an <code>else</code>?</li>\n<li>Why <code>==</code> instead of <code>===</code>?</li>\n<li>Pick a style for use of whitespace and stick with it.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:12:50.860",
"Id": "84529",
"Score": "0",
"body": "Thanks! For your answer this is a very complete answer I couldn't ask for more. also Sorry for my ignorance but :P you missed me for the first paragraph of salt entropy,. \"Firstly, using a base-77 encoding. If you configure your database correctly then you can use the full 8 bits of each byte of salt. \" huh ? Then \" how sure are you that strlen($CharStr) === 78? \" Im not sure what you mean again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:16:18.850",
"Id": "84531",
"Score": "0",
"body": "`CreateSalt` has a set of permitted bytes which the salt can use. I'm saying that you should allow it to use all 256 possible values for each byte."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:19:02.333",
"Id": "84532",
"Score": "0",
"body": "Ohhh!, Okay I Think I understand. Again sorry for my ignorance. How can put some byte that are not associated with a char in a string :S"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:20:43.447",
"Id": "84533",
"Score": "0",
"body": "If you get your random data from either of the routes I suggested then you don't need to. If you get it from `mt_rand(0, 255)` then `chr`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:54:30.810",
"Id": "48164",
"ParentId": "48146",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48164",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:44:43.690",
"Id": "48146",
"Score": "6",
"Tags": [
"php",
"mysql",
"security"
],
"Title": "Is this user login secure?"
} | 48146 |
<p>Using <a href="https://codereview.stackexchange.com/questions/43111/a-generic-memorycache-class">this question</a> as a base, and using some of the advice in the answers, I wanted to build out something that would be generic, thread-safe, and easy to use for at least one current and several future projects.</p>
<p>The idea is to be able to call one function, passing a key and passing another function to generate the data, if needed. It returns true/false to indicate success and saves the data to an OUT parameter. There's a default cache time but also overload methods that allow the developer to pass a new absolute duration (in minutes).</p>
<p>The class and functions work, I can step through the code and see that it hits the passed function the first time, then skips it in subsequent requests.</p>
<p>The external static call to IsCachingEnabled is basically just looking for an AppSetting in the web.config.</p>
<p>Some functions are marked internal but could be set to public - they're there partly as an offshoot of the original sample and partly because I may enable them in the future. For my current project, I'm only interested in using the TryGetAndSet method from outside.</p>
<p>Here's the code. I'm interested to hear whether anything here just doesn't make sense, isn't thread-safe, or is just plain bad practice.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Caching;
using System.Collections.Concurrent;
namespace Ektron.Com
{
/// <summary>
/// Uses System.Runtime.Caching to provide a thread-safe caching class.
/// Recommended use is to employ the TryGetAndSet method as a wrapper to call
/// your data-building function.
/// </summary>
public static class CacheManager
{
/// <summary>
/// The cache store. A dictionary that stores different memory caches by the type being cached.
/// </summary>
private static ConcurrentDictionary<Type, ObjectCache> cacheStore;
/// <summary>
/// The default minutes (15)
/// </summary>
private const int DefaultMinutes = 15;
#region constructors
/// <summary>
/// Initializes the <see cref="CacheManager"/> class.
/// </summary>
static CacheManager()
{
cacheStore = new ConcurrentDictionary<Type, ObjectCache>();
}
#endregion
#region Setters
/// <summary>
/// Sets the specified cache using the default absolute timeout of 15 minutes.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
/// <param name="cacheItem">The data to be cached.</param>
static internal void Set<T>(string cacheKey, T cacheItem)
{
Set<T>(cacheKey, cacheItem, DefaultMinutes);
}
/// <summary>
/// Sets the specified cache using the absolute timeout specified in minutes.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
/// <param name="cacheItem">The data to be cached.</param>
/// <param name="minutes">The absolute expiration (in minutes).</param>
static internal void Set<T>(string cacheKey, T cacheItem, int minutes)
{
if (Ektron.Com.Helpers.Constants.IsCachingEnabled)
{
Type t = typeof(T);
if (!cacheStore.ContainsKey(t))
{
RegisterCache(t);
}
var cache = cacheStore[t];
cache.Set(cacheKey, cacheItem, GetCacheItemPolicy(minutes));
}
}
/// <summary>
/// Sets the specified cache using the passed function to generate the data.
/// Uses default absolute timeout of 15 minutes.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
/// <param name="getData">The function to generate the data to be cached.</param>
static internal void Set<T>(string cacheKey, Func<T> getData)
{
Set<T>(cacheKey, getData, DefaultMinutes);
}
/// <summary>
/// Sets the specified cache using the passed function to generate the data.
/// Uses the specified absolute timeout (in minutes).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
/// <param name="getData">The function to generate the data to be cached.</param>
/// <param name="minutes">The absolute expiration (in minutes).</param>
static internal void Set<T>(string cacheKey, Func<T> getData, int minutes)
{
if (Ektron.Com.Helpers.Constants.IsCachingEnabled)
{
Type t = typeof(T);
if (!cacheStore.ContainsKey(t))
{
RegisterCache(t);
}
var cache = cacheStore[t];
T data = getData();
cache.Set(cacheKey, data, GetCacheItemPolicy(minutes));
}
}
#endregion
#region Getters
/// <summary>
/// Tries to retrieve data from cache first. If the data is not found in cache, the passed function
/// will be used to generate and store the data in cache. Data is returned via the returnData parameter.
/// Function returns true if successful.
/// Uses the default absolute timeout of 15 minutes.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
/// <param name="getData">The function to generate the data to be cached.</param>
/// <param name="returnData">The return data.</param>
/// <returns>True if successful. False if data is null.</returns>
public static bool TryGetAndSet<T>(string cacheKey, Func<T> getData, out T returnData)
{
if (!Ektron.Com.Helpers.Constants.IsCachingEnabled)
{
Remove<T>(cacheKey);
}
Type t = typeof(T);
bool retrievedFromCache = TryGet<T>(cacheKey, out returnData);
if (retrievedFromCache)
{
return true;
}
else
{
returnData = getData();
Set<T>(cacheKey, returnData);
return returnData != null;
}
}
/// <summary>
/// Tries to retrieve data from cache first. If the data is not found in cache, the passed function
/// will be used to generate and store the data in cache. Data is returned via the returnData parameter.
/// Function returns true if successful.
/// Uses the specified absolute timeout (in minutes).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
/// <param name="getData">The function to generate the data to be cached.</param>
/// <param name="minutes">The absolute expiration (in minutes).</param>
/// <param name="returnData">The return data.</param>
/// <returns>True if successful. False if data is null.</returns>
public static bool TryGetAndSet<T>(string cacheKey, Func<T> getData, int minutes, out T returnData)
{
Type t = typeof(T);
bool retrievedFromCache = TryGet<T>(cacheKey, out returnData);
if (retrievedFromCache && Ektron.Com.Helpers.Constants.IsCachingEnabled)
{
return true;
}
else
{
returnData = getData();
Set<T>(cacheKey, returnData, minutes);
return returnData != null;
}
}
/// <summary>
/// Attempts to retrieve data from cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
/// <param name="returnItem">The data from cache.</param>
/// <returns>True if successful. False if data is null or not found.</returns>
static internal bool TryGet<T>(string cacheKey, out T returnItem)
{
Type t = typeof(T);
if (cacheStore.ContainsKey(t))
{
var cache = cacheStore[t];
object tmp = cache[cacheKey];
if (tmp != null)
{
returnItem = (T)tmp;
return true;
}
}
returnItem = default(T);
return false;
}
#endregion
/// <summary>
/// Removes the specified item from cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheKey">The cache key.</param>
static internal void Remove<T>(string cacheKey)
{
Type t = typeof(T);
if (cacheStore.ContainsKey(t))
{
var cache = cacheStore[t];
cache.Remove(cacheKey);
}
}
/// <summary>
/// Registers the cache in the dictionary.
/// </summary>
/// <param name="t">The type used as the key for the MemoryCache that stores this type of data.</param>
private static void RegisterCache(Type t)
{
ObjectCache newCache = new MemoryCache(t.ToString());
cacheStore.AddOrUpdate(t, newCache, UpdateItem);
}
/// <summary>
/// Updates the item. Required for use of the ConcurrentDictionary type to make this thread-safe.
/// </summary>
/// <param name="t">The Type used as the key for the MemoryCache that stores this type of data.</param>
/// <param name="cache">The cache to be updated.</param>
/// <returns></returns>
private static ObjectCache UpdateItem(Type t, ObjectCache cache)
{
var newCache = new MemoryCache(cache.Name);
foreach (var cachedItem in cache)
{
newCache.Add(cachedItem.Key, cachedItem.Value, GetCacheItemPolicy(DefaultMinutes));
}
return newCache;
}
/// <summary>
/// Gets the cache item policy.
/// </summary>
/// <param name="minutes">The absolute expiration, in minutes.</param>
/// <returns>A standard CacheItemPolicy, varying only in expiration duration, for all items stored in MemoryCache.</returns>
private static CacheItemPolicy GetCacheItemPolicy(int minutes = 15)
{
var policy = new CacheItemPolicy()
{
Priority = CacheItemPriority.Default,
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes)
};
return policy;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-19T19:02:48.263",
"Id": "265858",
"Score": "0",
"body": "I am providing a small suggestion. Please invert your `if` statements. It's easier to return from a quick `if` than to wrap the contents of entire methods in them. Makes code more readable, and less layers of \"nestiness\"..."
}
] | [
{
"body": "<p>Short version: it looks like you're just trying to get a per-type ObjectCache. That's a basic singleton pattern, so I'm unsure what you're trying to gain through all this extra cruft in the class. If it were me, I would consider the following code:</p>\n\n<pre><code>public static class GlobalTypedObjectCache<T>\n{\n public static ObjectCache Cache { get; private set; }\n static GlobalTypedObjectCache()\n {\n Cache = new MemoryCache(typeof(T).ToString());\n }\n}\n</code></pre>\n\n<p>to be a much simpler, nearly functional equivalent to what you've got going. If you want the convenience functions, you can implement them in a much simpler fashion based on the above template. I'd take it even further, and suggest that you throw the singleton out, make a generic/templated class that derives from MemoryCache, and implement your convenience functions there:</p>\n\n<pre><code>public class TypedObjectCache<T> : MemoryCache\n{\n LocalTypedObjectCache(string name, NameValueCollection nvc = null) : base(name, nvc) { }\n}\n</code></pre>\n\n<p>That way, you can throw <em>this</em> class behind a singleton as-needed for specific caching purposes. With those broad observations made, down to specifics...</p>\n\n<h1>Scope</h1>\n\n<p>Because the class is static, there can be only one cache in the system. However, because it's <em>also</em> effectively a generic, you really wind up with one cache per type (so the key \"foo\" refers to different things in and ). IMHO, you should strive for consistency, and either have a non-static, generic version of the class (which you can then put behind a singleton for specific cache applications, ensuring \"foo\" exists only once for a well-defined functional scope, rather than an implicit key scope based arbitrarily on type), OR have a fully global, Object-based cache that exists once and only once (so that the key \"foo\" cannot exist in more than one form in the cache). Of these two options, I would generally consider it more appropriate to have a non-static class and leave it to your consumers to put an instance behind a singleton pattern.</p>\n\n<h1>Call Consistency</h1>\n\n<p>The class has three functions (aside from the constructor) that don't use a generic type specifier. Two of those three functions instead take a <code>Type</code> parameter. Either all of the functions should take a <code>Type</code> parameter (if you're trying to reduce the amount of code generated), or all of the functions should use template typing. In the former case, you may as well make the entire static class take a type, and just call the functions without the type (note that this will mean there's a static class for each type, rather than a single static class containing all types, which means that the code can be further refactored down).</p>\n\n<h1>Behavior Consistency</h1>\n\n<p>There's a check in some of your functions for seeing if caching is enabled, whereas other functions omit these checks. You need to determine the consistent behavior you want (no gets, no sets if caching is turned off? No sets, but gets still allowed?), and then implement it across all of your functions that will do getting, setting, or both. Note also that there is a threading issue if the caching flag can switch between on/off during runtime, as some of your code paths have multiple checks of that flag.</p>\n\n<h1>Default Values</h1>\n\n<p>Instead of two declarations, e.g.:</p>\n\n<pre><code>static internal void Set<T>(string cacheKey, T cacheItem)\n{\n Set<T>(cacheKey, cacheItem, DefaultMinutes);\n}\nstatic internal void Set<T>(string cacheKey, T cacheItem, int minutes) { /* ... */ }\n</code></pre>\n\n<p>Just use a default argument, and implement the function once:</p>\n\n<pre><code> static internal void Set<T>(string cacheKey, T cacheItem, int minutes = DefaultMinutes) { /* ... */ }\n</code></pre>\n\n<p>Your <code>GetCacheItemPolicy</code> function should also use the named constant instead of a hard-coded 15 for its default value. The one place that it's called (inside UpdateItem) should simply omit any value being passed to take the default.</p>\n\n<h1>Cache Management</h1>\n\n<p>The cache is being forced into a default of absolute timeout, and then you provide <code>UpdateItem</code>... which goes through and forcefully resets every item's expiry in the cache. This leads us to (effectively) an all-or-nothing situation -- either everything will expire out of the cache at the same time, OR nothing will ever be expired from the cache (because it's being updated faster than the expiry time). This more or less defeats the purpose of caching, especially at such a broad scale (all items of the same type at the global/static level). Consider reviewing your other options re. <code>CacheItemPolicy</code> (like <code>SlidingExpiration</code>), staying out of the way, and letting <code>ObjectCache</code> do the job it was written to do.</p>\n\n<h1>Registration Thread Unsafe</h1>\n\n<p>The registration code will cause your old caches to get thrown out, if you register the same type twice. If you're going to keep it, you should make sure that you don't allow nuking entries by accident, because two people tried to register the first object of a type at the same time. That said, I've listed several ways by which you could do away with the registration altogether... :)</p>\n\n<h1>Null Coalescing</h1>\n\n<p>The null coalescing operator (<code>??</code>) can be used to trim down your code a little bit, rather than using complete \"if\" statements to do null checks and data merges.</p>\n\n<h1>Type Constraints</h1>\n\n<p>If you use type constraints (and didn't need to cache structs), then you can get rid of your need for <code>default(T)</code>. This may or may not be acceptable for your needs.</p>\n\n<h1>Example Rewrite</h1>\n\n<p>I leave comments as an exercise to the OP. I don't agree with all of the return values (e.g., IMO the bools should indicate whether the item was serviced from the cache or not -- the caller can do its own null checks, but it can't otherwise figure out a cache hit or miss), but I leave the behavior of the OP mostly intact.</p>\n\n<pre><code>using System;\nusing System.Collections.Specialized;\nusing System.Runtime.Caching;\n\npublic class TypedObjectCache<T> : MemoryCache where T : class\n{\n private CacheItemPolicy HardDefaultCacheItemPolicy = new CacheItemPolicy()\n {\n SlidingExpiration = new TimeSpan(0, 15, 0)\n };\n\n private CacheItemPolicy defaultCacheItemPolicy;\n\n public TypedObjectCache(string name, NameValueCollection nvc = null, CacheItemPolicy policy = null) : base(name, nvc)\n {\n defaultCacheItemPolicy = policy??HardDefaultCacheItemPolicy;\n }\n\n public void Set(string cacheKey, T cacheItem, CacheItemPolicy policy = null)\n {\n policy = policy??defaultCacheItemPolicy;\n if ( true /* Ektron.Com.Helpers.Constants.IsCachingEnabled */ )\n {\n base.Set(cacheKey, cacheItem, policy);\n }\n }\n\n public void Set(string cacheKey, Func<T> getData, CacheItemPolicy policy = null)\n {\n this.Set(cacheKey, getData(), policy);\n }\n\n public bool TryGetAndSet(string cacheKey, Func<T> getData, out T returnData, CacheItemPolicy policy = null)\n {\n if(TryGet(cacheKey, out returnData))\n {\n return true;\n }\n returnData = getData();\n this.Set(cacheKey, returnData, policy);\n return returnData != null;\n }\n\n public bool TryGet(string cacheKey, out T returnItem)\n {\n returnItem = (T)this[cacheKey];\n return returnItem != null;\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:52:52.587",
"Id": "84773",
"Score": "0",
"body": "In the `TryGet` method, use `returnItem = this[cacheKey] as T;` instead. It won't throw an exception then if the type cast fails."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T17:59:30.723",
"Id": "84848",
"Score": "0",
"body": "@StuartBlackler If the typecast fails, something has gone horribly, _horribly_ wrong, and we want to know about it. The whole point of this wrapper seems to be so only objects of one type wind up in the collection... so if a type that isn't T got in, an explosion is quite warranted. With that said, it would probably be a Good Thing to enforce that by overriding all the base class methods that could add non T type items to the collection, and throw at the point of addition, instead of the point of extraction. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:13:20.477",
"Id": "84953",
"Score": "0",
"body": "@TravisSnoozy You make a lot of great points. Thank you. While I can't say that supporting structs is absolutely necessary, I also don't want to rule it out. So I would keep default(T). I was not comfortable with the UpdateItem method, but couldn't point out why (code smell). With the sample rewrite you provided, would that mean that the developer would need to set up a global singleton for each type they wanted to cache?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:42:05.467",
"Id": "85251",
"Score": "0",
"body": "@egandalf that is correct -- this rewrite is not static, and therefore one way you could share it with the parts of your program that need access to the cache would be to stick an instance behind a singleton pattern. However, by not being static itself, it does not force a single, global cache -- allowing for other access patterns (esp. in cases where you don't want any random bit of code being able to add/remove items from the cache). If you do make a global singleton, consider making it \"internal\" scope. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-02T14:27:14.573",
"Id": "296662",
"Score": "0",
"body": "MemoryCache class is thread safe. stackoverflow.com/a/6738179/665783"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T20:28:17.640",
"Id": "48267",
"ParentId": "48148",
"Score": "18"
}
},
{
"body": "<p>In the rewrite TryGetAndSet, it might be better return false and not set the cache entry if the returned value is null. </p>\n\n<p>With the documented implementation, the first call to TryGetAndSet will return false and out a null value. Subsequent calls will return true and a null value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-15T19:40:27.703",
"Id": "164786",
"Score": "3",
"body": "Hi! Welcome to Code Review. A good first answer, but I would suggest to add an example of what you are trying to do. This way, it would be easier for the asker to just put that into his/her code, or edit it to match yours."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-15T19:30:06.393",
"Id": "90860",
"ParentId": "48148",
"Score": "0"
}
},
{
"body": "<h2>This is an addition to the accepted answer.</h2>\n\n<p>To have a really thread safe implementation of the derived <code>ObjectCache</code> you need to double check the <code>TryGet()</code> call. True, the <code>ObjectCache</code> uses a <code>Monitor</code> to manage possible race conditions, but the <code>Func<T> getData</code> will be called two times if a race condition exists.</p>\n\n<p>So a possible addition is adding a simple lock and double check the data.</p>\n\n<pre><code>[...]\n\nprivate object WriteLock { get; } = new object();\n\n[...]\n\npublic void TryGetOrSet( string cacheKey, Func<T> getData, out T returnData, CacheItemPolicy policy = null )\n{\n if( TryGet( cacheKey, out returnData ) )\n return true;\n\n lock( WriteLock )\n {\n if( TryGet( cacheKey, out returnData ) )\n return true;\n\n returnData = getData();\n Set( cacheKey, returnData, policy );\n }\n\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T08:06:29.527",
"Id": "426035",
"Score": "0",
"body": "Would you always initialise WriteLock or use InterLocked.CompareExchange instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T15:16:09.037",
"Id": "426496",
"Score": "0",
"body": "What would you compare with `InterLocked.CompareExchange`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T15:27:41.027",
"Id": "426498",
"Score": "0",
"body": "now you always initialize your lock, even if you never call TryGetOrSet, you could also lazy initialize that lock with InterLocked. Or is that overkill?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T15:42:23.823",
"Id": "426503",
"Score": "0",
"body": "You could use something like `private object writeLock; private object WriteLock => writeLock ?? (writeLock = new object())`. But I'm not quite sure about concurrent `lock` race conditions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T16:02:07.567",
"Id": "426512",
"Score": "0",
"body": "https://social.msdn.microsoft.com/Forums/vstudio/en-US/80aa8cc7-9db2-4b69-8a29-86a7648a005a/interlockedcompareexchange?forum=csharpgeneral -> the first paragraph, the lock is created with InterLocked"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-16T08:48:54.953",
"Id": "132157",
"ParentId": "48148",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48267",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:56:49.510",
"Id": "48148",
"Score": "15",
"Tags": [
"c#",
"thread-safety",
"generics",
"cache"
],
"Title": "Generic, thread-safe MemoryCache manager for C#"
} | 48148 |
<p>I'm using the following structure:</p>
<pre><code>class Map
{
public List<List<Point>> points;
public List<Base> bases;
}
</code></pre>
<p><code>Point</code> and <code>Base</code> are over-normal sized classes (has more than 30 attributes).</p>
<p>And I'm iterating this <code>Map</code> class like this:</p>
<pre><code>public static void calculateMatrix(Map map)
{
LineOfSight.LineOfSight los = new LineOfSight.LineOfSight();
foreach (var b in map.bases)
{
foreach (var cc in map.points)
{
foreach (var c in cc)
{
calculatePointValues(c, b, los);
}
}
}
}
</code></pre>
<p>There is around 500*500 points <code>List<List<T>></code> and around 10 bases.</p>
<p>This iterating is calling <code>calculatePointValues</code> method around 2.5 million.</p>
<p>And my application can be initiated around 30 seconds.</p>
<p>Shall I use Array instead of <code>List<></code>?
Shall I use <code>for()</code> instead of <code>foreach</code>?</p>
<p>Or, what should I do?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:10:39.203",
"Id": "84487",
"Score": "3",
"body": "Unless I'm very mistaking, both an array and `List<T>` have O(1) lookup time so there will be no difference in performance. If there is anything we can say with respect to performance then you should probably give more information about what it is exactly you use this for afterwards and how these collections are used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:34:50.330",
"Id": "84495",
"Score": "1",
"body": "In C#, methods are named in PascalCase. Private methods have no official standard since only your team sees them, but most people still name them in PascalCase. Really, only fields and variables are named in camelCase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:37:10.873",
"Id": "84496",
"Score": "0",
"body": "@Magus: both are [a form of CamelCasing](http://nl.wikipedia.org/wiki/CamelCase). But yes, I agree although I use the `_` prefix myself for most fields."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:40:11.553",
"Id": "84497",
"Score": "1",
"body": "@JeroenVannevel: While that's true, the C# documentation refers to them separately, making the distinction I did. And saying that one is part of the other does not change the fact that it is more specific to refer to them separately, as I did. As to underscoring fields, that becomes less important if your syntax highlighting colors them differently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:21:51.827",
"Id": "84505",
"Score": "1",
"body": "If you're going to use such short names, at least be consistent: `b` for `base` is fine, but `c` for `point`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T16:27:05.503",
"Id": "84521",
"Score": "0",
"body": "I wouldn't try to optimize this without knowing more about calculatePointValues -- the big chunk of speedup I'd be looking to access would be, e.g., if having viz between {0,0} on a map and {0,10} on a map implies visibility between the intervening 9 points (as well as if that visibility is reciprocal in all cases). In other words... I want to know if there are rules that would limit any algorithm we choose to Omega(N^2). Why try to loop faster, if we can find a way to fundamentally reduce complexity? :)"
}
] | [
{
"body": "<p>I think speed will only increase a bit, if at all, if you use arrays (The List implementation you use may already use an array).\nBut you will reduce memory consumption if you switch to an array based implementation if you reduce the number of objects used this way.</p>\n\n<p>You should profile both implementations to compare speed and memory consumption. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T14:26:55.473",
"Id": "48154",
"ParentId": "48150",
"Score": "6"
}
},
{
"body": "<p>As was said in the comments, I don't think <code>List<T></code> makes any significant difference over an array.</p>\n\n<p>But with a bit of LINQ you can reduce the nesting a bit:</p>\n\n<pre><code>foreach (var b in map.bases)\n{\n foreach (var c in map.points.SelectMany(cc => cc))\n {\n CalculatePointValues(c, b, los);\n }\n}\n</code></pre>\n\n<p>And it <em>could</em> be worth trying to profile it with some <code>Parallel</code> looping as well:</p>\n\n<pre><code>Parallel.ForEach(map.bases, b =>\n {\n foreach (var c in map.points.SelectMany(cc => cc))\n {\n CalculatePointValues(c, b, los);\n }\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:10:30.793",
"Id": "48156",
"ParentId": "48150",
"Score": "11"
}
},
{
"body": "<p>Your performance problem primarily stems from your algorithmic complexity; the loops themselves are reasonable, and any changes you make to either the types involved or using \"for\" instead of \"foreach\" instead of LINQ won't actually gain you too terribly much in terms of performance. The use of parallelization will result in a speedup by spreading the work out across more processors, but it won't actually reduce the total amount of work you're asking be done. If it is the absolute last resort, then tuning the aspects I've just mentioned might be all you can get in terms of speedup, but what's really interesting is the contents of <code>calculatePointValues()</code>.</p>\n\n<p>What you're showing, right now, is that you have an \\$O(N^3)\\$ algorithm complexity. That's a <em>bad thing</em> :). If you <em>have</em> to touch (# of bases * rows * columns) in order to calculate each {row,col} pair's value for each <code>Base</code>, and you <em>must</em> pre-calculate them (e.g., you can't calculate them on demand, as you need each point) then you might be in \"absolute last resort\" territory.</p>\n\n<p>Now, I'm not an expert on either matrix math or graph theory. However, given that you have only one <code>los</code> object for all of the bases and all of the points, and bases all seem to be on the same map, it seems reasonable that there may exist an algorithmic rabbit you could pull out of your hat to reduce this to \\$O((rows*cols) + base)\\$ (a.k.a. \\$O(N^2)\\$).</p>\n\n<p>Now, with all of that said, down to code.</p>\n\n<h1>Class Organization</h1>\n\n<p><code>CalculateMatrix()</code> and <code>CalculatePointValues()</code> should probably be part of <code>Map</code>. I don't have a lot of programmatic structure to base that on (you've pasted skeleton code, really :)), but it seems silly to have a second class who consumes a <code>Map</code> to spit out auxiliary data about that <code>Map</code>. If this other class is supposed to be generic/be performing a re-usable algorithm, it should take more generic inputs. If it's performing functions on Maps, relevant to Maps and things that consume Maps, it should be part of <code>Map</code>.</p>\n\n<p>I have a similar complaint for <code>LineOfSight</code>, which seems to be extra-nutty because its type has a nested type of the same name. LoS calculations seem like something that should belong with the <code>Map</code>.</p>\n\n<h1>Outputting to Nowhere</h1>\n\n<p>Your <code>los</code> object doesn't go anywhere. The result of all that churning is placed in a local variable that loses scope once the function ends, and that makes no sense at all.</p>\n\n<h1>Encapsulation</h1>\n\n<p>In <code>Map</code>, Don't use public containers, unless this <code>Map</code> class is hidden away inside another class for private use only. If you must expose these publicly, you should use interfaces (e.g., <code>IList<IList<Point>></code>) instead of concrete container types, and make these properties, not public members.</p>\n\n<p>Remember that C# doesn't have any good way to expose containers with non-modifiable contents. The containers themselves can be returned so that they are read-only (you can't modify which object references are or are not inside the container), but the contents within them can still be changed (you could mutate a <code>Base</code> or a <code>Point</code> using their reference, if they have mutator functions). Keep in mind that this breaks encapsulation, and try to make the contained classes (<code>Point</code> and <code>Base</code>, in these cases) immutable if possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:23:33.640",
"Id": "84535",
"Score": "0",
"body": "Nice answer! Wouldn't `ReadOnlyList<T>` address your last point?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:27:56.860",
"Id": "84536",
"Score": "4",
"body": "The answer, in a word, is \"no,\" and this is a very common misconception/misunderstanding. A ReadOnlyList<T> cannot be added to or removed from -- the list itself is fixed; it's a list that you can only read from. However, if T is a reference, then I can still call mutator functions on T. Say it was ReadOnlyList<StringBuilder> rol. I could call rol[0].Append(\"Hey, I just changed something!\"), and that would be OK -- because I didn't modify the *list*, I modified an object the list happens to point at."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:31:03.317",
"Id": "84537",
"Score": "0",
"body": "By contrast, C++ has true read-only containers -- but you have to carefully mark up each of your class' member functions with the \"const\" keyword (at the end of the signature), to tell the compiler which members are \"observers.\" Any member that is not an \"observer\" is automatically considered a \"mutator,\" and the compiler will not let you call those methods if you are passed a type* const, const type&, or a const type (or containers holding the same)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:11:55.587",
"Id": "48169",
"ParentId": "48150",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "48169",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T13:59:04.510",
"Id": "48150",
"Score": "6",
"Tags": [
"c#",
"performance"
],
"Title": "Any performance difficulties related to List<Type>?"
} | 48150 |
<p>Should the following <code>GetPhysicalFileLocation()</code> method in the <code>Car</code> class have its own Service Layer?</p>
<pre><code>public class Car
{
public int id;
public string model;
public int year;
public IList<Pic> lstCarPics;
}
</code></pre>
<p>Then we have the respective class:</p>
<pre><code>public class Pic
{
public string filename;
public string fileLocation;
public string GetPhysicalFileLocation()
{
string LocalDirectory = "~\\CarFiles\\";
DirectoryInfo diPath = new
DirectoryInfo(HttpContext.Current.Server
.MapPath(LocalDirectory + car.id);
}
}
</code></pre>
<p>Seeing that this method and others will access physical file locations throughout the application, would something like this justify having it's own <code>FileService</code>?</p>
<p>I'm having trouble understanding when methods like this should fall under it's own service layer vs leaving it in its class.</p>
| [] | [
{
"body": "<p>The convention for public fields and properties in c# is <code>PascalCasing</code>. This would make the following:</p>\n\n<pre><code>public class Car\n{\n public int Id; //{ get; set; } this makes it a property.\n public string Model;\n public int Year; \n public IList<Pic> LstCarPics;\n}\n\npublic class Pic\n{\n public string FileName;\n public string FileLocation;\n //...\n}\n</code></pre>\n\n<p>Furthermore there is (from the information you posted) no real necessity to shorten the classname to <code>Pic</code>. Why not just use <code>Picture</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:30:44.883",
"Id": "48159",
"ParentId": "48158",
"Score": "2"
}
},
{
"body": "<p>As @Vogel612 hinted, a class shouldn't expose its fields publicly - this:</p>\n\n<pre><code>public class Car \n{\n public int Id { get; set; }\n\n // ...\n}\n</code></pre>\n\n<p>Is equivalent to this:</p>\n\n<pre><code>public class Car\n{\n private int _id;\n public int Id \n { \n get { return _id; }\n set { _id = value; }\n }\n\n // ...\n}\n</code></pre>\n\n<p>As you can see, encapsulation is easily achieved with auto-properties - don't expose your fields!</p>\n\n<hr>\n\n<p>Method <code>GetPhysicalFileLocation</code> has <em>dependencies</em> on the file system <em>and</em> on an <code>HttpContext</code>, so you <em>definitely</em> want that to be abstracted away, so you can write a test that uses that code and doesn't <em>actually</em> hit the file system.</p>\n\n<p>I'd move it to some <code>IFileSystemService</code> implementation:</p>\n\n<pre><code>public interface IFileSystemService\n{\n string GetPhysicalFileLocation(int carId);\n\n // ...\n}\n</code></pre>\n\n<p>And then make a class that implements it:</p>\n\n<pre><code>public class FileSystemService : IFileSystemService\n{\n // load this value from application settings?\n private readonly string _localDirectory = \"~\\\\CarFiles\\\\\";\n\n public string GetPhysicalFileLocation(int carId)\n {\n var diPath = new DirectoryInfo(HttpContext.Current\n .Server.MapPath(_localDirectory + carId);\n }\n}\n</code></pre>\n\n<p>And now you can have client code like this:</p>\n\n<pre><code>public class MyClass\n{\n private readonly IFileSystemService _service;\n\n public MyClass(IFileSystemService service)\n {\n _service = service;\n }\n\n public void DoSomething(int carId)\n {\n var fileName = _service.GetPhysicalFileLocation(carId);\n // ...\n }\n}\n</code></pre>\n\n<p>This way you can inject a \"fake\"/\"mock\" implementation for <code>IFileSystemService</code> and test <em>DoSomething</em> without hitting the file system or depending on an <code>HttpContext</code>; the key being that depending on the file system and on an <code>HttpContext</code>, is an implementation detail that the client code doesn't need to know about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:56:13.130",
"Id": "84518",
"Score": "0",
"body": "Ok. How would this get \"glued\" back up? So then would I have a GetPhysicalFileLocation method within the Pic class that calls the IFileService?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:59:15.777",
"Id": "84519",
"Score": "1",
"body": "I'd make a separate class to implement the interface, and have whoever needs to `GetPhysicalFileLocation` call the interface's method (which would take a `fileName` parameter)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T16:11:12.487",
"Id": "84520",
"Score": "0",
"body": "Ok I'm lost in the code-woods now :( Can you create a quick sample using my code above how this would work? That's the part I'm not getting. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:46:10.603",
"Id": "84542",
"Score": "0",
"body": "@TheTruthIsInCode sorry that was confusing - edited with [hopefully] less confusing details ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:48:47.100",
"Id": "48163",
"ParentId": "48158",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48163",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T15:22:46.480",
"Id": "48158",
"Score": "2",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Is this method a good candidate for a service layer?"
} | 48158 |
<p>I've been working with PHP for a while now, but unfortunately haven't delved into the OO side of it until recently. I've been reading up on <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="nofollow">separation of concerns</a> and OOP best practices, and I think I have an idea of what is expected, but there's always room to improve. At any rate, is this heading in the right direction for PHP OOP?</p>
<p><strong>The Class (profile.php)</strong></p>
<pre><code><?php
$dbHost = "example.com";
$dbName = "exampleDB";
$user = "WouldntYou";
$password = "LikeToKnow";
//Get and parse the faculty name from the url
if(isset($_GET['facultyName'])) {
$facultyName = explode("-", $_GET['facultyName']);
$getFirstName = ucfirst($facultyName[1]);
$getLastName = ucfirst($facultyName[0]);
}
else {
$getFirstName = "";
$getLastName = "";
}
class Employee {
private $employeeId;
private $firstName;
private $middleName;
private $lastName;
private $suffix;
private $eMail;
private $phoneNumber;
private $faxNumber;
private $streetAddress;
private $city;
private $state;
private $zipCode;
private $profileWebsite;
private $profilePhoto;
private $jobName;
private $departmentName;
private $departmentURL;
/**
* @desc combines first, middle, and last name along with suffix
* @param - n/a
* @return string - formatted name and title
*/
public function display_name() {
$fullName = $this->firstName;
$fullName .= ($this->middleName!="") ? " " . $this->middleName . " " : " ";
$fullName .= $this->lastName;
$fullName .= ($this->suffix!="") ? ", " . $suffix : "";
return $fullName;
}
/**
* @desc wraps email in anchor tag
* @param - n/a
* @return string - link to email
*/
public function display_email() {
return "<a href='mailto:". $this->eMail . "'>". $this->eMail ."</a>";
}
/**
* @desc splits phone number, adds hyphens and parenthesis
* @param - n/a
* @return string - formatted phone number
*/
public function display_phone() {
return "(" . substr($this->phoneNumber, 0, 3) . ") " . substr($this->phoneNumber, 3, 3) . "-" . substr($this->phoneNumber, 6, 4);
}
/**
* @desc splits fax number, adds hyphens and parenthesis
* @param - n/a
* @return string - formatted fax number
*/
public function display_fax() {
return "(" . substr($this->faxNumber, 0, 3) . ") " . substr($this->faxNumber, 3, 3) . "-" . substr($this->faxNumber, 6, 4);
}
/**
* @desc wraps profilePhoto in image tag, using the display_name as alt text
* @param - n/a
* @return string - image tag
*/
public function display_photo() {
return "<img alt='". $this->display_name() . "' src='/profileImages/". $this->profilePhoto . "' class='profilePhoto'>";
}
/**
* @desc wraps profileWebsite in anchor tag
* @param - n/a
* @return string - link to profileWebsite
*/
public function display_website() {
return "<a href='". $this->profileWebsite . "' target='_blank'>". $this->profileWebsite ."</a>";
}
/**
* @desc displays the complete address, wrapped in a p tag
* @param - n/a
* @return string - streetAddress, city, state, and zip code wrapped in p tag
*/
public function display_address() {
return "<p>".$this->streetAddress."<br>".$this->city.", ".$this->state." ".$this->zipCode."</p>";
}
/**
* @desc Splits the jobTitle into an array, with "----" as delimiter
* @param - n/a
* @return array - each index contains a job title
*/
public function display_jobs() {
return explode("----", $this->jobName);
}
/**
* @desc Splits the departmentName and departmentURL and creates a link, with "----" as delimiter
* @param - n/a
* @return array - each index contains a formed link with departmentName and departmentURL
*/
public function display_departments() {
$deptName = explode("----", $this->departmentName);
$deptURL = explode("----", $this->departmentURL);
$deptLink = array();
$count = 0;
foreach($deptName as $name) {
$deptLink[] = "<a href='$deptURL[$count]'>$name</a>";
$count++;
}
return $deptLink;
}
}
try {
$pdo = new PDO("mysql:host=$dbHost;dbname=$dbName", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT employeeId, firstName, middleName, lastName, suffix, eMail, phoneNumber, faxNumber, streetAddress, city, state, zipCode, profileWebsite, profilePhoto, GROUP_CONCAT(DISTINCT jobName ORDER BY jobTitleId SEPARATOR "----") AS jobName, GROUP_CONCAT(DISTINCT departmentName ORDER BY departmentId SEPARATOR "----") AS departmentName, GROUP_CONCAT(DISTINCT departmentURL ORDER BY departmentId SEPARATOR "----") AS departmentURL
FROM employee
INNER JOIN employee_has_jobTitle ON employeeId = employee_has_jobTitle.employee_employeeId
INNER JOIN jobTitle ON employee_has_jobTitle.jobTitle_jobTitleId = jobTitleId
INNER JOIN employee_has_department ON employee.employeeId = employee_has_department.employee_employeeId
INNER JOIN department ON employee_has_department.department_departmentId = departmentId
WHERE firstName = :firstName AND lastName = :lastName AND employeeId <> 9');
/* <> 9?!? Yeah, I don't want people to be able to view my profile :) */
$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Employee');
$stmt->execute(array('firstName'=>$getFirstName,'lastName'=>$getLastName));
$employee = $stmt->fetch();
} catch(PDOException $e) {
echo "Oops! " . $e->getMessage();
}
?>
</code></pre>
<p>Wow, that's a HUGE class. At least it seems that way to me, but I'm no pro. Is that too long? How should it be split if so? Is this me doing a whole bunch of procedural code, wrapping it in a class, and deeming it OOP, or am I on the right track? Just a few of my concerns there.</p>
<p><strong>The Display Page</strong> </p>
<pre><code><?php
include 'includes/phpScripts/profile.php';
$title = "--- Profile: " . $employee->display_name();
$description = "--- Profile: " . $employee->display_name();
include 'includes/headerFooters/mainHeader.php';
?>
<div id="columnContainer">
<div id='centerColumn'>
<h1><?=$employee->display_name();?></h1>
<?=$employee->display_photo();?>
<div class='contactContainer'>
<?php
foreach($employee->display_departments() as $dept) {
echo "<h3>$dept</h3>";
}
?>
<p>
<?php
$firstJob = true;
foreach($employee->display_jobs() as $job) {
if($firstJob) {
$firstJob = false;
}
else {
echo ", ";
}
echo $job;
}
?>
</p>
<p>
<strong>Phone: </strong><?=$employee->display_phone();?><br>
<strong>Fax: </strong><?=$employee->display_fax();?><br>
<strong>E-mail: </strong><br><?=$employee->display_email();?>
</p>
<p><?=$employee->display_address();?></p>
<div class='clearfix'></div>
</div>
</div>
...
</div>
<?php include('includes/headerFooters/mainFooter.php'); ?>
</code></pre>
<p>I created this layout while I was still a student, and I look at the code now and cringe. I've recently been reading about <a href="http://oocss.org/" rel="nofollow">OOCSS</a> and <a href="http://css-tricks.com/a-line-in-the-sand/" rel="nofollow">not using <code>id</code> for styling</a>, but with hundreds of pages involved, we can't invest the time for a (much needed) redesign just yet. However, am I separating out the PHP enough here, or should more things be done inside the class methods (the for loops, adding the comma, etc)?</p>
<p>My apologies for the extremely long code, I expect some tl;dr. However, am I on the right track for OOP, or do I need to hit the books, and Google, a bit more?</p>
<p>Once I get a few good habits, I'll be diving into Laravel 4. Let me know if I'm ready for it, and thanks in advance for any tips!</p>
| [] | [
{
"body": "<p>Your <code>profile.php</code> file is doing way too much. A good test to see if you are adhering to the Separation of Concerns principle is: Do one thing, and do it well.</p>\n\n<p>It seems <code>profile.php</code> is doing the following things:</p>\n\n<ol>\n<li>Gathering information from the HTTP request params</li>\n<li>Defining a \"model\" class called <code>Employee</code></li>\n<li>The <code>Employee</code> class is formatting HTML</li>\n<li>The bottom of the file is querying the database for the Employee record</li>\n</ol>\n\n<p>You should read up on the <a href=\"https://www.google.com/search?q=model+view+controller&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla%3aen-US%3aofficial&client=firefox-a&channel=sb\" rel=\"nofollow\">Model-View-Controller programming pattern</a>. Since you are writing PHP, check out <a href=\"http://rads.stackoverflow.com/amzn/click/143022925X\" rel=\"nofollow\">PHP Objects, Patterns and Practices</a>. It's a great read about OOP in PHP and how you can apply many of the common programming patterns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:38:43.800",
"Id": "84538",
"Score": "0",
"body": "I've read quite a bit on MVC, and will be diving into it via the Laravel framework on my next project. I wanted to get a better grasp on OOP prior to that though. A few questions, If I may. Where should I be processing the HTTP requests? I originally had it at the top of the display page, but I was trying to keep as much of the PHP out of there as possible. Where should I be formatting the HTML, if not in the class methods? Also, where should the database query be located? Thanks for the quick response and input, plus one!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:37:04.210",
"Id": "84943",
"Score": "0",
"body": "These questions will get answered by diving into MVC. The essence of Separation of Concerns can be boiled down to a couple statements: Do one thing and do it well; Favor composition over inheritance. Your specific code example is hard because to follow Separation of Concerns is to implement MVC."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:01:24.517",
"Id": "48168",
"ParentId": "48165",
"Score": "2"
}
},
{
"body": "<p>There is a lot that could be improved, so just a few remarks.</p>\n\n<p>1.) Configuration should be put into separate file.</p>\n\n<pre><code>$dbHost = \"example.com\";\n$dbName = \"exampleDB\";\n$user = \"WouldntYou\";\n$password = \"LikeToKnow\";\n</code></pre>\n\n<p>It is better to use constants for configuration, so their values can't be overwritten.</p>\n\n<pre><code>define('DB_HOST', 'example.com');\ndefine('DB_NAME', 'exampleDB');\ndefine('DB_USER', 'WouldntYou');\ndefine('DB_PASSWORD', 'LikeToKnow');\n</code></pre>\n\n<p>2.) You should do some validation of input and you should initialise your variables, with initialisation you will get rid of unnecessary <code>else</code> block as well.</p>\n\n<p>Original code:</p>\n\n<pre><code>if(isset($_GET['facultyName'])) {\n $facultyName = explode(\"-\", $_GET['facultyName']);\n $getFirstName = ucfirst($facultyName[1]);\n $getLastName = ucfirst($facultyName[0]);\n}\nelse {\n $getFirstName = \"\";\n $getLastName = \"\";\n}\n</code></pre>\n\n<p>Updated code:</p>\n\n<pre><code>$getFirstName = '';\n$getLastName = '';\nif (array_key_exists('facultyName', $_GET)){\n $facultyName = explode(\"-\", $_GET['facultyName']);\n\n if (count($facultyName) == 2 && strlen($facultyName[0]) && strlen($facultyName[1])){\n $getFirstName = ucfirst($facultyName[1]);\n $getLastName = ucfirst($facultyName[0]);\n }\n}\n</code></pre>\n\n<p>3.) Class should be defined in a separate file, so it can be used elsewhere.</p>\n\n<p>4.) In your class there is unuses attribute <code>private $employeeId;</code>.</p>\n\n<p>5.) In method <code>display_name</code> there is undeclared variable <code>$suffix</code>, you should always initialize your variables before using them.</p>\n\n<p>6.) You are using class attributes, but you are not setting them anywhere, they all containg <code>null</code> value.</p>\n\n<p>7.) You should set class attributes in __constructor or via <code>setAttributeName($attributeName)</code> methods.</p>\n\n<p>8.) If you are accessing attributes from outside of class you should do it via <code>getAttribtueName()</code> methods.</p>\n\n<p>9.) You are creating HTML inside class, it is better to use MVC pattern.</p>\n\n<p>10.) In your SQL query you are using hard coded value 9, the value should be in configuration.</p>\n\n<p>11.) The SQL query is overly complex, you should think about if it can be simplified, the query will be probably very slow with more rows in the tables.</p>\n\n<p>12.) You put too much to <code>try {...} catch(...) {...}</code> block, you should put your database connection and query execution into separate blocks.</p>\n\n<p>13.) Your PHPDoc comments are wrong:</p>\n\n<p>Original:</p>\n\n<pre><code>/**\n * @desc Splits the jobTitle into an array, with \"----\" as delimiter\n * @param - n/a\n * @return array - each index contains a job title\n */\n</code></pre>\n\n<p>Updated:</p>\n\n<pre><code>/**\n * Splits the jobTitle into an array, with \"----\" as delimiter\n * \n * @return array Each index contains a job title.\n */\n</code></pre>\n\n<p>If there are no parameters then don't use any <code>@param</code> in documentation. Do not use <code>-</code> here <code>@return array - each ...</code>.</p>\n\n<p>14.) If you use <code>\"\"</code> for wrapping strings then PHP interpreter will look into those strings and search for variables, if you use <code>''</code> then PHP interpreter won't need to do that.</p>\n\n<p>15.) You are using unnecessary semicolon in single line PHP code <code><?=$employee->display_name();?></code>, can be written like this <code><?= $employee->display_name() ?></code>, it is common to leave out semicolon in one line PHP code.</p>\n\n<p>16.) In view files it is more readable to use alternative PHP syntax:</p>\n\n<p>Original:</p>\n\n<pre><code><?php\nforeach($employee->display_departments() as $dept) {\n echo \"<h3>$dept</h3>\";\n}\n?>\n</code></pre>\n\n<p>Updated:</p>\n\n<pre><code><? foreach($employee->display_departments() as $dept) : ?>\n <h3><?= $dept ?></h3>\n<? endforeach ?>\n</code></pre>\n\n<p>17.) You should read about MVC design pattern and try to implement it, or even better to use some PHP Framework like Symfony2, Laravel or something similar.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:10:20.027",
"Id": "84562",
"Score": "0",
"body": "Very well laid out, thank you! The class attributes are set when the query is fetched. Should I put the query in the constructor, or leave it where it is and just put it in a different `try`? As for the complex query, should that be split into multiple queries? There are 5 tables showing, but I actually need to join a few more for education and biographical background information. Diving into Laravel 4 with my next project, in the process of setting up the server in my spare time. Trying to understand OOP better in the mean time. Thanks for the input!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:13:25.670",
"Id": "84563",
"Score": "0",
"body": "Also, should the `$_GET` processing be placed into the config file too, or on the display page?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:20:00.293",
"Id": "84565",
"Score": "0",
"body": "Sorry to pepper you with more questions. Last one, I promise! Until I move into MVC, where should the HTML be formatted?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:26:49.533",
"Id": "84570",
"Score": "0",
"body": "You can leave the SQL query where it is, but you should move the Employee class into separate file, so it can be reused somewhere else. Regarding the query it does not necessarily mean to split the query into more queries, but if it can be simplified (for example by changing table structure and table relations) then it should be simplified."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:28:19.337",
"Id": "84571",
"Score": "0",
"body": "I'll look in to that then. So the `$_GET` processing and query in one file, the config in another, and then a file for the class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:29:15.643",
"Id": "84572",
"Score": "0",
"body": "Regarding `$_GET`, in configuration there should be mostly static values, it is quite unusual to have there something that comes from URL. Processing of inputs (like validation etc.) should not be done in views (your display page) but somewhere else, if it was MVC pattern then it would be in C or M. HTML should be formatted in the display page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:30:21.187",
"Id": "84573",
"Score": "0",
"body": "Yes, 1 class per file (or 1 class + related exception), config another file, displaying HTML another file, processing requests / executing queries another file(s)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:54:28.347",
"Id": "48179",
"ParentId": "48165",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48179",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T16:19:40.390",
"Id": "48165",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"pdo"
],
"Title": "Is this following Separation of Concerns and PHP OOP standards?"
} | 48165 |
<p>Another piece of Roslyn-based code, this time a <code>CodeFixProvider</code>. </p>
<p>I'm looking for feedback on Roslyn-specific code: </p>
<ul>
<li>Am I using the <code>SemanticModel</code> correctly?</li>
<li>Are there any codeflows I have overlooked that might cause issues?</li>
<li>Am I violating any best practices I'm unaware of?</li>
<li>etc</li>
</ul>
<h3>Analyzer</h3>
<pre><code>namespace DiagnosticTools.Collections.NotInitializedException
{
[DiagnosticAnalyzer]
[ExportDiagnosticAnalyzer(DiagnosticId, LanguageNames.CSharp)]
internal class NotInstantiatedCollectionAnalyzer : ISyntaxNodeAnalyzer<SyntaxKind>
{
internal const string DiagnosticId = "CollectionNotInstantiated";
private static string Description = Resources.NotInstantiatedCollection_Description;
private static string MessageFormat = Resources.NotInstantiatedCollection_MessageFormat;
private static string Category = Resources.Category_Collections;
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning);
public ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest
{
get
{
return ImmutableArray.Create(SyntaxKind.VariableDeclaration);
}
}
public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
var declaration = node as VariableDeclarationSyntax;
var typeOfVariable = semanticModel.GetTypeInfo(declaration.Type).Type;
var isCollection = typeOfVariable.IsCollection();
var isInitialized = declaration.Variables[0].Initializer != null;
if (isCollection && !isInitialized)
{
addDiagnostic(Diagnostic.Create(Rule, declaration.GetLocation(), declaration.Variables[0].Identifier.Value));
}
}
}
}
</code></pre>
<h3>CodeFixProvider</h3>
<pre><code>namespace DiagnosticTools.Collections.NotInitializedException
{
[ExportCodeFixProvider(NotInstantiatedCollectionAnalyzer.DiagnosticId, LanguageNames.CSharp)]
class NotInstantiatedCollectionFixProvider : ICodeFixProvider
{
public IEnumerable<string> GetFixableDiagnosticIds()
{
return new[] { NotInstantiatedCollectionAnalyzer.DiagnosticId };
}
public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var token = root.FindToken(span.Start);
document.TryGetSemanticModel(out SemanticModel semanticModel);
var statement = token.Parent.Parent as VariableDeclarationSyntax;
// Construct variable declaration
var declarator = new SeparatedSyntaxList<VariableDeclaratorSyntax>();
var identifier = statement.Variables[0].Identifier;
var newType = semanticModel.GetTypeInfo(statement.Type);
// Leave the method when we encounter an interface like IEnumerable<T>.
// The warning remains, but there will be no solution proposal.
if (newType.Type.IsAbstract)
{
return new CodeAction[] { };
}
var genericArguments = statement.Type
.DescendantNodes()
.OfType<TypeArgumentListSyntax>()
.FirstOrDefault();
var newObject = RoslynUtils.GetInstantiationExpressionFromType(newType.Type.Name, genericArguments);
var equalsClause = SyntaxFactory.EqualsValueClause(
SyntaxFactory.Token(SyntaxKind.EqualsToken)
.WithLeadingTrivia(
new SyntaxTriviaList() {
SyntaxFactory.Space
}),
newObject);
declarator = declarator.Add(SyntaxFactory.VariableDeclarator(identifier, null, equalsClause));
var newStatement = SyntaxFactory.VariableDeclaration(statement.Type, declarator);
var newRoot = root.ReplaceNode(statement, newStatement);
return new[]
{
CodeAction.Create(Resources.NotInstantiatedCollection_ActionMessage, document.WithSyntaxRoot(newRoot))
};
}
}
}
</code></pre>
<h3>Extensions</h3>
<pre><code>namespace DiagnosticTools.Utilities
{
public static class Extensions
{
public static bool IsSubclassOf(this ITypeSymbol symbol, Type type)
{
var @base = symbol.BaseType;
while(@base != null)
{
if (@base.Name == type.Name) { return true; }
@base = @base.BaseType;
}
return false;
}
public static bool ImplementsInterface(this ITypeSymbol symbol, Type type)
{
return symbol.Interfaces.Any(x => x.Name == type.Name);
}
public static bool IsCollection(this ITypeSymbol symbol)
{
return symbol.Interfaces.Any(x => x.Name == typeof(IEnumerable).Name
|| x.Name == typeof(IEnumerable<>).Name);
}
}
}
</code></pre>
<h3>RoslynUtils</h3>
<pre><code>namespace DiagnosticTools.Utilities
{
public static class RoslynUtils
{
public static ExpressionSyntax GetInstantiationExpressionFromType(string typeName, TypeArgumentListSyntax typeArgumentsSyntax)
{
// 0: Name of type
// 1: (Optional) generic arguments
// 2: (Optional) arguments
var result = " new {0}{1}({2})";
var typeArguments = GetParsedTypeArguments(typeArgumentsSyntax);
var arguments = ""; // Not implemented until I find out a place where to use them
return SyntaxFactory.ParseExpression(string.Format(result, typeName, typeArguments, arguments));
}
private static string GetParsedTypeArguments(TypeArgumentListSyntax arguments)
{
if (arguments.Arguments.Count == 0) { return ""; }
var sb = new StringBuilder("<");
for (var i = 0; i < arguments.Arguments.Count; i++)
{
sb.Append(arguments.Arguments[i].ToString());
if (i != arguments.Arguments.Count - 1)
{
sb.Append(", ");
}
}
sb.Append(">");
return sb.ToString();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:09:31.713",
"Id": "84550",
"Score": "0",
"body": "Removed a line of code that was a leftover from experimenting."
}
] | [
{
"body": "<p>I know nothing about rosyln, so there would be someone better to check that, however...</p>\n<h1>Analyzer</h1>\n<ul>\n<li>You create <code>Description</code>, <code>MessageFormat</code> & <code>Category</code> as static strings but only use them in the constructor of <code>Rule</code>. I don't think that the extra fields provide anything other than a minor increase in readability.</li>\n<li>Inconsistent use of <code>readonly</code>. If you keep the fields I suggested removing above, make them all readonly. This will give clear intention that they should not be used (I guess that you want them as const's ideally)</li>\n<li>The result of <code>SyntaxKindsOfInterest</code> is deterministic, therefore, it can be made a readonly static (A Micro-Optimisation I know). I can't remember the language semantics off hand, but the same could probably happen for <code>SupportedDiagnostics</code></li>\n<li>There is no parameter checking inside of <code>AnalyzeNode</code></li>\n<li>Inside <code>AnalyzeNode</code>, you don't check for a null reference after the type cast of <code>declaration</code> before attempting to use it</li>\n<li>You assume that the <code>Variables</code> collection is going to always have 1 or more elements in the collection</li>\n</ul>\n<h1>CodeFixProvider</h1>\n<ul>\n<li>The result of <code>GetFixableDiagnosticIds</code> is deterministic and can be kept as a static readonly field</li>\n<li>No parameter checking inside of <code>GetFixesAsync</code></li>\n<li>No checking for a null reference after the type case of <code>statement</code></li>\n<li>You assume that the <code>Variables</code> collection is going to always have 1 or more elements in the collection</li>\n<li>You could have something similar to <code>EventArgs.Empty</code> for the result of <code>if (newType.Type.IsAbstract)</code></li>\n</ul>\n<h1>Misc</h1>\n<ul>\n<li><code>RosylnUtils</code> performs no parameter checking</li>\n<li><code>GetTypedArguments</code> should use return <code>String.Empty</code> not <code>""</code></li>\n</ul>\n<p>I relise that this is probably just test code, hope this helps in either case. These are just the things that I would do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:27:23.553",
"Id": "48433",
"ParentId": "48170",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48433",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:13:02.593",
"Id": "48170",
"Score": "7",
"Tags": [
"c#",
"roslyn"
],
"Title": "CodeFixProvider that instantiates collections"
} | 48170 |
<p>I'm new to OOP PHP and I created a simple input helper class. And was wondering if it's good? Are my dependencies good?</p>
<p>Also the reason I'm not throwing an exception with the get method is that I will mainly use this class for form validation purposes.</p>
<p>I'll take any suggestion for improvement!</p>
<pre><code>class Input {
private $_get,
$_post;
public function __construct(Array $get, Array $post) {
$this->_get = $get;
$this->_post = $post;
}
public function exists($type = 'POST') {
switch($type) {
case 'POST':
return (!empty($this->_post)) ? true : false;
break;
case 'GET':
return (!empty($this->_get)) ? true : false;
break;
default:
return false;
break;
}
}
public function get($input, $source = 'POST') {
if($source == 'POST' && isset($this->_post[$input])) {
return $this->_post[$input];
} elseif($source == 'GET' && isset($this->_get[$input])) {
return $this->_get[$input];
}
return false;
}
}
</code></pre>
<p><strong>I figured I could made my code shorter:</strong></p>
<pre><code>class Input {
private $_source;
public function __construct(Array $source) {
$this->_source = $source;
}
public function exists() {
return !empty($this->_source);
}
public function get($input) {
return (isset($this->_source[$input])) ? $this->_source[$input] : false;
}
}
</code></pre>
| [] | [
{
"body": "<p>In Java and C# you can simply put </p>\n\n<pre><code>return !empty($this->_source);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>return isset($this->_source[$input]);\n</code></pre>\n\n<p>since the evaluation of that is a boolean by itself and thus there is no need for the additional ternary operation. I would suspect that this is the same in PHP.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:42:49.203",
"Id": "84539",
"Score": "0",
"body": "Thanks for the tip. You also made me aware of something that wasn't suppose to be. As far as the rest of my code, I think it's clean now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:46:00.057",
"Id": "84541",
"Score": "0",
"body": "No problem, pleasure to help. Keep in mind though that you shouldn't edit your question to reflect the new situation: it confuses future readers. If you have a new question you can always make a new post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:47:36.123",
"Id": "84543",
"Score": "0",
"body": "Yea, I thought it wouldn't be worth to create an entire new question. But will keep that in mind the second time."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:36:19.297",
"Id": "48172",
"ParentId": "48171",
"Score": "4"
}
},
{
"body": "<p>In this <code>switch</code> :</p>\n\n<pre><code> switch($type) {\n case 'POST':\n return (!empty($this->_post)) ? true : false;\n break;\n case 'GET':\n return (!empty($this->_get)) ? true : false;\n break;\n default:\n return false;\n break;\n }\n</code></pre>\n\n<p>You should not have <code>break</code> after <code>return</code>. It cannot be executed and is thus dead code.</p>\n\n<p>As Jeroen mentioned, ternaries to determine a boolean do not make sense, just return the boolean expression immediately.</p>\n\n<p>Also, I see you realized in the shorter version that for one request you can only have <code>GET</code> or <code>POST</code>, so it does not make sense to pass both.</p>\n\n<pre><code>class Input {\n private $_source;\n\n public function __construct(Array $source) {\n $this->_source = $source;\n }\n\n public function exists() {\n return !empty($this->_source)\n }\n\n public function get($input) {\n return isset($this->_source[$input])\n }\n}\n</code></pre>\n\n<p>I am not sure how you can assign to <code>_source</code> if the variable name is <code>$_source</code> though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:44:16.087",
"Id": "48173",
"ParentId": "48171",
"Score": "2"
}
},
{
"body": "<p>Your input object is basically just a wrapper around an array, so why don't you just use one.\nThere are many advantages to do so when you can, simplicity and predictability mainly, also you will just have access to all the other methods arrays have.</p>\n\n<pre><code>// Construction\n$input = array(...)\n\n// Checking if it exists\n!empty($input)\n\n// Getting an item from the input\n$input['key']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:59:30.043",
"Id": "48238",
"ParentId": "48171",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48172",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:14:59.137",
"Id": "48171",
"Score": "1",
"Tags": [
"php",
"object-oriented"
],
"Title": "Does my input helper class look good?"
} | 48171 |
<p>I don't know that my title describes the code I want reviewed. Hopefully the code is explanatory.</p>
<p>I have an abstract parent class with two children. The parent listens to some hardware notifications and, when the appropriate hardware is connected/removed/fried in butter etc.., raises an event to its children who perform some processing with the data from the change. </p>
<p>The children then raise a public event on the parent with the processed data, which is what I'm unsure of. Here are the (stripped down) classes.</p>
<pre><code>public abstract class DeviceDetector<TEventArgs>
{
public event Action<TEventArgs> DeviceArrived;
public event Action<TEventArgs> DeviceRemoved;
protected void OnDeviceChange(TEventArgs e)
{
if (e.Arrival && DeviceArrived != null)
DeviceArrived(e);
if (!e.Arrival && DeviceRemoved != null)
DeviceRemoved(e);
}
protected event Action<string> DeviceArrival;
protected event Action<string> DeviceRemoval;
}
</code></pre>
<p>Each of the two children is defined as follows:</p>
<pre><code>public class SomeDescriptiveChildName: DeviceDetector<DeviceChild1EventArgs>
{
public SomeDescriptiveChildName()
{
this.DeviceArrival += new Action<string>(HandleProtectedEvent);
this.DeviceRemoval += new Action<string>(HandleProtectedEvent);
}
private void HandleProtectedEvent(string e)
{
//Class names have been changed to protect the innocent.
DeviceChild1EventArgs e = new DeviceChild1EventArgs();
base.OnDeviceChange(e);
}
}
public class AnotherDescriptiveChildName: DeviceDetector<DeviceChild2EventArgs>
{
public AnotherDescriptiveChildName()
{
this.DeviceArrival += new Action<string>(HandleProtectedEvent);
this.DeviceRemoval += new Action<string>(HandleProtectedEvent);
}
private void HandleProtectedEvent(string e)
{
DeviceChild2EventArgs e = new DeviceChild2EventArgs();
base.OnDeviceChange(e);
}
}
</code></pre>
<p>The <code>DeviceChild1EventArgs</code> and <code>DeviceChild2EventArgs</code> are classes inheriting from EventArgs to represent the data from each child.</p>
<p>My question is this: Is there a better way to represent the data passed to the children through <code>DeviceArrival</code> and <code>DeviceRemoval</code> (in this example I used string, it's not a string) without the use of generics etc... </p>
<p>To me this seems somewhat like overkill, but it's the only way I could think of doing this.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:56:43.723",
"Id": "84544",
"Score": "0",
"body": "Are `DeviceChild1` and `DeviceChild2` *actual* class names?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:57:18.603",
"Id": "84545",
"Score": "3",
"body": "Gods no. I had a feeling someone would mention that. I'll edit it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:59:17.943",
"Id": "84546",
"Score": "0",
"body": "@Brandon these names are definitely more *descriptive* :D, you sir made my day."
}
] | [
{
"body": "<p>The events in the base class don't follow the standards:</p>\n\n<pre><code>public event Action<TEventArgs> DeviceArrived;\npublic event Action<TEventArgs> DeviceRemoved;\n\nprotected event Action<string> DeviceArrival;\nprotected event Action<string> DeviceRemoval;\n</code></pre>\n\n<p>I'd be expecting something like this:</p>\n\n<pre><code>public event EventHandler<TEventArgs> AfterDeviceArrived;\npublic event EventHandler<TEventArgs> AfterDeviceRemoved;\n\nprotected event EventHandler<SomeEventArgsClass> BeforeDeviceArrived;\nprotected event EventHandler<SomeEventArgsClass> BeforeDeviceRemoved;\n</code></pre>\n\n<p>Couple points:</p>\n\n<ul>\n<li>Events can be declared with any delegate type (<code>Action<T></code> works), but the convention is to use an <code>EventHandler</code> or <code>EventHandler<TEventArgs></code> delegate.</li>\n<li>Convention for naming events that come in pairs (raised before and after such or such \"thing\" happens) is to prefix the event names with \"Before\" and \"After\", and use past tense as you've done.</li>\n<li><code>OnDeviceChange</code> should be called <code>OnDeviceChanged</code>.. but it's not clear why the method needs to raise both <em>...Arrived</em> and <em>...Removed</em> events without [apparently] doing anything in-between.</li>\n</ul>\n\n<hr>\n\n<p>A base class shouldn't know, or care, about whether it has derived classes or not. You've got that right, but a derived class that's listening for events raised in the base class, doesn't make sense to me.</p>\n\n<p>I don't think events are the appropriate way to accomplish what you're trying to do here. That said I'm not sure exactly <em>what</em> you're trying to accomplish (<em>trimmed code does that</em> ;) - but I'd venture to suggest <em>templated methods</em> instead of events.</p>\n\n<p>In the base class:</p>\n\n<pre><code>// todo: remove notion of \"event args\"\nprotected abstract void OnDeviceArrived(TEventArgs e);\nprotected abstract void OnDeviceRemoved(TEventArgs e);\n</code></pre>\n\n<p>The base class can call these methods even though they're not implemented - <code>abstract</code> methods <em>must</em> be implemented in the derived classes for the code to even compile.</p>\n\n<p>So instead of this:</p>\n\n<pre><code> if (e.Arrival && DeviceArrived != null)\n DeviceArrived(e);\n if (!e.Arrival && DeviceRemoved != null)\n DeviceRemoved(e);\n</code></pre>\n\n<p>You just have that:</p>\n\n<pre><code> if (e.Arrival) \n {\n OnDeviceArrived(e);\n }\n else\n {\n OnDeviceRemoved(e);\n }\n</code></pre>\n\n<p>And the derived classes have the implementations:</p>\n\n<pre><code>protected override void OnDeviceArrived(TEventArgs e)\n{\n // ...\n}\n\nprotected override void OnDeviceRemoved(TEventArgs e)\n{\n // ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:58:03.400",
"Id": "48180",
"ParentId": "48174",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48180",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T17:51:07.673",
"Id": "48174",
"Score": "5",
"Tags": [
"c#",
"generics",
"inheritance",
"event-handling"
],
"Title": "Having children call parent's public events with data generated from a protected event"
} | 48174 |
<p>I have implemented stochastic gradient descent in matlab and I would like to compare my results with another source but the error I am getting is higher (I am using squared error). I am worried I am misunderstanding the algorithm or have a bug. I have done trial and error parameter tuning, and am quite confident I have appropriate value for B, and know that I am working with the same data as my comparison. Please let me know what can be improved and if there is a mistake.</p>
<pre><code> % [w] = learn_linear(X,Y,B)
%
% Implement the online gradient descent algorithm with a linear predictor
% and minimizes over squared loss.
% Inputs:
% X,Y - The training set, where example(i) = X(i,:) with label Y(i)
% B - Radius of hypothesis class.
% Output:
% w - predictor (as a row vector) from the hypothesis class (norm(w) <= %B)
function [w] = learn_linear_sq_error(X, Y, B)
[r c] = size(X);
w = zeros(1, c);
sum_w = zeros(1, c);
% number of iterations
T = 1000;
% Run T iterations of online gradient descent:
for t = 1:T,
% Calculate step size for the current iteration.
eta_t = 1 / sqrt(t);
% Choose a random sample, and calculate its gradient.
i_t = round(rand(1) * (r - 1)) + 1;
g_t = calc_g_t(X(i_t, :), Y(i_t), w);
% Apply the update rule/projection using the chosen sample, by %finding
% the w that minimizes '|w - (w_t - eta_t * g_t)|' while %maintaining norm(w) <= B.
pw = w - eta_t * g_t;
norm_pw = norm(pw);
if norm_pw <= B
w = pw;
else
w = B * pw / norm_pw;
end
% accumulate the sum in preparation for calculating the final average.
sum_w = sum_w + w;
end
% Return the average of all intermediate w's.
w = sum_w / T;
end
%
% Calculate the sub gradient, with respect to squared loss, for a given sample
% and intermediate predictor.
% Inputs:
% x,y - A sample x (given as a row vector) and a tag y in R.
% w - our current predictor.
% Output:
% g_t - the gradient (as a row vector) for the given values of x, y, w.
function g_t = calc_g_t(x, y, w)
g_t = 2 * (w*x' - y) * x;
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T13:01:41.640",
"Id": "84643",
"Score": "0",
"body": "One thing you could try is to keep the error data at each iteration and make a plot to see if you are converging to the error value of the comparison."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T14:29:58.980",
"Id": "84649",
"Score": "0",
"body": "Thanks. I tried this but I seem to not be going too much lower than the error I am getting. I tried running for 400,000+ iterations and do not get significantly lower error."
}
] | [
{
"body": "<p>You probably do not need help with this question anymore (looks like it's been a year), but I thought I'd point something out in case someone else finds it useful. I think your squared loss expression should be \\$(w'*x - y)^2\\$ and the derivative of that with respect to \\$x\\$ is: \\$2*(w'*x-y)*w\\$. What you have is the outer product which results in a matrix minus a scalar. So I noticed two errors: </p>\n\n<ol>\n<li>You need an inner product instead of an outer product. </li>\n<li>You applied the chain rule wrong when you took the derivative w.r.t x. </li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-14T23:29:18.930",
"Id": "100982",
"ParentId": "48175",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:10:41.753",
"Id": "48175",
"Score": "0",
"Tags": [
"algorithm",
"matlab",
"machine-learning"
],
"Title": "Stochastic gradient descent squared loss"
} | 48175 |
<p>This gallery uses the Orbit gallery from the Foundation framework (version 3). I've set it up so that on smaller screens it appears as an accordion.</p>
<p>It works just fine, but is there a more concise way this could've been written? Perhaps in an object oriented way?</p>
<p><strong>The script:</strong> </p>
<pre><code>function activateSlider() {
if (window.Foundation && window.matchMedia) {
// Establishing media check
widthCheck = window.matchMedia("(max-width: 767px)");
if (widthCheck.matches) {
$('.orbit-container').after($('.orbit-timer'));
$('#slider, #slider li').attr('style', '');
$('#slider').removeClass('orbit-slides-container').removeAttr('data-orbit').addClass('accordion-container');
$('#slider li').removeAttr('data-orbit-slide').removeClass('active');
$('.orbit-container > a, #slider li .slider-content').hide();
$('#slider li:not(.active) .slider-content').css('display', 'none');
//Init accordion click functions
$('#slider li').unbind().bind('click', function(){
$(this).toggleClass('active').siblings().removeAttr('class');
$(this).siblings().find('.slider-content').slideUp();
$(this).find('.slider-content').slideToggle();
});
}
else
{
//If accordion styles are present, clean it up
var OrbitStyles = ($('.accordion-container').length === 0);
if (!OrbitStyles) {
$('.orbit-container > a').show();
$('#slider').removeClass('accordion-container');
$('#slider').addClass('orbit-slides-container');
$('#slider').attr('data-orbit', '');
$('.orbit-bullets-container').before($('.orbit-timer'));
$('.orbit-timer').removeClass('paused');
}
//Then set it up for the slider
$('.slider-content').show();
$('#slider li:first-child').addClass('active').siblings().removeAttr('class');
}
}
}
//Run the script
$(function(){
activateSlider();
});
//Run the script on resize
if (window.addEventListener) {
window.addEventListener('resize', debounce(function () {
activateSearch();
//fade in the slider while loading to prevent that second of ugly formatting
if ($('#slider').length > 0) {
$('#slider').delay(700).animate({ opacity: 1 }, 500);
}
}, 250));
} else {
window.attachEvent('resize', debounce(function () {
activateSearch();
//fade in the slider while loading to prevent that second of ugly formatting
if ($('#slider').length > 0) {
$('#slider').delay(700).animate({ opacity: 1 }, 500);
}
}, 250));
}
</code></pre>
<p><strong>And the html markup:</strong></p>
<pre><code><div class="orbit-container">
<ul id="slider" class="orbit-slides-container" data-orbit>
<li data-orbit-slide="slide-1" class="active">
<img src="http://placehold.it/1400x348" alt="" width="1400" height="348">
<section id="Walrus" class="orbit-caption">
<strong>Oh got walrus</strong>
<div class="slider-content">
<p>More hence euphemistic oriole let tediously dear repeatedly.</p>
<a class="read-more" href="#">Read More</a>
</div>
</section>
</li>
<li data-orbit-slide="slide-2">
<img src="http://placehold.it/1400x348" alt="" width="1400" height="348">
<section id="Overslept" class="orbit-caption">
<strong>Overslept wiped yikes</strong>
<div class="slider-content">
<p>Much supreme quick rakishly tamarin</p>
<a class="read-more" href="#">Read More</a>
</div>
</section>
</li>
</ul>
</div>
</code></pre>
| [] | [
{
"body": "<p>The most important bit here is the resize handler, since it fires many times per scroll.</p>\n\n<pre><code>//Run on document ready\n$(function () {\n\n // Cache the slider jQuery object\n var slider = $('#slider');\n\n // Pass in the existing reference. Explanation after the code\n activateSlider(slider);\n\n // Move out the debouncing function outside the resize handler\n // so that the function isn't recreated on every risize call\n function debounceAction() {\n activateSearch();\n\n //Personal preference. The \"early return\" looks better since\n // it avoids any additional indention\n if (!slider.length) return;\n\n slider.delay(700).animate({opacity: 1}, 500);\n\n }\n\n // Since you use jQuery, use it to abstract the resize function instead.\n $(window).on('resize', function () {\n // And all the handler's got to do is call debounce\n debounce(debounceAction, 250);\n });\n});\n</code></pre>\n\n<p>As for your <code>activateSlider</code>, you should cache the fetched DOM elements into variables and reuse them when necessary. Each time you do something like <code>$('.slider')</code>, it looks for elements with class <code>slider</code>. Caching them avoids this searching. I have already done it with <code>$('#slider')</code> by fetching it once, and passing it into <code>activateSlider</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:56:16.637",
"Id": "48191",
"ParentId": "48177",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48191",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:30:53.857",
"Id": "48177",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"object-oriented"
],
"Title": "How could I have approached this responsive image gallery differently?"
} | 48177 |
<blockquote>
<p>Given a "folder" which contains many "files," each file contains a time-table of trains, which stations they halt on and what time, per day.</p>
<pre><code>File-1 for day-1
Train1 [station1, <1 - 3> ] [station2, <5 - 6> ]
Train2 [station1, <10 - 12>] [station3, <15 - 18>]
File-2 for day-2
Train1 [station1, <11 - 4> ] [station2, <5 - 6> ]
Train2 [station1, <8 - 2>] [station3, <15 - 18>]
</code></pre>
<p>Overlapping days are included in the same file.</p>
<p>E.g: If trains halt from 23.00 - 00.30 then this data would be present
in one of the files only.</p>
<p>We ignore timezones and use 00 - 23.59 scale instead of am and pm.</p>
<p>To find how many platforms a station would need given such daily
schedules.</p>
<p>E.g: If <code>Train1</code> and <code>Train2</code> both use <code>Station1</code> from 10 - 12 then
<code>Station1</code> needs two platforms.</p>
<p><strong>Complexity:</strong></p>
<p>\$O\$ ( file * stations * (intervals * log intervals) )</p>
<ul>
<li><p>file - each file in the folder, aka number of days, whose schedule has been given :
constituted by - <code>for (File file : folder.listFiles()) {</code></p></li>
<li><p>stations - constituted by <code>dailyStationPlatformCountMap()</code></p></li>
<li>intervals - sort inside <code>maxOverlappingInterval</code></li>
</ul>
</blockquote>
<p>Note: I do understand merits of unit testing in separate files. But I deliberately added it to the main method for personal convenience, so I request that you don't consider that in your feedback.</p>
<p>I'm looking for request code review, optimizations and best practices.</p>
<pre><code>final class Intervals implements Serializable {
private final int start;
private final int end;
public Intervals (int start, int end) {
this.start = start;
this.end = end;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
}
public final class TrainTimeTable {
private TrainTimeTable() { }
public static Map<String, Integer> stationMaxPlatformMap(String folderName) throws IOException, ClassNotFoundException {
File folder = new File(folderName);
final List<Map<String, Integer>> stationPlatformCountList = new ArrayList<Map<String,Integer>>();
for (File file : folder.listFiles()) {
if (file.toString().contains("DS_Store")) continue;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
final Map<String, Map<String, Intervals>> dailyTrainStationIntervalMap = (Map<String, Map<String, Intervals>>) ois.readObject();
final Map<String, List<Intervals>> dailyStationIntervalMap = getDailyPerStationIntervalMap(dailyTrainStationIntervalMap);
final Map<String, Integer> dailyStationPlatformCountMap = dailyStationPlatformCountMap(dailyStationIntervalMap);
stationPlatformCountList.add(dailyStationPlatformCountMap);
}
return yearlyMaxPlatforms(stationPlatformCountList);
}
/**
* Breaks down the the information 'per train' into information 'per station'
* From here on the 'trains' don't hold any relevance, as we have created the time-table per station.
* ie - all intervals with respect to a station are mapped to the station.
*
* @param trainStationIntervalMap : map of trains -> to stations and train's intervals on those stations
* @return : map of station -> to all intervals of all trains on that station.
*/
private static Map<String, List<Intervals>> getDailyPerStationIntervalMap(Map<String, Map<String, Intervals>> trainStationIntervalMap) {
final Map<String, List<Intervals>> dailyStationInterval = new HashMap<String, List<Intervals>>();
for (Map<String, Intervals> map : trainStationIntervalMap.values()) {
for (Entry<String, Intervals> entry : map.entrySet()) {
final String station = entry.getKey();
final Intervals interval = entry.getValue();
if (!dailyStationInterval.containsKey(station)) {
dailyStationInterval.put(station, new ArrayList<Intervals>());
}
dailyStationInterval.get(station).add(interval);
}
}
return dailyStationInterval;
}
/**
* Given a map of station -> all intervals belonging to the station, return the maximum platforms that may be needed.
*
* @param dailyStationIntervalMap : map of station -> all intervals of that station.
* @return
*/
private static Map<String, Integer> dailyStationPlatformCountMap(Map<String, List<Intervals>> dailyStationIntervalMap) {
final Map<String, Integer> dailyStationMaxPlatformCount = new HashMap<String, Integer>();
for (Entry<String, List<Intervals>> entry : dailyStationIntervalMap.entrySet()) {
String station = entry.getKey();
List<Intervals> intervalList = entry.getValue();
dailyStationMaxPlatformCount.put(station, maxOverlappingInterval(intervalList));
}
return dailyStationMaxPlatformCount;
}
/**
* Given a station and its intervals, find the max platforms needed.
* Station is a 'meeting room'
* interval is understandably 'interval'
* platforms simply corresponds to 'overlap'
*
* http://stackoverflow.com/questions/8969823/how-to-find-the-maximal-number-of-these-intervals-that-have-a-common-point
*
* @param startTime
* @param endTime
* @return
*/
private static int maxOverlappingInterval (List<Intervals> interval) {
int[] startTime = new int[interval.size()];
int[] endTime = new int[interval.size()];
populateAndSort(startTime, endTime, interval);
int i = 0; // ctr for start time array
int j = 0; // ctr for end time array
int count = 0;
int max = -1;
while (i < startTime.length) {
if (startTime[i] < endTime[j]) {
count++;
i++;
if (count > max) {
max = count;
}
} else if (startTime[i] > endTime[j]) {
count--;
j++;
} else {
i++;
j++;
}
}
return max;
}
private static void populateAndSort(int[] startTime, int[] endTime, List<Intervals> interval) {
for (int i = 0; i < interval.size(); i++) {
startTime[i] = interval.get(i).getStart();
endTime[i] = interval.get(i).getEnd();
}
Arrays.sort(startTime);
Arrays.sort(endTime);
}
/**
* Once a list of 365 maps of Stations -> max plaform needed per day, we need to find,
* wbat was the max platform needed by Station for entire year.
* Example:
* If station "foo" needed 6 plaforms on Jan 16, and 4 plaforms on July 8th, then 6 should be added to map.
* ie
* foo -> 6
* bar -> 8 etc.
*
* @param stationPlatformCountList : list of daily station to max platform count per day map.
* @return
*/
private static Map<String, Integer> yearlyMaxPlatforms(List<Map<String, Integer>> stationPlatformCountList) {
final Map<String, Integer> yearlyStationPlatformCountMap = new HashMap<String, Integer>();
for (int i = 0; i < stationPlatformCountList.size(); i++) {
for (Entry<String, Integer> entry : stationPlatformCountList.get(i).entrySet()) {
String station = entry.getKey();
int platformCount = entry.getValue();
if (!yearlyStationPlatformCountMap.containsKey(station) || yearlyStationPlatformCountMap.get(station) < platformCount) {
yearlyStationPlatformCountMap.put(station, platformCount);
}
}
}
return yearlyStationPlatformCountMap;
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
// create a directory:
new File("/Users/ameya.patil/Desktop/schedules").mkdir();
Map<String, Map<String, Intervals>> map1 = new HashMap<String, Map<String,Intervals>>();
Map<String, Intervals> stationInterval11 = new HashMap<String, Intervals>();
stationInterval11.put("Churchgate", new Intervals(1, 2));
stationInterval11.put("Dadar", new Intervals(4, 6));
stationInterval11.put("Bandra", new Intervals(8, 10));
map1.put("T1", stationInterval11);
Map<String, Intervals> stationInterval12 = new HashMap<String, Intervals>();
stationInterval12.put("Churchgate", new Intervals(1, 3));
stationInterval12.put("Dadar", new Intervals(6, 9));
stationInterval12.put("Bandra", new Intervals(12, 15));
map1.put("T2", stationInterval12);
Map<String, Intervals> stationInterval13 = new HashMap<String, Intervals>();
stationInterval13.put("Churchgate", new Intervals(1, 4));
stationInterval13.put("Dadar", new Intervals(5, 9));
stationInterval13.put("Bandra", new Intervals(13, 17));
map1.put("T3", stationInterval13);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/ameya.patil/Desktop/schedules/dayOne"))) {
oos.writeObject(map1);
}
Map<String, Map<String, Intervals>> map2 = new HashMap<String, Map<String,Intervals>>();
Map<String, Intervals> stationInterval21 = new HashMap<String, Intervals>();
stationInterval21.put("Churchgate", new Intervals(1, 2));
stationInterval21.put("Dadar", new Intervals(4, 6));
stationInterval21.put("Bandra", new Intervals(8, 10));
map2.put("T1", stationInterval21);
Map<String, Intervals> stationInterval22 = new HashMap<String, Intervals>();
stationInterval22.put("Churchgate", new Intervals(1, 3));
stationInterval22.put("Dadar", new Intervals(6, 9));
stationInterval22.put("Bandra", new Intervals(9, 15));
map2.put("T2", stationInterval22);
Map<String, Intervals> stationInterval23 = new HashMap<String, Intervals>();
stationInterval23.put("Churchgate", new Intervals(12, 14));
stationInterval23.put("Dadar", new Intervals(5, 9));
stationInterval23.put("Bandra", new Intervals(13, 17));
map2.put("T3", stationInterval23);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/ameya.patil/Desktop/schedules/dayTwo"))) {
oos.writeObject(map2);
}
/**
* Expected stuff:
* Dadar : 2
* Churchgate : 3
* Bandra : 2
*/
final Map<String, Integer> expected = new HashMap<String, Integer>();
expected.put("Dadar", 2);
expected.put("Churchgate", 3);
expected.put("Bandra", 2);
assertEquals(expected, stationMaxPlatformMap("/Users/ameya.patil/Desktop/schedules"));
}
}
</code></pre>
| [] | [
{
"body": "<p>Quick review, but still good coding like usual.</p>\n\n<h2>Naming :</h2>\n\n<pre><code>int i = 0; // ctr for start time array\nint j = 0; // ctr for end time array\n</code></pre>\n\n<p>Isn't it better to call them <code>pointerStartTime</code> and <code>pointerEndTime</code>?<br/>\nIt helps you when you are programming. Take in mind that you get this code and must find a little bug.<br/> You are getting a headache just by always thinking what <code>i</code> and <code>j</code> are</p>\n\n<h2>Check for your own faults :</h2>\n\n<pre><code>private static void populateAndSort(int[] startTime, int[] endTime, List<Intervals> interval) {\n for (int i = 0; i < interval.size(); i++) {\n startTime[i] = interval.get(i).getStart();\n endTime[i] = interval.get(i).getEnd();\n }\n Arrays.sort(startTime);\n Arrays.sort(endTime);\n}\n</code></pre>\n\n<p>Its a strange set up and you can make a mistake when you call this method, by not setting the length of the array big enough.<br/>\nAt least this you should be doing :</p>\n\n<pre><code>private static void populateAndSort(int[] startTime, int[] endTime, List<Intervals> interval) {\n if ((startTime.length != endTime.length) || (startTime.length != interval.size())) {\n throw new IllegalArgumentException(\"All sizes must be the same\");\n }\n for (int i = 0; i < interval.size(); i++) {\n startTime[i] = interval.get(i).getStart();\n endTime[i] = interval.get(i).getEnd();\n }\n Arrays.sort(startTime);\n Arrays.sort(endTime);\n}\n</code></pre>\n\n<p>To avoid \"abuse\" of the method you should do the creation of the <code>int[]</code> in your method self :</p>\n\n<pre><code>private static Map<String,int[]> getTimesFromIntervals (List<Intervals> intervals>) {\n</code></pre>\n\n<p>In the javaDoc you tell exactly that the key for <code>startTime[]</code> is <code>starttime</code> and so on.<br/>\nThis is then clear for every programmer that will use that method.<br/>\nYou see that I cut the sorting to from that method.<br/>\nI prefer a new method for sorting the 2 arrays :</p>\n\n<pre><code>private static void sortIntegerMap (Map<String,int[]> timesMap) {\n for (int[] time : timesMap.values()) {\n Arrays.sort(time);\n }\n}\n</code></pre>\n\n<p>Now you have a more generic method that can sort, even more entries in the map is no problem.</p>\n\n<p>Hope you have something from this review.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T07:06:01.797",
"Id": "49121",
"ParentId": "48178",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T18:32:55.290",
"Id": "48178",
"Score": "3",
"Tags": [
"java",
"algorithm",
"hash-map"
],
"Title": "Trains scheduled, find max platforms per stations"
} | 48178 |
<p>I have to update a class property with the method name and then call a method that executes some code based on this property. The code is the same in both methods, but I am not seeing a way to remove this code duplication. I am trying to avoid using a parameter.</p>
<pre><code>public function register(){
$this->operation = __FUNCTION__;
$this->handleOperation();
}
public function unregister(){
$this->operation = __FUNCTION__;
$this->handleOperation();
}
</code></pre>
<p><strong>Update 1</strong></p>
<p>As <a href="https://codereview.stackexchange.com/users/40964/yoda">Yoda</a> suggested, here is a more complete code. It is a class to manipulate multiple functions for PHP autoloading. Now I am using parameters in <code>handleOperation()</code>. Example of use:</p>
<pre><code>$Autoloader = new Autoloader();
$Autoloader->setFunctions(array('controllers', 'commons'));
$Autoloader->setModule('default');
$Autoloader->register();
</code></pre>
<p>Class code:</p>
<pre><code>class Autoloader {
private $functions_to_handle = array();
private $module;
private $function;
private $paths = array();
public function setFunctions($functions){
$this->functions_to_handle = is_array($functions) ? $functions : array($functions);
}
public function setModule($module){
$this->module = $module;
}
public function register(){
$this->handleOperation(__FUNCTION__);
}
public function unregister(){
$this->handleOperation(__FUNCTION__);
}
private function handleOperation($operation){
$built_in_function = $this->mountBuiltInFunctionName($operation);
foreach($this->functions_to_handle as $function){
$built_in_function(array($this, $function));
}
}
private function mountBuiltInFunctionName($operation){
return 'spl_autoload_' . $operation;
}
private function controllers($classe) {
$this->function = __FUNCTION__;
$this->refreshPaths($classe);
$this->loadClass();
}
private function commons($classe) {
$this->function = __FUNCTION__;
$this->refreshPaths($classe);
$this->loadClass();
}
private function refreshPaths($classe){
switch ($this->function) {
case 'commons' :
$this->paths = array(
'/usr/share/evokernel/core/common/' . $classe . '.php',
);
break;
case 'controllers':
$this->paths = array(
'core/controllers/' . $classe . '.php',
'modules/' . $this->module . '/controllers/' . $classe . '.php',
'shared/modules/' . $this->module . '/controllers/' . $classe . '.php'
);
break;
default:
throw new Exception('Invalid function: ' . $this->function);
}
}
private function loadClass(){
foreach ($this->paths as $path) {
if (is_file($path)) {
require_once($path);
break;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:19:11.417",
"Id": "84564",
"Score": "0",
"body": "Why are you trying not to use a parameter ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:21:54.110",
"Id": "84567",
"Score": "0",
"body": "@konijn, I read recently \"Clean Code\" by Robert Martin, there he discourages to use parameters, so i am trying to follow this recommendation when possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:37:18.537",
"Id": "84578",
"Score": "0",
"body": "That sounds so wrong ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:39:13.903",
"Id": "84579",
"Score": "0",
"body": "@konijn, I didn't agree completly with this, but i am trying to see the benefits. Do you have a suggestion with parameters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:41:05.257",
"Id": "84580",
"Score": "2",
"body": "Too many parameters is a bad thing, but even in Uncle Bob's own \"clean\" examples, some functions have parameters. I think it is good to avoid using parameters that make the code less readable and understandable, but also advisable to use a parameter (or two, or even three) when the alternative is worse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:45:41.257",
"Id": "84582",
"Score": "0",
"body": "This looks more like bad class design, we could probably help you better if you could post whole class here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:00:07.053",
"Id": "84592",
"Score": "0",
"body": "@Yoda, I inserted more code, please take a look"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:00:50.357",
"Id": "84593",
"Score": "0",
"body": "@konijn, I putted more code, please take a look"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:01:07.860",
"Id": "84594",
"Score": "0",
"body": "@DavidK, There is more code now, please take a look"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:18:21.920",
"Id": "84595",
"Score": "0",
"body": "@MarcioSimao Are you building some kind of framework?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:19:51.443",
"Id": "84596",
"Score": "0",
"body": "Other than swapping out `__FUNCTION__` in favor of `\"register\"` and `\"unregister\"`, I don't see a problem *with these three specific methods* (including `handleOperation`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:27:39.327",
"Id": "84597",
"Score": "0",
"body": "@Yoda, Yes, we are building a micro framework, it will fit better in our system requirements. We had some problems with our old autoloader because now we are using PHP [namespaces](http://www.php.net/manual/en/language.namespaces.php)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:42:39.420",
"Id": "84599",
"Score": "0",
"body": "@MarcioSimao In my opinion duplicating code in this case is alright and is preferable over use of parameters. In the class there is one pretty obvious thing and that is use of Exception. You should rather create something like `class AutoloaderException extends Exception { ... }` and then use it instead of `Exception`. Using just `Exception` is too wide in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T23:45:25.117",
"Id": "84726",
"Score": "0",
"body": "I also think the duplication is OK in this amount. Basically you have two functions that must do the same thing, and you do it by writing the same (single) line of code inside each function. It is hard to imagine a much clearer or more concise way of expressing that idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T12:31:06.940",
"Id": "84933",
"Score": "0",
"body": "@DavidK, Do you preffer with or without parameters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:21:51.397",
"Id": "84936",
"Score": "0",
"body": "Do you mean the register() and unregister() functions? To me, the two-line versions say, \"Here is an operation you might perform if I ask you to (that's the first line); OK, now perform the operation I told you about before (second line).\" Using a parameter, you do have to understand how the parameter relates to the method, but it seems obvious enough in this case. Without the parameter, you not only have to understand how the property relates to the method, you have to understand these two lines aren't doing two independent things, which in my view makes this more complicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:22:30.420",
"Id": "84937",
"Score": "0",
"body": "Short answer: I liked the one-parameter version better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:34:57.173",
"Id": "84942",
"Score": "0",
"body": "@DavidK, I think the same, i am going to use the one-parameter version. Thanks for your colaboration!"
}
] | [
{
"body": "<p>Short version: <strong>Use a parameter!</strong></p>\n\n<pre><code>public function handleOperation($action) {}\npublic function register() { $this->handleOperation(\"register\"); }\npublic function unregister() { $this->handleOperation(\"unregister\"); }\n</code></pre>\n\n<hr>\n\n<p>Slightly longer version: <strong>Don't be a smartass</strong></p>\n\n<p>You don't need to dynamically call <code>spl_autoload_$function</code>, it's pointless and unreadable. Just call <code>spl_autoload_register</code>and <code>spl_autoload_unregister</code>when you need it. It's unlikely for the function names to change.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-12T13:52:38.230",
"Id": "54071",
"ParentId": "48181",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:10:27.043",
"Id": "48181",
"Score": "2",
"Tags": [
"php"
],
"Title": "Find a better logic to remove duplicated code from two different methods"
} | 48181 |
<pre><code>from time import time
def baseRandom():
return hash(str(time()))
def randFromZero(maximum):
return baseRandom() % maximum
def randRange(minimum, maximum):
return randFromZero(maximum - minimum) + minimum
</code></pre>
<p>I ask what's wrong because it seems so simple and stupid. This is something I just thought up one day and put together in 5 minutes, but it seems to generate even and unpredictable results. I've done a couple of simple tests like generating a lot of numbers and looking at the variance between the amount of times each number is generated, and using it to create a little grid which has tiles that are either black or white with equal probability, in which I saw no clear patterns. Hopefully someone who knows a thing or two about this can educate me.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:24:40.463",
"Id": "84569",
"Score": "0",
"body": "How are you intending to use the \"random\" output? Why aren't you using the builtin random functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:35:39.270",
"Id": "84577",
"Score": "0",
"body": "@JeffS I'm not intending to use it and always use the built-in functions. This is just a bit of fun."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:50:17.863",
"Id": "84583",
"Score": "2",
"body": "The `time()` function returns quantized time; the least significant digits of the time are \"chunky\" and usually represent a small subset of available numbers. Hashing the string will introduce more clumpiness; ASCII strings tend to be very sparse, and you are taking the string of a number. The hash function will map to a very small portion of the integer space. Now, the modulus of a small portion of the integer space is an even smaller portion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-07T06:20:12.623",
"Id": "106897",
"Score": "0",
"body": "Worth saying, that (although small) there is a chance that if you run this program on two computers with synchronized clocks they will both generate the same numbers. You could (just for fun) append the PID to what gets hashed. Also, if someone wanted, they could use it to generate the entire series of possible numbers your program could have used in a given time period.\n\nIt looks a little like you have written a poorly seeded PRNG :), consider (for fun) adding more sources of randomish data to the hash input."
}
] | [
{
"body": "<p>It looks like you're relying on running this on a system where the granularity of the time() function is smaller than the amount of time it takes to execute baseRandom(), do what you want with the results, and come back to call baseRandom() again. If not, you'll get more repeating numbers than you should. You're also relying on the result of the hash() function to be sufficiently pseudorandom given the input you're feeding to it.</p>\n\n<p>Detecting an obvious pattern depends on how you look for it. I think Knuth gave an example of a RNG that looked OK when you plotted pairs of numbers on an x-y plane, but if you took three numbers in a row as x-y-z coordinates, and look at the resulting cube from the right direction, you can clearly see a finite number of planes where all the outcomes lie. In other words, just because you tried a couple of things and didn't see a pattern doesn't mean a non-random pattern isn't there.</p>\n\n<p>There are fifteen tests for randomness listed here, if you're interested: <a href=\"http://csrc.nist.gov/groups/ST/toolkit/rng/stats_tests.html\">http://csrc.nist.gov/groups/ST/toolkit/rng/stats_tests.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:14:50.060",
"Id": "48186",
"ParentId": "48182",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "48186",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:11:44.697",
"Id": "48182",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"random",
"reinventing-the-wheel"
],
"Title": "Random number generator based on a hash of the time"
} | 48182 |
<p>I've benchmarked my program, and have discovered that the single function taking the most time is the one that does the following.</p>
<ul>
<li>Takes string that is a delimited list, and splits it into individual strings (Within the program, the individual strings are called statements)</li>
<li>Looks at the individual strings, compares them to a known set of strings (Called a statement library. It contains additional information relating to these strings that I need)</li>
</ul>
<p>I cannot change the input data, since it comes from several different systems, and the closest thing we can get to something in common is a delimited list of strings.</p>
<p>So, enough background, the first implementation of this was a naive set of LINQ statements:</p>
<pre><code>var statements = textStatements
.Select(ts => Library.Statements
.FirstOrDefault(s => ts.Equals(s.FullText, StringComparison.OrdinalIgnoreCase)))
.Where(s => s != null).ToList();
</code></pre>
<p>So, <code>statements</code> is a list of <code>Statement</code> objects, which contain the additional data I need. I figure this is worst case is about O(n^2)-ish.</p>
<p>Once this function was identified as a bottleneck, I made a first attempt at optimizing this function. First, I ensured the split list of statements, and the known list of statements were both sorted, and then implemented this:</p>
<pre><code>var textStatements = SplitStatements(data).ToList();
var statementCount = textStatements.Count;
var libraryCount = Library.Statements.Count;
var libraryOffset = 0;
var foundStatements = new Dictionary<string, Statement>();
for (var i = 0; i < statementCount; i++)
{
var thisStatement = textStatements[i];
for (var j = libraryOffset; j < libraryCount; j++)
{
var currentLibraryStatement = Library.Statements[j];
if (string.Equals(thisStatement, currentLibraryStatement.FullText, StringComparison.OrdinalIgnoreCase))
{
foundStatements[(currentLibraryStatement.Category.Name + currentLibraryStatement.Code).ToUpperInvariant()] = currentLibraryStatement;
libraryOffset = j + 1;
break;
}
if (string.Compare(thisStatement, currentLibraryStatement.FullText, StringComparison.OrdinalIgnoreCase) < 0)
{
libraryOffset = j;
break;
}
}
}
</code></pre>
<p>Essentially, I loop through the statements I need to look up, and start working through the library of statements, remembering where the last statement was found, so I can exclude all statements in the library that are before the last one found.</p>
<p>This did result in a speedup, but not as much as I would hope, hence me throwing this out here to see if I can get another perspective.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:33:35.027",
"Id": "84574",
"Score": "1",
"body": "If I understand correctly. You can store all your library statement words in a dictionary and look them up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:54:48.037",
"Id": "84584",
"Score": "0",
"body": "@hocho, I have absolutely no clue why I didn't think of that. I made that change, and the exclusive time for that function fell through the floor. Make it an answer, and I'll accept it (The new function on top of the list is a constructor that does nothing but set properties...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:21:46.037",
"Id": "84588",
"Score": "0",
"body": "You can also store the library word in a map with a hash value as a key to reduce the look up time in the library to about *O(1)*"
}
] | [
{
"body": "<p>You're just looking to find any <code>textStatement</code>'s that exist in <code>Library.Statements</code>? A <code>HashSet</code> will make easy work of this:</p>\n\n<pre><code>IEnumerable<string> splitInputStatements = SplitStatements(data);\nHashSet<string> inputStatements = new HashSet<string>(splitInputStatements);\n\n// If you're using Library.Statements in this way many times, it might just\n// be a good idea to keep all of them cached in a HashSet to begin with so\n// you don't have to build this.\nIEnumerable<string> libraryStatementTexts = Library.Statements.Select(s => s.FullText);\nHashSet<string> libraryStatements = new HashSet<string>(libraryStatementTexts);\n\n// That's it, this is your result:\nvar matches = inputStatements.Intersect(libraryStatements);\n</code></pre>\n\n<p><a href=\"http://geekswithblogs.net/BlackRabbitCoder/archive/2011/06/16/c.net-fundamentals-choosing-the-right-collection-class.aspx\" rel=\"nofollow\">This site</a> has some handy notes for when to use collections of certain types.</p>\n\n<p>Alternatively, you can skip making inputStatements a <code>HashSet</code> and continue using the <code>IEnumerable</code> directly like so::</p>\n\n<pre><code>inputStatements.Where(is => libraryStatements.Contains(is));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:49:50.670",
"Id": "48189",
"ParentId": "48183",
"Score": "1"
}
},
{
"body": "<p>If I understand correctly. You can store all your library statement words in a dictionary and look them up. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:25:04.223",
"Id": "48195",
"ParentId": "48183",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:21:08.793",
"Id": "48183",
"Score": "3",
"Tags": [
"c#",
"strings"
],
"Title": "Increase performance of string matching function"
} | 48183 |
<p><strong>Background information</strong></p>
<p>I've been asked to write a little Perl script that allows genomic data to be screened against reference files in order to determine locations of specific mutations.</p>
<p>The input file format look like this (information are tab-separated). <strong>In the script it's referred to as <em>Funestus_NON_SYN.txt</em></strong>.</p>
<pre><code>KB669306 9962 . C T 520.77 PASS AC=13;AF=0.929;AN=14;BaseQRankSum=0.540;DP=103;Dels=0.00;EFF=SYNONYMOUS_CODING(LOW|SILENT|cgC/cgT|R15||AFUN012013|||AFUN012013-RA|1|1);FS=0.000;HaplotypeScore=0.0000;MQ0=0;MQRankSum=0.231;ReadPosRankSum=0.694;set=variant-variant2-variant3-variant5-variant6-variant7-variant10 GT:AD:DP:GQ:PL 1/1:0,18:18:42:549,42,0 1/1:0,12:12:33:399,33,0 1/1:0,13:13:39:505,39,0 ./. 0/1:9,4:13:99:104,0,297 1/1:0,17:17:45:570,45,0 1/1:0,18:18:51:624,51,0 ./. ./. 1/1:0,12:12:33:420,33,0
KB669306 10439 . C T 668.77 PASS AC=15;AF=0.938;AN=16;BaseQRankSum=-0.643;DP=139;Dels=0.00;EFF=SYNONYMOUS_CODING(LOW|SILENT|gcC/gcT|A174||AFUN012013|||AFUN012013-RA|1|1);FS=0.000;MQ0=0;MQRankSum=-0.746;ReadPosRankSum=-1.106;set=variant-variant3-variant5-variant6-variant7-variant8-variant9-variant10 GT:AD:DP:GQ:PL 1/1:0,22:22:51:697,51,0 ./. 1/1:0,20:20:48:667,48,0 ./. 0/1:14,12:25:99:317,0,403 1/1:0,15:15:36:469,36,0 1/1:0,16:16:36:499,36,0 1/1:0,13:13:30:415,30,0 1/1:0,14:14:30:412,30,0 1/1:0,13:13:36:492,36,0
KB668289 903 . T C 577.77 PASS AC=14;AF=0.875;AN=16;DP=173;Dels=0.00;EFF=DOWNSTREAM(MODIFIER||3412|||AFUN005870|||AFUN005870-RA||1),SYNONYMOUS_CODING(LOW|SILENT|ctA/ctG|L578||AFUN005868|||AFUN005868-RA|4|1),UPSTREAM(MODIFIER||2667|||AFUN005869|||AFUN005869-RA||1);MQ0=0;set=variant-variant2-variant3-variant5-variant6-variant7-variant9-variant10 GT:AD:DP:GQ:PL 1/1:0,20:20:45:606,45,0 1/1:0,19:19:42:588,42,0 1/1:0,22:22:54:720,54,0 ./. 1/1:0,29:29:63:882,63,0 0/1:16,13:28:99:401,0,391 1/1:0,13:13:30:425,30,0./. 1/1:0,26:26:57:785,57,0 0/1:8,7:15:99:223,0,243
KB668289 1224 . A C 572.77 PASS AC=10;AF=0.833;AN=12;DP=122;Dels=0.00;EFF=DOWNSTREAM(MODIFIER||3091|||AFUN005870|||AFUN005870-RA||1),SYNONYMOUS_CODING(LOW|SILENT|cgT/cgG|R471||AFUN005868|||AFUN005868-RA|4|1),UPSTREAM(MODIFIER||2346|||AFUN005869|||AFUN005869-RA||1);HaplotypeScore=0.0000;MQ0=0;set=variant-variant3-variant6-variant7-variant8-variant9 GT:AD:DP:GQ:PL 1/1:1,20:20:42:601,42,0 ./. 1/1:0,26:26:63:865,63,0 ./. ./. 0/1:9,10:19:99:276,0,236 1/1:0,17:17:42:583,42,0 0/1:14,5:19:99:119,0,406 1/1:0,20:20:45:630,45,0 ./.
</code></pre>
<p>Now, I have to screen the first column against files containing genes in the following format. <strong>Referred to as <em>gsts-funestus.gff</em> in the script</strong></p>
<pre><code># start gene FUNEGST002
KB668289 AUGUSTUS gene 410926 411627 0.18 + . FUNEGST002; gene_name "GSTd3"; auto "g17128_modified";
KB668289 AUGUSTUS transcript 410926 411627 0.18 + . FUNEGST002.t1
KB668289 AUGUSTUS start_codon 410926 410928 . + 0 transcript_id "FUNEGST002.t1"; gene_id "FUNEGST002";
KB668289 AUGUSTUS intron 411058 411126 0.99 + . transcript_id "FUNEGST002.t1"; gene_id "FUNEGST002";
KB668289 AUGUSTUS CDS 410926 411057 0.58 + 0 transcript_id "FUNEGST002.t1"; gene_id "FUNEGST002";
KB668289 AUGUSTUS CDS 411127 411627 0.74 + 0 transcript_id "FUNEGST002.t1"; gene_id "FUNEGST002";
KB668289 AUGUSTUS stop_codon 411625 411627 . + 0 transcript_id "FUNEGST002.t1"; gene_id "FUNEGST002";
# end gene FUNEGST002
</code></pre>
<p>Basically I have to extract the first line containing <code>gene</code> in the 3rd column and print a hybrid output in the following format.</p>
<pre><code>GSTd3 KB668289 903 T=>C AC=14;AF=0.875;AN=16;DP=173;Dels=0.00;EFF=DOWNSTREAM(MODIFIER||3412|||AFUN005870|||AFUN005870-RA||1),SYNONYMOUS_CODING(LOW|SILENT|ctA/ctG|L578||AFUN005868|||AFUN005868-RA|4|1),UPSTREAM(MODIFIER||2667|||AFUN005869|||AFUN005869-RA||1);MQ0=0;set=variant-variant2-variant3-variant5-variant6-variant7-variant9-variant10 GT:AD:DP:GQ:PL 1/1:0,20:20:45:606,45,0 1/1:0,19:19:42:588,42,0 1/1:0,22:22:54:720,54,0 ./. 1/1:0,29:29:63:882,63,0 0/1:16,13:28:99:401,0,391 1/1:0,13:13:30:425,30,0./. 1/1:0,26:26:57:785,57,0 0/1:8,7:15:99:223,0,243
GSTd3 KB668289 1224 A=>C AC=10;AF=0.833;AN=12;DP=122;Dels=0.00;EFF=DOWNSTREAM(MODIFIER||3091|||AFUN005870|||AFUN005870-RA||1),SYNONYMOUS_CODING(LOW|SILENT|cgT/cgG|R471||AFUN005868|||AFUN005868-RA|4|1),UPSTREAM(MODIFIER||2346|||AFUN005869|||AFUN005869-RA||1);HaplotypeScore=0.0000;MQ0=0;set=variant-variant3-variant6-variant7-variant8-variant9 GT:AD:DP:GQ:PL 1/1:1,20:20:42:601,42,0 ./. 1/1:0,26:26:63:865,63,0 ./. ./. 0/1:9,10:19:99:276,0,236 1/1:0,17:17:42:583,42,0 0/1:14,5:19:99:119,0,406 1/1:0,20:20:45:630,45,0 ./.
</code></pre>
<p><strong>The Script</strong></p>
<p>My script contains this part to read and process all lines in the input file.</p>
<pre><code>#!/usr/bin/perl -w
use strict;
use warnings;
print "Enter your input file containing all SNPs [e.g. Funestus_NON_SYN.txt]:\t";
chomp (my $input_file = <STDIN>);
# Open and import the information found in the files #
my @input = &InputFileHandler($input_file);
# Store the gene information in a hash with the key as scaffold and location #
my %genes = ();
foreach (@input)
{
next if $_ !~ /^KB.*/;
my($scaffold,$location,$dot,$start,$end,$unknown,$pass,$rest) = split(/\t/, $_, 8);
my $mutation = "$start=>$end";
my $key = $scaffold."_".$location;
my $value = "$scaffold\t$location\t$mutation\t$rest";
$genes{$key} = $value;
}
</code></pre>
<p>The next part allows the user to define the number of reference files and screens out input file against it. Furthermore, it prints the results in a tab-separated output file.</p>
<pre><code># Open the output file
my $output_file = &GenerateFilename();
open my $fh_out,">",$output_file.".tsv" or die "Cannot open $output_file: $!\n";
# Print the header in the CSV file
print $fh_out "Gene\tSNP\tLocation\tMutation\tRemaining information\n###\n";
print "Enter the number of reference files [e.g. gff files]:\t";
chomp (my $i = <STDIN>);
# Generic loop that let's the user enter as many reference files as required #
for (my $j = 1; $j <= $i;$j++)
{
print "Enter filename $j [e.g. gsts-funestus.gff]:\t";
chomp (my $file = <STDIN>);
my @file_raw = &InputFileHandler($file);
my @file_genes = &ScanArray(@file_raw);
my @file_genes_print = &ScanPrint(@file_genes);
print $fh_out "$_\n" foreach (@file_genes_print);
print $fh_out "\n###\n";
}
</code></pre>
<p>Finally, my subroutines are the following.</p>
<pre><code>sub GenerateFilename # Generates a filename based on the current date and time.
{
my @timeData = localtime(time);
my $filename = join('_', @timeData);
return $filename;
}
sub InputFileHandler # Opens a file and saves its content in an array
{
my $file = shift;
my @lines;
open my $fh,"<",$file or die "Cannot open $file: $!\n";
while (my $line = <$fh>)
{
chomp($line);
push (@lines,$line);
}
close ($fh);
return @lines;
}
sub Information # Separates the mutation from the remaining information
{
my $rest = shift;
my @rest = split (/\t/,$rest);
my $aa_change = "$rest[1]=>$rest[2]";
my $return = "$aa_change,$rest[5]";
return $return;
}
sub ScanArray # Scans a file array for lines containing SNPs, discards rest
{
my @array = @_;
my @return;
foreach (@array)
{
next if $_ !~ /^KB.*\t.*\t[Gg][Ee][Nn][Ee]/;
my ($scaffold,$second,$type,$start,$end,$sixth,$seventh,$eigth,$info) = split (/\t/,$_);
my ($unknown,$gene_name,$auto) = split (/; /,$info,3);
$gene_name =~ s/.*"(.*?)".*/$1/s;
my $gene = $scaffold."_".$gene_name;
push (@return,$gene);
}
return @return;
}
sub ScanPrint # Filters for genes that contain SNPs
{
my @array = @_;
my @return;
foreach (@array)
{
my ($scaffold,$gene_name) = split (/_/,$_,2);
foreach my $key (keys %genes)
{
next if $key !~ /$scaffold/;
my $line = "$gene_name\t$genes{$key}";
push (@return, $line);
}
}
return @return;
}
</code></pre>
<p><strong>Question</strong></p>
<p>Do you people have any suggestions or ways of improving this script. It all works and no warnings have been returned with all search queries I've done (I used different files of the same format).</p>
<p><strong>EDIT 1</strong></p>
<p>As pointed out to me by @Edward: Yes, my output should be the two lines. I have adjusted it in the main part of the question.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:20:57.043",
"Id": "84587",
"Score": "0",
"body": "When I run your script, the output contains two lines both for KB668289: one for location 903 and the other for 1224. Is it correct? Your descriptions seems to indicate that only the first line (location 903) should be output."
}
] | [
{
"body": "<h1>Style Guides</h1>\n\n<p>The Perl community does not have a single universal style – there is more than one way to do it. But sometimes, consistency isn't a bad thing either. Here are the three important cornerstones of Perl style:</p>\n\n<ul>\n<li>A <a href=\"https://metacpan.org/pod/distribution/perl/pod/perlstyle.pod\" rel=\"nofollow\"><code>perlstyle</code> manpage</a> exists which explains a sensible core of a style guide.</li>\n<li>Damian Conway published the <a href=\"http://shop.oreilly.com/product/9780596001735.do\" rel=\"nofollow\">Perl Best Practices</a> book with many valuable tips, although I'd view his preferences as over-zealous.</li>\n<li>The <code>perlcritic</code> tool exists to automatically check your code for a set of style violations. It's inspired by Perl Best Practices. You can install it via the <a href=\"https://metacpan.org/pod/Perl%3a%3aCritic\" rel=\"nofollow\">Perl::Critic</a> module. You can layout your code automatically with <code>perltidy</code>, installable via <a href=\"https://metacpan.org/pod/distribution/Perl-Tidy/bin/perltidy\" rel=\"nofollow\">Perl::Tidy</a>.</li>\n</ul>\n\n<p>Based on those references, I make the recommendations below.</p>\n\n<h1>Objective Style Issues</h1>\n\n<p>Now lets look at what you've written.</p>\n\n<ul>\n<li><p>Don't use the <code>-w</code> command line flag, only <code>use warnings</code>, and use it always. They are fundamentally the same (they activate warnings), but <code>-w</code> has an unfortunate global effect. In your case it doesn't matter, but <code>-w</code> is a bad habit to get into.</p></li>\n<li><p>Don't call functions with an ampersand, like <code>&foo()</code>. This has a specific meaning (it disables so-called prototypes), but it hasn't been necessary to use it for over 20 years. Simply invoke your functions like <code>foo()</code>.</p></li>\n<li><p>When looping over a range, do not use the C-style <code>for (my $j = 1; $j <= $i; $j++)</code>. Instead, use the range operator, and a foreach loop:</p>\n\n<pre><code>for my $j (1 .. $i) {\n</code></pre></li>\n<li><p>Since perl 5.10.0 (released 2007), you can <code>use feature 'say'</code> to enable the <code>say</code> function. It behaves exactly like <code>print</code> but always appends a newline, making it more convenient to use in most cases.</p></li>\n<li><p>The keywords <code>for</code> and <code>foreach</code> are absolutely equivalent, so we'd use the shorter form. When used as a statement modifier, the parens around the iterated values are optional:</p>\n\n<pre><code>... for @file_genes_print;\n</code></pre></li>\n<li><p>In a foreach loop, always name the iteration variable rather than using <code>$_</code>. This is not possible in the statement modifier use case.</p>\n\n<pre><code>for my $iteration_variable (@list) {\n ...\n}\n</code></pre></li>\n<li><p>Hash variables are initialized by declaration. Assigning them the empty list is unnecessary – <code>my %hash;</code> rather than <code>my %hash = ();</code>.</p></li>\n<li><p>For readability, any comma should be followed by a space.</p>\n\n<pre><code>open my $fh_out, \">\", \"$output_file.tsv\" or die ...\n</code></pre></li>\n<li><p>Prefer interpolation over concatenation. <code>$scaffold.\"_\".$location</code> could be <code>\"${scaffold}_${location}\"</code> and <code>$output_file.\".tsv\"</code> could be <code>\"$output_file.tsv\"</code>.</p></li>\n<li><p>Sometimes, <code>join</code> is more preferable than both interpolation or concatenation. For example, <code>\"$scaffold\\t$location\\t$mutation\\t$rest\"</code> becomes more readable as</p>\n\n<pre><code>join \"\\t\", $scaffold, $location, $mutation, $rest\n</code></pre></li>\n<li><p>The <code>print</code> (and <code>say</code>) syntax is horrible because of the difference between <code>print $foo $bar</code> and <code>print $foo, $bar</code> – the former prints <code>$bar</code> to the filehandle <code>$foo</code>, whereas the latter prints <code>\"$foo$bar\"</code> to the currently selected filehandle (usually STDOUT).</p>\n\n<ul>\n<li><p>We could use the object-oriented interface.</p>\n\n<pre><code>use IO::File;\n$foo->print($bar);\n</code></pre></li>\n<li><p>We can use curly braces for the indirect object notation</p>\n\n<pre><code>print { $foo } $bar\n</code></pre></li>\n</ul>\n\n<p>I'd recommend to always use the curly braces. You only really need them when the file handle is something else than a simple variable, but it's a good visual distinction.</p></li>\n<li><p>The <code>ScanPrint</code> uses the <code>%genes</code> hash which is therefore essentially a global variable. Instead, pass it in as an argument:</p>\n\n<pre><code>scan_print(\\%genes, @file_genes);\n\n...\n\nsub scan_print {\n my ($genes, @array) = @_;\n ...\n for my $key (keys %$genes) {\n</code></pre></li>\n<li><p>Don't load a whole file into memory unless you have to. If you can, process files line-by-line. Especially your use of <code>InputFileHandler</code> violates this. On the other hand this may be absoluetly OK for smaller files, or when you are going to use that amount of memory anyway.</p></li>\n</ul>\n\n<h1>Subjective Style Issues</h1>\n\n<ul>\n<li><p>Variable and function names should generally be <code>snake_case</code>: lowercase, and words separated by underscores. You apply this for variables, but not for subroutine names.</p></li>\n<li><p>Consider using the K&R style/egyptian brackets. This means that the opening curly brace is on the same line as it's introducing keyword and not on a line of its own:</p>\n\n<pre><code>for (...) {\n ...\n}\n</code></pre>\n\n<p>Why? For no other reason than that most Perl programmers do this.</p></li>\n<li><p>It is customary to call builtins without parentheses. This is partly because builtins are actually operators, not functions, and partly because it looks nicer. So let's do <code>close $fh</code> rather than <code>close ($fh)</code>.</p></li>\n<li><p>In regexes, put symbols into character classes to emphasize them: <code>/; /</code> might become <code>/[;][ ]/</code>.</p></li>\n</ul>\n\n<h1>Performance Issues, Bugs, and Other Notes</h1>\n\n<ul>\n<li><p>You are using a regex <code>/^KB.*/</code>. The trailing <code>.*</code> is entirely unnecessary as this always matches any string. Remove it: <code>/^KB/</code>.</p></li>\n<li><p>Do not prompt for file names. Instead, take these from the command line arguments. The arguments are in the <code>@ARGV</code> array. So you could do:</p>\n\n<pre><code>my ($input_file, @reference_files) = @ARGV;\n</code></pre>\n\n<p>and invoke your script like <code>perl my_script.pl input_file.tsv ref1 ref2</code>.</p></li>\n<li><p><code>$key !~ /$scaffold/</code> interprets <code>$scaffold</code> as a regex. To test that <code>$key</code> does not contain the <code>$scaffold</code>, use the more efficient <code>-1 == index $key, $scaffold</code>. To test that they are not equal, use <code>$key ne $scaffold</code>, in which case you could reduce the surrounding loop to</p>\n\n<pre><code>if (exists $genes{$scaffold}) {\n push @return, \"$gene_name\\t$genes{$scaffold}\";\n}\n</code></pre></li>\n<li><p>The substitution <code>s/.*\"(.*?)\".*/$1/s</code> is iffy. If you want to match a quoted string, <code>\"[^\"]*\"</code> is simpler for the regex engine to handle than <code>\".*?\"</code>. Of course, it also doesn't support escapes.</p>\n\n<p>If you want to replace the whole string by the thing in the quotes, just use a normal match rather than a substitution, e.g:</p>\n\n<pre><code>if ($gene_name =~ /[\"]([^\"]*)[\"]/) {\n $gene_name = $1;\n}\n</code></pre>\n\n<p>which is more straightforward.</p></li>\n<li><p>Creating a time-based filename is fragile and unintuitive for a user. Instead, let the user specify the output file name manually. Alternatively, generate a more unique filename (e.g. by using the process ID <code>$$</code> in the filename).</p>\n\n<p>Another approach, which I have taken below, is to print to standard output, and let the user write the results to a file using shell redirection.</p></li>\n<li><p>The <code>Information</code> subroutine isn't used.</p></li>\n</ul>\n\n<h1>Suggested Rewrite</h1>\n\n<p>This rewrite doesn't use any prompting (instead it uses command line arguments and shell redirection), and it doesn't use any subroutines. The result should be shorter, simpler, and more efficient.</p>\n\n<p>This code has not been tested.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\nuse feature 'say';\n\n# we take the input file as STDIN\n# and the output file as STDOUT\n# the user can redirect this to desired files:\n# $ perl my_script.pl ref1 ref2 <input >output\n\nmy @reference_files = @ARGV;\n\n# early input validation\nif (not @reference_files) {\n die \"You have to specify at least one reference file as argument\\n\";\n}\nfor my $file (@reference_files) {\n die \"The reference file '$file' does not exist\\n\" if not -e $file;\n}\n\n# parse the input file\nmy %genes;\nwhile (my $line = <STDIN>) {\n chomp $line;\n next if not $line =~ /^KB/;\n my ($scaffold, $location, $dot, $start, $end, $unknown, $pass, $rest) = split /\\t/, $line, 8;\n $genes{$scaffold}{$location} = join \"\\t\", $scaffold, $location, \"$start=>$end\", $rest;\n}\n\n# print the header\nsay join \"\\t\", 'Gene', 'SNP', 'Location', 'Mutation', 'Remaining Information';\nsay \"###\";\n\n# go through each reference file\nfor my $file (@reference_files) {\n open my $ref, \"<\", $file or die \"Can't open reference file '$file': $!\";\n while (my $line = <$ref>) {\n chomp $line;\n my ($scaffold, undef, $type, $start, $end, undef, undef, undef, $info) = split /\\t/, $line;\n next if not $scaffold =~ /^KB/;\n next if not $type =~ /^GENE/i;\n\n my ($transcript_id, $gene_name, $auto) = split /[;][ ]/, $info;\n $gene_name = $1 if $gene_name =~ /[\"]([^\"]*)[\"]/;\n\n if (my matching_genes = $genes{$scaffold}) {\n say join \"\\t\", $gene_name, $_ for values %$matching_genes;\n }\n }\n\n say \"\";\n say \"###\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T08:46:48.203",
"Id": "84626",
"Score": "0",
"body": "Thanks very much for the extended explanations and code. I have a few questions that I'd like to ask you to explain to me. \n**1.** In another answer you pointed out that using `undef` is not very good practice (review by Edward). How come you decided to use it here?\n`my ($scaffold, undef, $type, $start, $end, undef, undef, undef, $info) = split /\\t/, $line;`\n**2.** How is the key defined in this `$genes{$scaffold}{$location}`? Are the two words simply concatenated or *connected* by a meta-character?\n\nExcept that, very nice code! Got a lot to learn by the looks of it ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T12:12:25.097",
"Id": "84638",
"Score": "0",
"body": "@Felix_Sim (1) Well, variables are good because they help documenting the code, but unused variables are bad because they are confusing (why do we have a variable if we are not going to use it?). So I used variables wherever there was a good name that actually contributed to the readability of the code, but `undef` when there was no such name and I wanted to discard a value. It's good to be aware of this feature that you can discard values with `undef` in a list assignment, but *when* to use it is a bit subjective."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T12:12:52.277",
"Id": "84639",
"Score": "0",
"body": "(2) my `%genes` is a hash with another hash as value. The 1st level uses `$scaffold` as key. That gets us another hash for which `$location` is the key. If the 2nd level doesn't already exist, it's created transparently. (cont…)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T12:13:13.153",
"Id": "84640",
"Score": "0",
"body": "(…cont) Later we want all entries with a matching `$scaffold`. So we use a constant-time lookup (rather than slowly looping through all keys) which gives us the 2nd level (or `undef` if that doesn't exist). We then display the `values` in this 2nd level, which are the strings. To learn more about complex data structures, start with [perlreftut](http://perldoc.perl.org/perlreftut.html)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:59:11.137",
"Id": "48197",
"ParentId": "48184",
"Score": "6"
}
},
{
"body": "<h2>Scan file directly into data structures</h2>\n\n<p>You have a routine <code>InputFileHandler</code> that puts every line of an input file into an array. That array is then subsequently dissected into either the <code>%genes</code> hash or <code>@file_genes</code> array. What would be more Perl-ish would be to avoid the intermediate step and scan directly into the desired data structures. That would eliminate <code>InputFileHandler</code> and modify and rename <code>ScanArray</code>.</p>\n\n<h2>Remove unused <code>Information</code> subroutine</h2>\n\n<p>It's possible that it's needed for some other processing that you intend to do, however. If that's the case, I'd suggest renaming it to be a little more suggestive of its purpose. The comment suggests that a better name might be <code>ExtractMutation</code>.</p>\n\n<h2>Use <code>undef</code> rather than dummy variable names for split</h2>\n\n<p>When you're <code>split</code>ting variables, use <code>undef</code> instead of dummy variable names. It will be clearer to those who read the code which fields are not of interest and your program will run faster and with less memory as a result.</p>\n\n<h2>Prefer command line arguments to interactive I/O</h2>\n\n<p>It's easier and more clear if you accept command-line arguments as filenames rather than prompting for them. Since you have one input file and then one or more gff files, you can treat the first argument as the <code>txt</code> file and all subsequent args as <code>gff</code> files.</p>\n\n<h2><code>GenerateFilename</code> might be improved</h2>\n\n<p>The current <code>GenerateFilename</code> function generates filenames from timestamps, which might not be too bad, but it does so in a way that will make it difficult to parse the resulting files because the seconds are first, followed by minutes, hours, etc. Better would be to generate file names in a way that they can be rationally sorted (e.g. with year, month, day first) or to omit generation of output filenames entirely and assume that the user will redirect output to an appropriately named file. This is what I would choose, but your application may dictate some other choice, which is why I left it in place in the example code below.</p>\n\n<h2>Consolidate reading and output</h2>\n\n<p>Once the <code>%genes</code> memory structure is populated, there seems to be little use in storing the subsequent <code>gff</code> file contents in memory. Better would be to process each <code>gff</code> line as received and correlate it to the matching <code>%genes</code> for immediate output. This will save a lot of runtime memory and be faster.</p>\n\n<h2>Results:</h2>\n\n<p>With all of that done, my rewrite looks like this:</p>\n\n<pre><code>#!/usr/bin/perl \n\nuse strict;\nuse warnings;\n\nmy $input_file = shift;\n\n# Store the gene information in a hash with the key as scaffold and location #\nmy %genes;\nopen my $fh,\"<\",$input_file or die \"Cannot open $input_file: $!\\n\";\nwhile (<$fh>)\n{\n next if $_ !~ /^KB.*/;\n chomp;\n my($scaffold,$location,undef,$start,$end,undef,undef,$rest) = split(/\\t/, $_, 8);\n my $mutation = \"$start=>$end\";\n my $key = \"$scaffold\\_$location\";\n my $value = \"$scaffold\\t$location\\t$mutation\\t$rest\";\n $genes{$key} = $value;\n}\nclose $fh;\n\n# Open the output file\nmy $output_file = &GenerateFilename();\nopen my $fh_out,\">\",$output_file.\".tsv\" or die \"Cannot open $output_file: $!\\n\";\n\n# Print the header in the CSV file\nprint $fh_out \"Gene\\tSNP\\tLocation\\tMutation\\tRemaining information\\n###\\n\";\n\n# Generic loop that lets the user enter as many reference files as required\nwhile (my $file = shift) {\n &ReadSNPFile($fh_out, $file);\n}\nprint $fh_out \"\\n###\\n\";\n\nsub GenerateFilename # Generates a filename based on the current date and time.\n{\n my @timeData = localtime(time);\n my $filename = join('_', @timeData);\n return $filename;\n}\n\n# passed an output file name, and an SNP filename, \n# this scans the file for lines containing SNPs\n# and emits matches.\n#\nsub ReadSNPFile \n{\n my $out_file = shift;\n my $file = shift;\n open my $fh,\"<\",$file or die \"Cannot open $file: $!\\n\";\n while (<$fh>)\n {\n next if $_ !~ /^KB.*\\t.*\\t[Gg][Ee][Nn][Ee]/;\n my ($scaffold,undef,undef,undef,undef,undef,undef,undef,$info) = split (/\\t/,$_);\n my ($unknown,$gene_name,$auto) = split (/; /,$info,3);\n $gene_name =~ s/.*\"(.*?)\".*/$1/s;\n foreach my $key (keys %genes)\n {\n next if $key !~ /$scaffold/;\n print $out_file \"$gene_name\\t$genes{$key}\\n\";\n }\n }\n close ($fh);\n}\n</code></pre>\n\n<p>I've tested it and it produces results identical to your original but in about half the number of lines of code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T05:54:29.423",
"Id": "84617",
"Score": "0",
"body": "I partially disagree about using `undef` for any unused variable in a list assignment. The variable names serve as valuable documentation of the file format, and the amount of memory wasted with those unused variables should be negligible. Otherwise, very nice review!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:58:22.923",
"Id": "84714",
"Score": "0",
"body": "It's true that there is likely little memory used by such \"dummy\" variables, but it's also the case that variable names such as `fifth`, `sixth`, etc. don't really add much in the way of useful documentation. If they were more meaningful names, they might be worth retaining, but in this particular case, it seemed that they were more just visual clutter. In general, though, your point is a good one. It's the kind of thing that should be decided on a case-by-case basis, I think."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T02:27:53.020",
"Id": "48206",
"ParentId": "48184",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48197",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T19:44:41.380",
"Id": "48184",
"Score": "4",
"Tags": [
"perl",
"csv",
"bioinformatics",
"join"
],
"Title": "Data screening using Perl"
} | 48184 |
<p>I have finally finished creating my first real project. It's just a simple music player that can provides the user with the latest music from any site (as long as it contains MP3 files) he provides in the settings file. It can play it, download it and has an simple settings file from which the user can: add/change sites to get music from and change the music player used when playing music. It was first created as a simple bash script to play music to keep me focused when learning programming, but I think that after its development it can be treated as a self-contained music program.</p>
<p>I would really appreciate it if anybody can check it for me. I would also like to hear suggestions or improvements about it since this would really help me along the way.</p>
<pre><code>#!/bin/bash
cd "$HOME/Music" # So that any download will be in the music directory
######################################### Initial Values and Declarations ######################################
declare -r settings_file='/usr/local/settings/PlayMusic.settings';line_number=0;declare SITES=();declare -A Tracks;declare -r OlD="$IFS";declare all=false;
declare player='mplayer';declare FILE;declare TIMES=1;declare FILE2;declare no_choice=true;declare only_download=false;declare restricted=false;
############################################## Functions ##############################################
function Play { # Function for playing music according to user preferences
if $2 && [[ ${#1} -lt 23 ]];then notify-send "Now Playing: \"$1\" .." "$track";fi # Notifing the user,only if he'll play freely ($2 ) & the track's name isn't too long
for ((i=0; i<TIMES; i++));do $player "$1";done
}
function Find { # function to look for a previously downloaded file on disk
unset FILE;echo "Looking for '$1' on disk .. "; # Informing the user, if that's going to take long ( which depends on the contents of his home directory )
local FILES=$(find ~ -name "$1*.mp3" 2>/dev/null);clear # The main file ( the found file, or null if not found ) ..
if [[ $(echo "$FILES" | wc -l) -gt 1 ]];then
IFS=$'\n';echo 'File was found at various places .. Which one to use ?';local file
select file in $FILES; do
[[ -n $file ]] || continue
FILE="$file";break
done
read -p 'Do you want to Delete the other ones ? ' rrf
if IsYes $rrf;then for file in $FILES;do if ! [[ "$file" == "$FILE" ]];then rm "$file";fi;done;IFS="$OlD";fi
else FILE="$FILES";fi;clear
}
function IsYes { d=$(echo $1 | tr [[:upper:]] [[:lower:]]);if ([[ "${d:0:1}" == 'y' ]] && [[ "${#d}" -le 4 ]]) || [[ $d == 'ok' ]];then return 0; else return 1;fi; }
function create_settings_file {
local tmp_file="$HOME/Desktop/File_$RANDOM"
cat > $tmp_file <<- EOF
mplayer \# the first line is always the media player
\# other than that is only sites ..
http://ccmixter.org/view/media/samples/mixed
http://ccmixter.org/view/media/remix
http://mp3.com/top-downloads/genre/jazz/
http://mp3.com/top-downloads/
http://mp3.com/top-downloads/genre/rock/
http://mp3.com/top-downloads/genre/hip hop/
\# empty or fully-commented lines are ignored ..
http://mp3.com/top-downloads/genre/emo/
http://mp3.com/top-downloads/genre/pop/
\# PS: '#' is marking a comment , and is ignored by the settings parser ..
EOF
sudo mv $tmp_file '/usr/local/settings/PlayMusic.settings'
rm $tmp_file &>/dev/null # just in case ..
}
function DOWNLOAD {
local name="$track.mp3";Find "$track" # Looking for the specified track on disk
if [[ -n $FILE ]] ;then # if the track was found on disk
[[ $(dirname "$FILE") == "$HOME/Music" ]] || { # if the found file is not in the music directory
notify-send "$track was found at ($(dirname $FILE)) and was moved to ($HOME/Music)" # inform the user of the changes
mv "$FILE" "$HOME/Music" &>/dev/null;FILE="$HOME/Music/$name" # move the file to the music home directory
}
name="$FILE"
fi;notify-send "Downloading ($track) .." "in [ $PWD ] ..";wget -cO "$name" "${Tracks[$track]}" && Play "$name" true
}
function UNINSTALL {
read -p 'Do you want to keep settings ? '
if ! IsYes $REPLY;then sudo rm '/usr/local/settings/PlayMusic.settings';fi
sudo rm '/usr/local/bin/PlayMusic'
sudo rm '/usr/local/man/man1/PlayMusic.1.gz'
echo 'Uninstallation Success !';exit 0
}
function load_sites {
local counter=0;IFS="$OlD" # recreating Everything ..
for SITE in "${SITES[@]}";do
echo -e "\tSite #$((++counter)): '$SITE'"
for site in $(lynx -source "$SITE" | egrep -o 'http://.*\.mp3');do # Grabbing all music links ( newline delimeted )
local name="$(echo $site | sed -Ee 's/_/ /g' -e 's#.*/##g' -e 's#.mp3##g' -e 's#.*%2D ##g' -e 's#%2B# #g' |
sed -Ee "s#%2527#\'#g" -e 's#%2528#(#g' -e 's#%2529#)#g' -e 's#.* - ##' -e "s#(\w+) (s$|s )#\1'\2#")" # Filtering names out of sites ..
if echo "$name" | grep -q '%';then continue;fi
if $restricted;then
local dupp=false;local Ty
for Ty in "${!Tracks[@]}";do if (echo "$Ty" | grep -Eq ".* - $name") || (echo "$name" | grep -Eq ".* - $Ty");then dupp=true;break;fi;done
if $dupp;then continue;fi
fi
Tracks[$name]="$site" # Adding the name as the key, and the site as the value
done
done;clear
if [[ ${#Tracks[@]} == 0 ]];then echo 'No Music was Found ! '
echo 'Please either check your internet connection or recreate the settings file using "( '"$(basename $0) -s )"'"' >&2;exit 1;fi # Just in Case ;)
}
function parse_settings { # function to parse settings file
IFS=$'\n'
if [[ -f $settings_file ]];then
for line in $(cat /usr/local/settings/PlayMusic.settings | sed -Ee 's/^ +//g' -e 's/(.*) *#.*/\1/g' -e 's/( *)$//g' -e 's/ *#.*//g');do
[[ -n $line ]] || continue
case $((++line_number)) in
1 ) player="$line";;
* ) SITES[${#SITES[@]}]="$line";;
esac
done
else
notify-send "Settings File not Found .. !";read -p "You haven't created your settings file .. Do you want to create it ? ";
if IsYes $REPLY; then create_settings_file;sudo nano $settings_file;notify-send 'Done !'
else echo 'Then, The Default settings are going to be used this time ..';fi
fi;IFS="$IFS";if [[ ${#SITES[@]} == 0 ]];then SITES=('http://ccmixter.org/view/media/samples/mixed');fi # If no Site was specified in the settings file
}
############################################### Parsing Arguments #################################
while getopts r:svdupaR opt;do # Getting options
case $opt in
r ) if IsNum "$OPTARG" && [[ "$OPTARG" -gt 1 ]];then TIMES="$OPTARG";else echo 'Invalid Number of Times ..' >&2;fi;;
s ) create_settings_file;notify-send "Settings File Recreated Successfully !";exit 0;;
v ) read -p 'Editor ? ';sudo $REPLY '/usr/local/settings/PlayMusic.settings';exit 0;;
u ) read -p 'Are you sure you want to UnInstall ? ';if IsYes $REPLY;then UNINSTALL;fi;;
d ) only_download=true;no_choice=false;; # download without asking
p ) only_download=false;no_choice=false;; # play online without asking
a ) all=true;;
R ) restricted=true;; # turn on restricted mode ( it is an experimantal feature for now .. )
esac
done
############################################### Starting Work #####################################
parse_settings;clear;echo "Loading (${#SITES[@]}) Sites ..";load_sites
function EVERYTHING {
if ! $no_choice;then
$only_download && notify-send 'Downloading Everything .. !' || notify-send 'Playing Everything .. !'
for track in "${!Tracks[@]}";do
$only_download && DOWNLOAD || Play "${Tracks[$track]}"
done;exit 0
fi
echo 'What "all" ? '
select opt in 'Download All' 'Play All' 'Cancel'
do [[ -n $opt ]] || continue;no_choice=false;
[[ "$opt" == 'Download All' ]] && only_download=true
[[ "$opt" == 'Cancel' ]] && { all=false;return 1;no_choice=true; }
break;done
EVERYTHING
}
$all && EVERYTHING
select track in "${!Tracks[@]}";do # interacting with the USER ..
[[ -n $track ]] || continue # Continues the loop if choice is empty ( meaning that user's choice wasn't appropriate ) ..
clear;if $only_download && ! $no_choice;then DOWNLOAD;exit 0;elif ! $only_download && ! $no_choice;then Play "${Tracks[$track]}" true;fi
echo 'What do you want to do ?';name="$track.mp3" # Setting the name and asking the user ..
select choice in "Download then Play" "Just Play Online";do [[ -n $choice ]] || continue # ( already demonstrated )
if [[ $choice == "Download then Play" ]];then DOWNLOAD
else Play "${Tracks[$track]}" true # Play Online
fi;break
done;break
done;exit 0
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T18:45:47.043",
"Id": "86408",
"Score": "0",
"body": "I updated the code [here](http://codereview.stackexchange.com/questions/49128/bash-music-player-2) .."
}
] | [
{
"body": "<p>Whitespace is not a precious resource: your code is <strong>far</strong> too dense for my taste</p>\n\n<ul>\n<li>fewer semicolons, more newlines.</li>\n<li>try to limit your line length to 90 chars for readability</li>\n</ul>\n\n<p>You rely upon the presence of ~/Music, but never test that it exists.</p>\n\n<ul>\n<li>add <code>mkdir -p \"$HOME/Music\"</code> at the top</li>\n</ul>\n\n<p>Variable names: stick with one style, and don't make that style UPPER_CASE (one day you'll accidentally use <code>PATH=something</code> and then your script cannot find any programs anymore.</p>\n\n<p>If you're changing <code>$IFS</code> in a function, use <code>local IFS=...</code> to localize the change to that function.</p>\n\n<p>Use <code>mktemp</code> for creating temp files.</p>\n\n<p>Use ~/.config for user-specific configuration files instead of /usr/local/settings (where you need root-access)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:53:05.567",
"Id": "48520",
"ParentId": "48187",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48520",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:15:35.817",
"Id": "48187",
"Score": "5",
"Tags": [
"beginner",
"bash",
"shell",
"unix",
"audio"
],
"Title": "Bash Music Player"
} | 48187 |
<pre><code> \0
/ \
a b-a-t-s
/|\
m s t
</code></pre>
<p>which contains [am, as, at, bat, bats]</p>
<p>The goal I'm trying to reach is to iterate through the trie to find if there's a next word or not, then if so get that word.</p>
<p>I would like to know your opinion on my approach.</p>
<p>The goal for this is that, at any point in the trie if there is a node that hasn't been visited, there's another word.</p>
<pre><code>public boolean hasNext() {
if (position < this.trie.nodeCount()) return true;
return false;
}
</code></pre>
<p>What I'm trying to go for here is to check to see if the trie is not empty, then at the first trienode in the trie traverse it's children and descendants to find the next word in the trie. so for the trie above it would would go to a then first to m then back to a to s, then t. then eventually go onto b and it's children. then on the way, if it passes a full word, it will repeat that. so in this case, since bat is part of bats it would return 'bat' first then on the next iteration return bats</p>
<p>The logic in plain words is</p>
<pre><code>string temp = null
if has next
while current != null
look at current nodes children
keep track of nodes visited
(temp += char at that node)
current = current nodes next node in trie (so a step down the trie)
if fullword at that node found return next
return false;
</code></pre>
<p>I also thought of trying a pre-order traversal but couldn't figure out how to do it with the arrays.</p>
<p>Current implementation:</p>
<pre><code>public String next() {
String next = null;
if(hasNext()){
current = trie.root.children[position];
while(!current.children[position].isEndOfWord()){
position++;
current = current.children[position];
next += current.letter;
if (current.isEndOfWord()) return next;
}
}
return null;
}
</code></pre>
<p>Here's the declaration of the trienodes:</p>
<pre><code> protected char letter = ' ';
protected TrieNode parentNode = null;
protected boolean fullWord = false;
protected TrieNode[] children = new TrieNode[26];
protected int prefixes = 0;
public TrieNode(char letter, TrieNode parentNode){
this.letter = letter;
this.parentNode = parentNode;
}
</code></pre>
<p>How the trie is built:</p>
<pre><code>public void addWord(String s) {
if (hasWord(s)) return;
int index = 0;
TrieNode current = root;
char[] letters = s.toCharArray();
while(index < s.length()){
TrieNode child = current.children[letters[index] - 97];
if(child == null){
child = new TrieNode(letters[index], current);
child.prefixes++;
numOfNodes++;
}
current = child;
index++;
if(index == s.length()){
current.fullWord = true;
numOfWords++;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>This doesn't look too bad to me, though it would be nice to have the full source code that I could run. I'll comment on the things that stand out to me, though.</p>\n\n<p><strong>Unncessary logic</strong></p>\n\n<pre><code>public boolean hasNext() {\n if (position < this.trie.nodeCount()) return true;\n return false;\n}\n</code></pre>\n\n<p>can be written simply as </p>\n\n<pre><code>public boolean hasNext() {\n return position < this.trie.nodeCount();\n}\n</code></pre>\n\n<p><strong>Whitespace is your friend</strong></p>\n\n<p>This is purely stylistic, but to me</p>\n\n<pre><code> if (hasNext()) {\n</code></pre>\n\n<p>is much easier on the eyes than</p>\n\n<pre><code> if(hasNext()){\n</code></pre>\n\n<p>A lot of IDEs provide automatic formatting to do this for you, too (In Eclipse, Window -> Preferences -> Java -> Code Style -> Formatter).</p>\n\n<p><strong>More on the <code>next</code> method</strong></p>\n\n<ul>\n<li><p>Avoid nulls if you can. See <a href=\"https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained\" rel=\"nofollow\">Google Guava's rational</a> and <em>Effective Java</em> Item 43. If you initialize <code>next</code> to <code>\"\"</code> instead of <code>null</code>, you can avoid some potential errors downstream.</p></li>\n<li><p>This can be simplified:</p>\n\n<pre><code>position++;\ncurrent = current.children[position];\n</code></pre>\n\n<p>to just</p>\n\n<pre><code>current = current.children[++position];\n</code></pre></li>\n<li><p>Alarm bells should be going off anytime you're iteratively adding to a <code>String</code>. You should be using a <code>StringBuilder</code> instead. Read more about them <a href=\"http://docs.oracle.com/javase/tutorial/java/data/buffers.html\" rel=\"nofollow\">here</a>.</p></li>\n<li><p>Using an <code>if</code> statement without brackets is rarely a good idea.</p></li>\n<li><p>Some standards discourage more than one return statement per method.</p></li>\n</ul>\n\n<p>With that said, here is how I would refactor the method:</p>\n\n<pre><code>public String next() {\n StringBuilder next = new StringBuilder();\n\n if (hasNext()) {\n current = trie.root.children[position];\n while (!current.children[position].isEndOfWord()) {\n next.append(current.children[++position]);\n if (current.isEndOfWord()) {\n break;\n }\n }\n }\n\n return next.toString();\n}\n</code></pre>\n\n<p><strong>Regarding <code>TrieNode</code></strong></p>\n\n<ul>\n<li><p>Why are the fields <code>protected</code>? This suggests that the class is to be extended. If that's the case, <code>TrieNode</code> should be abstract (See <a href=\"https://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow\">Open-Closed principle</a> and <em>Effective Java</em> Item 17: \"Design and document for inheritance or else prohibit it\").</p></li>\n<li><p>If <code>letter</code> and <code>parentNode</code> variables don't change, you can make them <code>final</code> (again, IDEs like Eclipse can also do this automatically for you).</p></li>\n<li><p>On the line</p>\n\n<pre><code>protected TrieNode[] children = new TrieNode[26];\n</code></pre>\n\n<p>26 is a magic number, and should be replaced with a constant.</p></li>\n</ul>\n\n<p><strong>Final thoughts on <code>addWord</code></strong></p>\n\n<ul>\n<li><p>Use a <code>for</code> loop instead of the current <code>while</code> loop. Then you can remove two lines that deal with updating <code>index</code>.</p></li>\n<li><p>Instead of </p>\n\n<pre><code>TrieNode child = current.children[letters[index] - 97];\n</code></pre>\n\n<p>you should be able to go</p>\n\n<pre><code>TrieNode child = current.children[letters[index] - 'a'];\n</code></pre>\n\n<p>which has the benefit of not using a magic number and is more clear.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:57:08.913",
"Id": "84712",
"Score": "1",
"body": "What a great first review! Keep up the good work!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:31:30.393",
"Id": "48273",
"ParentId": "48190",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:50:36.867",
"Id": "48190",
"Score": "5",
"Tags": [
"java",
"trie"
],
"Title": "Trie string iterations"
} | 48190 |
<p>Please treat this as a interview at a top tech firm, and share your thoughts on how you think I did. Be honest, and leave no stone unturned.</p>
<blockquote>
<p>Problem:</p>
<p>Given two words (start and end), and a dictionary, find the length of
shortest transformation sequence from start to end, such that:</p>
<p>Only one letter can be changed at a time. Each intermediate word must
exist in the dictionary</p>
<p>For example,</p>
<p>Given:</p>
<ul>
<li>start = "hit"</li>
<li>end = "cog"</li>
<li>dict = ["hot","dot","dog","lot","log"]</li>
</ul>
<p>As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" ->
"cog", return its length 5.</p>
<p>Note:</p>
<ul>
<li>Return 0 if there is no such transformation sequence.</li>
<li>All words have the same length.</li>
<li>All words contain only lowercase alphabetic characters.</li>
</ul>
</blockquote>
<p>Time Complexity: \$O(n^2)\$ (please confirm)</p>
<p>Space complexity: \$O(n)\$</p>
<p>My code:</p>
<pre><code> private static int ladderLength(String start, String end, HashSet<String> dict) {
Deque<String> wordSearch = new ArrayDeque<>();
Deque<Integer> lengthCount = new ArrayDeque<>();
wordSearch.add(start);
lengthCount.add(1);
while(!wordSearch.isEmpty()){
String analyzing = wordSearch.poll();
int curCount = lengthCount.poll();
if(analyzing.equals(end)){
return curCount;
}
for(int j = 0; j < analyzing.length(); j++){
for(char i = 'a'; i <= 'z'; i++){
char[] possibleMatch = analyzing.toCharArray();
possibleMatch[j] = i;
String checkMatch = new String(possibleMatch);
if(dict.contains(checkMatch)){
dict.remove(checkMatch);
lengthCount.add(curCount + 1);
wordSearch.add(checkMatch);
}
}
}
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-13T23:03:13.650",
"Id": "259198",
"Score": "0",
"body": "From: https://leetcode.com/problems/word-ladder/"
}
] | [
{
"body": "<p>First of all, I really liked that your logic doesn't need to compare lengths: as soon as a match is found, it must be one of the shortest lengths, nice! And when the <code>end</code> is unreachable, the method returns 0, an impossible answer (since a valid length must be >= 1), so that's good too.</p>\n\n<p>A couple of things can be improved.</p>\n\n<hr>\n\n<h3>Choose the right interfaces</h3>\n\n<p>Your method should work with <code>Set<String> dict</code>, and should not limit users to <code>HashSet<String> dict</code>.</p>\n\n<h3>Choose the right classes</h3>\n\n<p>A <code>Deque</code> is a collection that supports element insertion and removal at both ends. That's more than what you need. A <code>Stack</code> would have been enough for your purpose.</p>\n\n<h3>Simplify the inner <code>for</code> loops</h3>\n\n<p>The inner for loops are a bit wasteful and can be simplified. You are basically iterating over all possible 1-letter differences and check if in the dictionary. Instead, you could iterate elements of the dictionary and see if they have 1 letter difference. For example like this:</p>\n\n<pre><code>for (String item : dict.toArray(new String[dict.size()])) {\n if (isSingleCharDiff(analyzing, item)) {\n dict.remove(item);\n lengthCount.add(curCount + 1);\n wordSearch.add(item);\n }\n}\n</code></pre>\n\n<h3>Discrepancy with the specs</h3>\n\n<p>The problem description says:</p>\n\n<blockquote>\n <p>dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]</p>\n</blockquote>\n\n<p>With this exact input your method returns 0 because it will never reach <code>end</code>. The fix is simple enough, just add it to the dictionary somewhere near the start:</p>\n\n<pre><code>dict.add(end);\n</code></pre>\n\n<h3>A wasted operation</h3>\n\n<p>Before the <code>while</code> loop, you do this:</p>\n\n<pre><code>wordSearch.add(start);\nlengthCount.add(1);\n</code></pre>\n\n<p>but then inside the loop you immediately pop them. You could rework the code to eliminate that wasted operation:</p>\n\n<pre><code>String analyzing = start;\nint curCount = 1;\nwhile (true) {\n if (analyzing.equals(end)) {\n return curCount;\n }\n for (String item : dict.toArray(new String[dict.size()])) {\n if (isSingleCharDiff(analyzing, item)) {\n dict.remove(item);\n lengthCount.add(curCount + 1);\n wordSearch.add(item);\n }\n }\n if (wordSearch.isEmpty()) {\n break;\n }\n analyzing = wordSearch.pop();\n curCount = lengthCount.pop();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:32:27.383",
"Id": "84676",
"Score": "0",
"body": "@janos thank you for your time, is my complexity correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:33:04.173",
"Id": "84677",
"Score": "0",
"body": "@janos also, why should I use an interface as the apparent state?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T18:37:48.450",
"Id": "84687",
"Score": "0",
"body": "You implementation doesn't use any unique features of a `HashSet`. It would work just the same with any other `Set`, for example a `TreeSet`. Using a `Set` is good enough for your case, and allows the widest possible uses."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T07:56:22.840",
"Id": "48215",
"ParentId": "48192",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48215",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:02:49.650",
"Id": "48192",
"Score": "9",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Finding the length of shortest transformation sequence from start to end"
} | 48192 |
<p>I'm wondering what the best way of initializing variables so that I don't over use the garbage collector with a <code>for</code>-loop. Assuming the variable is only used inside the <code>for</code>-loop. Is it better to declare the variable outside of the <code>for</code>-loop?</p>
<pre><code>public void foo() {
String tempName;
for (Person person : personList) {
tempName = person.getName();
//Do work with name
}
}
</code></pre>
<p>Or inside the for-loop?</p>
<pre><code>public void foo() {
for (Person person : personList) {
String tempName = person.getName();
//Do work with name
}
}
</code></pre>
| [] | [
{
"body": "<p>For the Garbage Collector, it doesn't matter at all. You don't <em>create</em> the object. You just use an object reference to it in the above code.</p>\n\n<p>The String object itself is still stored in the <code>Person</code> class and is therefore not garbage-collected until it is changed inside the Person object, or the Person object itself is garbage collected (which will happen when the Person does not have any more references to it).</p>\n\n<p>Normally, you don't need to worry about \"over-using\" the Garbage Collector.</p>\n\n<p>However, for the sake of readability it is a good practice to declare the variable in the smallest scope as possible. Therefore, I would go with the inside the for-loop approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-03T21:04:20.603",
"Id": "98588",
"Score": "0",
"body": "To be accurate, String object is not stored in the Person class. The String object is lying on the heap and all references to it are equal. There is no notion of ownership of any object on the heap."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-03T21:05:56.737",
"Id": "98589",
"Score": "0",
"body": "@Teddy I did not want to imply ownership. Perhaps \"referenced\" would be a better word instead of \"stored\"?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:23:30.047",
"Id": "48194",
"ParentId": "48193",
"Score": "14"
}
},
{
"body": "<p>The first code snippet looks better for computer but second is better for human. \nI suggest to write understandable code and let the Java compiler do the optimization for you :) Believe me, compiler can do this job very well</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T22:21:57.843",
"Id": "84600",
"Score": "2",
"body": "What exactly is the difference for the computer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:07:48.757",
"Id": "84607",
"Score": "1",
"body": "-1: It makes no difference whatsoever from a bytecode point of view."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:12:22.733",
"Id": "84608",
"Score": "0",
"body": "-1: The java compiler (Eclipse's or javac) seldom does any kind of optimization. Optimizations, when happening, ocurr at the JIT compiler level."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:36:06.550",
"Id": "48196",
"ParentId": "48193",
"Score": "0"
}
},
{
"body": "<p>As long as your string lives under Person Obejct and Person object is not eligible for GC, your string will never be collected. Also invocation of GC is not guaranteed. JVM manages it for you. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T22:56:38.113",
"Id": "48199",
"ParentId": "48193",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T21:07:35.853",
"Id": "48193",
"Score": "4",
"Tags": [
"java",
"performance",
"garbage-collection"
],
"Title": "How do I avoid over-using the garbage collector?"
} | 48193 |
<blockquote>
<p>Write a function that takes two parameters:</p>
<ol>
<li>a <code>String</code> representing a text document</li>
<li>an integer providing the number of items to return</li>
</ol>
<p>Implement the function such that it returns a list of Strings ordered
by word frequency, the most frequently occurring word first.</p>
<p>Runtime not to exceed \$O(n)\$</p>
</blockquote>
<p>I decided to use a map to count the frequency of the words and then do the count sort to achieve sorting in linear time. Is this the best approach or there is some other solution that I am not aware of?</p>
<pre><code>import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
interface IFrequencyCounter{
public String[] getMostFrequenctWords(String content, int numberOfwords );
}
public class FrequencyCounter implements IFrequencyCounter{
/**
* This is the Frequency Class
* which has only one property count.
* This is used to save autoboxing/unboxing
* overhead when using maps.
*/
private class Frequency{
private Frequency(){
this.count = 1;
}
private int count;
public int getFrequency(){
return this.count;
}
public void incrementFrequency(){
this.count++;
}
public void setCount(int count){
this.count = count;
}
}
/**
* Token class extends Frequency. This is
* used to maintain word frequency relationship.
* (Just like a pair.)
*/
private class Token extends Frequency{
private Token(String word, int count){
super();
this.word = word;
setCount(count);
}
private String word;
}
/**
* This method returns String array sorted by most frequent word. If null/empty string
* is provided as input then empty array is returned. If numberOfWords is greater then
* unique words then all the words are returned.
*
* @see com.evernote.util.IFrequencyCounter#getMostFrequenctWords(java.lang.String, int)
*/
@Override
public String[] getMostFrequenctWords(String content, int numberOfwords) {
// basic validations
if( null == content) content = "";
if(numberOfwords <= 0) return new String[0];
int maxSofar = 0;
HashMap<String,Frequency> wordMap = new HashMap<String,Frequency>();
String[] contentArray = content.split("\\s+");
addWordsToMap(contentArray, wordMap);
return getSortedArray(numberOfwords, maxSofar, wordMap);
}
/**
* returns sorted array of words(String) in decreasing order of frequency.
* @param numberOfwords
* @param i
* @param maxSofar
* @param wordMap
* @param wordsArr
* @return String[]
*/
private String[] getSortedArray(int numberOfwords, int maxSofar, Map<String, Frequency> wordMap) {
String[] mostFreqWordsArr;
int i =0;
Token[] wordsArr = new Token[wordMap.keySet().size()];
for (String key : wordMap.keySet()) {
wordsArr[i++] = new Token(key, wordMap.get(key).getFrequency());
if(maxSofar < wordMap.get(key).getFrequency()){
maxSofar = wordMap.get(key).getFrequency();
}
}
wordMap = null; // just to free memory in case input is a very large string
int[] frequencyArr = new int[maxSofar+1];
String[] stringArr = new String[wordsArr.length];
for(i =0; i<wordsArr.length; i++) frequencyArr[wordsArr[i].getFrequency()] += 1;
for(i =1; i<frequencyArr.length; i++) frequencyArr[i] += frequencyArr[i-1];
for(i= 0; i<wordsArr.length; i++) {
stringArr[frequencyArr[wordsArr[i].getFrequency()]-1] = wordsArr[i].word;
frequencyArr[wordsArr[i].getFrequency()] -=1;
}
if(stringArr.length-numberOfwords >= 0)
mostFreqWordsArr = Arrays.copyOfRange(stringArr, stringArr.length-numberOfwords, stringArr.length);
else
mostFreqWordsArr = Arrays.copyOfRange(stringArr, 0, stringArr.length);
// reverse the string so most frequent words come first
for(i = 0; i < mostFreqWordsArr.length / 2; i++){
String temp = mostFreqWordsArr[i];
mostFreqWordsArr[i] = mostFreqWordsArr[mostFreqWordsArr.length-1 - i];
mostFreqWordsArr[mostFreqWordsArr.length-1 - i] = temp;
}
return mostFreqWordsArr;
}
/**
* @param contentArray
* @param wordMap
*/
private void addWordsToMap(String[] contentArray, Map<String, Frequency> wordMap) {
for (String string : contentArray) {
if(wordMap.containsKey(string)){
wordMap.get(string).incrementFrequency();
}else {
Frequency token = new Frequency();
wordMap.put(string,token);
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T06:46:34.643",
"Id": "84618",
"Score": "0",
"body": "Nicely done for homework."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:06:02.970",
"Id": "84733",
"Score": "0",
"body": "Lets say if I want to use this code in production then are there any changes which I should make ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T04:54:54.127",
"Id": "84751",
"Score": "0",
"body": "That depends on you, if it works you can, if you want to go for more perfection, listen to the answers and refactor your code to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-22T14:18:38.127",
"Id": "199181",
"Score": "0",
"body": "I believe the suggested solution runs in o(nlogn) complexity at the worst case due to the sorting of the map entries so seems to me it fails to answer the question."
}
] | [
{
"body": "<p>There are a number of things in here you have done well, and your algorithm is good. I like that you have created an object to contain the frequency. Using the HashMap is the right solution too.</p>\n\n<p>Overall, the OOP, and algorithm is good, but.... the presentation is messy, and there's a couple of things you can do better.</p>\n\n<p>The indentation and code style in general are very inconsistent. I imagine you are using an IDE to write your code (based on the boilerplate JavaDoc comments), so, there is no real excuse for the inconsistent indentation. Maybe you had a problem pasting it in to Code Review... (I see this is your first question). There's a trick in Code Review (and all Stack Exchange sites). When editing your question, you can select the code, and click the \"code\" button, or press Ctrl-k to indent things 4 spaces to get the formatting right.</p>\n\n<h2>Code Style</h2>\n\n<p>The indentation is a problem. Part of it is probably the pasting and manual fix up you may have done. But, even then, there are some lines indented one space more than I expect.</p>\n\n<p>The bigger issue is the consistency and conformance-to-standards of where you declare your variables.</p>\n\n<p>It is standard in Java for the class to have the class declaration, static fields, static methods, instance fields, the constructor, then public methods, finally private methods. There are some variations, but, the private variables should always be declared before the constructor....</p>\n\n<p>While we are looking at this class, the variable should be final, and there is no need for the call to <code>super()</code> in the constructor.</p>\n\n<p>The code:</p>\n\n<blockquote>\n<pre><code>private class Token extends Frequency{\n\nprivate Token(String word, int count){\n super();\n this.word = word;\n setCount(count);\n}\n\nprivate String word;\n}\n</code></pre>\n</blockquote>\n\n<p>should be:</p>\n\n<pre><code>private class Token extends Frequency{\n\n private String word;\n\n private Token(String word, int count){\n this.word = word;\n setCount(count);\n }\n\n}\n</code></pre>\n\n<h2>Frequency</h2>\n\n<p>The good thing about Frequency is that you are using it. You are correct when you say it is better than the autoboxing system (keeping an Integer in the HashMap). I have to question why you felt it was necessary to add the intermediate class Token though. There is no need for them both. Choose one, and merge the other in to it. For example, there is no reason why you can't add the String value to the Frequency class. As it stands, the logic is a little bit too abstracted.</p>\n\n<h2>Map efficiency</h2>\n\n<p>The code</p>\n\n<blockquote>\n<pre><code>for (String string : contentArray) {\n if(wordMap.containsKey(string)){\n wordMap.get(string).incrementFrequency();\n }else {\n Frequency token = new Frequency();\n wordMap.put(string,token);\n }\n } \n }\n</code></pre>\n</blockquote>\n\n<p>is not doing efficient HashMap lookups. Consider rewriting it like (only one lookup to the map):</p>\n\n<pre><code>for (String string : contentArray) {\n Frequency token = wordMap.get(string);\n if(token == null) {\n wordMap.put(string,new Frequency());\n }else {\n token.incrementFrequency();\n }\n} \n</code></pre>\n\n<h2>Other....</h2>\n\n<ul>\n<li>The variable <code>int maxSofar = 0;</code> and the maxSoFar parameter is useless, just initialize maxSoFar inside the <code>getSortedArray</code> method.</li>\n<li>Using a variable name <code>string</code> is a bad idea.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T00:32:05.210",
"Id": "84603",
"Score": "0",
"body": "Woha.. awesome review. I liked it. Yes the formatting is bad because I did it after pasting and pressing space bar 4 times for most of the lines. Sorry for that. Also why is the other look up in may is better than the previous one ? Also I made two classes because I wanted proper abstraction. String class wasn't needed in map so I created two classes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T00:28:18.347",
"Id": "48203",
"ParentId": "48198",
"Score": "15"
}
},
{
"body": "<h2>Naming</h2>\n\n<p>You should give variables and methods proper names:</p>\n\n<p><strong>Consistency</strong><br>\nYour <code>Frequency</code> class contains a <code>getFrequency</code> method and an <code>incrementFrequency</code> method, but also a <code>count</code> variable and a <code>setCount</code> method. </p>\n\n<p>Either rename <code>count</code> to <code>frequency</code> or the other way around (not including the class name of course).</p>\n\n<p><strong>Typos</strong><br>\nIt is a very awkward \"oopsy\" moment when you find a typo in your code, even more so if it is a method name which is already in use or overridden - so re-read your code and try to find them before they become harder to replace... (<code>getMostFrequenctWords</code> should be <code>getMostFrequentWords</code>)</p>\n\n<p><strong>Convey meaning</strong><br>\nYour variable/parameter names should convey the meaning of what do they hold, and how they should be used. </p>\n\n<p><code>numberOfWords</code> is maybe technically accurate, but does not help the reader know what it is for. Perhaps <code>maxResults</code> would do a better job.</p>\n\n<p><code>getSortedArray</code> is also a little too generic, and <code>sortWordsByFrequency</code> might be more appropriate.</p>\n\n<p><code>addWordsToMap</code> is also very technical, and I think that <code>Map countWords(String[])</code> is more readable, and gives a better flow to the calling code.</p>\n\n<p><strong>Don't be lazy</strong><br>\nIn most cases it is a bad idea to shorten words in variable names, as they make the name less readable - don't use <code>Freq</code> - say <code>Frequency</code>.</p>\n\n<p><strong>Don't repeat type in the name</strong><br>\nThere is no need in repeating the type of a variable in its name - <code>mostFrequentWords</code> does not reduce anything by omitting the word <code>Arr</code> from it.</p>\n\n<h2>Comments</h2>\n\n<p>When you have good naming to your classes, methods and parameters, you will find that most method comments are simply re-iterations of the method signatures. Likewise, when you find that a method/parameter needs extra explanation in a comment, it might be because it has a bad name. </p>\n\n<p>So, <code>String[] getMostFrequentWords(String content, int maxResults)</code> is very self-descriptive, and doesn't actually need <em>any</em> documentation.</p>\n\n<p>Comments have a nasty habit of rotting - when you change the code, you tend not the maintain the comments, which after awhile will stop describing the code, and sometimes even totally mislead the reader. (see <code>@param wordsArr</code>, for example)</p>\n\n<h2>Encapsulation</h2>\n\n<p>Keep internal data of a method <em>inside</em> it - don't expose it in your signature. <code>maxSofar</code> and <code>wordMap</code> have no business in the method signatures. One is totally internal, and the other should be instantiated within the method and returned rather than passed by reference.</p>\n\n<h2>Declare variables only when they are needed</h2>\n\n<p>There is no need to declare variables at the beginning of a method if they are only used at its end.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:10:08.323",
"Id": "84734",
"Score": "0",
"body": "Very nice review. Thanks a lot Uri Agassi. I never thought it that way you mentioned and gave me a good insight to enhance my way of writing code. A great thanks to you again ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T10:01:33.390",
"Id": "48221",
"ParentId": "48198",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48203",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T22:20:23.163",
"Id": "48198",
"Score": "10",
"Tags": [
"java",
"algorithm",
"strings",
"sorting"
],
"Title": "Count frequency of words in a given file"
} | 48198 |
<p>From the command line, I can easily find the path to <code>rubygems.rb</code></p>
<pre><code>$ gem which rubygems
/usr/lib/ruby/1.9.1/rubygems.rb
</code></pre>
<p>and from a Ruby script I can also do this</p>
<pre><code>require 'rubygems/commands/which_command'
wc = Gem::Commands::WhichCommand.new
puts wc.find_paths 'rubygems', $LOAD_PATH
</code></pre>
<p>However is a simpler way available to do this, for example without using<br>
<code>require 'rubygems/commands/which_command'</code>, and without a <code>system()</code> call?</p>
<p>Update from posted answer</p>
<pre><code>puts $".grep(/rubygems.rb/).first
</code></pre>
<p>Update from posted comment</p>
<pre><code>puts Gem.method(:dir).source_location.first
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T08:26:47.897",
"Id": "84623",
"Score": "0",
"body": "Don't you think this question should go on SO?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T09:01:37.173",
"Id": "84629",
"Score": "0",
"body": "Sounds strange... I agree the answer is excellent, it is just a pity (IMHO) that it is not on SO... I think that people will look for similar things there, not here..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:19:45.673",
"Id": "84735",
"Score": "1",
"body": "http://stackoverflow.com/a/660129"
}
] | [
{
"body": "<p>Whether a simpler solution exists depends on what your motivation is.</p>\n\n<p>Let's look inside the implementation of <code>Gem::Commands::WhichCommand#find_paths</code>.</p>\n\n<pre><code> def find_paths(package_name, dirs)\n result = []\n\n dirs.each do |dir|\n Gem.suffixes.each do |ext|\n full_path = File.join dir, \"#{package_name}#{ext}\"\n if File.exist? full_path and not File.directory? full_path then\n result << full_path\n return result unless options[:show_all]\n end\n end\n end\n\n result\n end\n</code></pre>\n\n<p>That's the code you need. If there were a simpler way, <code>find_paths</code> would have used it.</p>\n\n<p><em>However,</em> there is a way to cheat: <a href=\"http://www.ruby-doc.org/core-2.1.1/Kernel.html#method-i-require\" rel=\"nofollow\"><code>Kernel#require</code></a> needs to do a very similar thing when it actually tries to load a module:</p>\n\n<blockquote>\n <h3>require(name) → true or false</h3>\n \n <p>Loads the given <code>name</code>, returning <code>true</code> if successful and <code>false</code> if\n the feature is already loaded.</p>\n \n <p>If the filename does not resolve to an absolute path, it will be\n searched for in the directories listed in <code>$LOAD_PATH</code> (<code>$:</code>).</p>\n \n <p>If the filename has the extension “.rb”, it is loaded as a source\n file; if the extension is “.so”, “.o”, or “.dll”, or the default\n shared library extension on the current platform, Ruby loads the\n shared library as a Ruby extension. Otherwise, Ruby tries adding\n “.rb”, “.so”, and so on to the name until found. If the file named\n cannot be found, a <code>LoadError</code> will be raised.</p>\n \n <p>For Ruby extensions the filename given may use any shared library\n extension. For example, on Linux the socket extension is “socket.so”\n and <code>require 'socket.dll'</code> will load the socket extension.</p>\n \n <p>The absolute path of the loaded file is added to <code>$LOADED_FEATURES</code>\n (<code>$\"</code>). A file will not be loaded again if its path already appears in\n <code>$\"</code>. For example, <code>require 'a'; require './a'</code> will not load <code>a.rb</code>\n again.</p>\n</blockquote>\n\n<p>Or, it might be more accurate to say that <code>find_paths</code> simulates what <code>require</code> would do.</p>\n\n<p>Therefore, if you are willing to let Ruby actually load the file first, then you could ask Ruby after the fact:</p>\n\n<pre><code>require 'rubygems'\n$LOADED_FEATURES.grep /\\/rubygems\\./\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T00:12:08.470",
"Id": "48202",
"ParentId": "48200",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48202",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T23:21:58.477",
"Id": "48200",
"Score": "3",
"Tags": [
"ruby",
"file-system",
"modules"
],
"Title": "Return path to rubygems.rb"
} | 48200 |
<blockquote>
<p>145 is a curious number, as \$1! + 4! + 5! = 1 + 24 + 120 = 145\$.</p>
<p>Find the sum of all numbers which are equal to the sum of the
factorial of their digits.</p>
<p><strong>Note:</strong> as \$1! = 1\$ and \$2! = 2\$ are not sums they are not included.</p>
</blockquote>
<p>I can't figure out a fair way to optimize the upper bound from the information given in the question. I went on the PE forum and found many people setting the upper bound to 50000 because they knew that would be large enough after testing. This doesn't seem fair to me; I want to set the bound based on the information in the question. Right now it runs in around 20 seconds.</p>
<p>EDIT: I'm not looking for a mathematical algorithm. I'm looking for ways to make this code faster.</p>
<pre><code>from math import factorial as fact
from timeit import default_timer as timer
start = timer()
def findFactorialSum():
factorials = [fact(x) for x in range(0, 10)] # pre-calculate products
total_sum = 0
for k in range(10, fact(9) * 7): # 9999999 is way more than its fact-sum
if sum([factorials[int(x)] for x in str(k)]) == k:
total_sum += k
return total_sum
ans = findFactorialSum()
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T23:58:07.383",
"Id": "84601",
"Score": "0",
"body": "Please remember to tag these questions with [programming-challenge] and [optimization]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T04:23:14.577",
"Id": "84613",
"Score": "0",
"body": "Are you hoping to mathematically determine the upper bound on the largest number which is equal to the sum of the factorials of its digits? If so that sounds like a question for [math.SE]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T04:25:32.097",
"Id": "84614",
"Score": "0",
"body": "Further to @DavidZ comment, finding the upper bound is a topic you can find using Google. It seems as if you're asking for an algorithm, not a code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:45:40.820",
"Id": "84772",
"Score": "1",
"body": "The upper bound is the topic of [a Mathematics question](http://math.stackexchange.com/questions/620877/project-euler-34-find-a-mathematical-approach-for-upper-bound)"
}
] | [
{
"body": "<p>I'm not aware of any mathematical way to establish the upper bound for the search space (I used the same upper limit as you did). However, there are some optimizations you can make:</p>\n\n<ol>\n<li><p>Use integer math throughout instead of converting to a string, extracting the digits, then converting back to an integer. On my PC, your algorithm ran in approximately 6200ms. Using integer math as follows (there may be a more Pythonic way to do this; my code is a direct transliteration of C++ that I used), it ran in approximately 1600ms -- almost 4 times as fast:</p>\n\n<pre><code>def findFactorialSum():\n factorials = [fact(x) for x in range(0, 10)] # pre-calculate products\n total_sum = 0\n for k in range(10, fact(9) * 7): # 9999999 is way more than its fact-sum\n tmp = k\n total = 0\n while tmp > 0:\n total += factorials[tmp % 10]\n tmp //= 10\n\n if total == k:\n total_sum += k\n\n return total_sum\n</code></pre>\n\n<p>(For my curiosity, I also tried it with the '/' operator instead of the '//' operator, and consistently got 100ms longer run times with the former.)</p></li>\n<li><p>You're doing an exhaustive search of the numbers from [10...7*9!] to see which ones meet the problem criteria. You can eliminate a large proportion of those numbers:</p>\n\n<h3>Hint 1:</h3>\n\n<blockquote class=\"spoiler\">\n <p> No 2-digit number can have a digit >= 5. This is because 5! == 120, so any 2-digit number with a 5 (or higher) in it will automatically have a 3-digit (or longer) sum. You can extend this rule for 3-, 4- and 5- digit numbers. </p>\n</blockquote>\n\n<h3>Hint 2:</h3>\n\n<blockquote class=\"spoiler\">\n <p> Extending Hint 1: No 3-digit number can have more than one 7 in it. 7! is 720, so if you have two 7s, you have 1440, a 4-digit number. There are a few more opportunities like this to eliminate numbers to check</p>\n</blockquote>\n\n<h3>Hint 3:</h3>\n\n<blockquote class=\"spoiler\">\n <p> Think of the number 145 given in the problem; since you know that this works, there's no need to check numbers that are a permutations of its digits: 154, 415, 451, 514, 541. The trick here is to look at the problem the other way around: instead of finding numbers whose Sum of Factorials of Digits equals the original number, find an ordered sequence of digits whose Sum of Factorials can be split into a sequence of digits, sorted, and that compares equal to the original sequence.</p>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:53:59.717",
"Id": "84889",
"Score": "0",
"body": "Your code returned zero when I ran it on my machine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:43:09.400",
"Id": "84895",
"Score": "0",
"body": "@jshuaf ... Hmm, when I ran the code on my machine, it returned `Found 40730 in 2611.125946044922 ms.` Ran the code on ideone too: http://ideone.com/qZqPIW"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:49:32.997",
"Id": "84899",
"Score": "0",
"body": "On this machine I get `Found 40730 in 8652.6780128479 ms.` under Python 2.7 and `Found 40730 in 11760.103859938681 ms.` under Python 3.3 (when I fix the print statement). The original code gives `Found 40730 in 26423.507928848267 ms.` on the same machine."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:25:38.580",
"Id": "48232",
"ParentId": "48201",
"Score": "4"
}
},
{
"body": "<p>This is much faster than both of your solutions(~50 ms compared to 5 and 13 seconds) jshuaf when you initialized the factorial values try using a dictionary instead of a list also allows me to use str keys and get int values,</p>\n\n<pre><code>import math\n\ndef problem34():\n total=0\n factorials={}\n for i in xrange(10):\n factorials[str(i)]=math.factorial(i) \n for i in xrange(3,50000):\n factorial_sum=0\n for j in str(i):\n factorial_sum+=factorials[j]\n if factorial_sum==i:\n total+=factorial_sum\n return total\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T04:03:20.987",
"Id": "58592",
"ParentId": "48201",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48232",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T23:46:40.610",
"Id": "48201",
"Score": "6",
"Tags": [
"python",
"optimization",
"programming-challenge"
],
"Title": "Project Euler 34 - digit factorials"
} | 48201 |
<p>So, generally when I write iOS code, I will start with a lot of calls to <code>NSLog</code>, which is a macro that with print the string you send it to the console.</p>
<p>There's a few problems with this.</p>
<p>First of all, whether you know it or not, you can see what's being printed to an iOS device's console even on apps you downloaded from the app store. Up till now, I've been preventing console printing by wrapping my <code>NSLog</code> calls with <code>#if DEBUG</code> followed by <code>#endif</code>. But this gets messy in a hurry, and it's quite easy to forget.</p>
<p>Plus, <code>NSLog</code> is quite busy. It has a lot of information in it, and a lot of it I don't need during development.</p>
<p>Here's what an example <code>NSLog</code> statement looks like:</p>
<pre><code>2014-04-25 20:05:55.226 NHGLogger[5780:60b] Hello World!
</code></pre>
<p>Where the first set of numbers is the date and time. This is useful information to me.</p>
<p>The "NHGLogger" is the name of the application that created the log statement. This is completely useless to me while debugging... I know what app I'm running. However... this HAS to go into NSLog, because it's the only way to sort out one app from another when there are tons of apps out there all with developers who aren't courteous enough to wrap their debug log statements in <code>#if DEBUG</code>. The next bit, in the brackets? I literally have no idea what this is. It might be some sort of reference to the block of memory that the NSLog call originated from, or the thread? I have no clue. And the final part is the actual message I wanted to log.</p>
<p>What's more... the operating system considers <code>NSLog</code> statements to be warnings. I doesn't actually do anything about them, but as far as the OS is consider, an <code>NSLog</code> call means a program is trying to log some sort of non-normal behavior.</p>
<p>So, I set out to write my own logging macro, with a few criteria.</p>
<ol>
<li>The log must be as easy to use as <code>NSLog()</code> is.</li>
<li>The log must include the time stamp... I always consider this useful information when logging stuff</li>
<li>The log must ONLY print to console in debug mode. It shouldn't print in release mode and I shouldn't have to write two extra lines of code every time I log anything to satisfy this criteria like I do with <code>NSLog()</code>.</li>
</ol>
<p>So, here's what I came up with:</p>
<h1>NHGLogger.h</h1>
<pre><code>@import Foundation.NSString;
void z_DebugLog(NSString *statement);
#define NHGLog(format_string,...) \
((z_DebugLog([NSString stringWithFormat:format_string,##__VA_ARGS__])))
</code></pre>
<h1>NHGLogger.m</h1>
<pre><code>#import "NHGLogger.h"
@import Foundation.NSDate;
@import Foundation.NSDateFormatter;
void z_DebugLog(NSString *statement) {
#if DEBUG
static NSDateFormatter *timeStampFormat;
if (!timeStampFormat) {
timeStampFormat = [[NSDateFormatter alloc] init];
[timeStampFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
[timeStampFormat setTimeZone:[NSTimeZone systemTimeZone]];
}
printf("%s\n",[[NSString stringWithFormat:@"<%@> %@",
[timeStampFormat stringFromDate:[NSDate date]],statement] UTF8String]);
#endif
}
</code></pre>
<p>The result is that in DEBUG (and only in DEBUG), stuff is printed to the console as such:</p>
<pre><code><2014-04-25 20:05:55.225> Hello World!
</code></pre>
<p>And the macro is used in the exact manner that <code>NSLog</code> is used.</p>
<p>Here are a few of my concerns with the code:</p>
<ul>
<li><code>z_DebugLog()</code> --named slightly oddly because I don't intend this function to be called directly. I'm not completely rock-solid on the function naming rules of C99, and what the best way to name this so as to make it as unlikely as possible that it will pop up with autocomplete. Or better yet, is there possibly a way to make it so the macro still knows about the function but nothing outside this file does? Probably not, huh?</li>
<li>Readability. Now, the whole point of this macro/function in the first place is to improve the readability of the code that calls this, but I'd like this code to be as readable as possible too. However, the readability can't trump my third concern:</li>
<li>Efficiency. These statements absolutely need to go as quickly as possible. Absolutely anything that can be done to minimize the amount of time it takes to make it through this macro at runtime should be done. I don't know how efficient this is, or what, if anything, could be done to improve the speed.</li>
</ul>
| [] | [
{
"body": "<p>The easiest way to avoid the extraneous function is going to be to use a function directly rather than using a macro. You do unfortunately have to drop down to a bit of C, but luckily since ObjC integrates rather pleasantly with C, it proves to not be very painful. The only C part is the use of the <code>stdarg.h</code> variable arugment list related items. (This is actually how <code>NSLog</code> works under the hood.)</p>\n\n<p>Declaration:</p>\n\n<pre><code>void NHLog(NSString* format, ...);\n</code></pre>\n\n<p>Definition:</p>\n\n<pre><code>void NHLog(NSString* format, ...)\n{\n#if DEBUG\n static NSDateFormatter* timeStampFormat;\n if (!timeStampFormat) {\n timeStampFormat = [[NSDateFormatter alloc] init];\n [timeStampFormat setDateFormat:@\"yyyy-MM-dd HH:mm:ss.SSS\"];\n [timeStampFormat setTimeZone:[NSTimeZone systemTimeZone]];\n }\n\n NSString* timestamp = [timeStampFormat stringFromDate:[NSDate date]];\n\n va_list vargs;\n va_start(vargs, format);\n NSString* formattedMessage = [[NSString alloc] initWithFormat:format arguments:vargs];\n va_end(vargs);\n\n NSString* message = [NSString stringWithFormat:@\"<%@> %@\", timestamp, formattedMessage];\n\n printf(\"%s\\n\", [message UTF8String]);\n#endif\n}\n</code></pre>\n\n<hr>\n\n<p>Anyway, on to a bit of a critique. The first problem that comes to mind is that I would always rather have too much information than not enough. Imagine if everyone used some kind of logging facility like this. Suddenly you'd have logging statements coming from who knows where for who knows what reason. </p>\n\n<p>Yes, people realy shouldn't leave debug statements in production code, but unfortunately people do and they do it a lot (just look at the incredibly widespread abuse of <code>NSLog</code>...). Then again, as long as you don't leave any of these statements lying around, you're correct that there's no need for extra information. Considering you plan on using this only in your end applications and not leaving it in library type code, it's probably better to not put anything more than the bare essentials.</p>\n\n<hr>\n\n<p>The other problem is perhaps a bit more obscure. Static variables are inherently unsafe in a non single threaded environment. Technically speaking, your <code>timeStampFormat</code> is unsafe unless you always run <code>NHLog</code> from the same thread (or you initialize it on one thread). The race condition only exists until <code>timeStampFormat</code> is actually created so it's a relatively small window, and the damage would likely be minimal, but considering how common threading is in ObjC applications, it seems an unacceptable flaw.</p>\n\n<p>Unfortunately though, I'm not quite sure how to get around that in a non-expensive way. You could use a mutex, but that adds a very meaningful overhead, and you could use thread local storage, but that is going to bring you deep into C land since <code>-[NSThread threadDictionary]</code> is not available to iOS (you would have to use <code>pthread_getspecific</code> with a raw, non-managed, C-style pointer)`.</p>\n\n<p>Since we're already edging into C, have you considered <code>strftime</code>? It's much more primitive than <code>NSDateFormatter</code>, but it should be fit your needs fine, and I can't imagine anything being faster than it. Also, it wouldn't have a costly formatting object to initialize, so you don't have to worry about thread safety.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:59:44.597",
"Id": "84612",
"Score": "0",
"body": "As to having more/less information, if there's something else I want to add to every message, that part is easy enough to format, and is probably purely a matter of opinion. I find stripping the unnecessary info makes the log more readable. As for the other comments, looks mostly good. I need to improve my pure C knowledge..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T02:29:01.757",
"Id": "48207",
"ParentId": "48204",
"Score": "7"
}
},
{
"body": "<p>There's another potential solution that relies on a feature of Xcode. For any other programming language, it's probably not a good idea to offer a potential solution that relies on an IDE-specific feature, but in the case of writing Cocoa/Cocoa-Touch apps (you'd have to be doing one or the other to be using NSLog), you're pretty much going to be using Xcode.</p>\n\n<p>Xcode, like many other IDEs, has a code snippet library. The reason if statements, and all the loops, and many other things autocomplete for you is because they're preloaded snippets in your code snippet library. There's no reason why we shouldn't be using this code snippet library ourselves. For example, I like to put the default <code>init</code> pattern in there.</p>\n\n<p>But here's a snippet we can do to keep our <code>NSLog</code> statements from showing up in our release code...</p>\n\n<p><img src=\"https://i.stack.imgur.com/3jUc4.png\" alt=\"enter image description here\"></p>\n\n<p>The title and summary for the snippet is pretty self-explanatory I think. It's worth noting that both of these things show up in the autocomplete context menu to help you know what you're about to autocomplete into. </p>\n\n<p>The platform options let you choose between iOS and OSX (or All). Choosing one or the other prevents it from showing up when you're writing code for the other platform. (This is a nice way to give two bits of platform specific code the same auto-complete, one using <code>UIView</code> and the other using <code>NSView</code> for example.)</p>\n\n<p>The language is pretty self-explanatory as well. Xcode is an IDE for numerous different languages, even if it is primarily used for Objective-C. This is the language that this snippet will autocomplete in.</p>\n\n<p>The completion shortcut is what you actually type to get this code snippet to show up as autocompletion. In this example, I've used \"DebugLog\", so as I start to type \"DebugLog\", it will show up in my autocomplete list. You can make this anything, and in fact it might be a good idea to make it just \"NSLog\" here so we don't forget to use it.</p>\n\n<p>The completion scopes tells Xcode in what code context to offer this autocompletion. Here, and with most of your code snippets this will be true, we have executable code, so \"Function or Method\" is the only option. But Xcode code snippets can autocomplete in any sort of scope (and the plus sign will let you give multiple scopes). You can have autocomplete comments, autocomplete preprocessor directives, etc, stuff for class interfaces and implementations, etc.</p>\n\n<p>Now for the actual code. This is the important part to know about how to use Xcode's code snippet library.</p>\n\n<p>The code is what Xcode will autocomplete into, regardless of anything else. But the important part is that little gray bubble with the words \"debug statement\" in there.</p>\n\n<p>First thing to know, these gray bubbles take over the tab key. Hitting tab will cycle you through these until they're all filled out, just like when you autocomplete a method call. You'll tab through the argument placeholders until they're all filled out.</p>\n\n<p>Second thing to know, now that you know how they work and when to use them, is how to create them.</p>\n\n<p>It works like this:</p>\n\n<pre><code><#Some text that serves as a hint to what gets filled in here#>\n</code></pre>\n\n<p>So in the example from the picture, the actual typed code for the snippet looks like this:</p>\n\n<pre><code>#if DEBUG\n NSLog(<#debug statement#>);\n#endif\n</code></pre>\n\n<p>When I autocomplete, it will show up almost exactly like the image I included. The difference is, when I tab to autocomplete, the \"debug statement\" bubble will be highlighted, and as soon as I start typing, it will replace that bubble with the format string I type to be logged in debug mode only.</p>\n\n<p>Now, this solution doesn't completely resolve all the criteria in the question, but it is a simple solution to consider.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:41:31.420",
"Id": "48561",
"ParentId": "48204",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T01:29:06.330",
"Id": "48204",
"Score": "9",
"Tags": [
"objective-c",
"logging"
],
"Title": "Creating a better NSLog"
} | 48204 |
<p>I wrote this program to match square brackets as part of a Brainf**k interpreter. I'm aware that it gets caught in an infinite loop if brackets are entered like this: <code>][</code>.</p>
<ol>
<li>Are there any performance improvements I can make?</li>
<li>Should I change any variable names?</li>
<li>Are there other syntax errors that will break the code?</li>
<li>How can I fix said errors?</li>
<li>Anything else I did wrong?</li>
</ol>
<p></p>
<pre><code>//Matches an opening or closing bracket to a corresponding opening or closing bracket
int getMatchingBraceIndex(unsigned int braceIndex, char* str) {
//Current nesting level
int level = 0;
//Matching brace's nesting level
//(Matching braces have to be at the same level)
int returnLvl = -1;
/*******************************************************************************\
* Note: *
* If brace given is open brace, iterate through string from beginning to end *
* If brace given is close brace, iterate through string from end to beginning *
\*******************************************************************************/
//If brace given is open brace
if (str[braceIndex] == '[') {
//Iterator
int i = 0;
//Iterate through given string
for (i; i < strlen(str); i++) {
//If current character of string is open brace
if (str[i] == '[') {
//Increment nesting level
level++;
//If current character is given brace, assume that matching brace is on the same nesting level
if (i == braceIndex) {
returnLvl = level;
}
//If current character of string is close brace
} else if (str[i] == ']') {
//If currnet nesting level is nesting level of matching brace, return current index
if (level == returnLvl) {
return i;
//Otherwise, decrement nesting level and keep going through the string
} else {
level--;
}
}
}
//If brace given is close brace
} else if (str[braceIndex] == ']') {
//Iterator
int i = strlen(str) - 1;
//Iterate through given string
for (i; i >= 0; i--) {
//If current character of string is close brace
if (str[i] == ']') {
//Increment nesting level
level++;
//If current character is given brace, assume that matching brace is on the same nesting level
if (i == braceIndex) {
returnLvl = level;
}
//If current character of string is open brace
} else if (str[i] == '[') {
//If nesting level is nesting level of matching brace, return current index
if (level == returnLvl) {
return i;
//Otherwise, decrement nesting level and keep going through the string
} else {
level--;
}
}
}
} else {
//Error
setColor(RED, BLACK);
printf("Unable to match brace at index %i\n", braceIndex);
setColor(DEFAULT, BLACK);
return -1;
}
return -1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T08:56:04.763",
"Id": "84628",
"Score": "1",
"body": "I would not scan backwards for the open brace. When you hit an open brace push the current position onto the stack. When you hit a close brace pop the value and just move the instruction pointer to that location."
}
] | [
{
"body": "<p>Do not use <code>strlen()</code> in <code>for</code> loops. <code>strlen()</code> walks over the string every time you call it. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:42:28.807",
"Id": "84611",
"Score": "0",
"body": "So I should assign it to a variable at the start and then access the variable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:04:58.447",
"Id": "84732",
"Score": "0",
"body": "yes. You should definitely do that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:35:43.330",
"Id": "48208",
"ParentId": "48205",
"Score": "5"
}
},
{
"body": "<p>The outer <code>if</code>/<code>else if</code> blocks have a lot of duplicate code. This should be put into a separate function to be called by both conditionals and given the relevant arguments.</p>\n\n<p>This will also make it easier to determine if that code itself should be refactored because you'll just have one occurrence of it. Overall, putting duplicate code into a separate function helps with maintainability, readability, and <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY (Don't Repeat Yourself)</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T04:03:06.973",
"Id": "48209",
"ParentId": "48205",
"Score": "3"
}
},
{
"body": "<p>You have way to many comments.</p>\n\n<pre><code> //Increment nesting level\n level++;\n</code></pre>\n\n<p>Thanks. But I can read the code. I don't need a comment to tell me that.<br>\nToo many comments is a real problem. Because the code can become out of sync with the comments then what does the maintainer do? Does he believe the comments and fix the code to make them align with the comments. What happens if the code was changed because there was a subtle bug?</p>\n\n<p>Reserve comments to describe what you are trying to achieve. <strong>NOT</strong> how you are achieving it (the code is a description of how). The comments should by <strong>WHY</strong> (and potentially the goal).</p>\n\n<p>Why is this in the middle of the loop?</p>\n\n<pre><code> if (i == braceIndex) {\n returnLvl = level;\n }\n</code></pre>\n\n<p>This is the start condition.<br>\nOK. I see its because you start scanning from the start of the string.</p>\n\n<pre><code>for (i; i < strlen(str); i++) { \n // Real performance hit if `braceIndex` is 10,000,000\n // You are scanning the program you just executed.\n // You only need to find the closing brace.\n</code></pre>\n\n<p>Why not start scanning from the position of the brace</p>\n\n<pre><code>int strend = strlen(str);\nreturnLvl = 1; // start after the opening '['\n\n// When returnLvl gets back to 0 you can exit\nfor (i = braceIndex + 1; i < strend && returnLvl > 0; ++i) {\n</code></pre>\n\n<p>Then what the other two said.</p>\n\n<p>The last thing is you don't need to scan backwards.<br>\nAs you hit an open brace push the current instruction pointer value onto a stack. As you hit a close pop the value. If the condition is correct reset the instruction pointer to the stored value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T09:06:01.677",
"Id": "48217",
"ParentId": "48205",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T01:56:15.907",
"Id": "48205",
"Score": "5",
"Tags": [
"c",
"validation"
],
"Title": "Matching square brackets"
} | 48205 |
<p>In the last 2 years or so, I've learned a great deal about how to write better Scala code, but I know that I've barely scratched the surface. This is part of a library that I've been using. It has evolved a great deal since the first version and I'm curious to see how many mistakes I'm still making. I am particularly curious about what I can do to make better use of the Scala language.</p>
<p>This is already fairly long, so I'm leaving out my test class, though I would be happy to see test case suggestions.</p>
<p>EventDispatch.scala</p>
<pre><code>package edu.stsci.efl.services
import edu.stsci.efl.events.EFLEvent
import net.liftweb.actor.LiftActor
/**
* This is the interface definition for classes that provide application event services.
*/
trait EventDispatchService {
def registerForEvent(name: String, callback: (EFLEvent) => Unit): EventRegistration
def registerConditionallyForEvent(name: String, callback: (EFLEvent) => Unit, condition: (String, Any)): EventRegistration
def registerActorForEvent(name: String, actor: LiftActor): EventRegistration
def postEvent(event: EFLEvent)
def postDelayedEvent(event: EFLEvent, delay: Int)
}
trait EventRegistration {
private var status: EventRegistrationStatus = ERSPending
def deregister()
def is (s: EventRegistrationStatus) = s == status
def update(s: EventRegistrationStatus) {status = s}
def isAcceptingEvents = status == ERSActive
}
case class EventRegistrationStatus(name: String)
object ERSPending extends EventRegistrationStatus("pending")
object ERSActive extends EventRegistrationStatus("active")
object ERSPaused extends EventRegistrationStatus("paused")
object ERSTerminating extends EventRegistrationStatus("terminating")
object ERSTerminal extends EventRegistrationStatus("terminal")
</code></pre>
<p>Event.scala</p>
<pre><code>package edu.stsci.efl.events
import edu.stsci.efl.ml.EFLContext
import org.slf4j.Logger
import scala.collection.mutable
import scala.xml.Node
/**
* A generic event class with a name and named properties.
*/
class EFLEvent(val name: String, properties: Map[String, Any]) {
var context: EFLContext = null
var state: EventState = ESConstructed
/**
* Query an event to see if it is in a particular state
* @param s - the state of interest
* @return true if the event is in that state
*/
def is(s: EventState): Boolean = state == s
def update(s: EventState) { if (state != ESComplete) state = s }
/**
* Retrieves the value of a named property
*
* @param name - the key under which the property is stored
* @return Object - the value attached to the given name
*/
def getProperty(name: String): Option[Any] = { properties.get(name) }
/**
* Check to see if an event contains a property
* @param name - the name of the property of interest
* @return Boolean - true if the property is defined for this event
*/
def hasProperty(name: String): Boolean = properties.contains(name)
/**
* Retrieves the value of a named property, but only if it is a String
*
* @param name - the key under which the property is stored
* @return String - the String value attached to the given name
*/
def getStringProperty(name: String): String = {
properties.get(name) match {
case None => null
case Some(s: String) => s
case _ => null
}
}
/** Copies the properties of this event into another map.
*
* @param data - the destination map for the contents of properties.
*/
def copyProperties(data: mutable.HashMap[String, Any]) { data ++= properties }
def dump(logger: Logger) {
logger.debug("[dump] event properties for '" + name + "' in context: " + context)
properties.foreach {
case (k: String, null) => logger.debug("[EFLEvent.dump] " + k + " is null.")
case (k: String, v: Any) => logger.debug("[EFLEvent.dump] " + k + ": " + v)
}
}
}
case class EventState(name: String)
object ESConstructed extends EventState("constructed")
object ESPending extends EventState("pending")
object ESComplete extends EventState("complete")
class EventBuilder(name: String) {
val properties = new mutable.HashMap[String, Any]()
def build(): EFLEvent = { new EFLEvent(name, properties.toMap) }
/**
* Sets the value of a property
*
* @param name - the key under which the property is stored.
* @param value - the value object attached to a property
*/
def setProperty(name: String, value: Any) { properties.put(name, value) }
/** Adds a collection of properties to this event.
*
* @param data - a map containing properties to be added
*/
def addProperties[A <: Any](data: mutable.HashMap[String, A]) { properties ++= data }
}
object XMLEventConstructor {
def createOneEvent(data: Node): EFLEvent = {
val eventName = data.attribute("name").head.toString()
val result = new EventBuilder(eventName)
data.child.foreach((n: Node) => {
if (n.label == "property") {
val name = n.attribute("name").head.toString()
val value = n.attribute("value").head.toString()
result.setProperty(name, value)
}
})
result.build()
}
}
</code></pre>
<p>EventModule.scala</p>
<pre><code>package edu.stsci.efl.events
import edu.stsci.efl.ml.{EFLContext, EFLModule}
import edu.stsci.efl.services._
import edu.stsci.util.ThreadTransactionMarker
import org.slf4j.{LoggerFactory, Logger}
import net.liftweb.actor.LiftActor
import net.liftweb.util.{Schedule, Helpers}
import scala.collection.mutable
import scala.xml.Node
import java.io.{StringWriter, PrintWriter}
import scala.Some
/**
* The event module creates and registers an EventService that provides application event services.
*/
class EventModule extends EFLModule {
private var logger: Logger = null
private var eventDispatchService: EventService = null
/**
* Called by the ModuleLoader at program startup so that the module can initialize its functional components
* and register its services.
*
* @param context - the specific EFLContext within which this module will be operating.
* @param data - XML giving module specific initialization and configuration details.
*/
def start(context: EFLContext, data: Node) {
context.findService(classOf[LoggerFactoryService]) match {
case None => // use whatever the default is, or was setup more conventionally
logger = LoggerFactory.getLogger(getClass.getName)
case Some(loggerFactory) => logger = loggerFactory.getLogger(getClass.getName)
}
logger.debug("[start] enter.")
eventDispatchService = new EventService(context, logger)
context.addService(eventDispatchService)
}
/**
* Called by the ModuleLoader when the context is unloaded (usually at or just before program termination)
* so that modules will be able to write out unsaved data, free up resources, etc.
*
* @param context - the EFLContext this module has been running in.
*/
def stop(context: EFLContext) {
logger.debug("[stop] enter.")
waitForShutdown()
eventDispatchService.shutDown()
context.removeService(eventDispatchService)
eventDispatchService = null
}
/**
* Called by a context that wants to import this module from a parent module.
*
* @param context - the context that wishes to use this module's services
*/
def addContext(context: EFLContext) {
context.addService(eventDispatchService)
}
/**
* Called by an importing context at shutdown
*
* @param context - the context that no longer needs this module's services
*/
def removeContext(context: EFLContext) {
context.removeService(eventDispatchService)
}
private def waitForShutdown() {
var iterationCount = 0
while (eventDispatchService.registerCount > 0 && iterationCount < 25 ) {
Thread.sleep(50)
iterationCount += 1
}
logger.trace("[waitForShutdown] waited {} iterations for shutdown.", iterationCount)
}
}
case object EVENT_SHUTDOWN
trait CallableRegistration extends EventRegistration {
def call(event: EFLEvent)
}
private class EventService(context: EFLContext, logger: Logger) extends EventDispatchService {
val actor = new EventActor(context, this)
var registerCount = 0
def shutDown() {actor ! EVENT_SHUTDOWN}
def postEvent(event: EFLEvent) {
logger.trace("[EventService.postEvent] ({}) posting: {}", context.name, event.name, "")
actor ! event
}
def postDelayedEvent(event: EFLEvent, delay: Int) {
Schedule.schedule(actor, event, Helpers.TimeSpan(delay))
}
def registerForEvent(name: String, callback: (EFLEvent) => Unit): EventRegistration = {
logger.trace("[EventService.registerForEvent] ({}) registering for: {}", context.name, name, "")
val registration = new SimpleRegistration(name, callback)
val message = new SimpleRegistrationMessage(registration)
actor ! message
registration
}
def registerConditionallyForEvent(name: String, callback: (EFLEvent) => Unit, condition: (String, Any)): EventRegistration = {
val result = new ConditionalRegistration(name, callback, condition)
val message = new ConditionalRegisterMessage(result)
actor ! message
result
}
def registerActorForEvent(name: String, actor: LiftActor): EventRegistration = {
val message = new ActorRegistration(name, actor)
this.actor ! new RegisterActorMessage(message)
message
}
class SimpleRegistration(val name: String, val callback: (EFLEvent) => Unit) extends CallableRegistration {
def call(event: EFLEvent) {
if (isAcceptingEvents) callback(event)
}
def deregister() {
actor ! this
}
override def equals(obj: scala.Any): Boolean = callback.equals(obj)
override def hashCode(): Int = callback.hashCode()
}
class ConditionalRegistration(val name: String, val callback: (EFLEvent) => Unit, val condition: (String, Any)) extends CallableRegistration {
def call(event: EFLEvent) {
callback(event)
}
def deregister() {
actor ! this
}
}
class ActorRegistration(val name: String, val callback: LiftActor) extends CallableRegistration {
def call(event: EFLEvent) {
if (isAcceptingEvents) callback ! event
}
def deregister() {
actor ! this
}
}
class EventActor(context: EFLContext, parent: EventService) extends LiftActor with ThreadTransactionMarker {
val logger = context.findService(classOf[LoggerFactoryService]).get.getLogger(getClass.getName)
val byEventName = new mutable.HashMap[String, mutable.HashSet[SimpleRegistration]]
val actorByEventName = new mutable.HashMap[String, mutable.HashSet[ActorRegistration]]
val conditionals = new mutable.HashMap[String, ConditionalDispatcher]
private def shutDown() {
logger.debug("[shutDown] Registrations not unregistered: {}", new Integer(byEventName.size))
byEventName.keys.foreach((k) => logger.debug("[shutDown] " + k))
byEventName.clear()
logger.debug("[shutDown] Actor registrations not unregistered: {}", actorByEventName.size)
actorByEventName.keys.foreach((k) => logger.debug("[shutDown] " + k))
actorByEventName.clear()
logger.debug("[shutDown] Conditional registrations not unregistered: {}" + conditionals.size)
conditionals.keys.foreach((k) => logger.debug("[shutDown] " + k))
conditionals.clear()
}
protected def messageHandler = {
case m: SimpleRegistrationMessage => registerForEvent(m.r)
case s: SimpleRegistration => deregisterForEvent(s)
case cr: ConditionalRegisterMessage => registerConditionallyForEvent(cr.c)
case cRe: ConditionalRegistration => deregisterConditionallyForEvent(cRe)
case RegisterActorMessage(r) => registerActorForEvent(r.name, r)
case ar: ActorRegistration => deregisterActorForEvent(ar)
case event: EFLEvent => doDispatch(event)
case EVENT_SHUTDOWN => shutDown()
case a: Any =>
val transKey = beginTrans(logger)
logger.warn("[EventService$EventActor.messageHandler] got unknown message: {}", a)
endTrans(logger, transKey)
}
def registerForEvent(r: SimpleRegistration) {
val transKey = beginTrans(logger, "registerForEvent." + context.name + "." + r.name)
try {
val forEvent = {
byEventName.get(r.name) match {
case None =>
val result = new mutable.HashSet[SimpleRegistration]
byEventName.put(r.name, result)
result
case Some(s) => s
}
}
logger.trace("[registerForEvent] {}", byEventName)
logger.trace("[registerForEvent] adding: {}", r)
forEvent.add(r)
r.update(ERSActive)
}
catch {
case t: Throwable => logger.error("[registerForEvent]", t)
}
parent.registerCount = byEventName.size + actorByEventName.size
endTrans(logger, transKey)
}
def deregisterForEvent(s: SimpleRegistration) {
val transKey = beginTrans(logger, "deregisterForEvent." + context.name + "." + s.name)
try {
byEventName.get(s.name) match {
case None =>
logger.warn("[deregisterForEvent] not found.")
case Some(hashSet) =>
hashSet.remove(s)
logger.trace("[deregisterForEvent] remaining callbacks: {}", hashSet.size)
if (hashSet.isEmpty) {
logger.trace("[deregisterForEvent] removing empty hash set.")
byEventName.remove(s.name)
}
}
s.update(ERSTerminal)
}
catch {
case t: Throwable => logger.error("[EventService$EventActor.deregisterForEvent]", t)
}
parent.registerCount = byEventName.size + actorByEventName.size
endTrans(logger, transKey)
}
def registerConditionallyForEvent(c: ConditionalRegistration) {
val transKey = beginTrans(logger, "registerConditionallyForEvent." + context.name + "." + c.name)
try {
val conditional = getConditional(c.name)
conditional.add(c)
c.update(ERSActive)
}
catch {
case t: Throwable => logger.error("[registerConditionallyForEvent]", t)
}
parent.registerCount = byEventName.size + actorByEventName.size
endTrans(logger, transKey)
}
def deregisterConditionallyForEvent(c: ConditionalRegistration) {
val transKey = beginTrans(logger, "deregisterConditionallyForEvent." + context.name + "." + c.name)
try {
val conditional = getConditional(c.name)
conditional.remove(c)
if (conditional.myConditions.isEmpty) {
conditionals.remove(c.name)
}
c.update(ERSTerminal)
}
catch {
case t: Throwable => logger.error("[deregisterConditionallyForEvent]", t)
}
parent.registerCount = byEventName.size + actorByEventName.size
endTrans(logger, transKey)
}
def registerActorForEvent(name: String, reg: ActorRegistration) {
val transKey = beginTrans(logger, "EventService.registerActorForEvent." + context.name + "." + name)
try {
val forEvent = {
actorByEventName.get(name) match {
case None =>
val result = new mutable.HashSet[ActorRegistration]
actorByEventName.put(name, result)
result
case Some(m) => m
}
}
forEvent.add(reg)
reg.update(ERSActive)
}
catch {
case t: Throwable => logger.error("[registerActorForEvent]", t)
}
parent.registerCount = byEventName.size + actorByEventName.size
endTrans(logger, transKey)
}
def deregisterActorForEvent(ar: ActorRegistration) {
val transKey = beginTrans(logger, "deregisterActorForEvent." + context.name + "." + ar.name)
try {
actorByEventName.get(ar.name) match {
case None => logger.warn("[deregisterActorForEvent] did not find registration.")
case Some(hashSet) =>
hashSet.remove(ar)
if (hashSet.isEmpty) actorByEventName.remove(ar.name)
}
ar.update(ERSTerminal)
}
catch {
case t: Throwable => logger.error("[deregisterActorForEvent]", t)
}
parent.registerCount = byEventName.size + actorByEventName.size
endTrans(logger, transKey)
}
def getConditional(name: String): ConditionalDispatcher = {
conditionals.get(name) match {
case None =>
val conditional = new ConditionalDispatcher(name)
conditionals.put(name, conditional)
conditional
case Some(conditional) => conditional
}
}
def doDispatch(event: EFLEvent) {
val transKey = beginTrans(logger, "messageHandler.dispatching." + event.name)
try {
event.context = context
event.update(ESPending)
logger.trace("[doDispatch] {}", byEventName)
logger.trace("[doDispatch] {}", actorByEventName)
Thread.sleep(5)
byEventName.get(event.name) match {
case None => logger.trace("[doDispatch] no regular callbacks.")
case Some(set) =>
logger.trace("[doDispatch] {} callbacks.", set.size)
set.foreach(_.call(event))
}
actorByEventName.get(event.name) match {
case None => logger.trace("[doDispatch] no actor callbacks.")
case Some(set) =>
logger.trace("[doDispatch] actors: {}", set.size)
set.foreach(_.call(event))
}
}
catch {
case t: Throwable => logger.error("[doDispatch] ", t)
}
event.update(ESComplete)
endTrans(logger, transKey)
}
}
case class SimpleRegistrationMessage(r: SimpleRegistration)
case class ConditionalRegisterMessage(c: ConditionalRegistration)
case class DeregisterMessage(name: String, callback: (EFLEvent) => Unit)
case class ConditionalDeregisterMessage(name: String, callback: (EFLEvent) => Unit, condition: (String, Any))
case class RegisterActorMessage(r: ActorRegistration)
case class DeregisterActorMessage(name: String, actor: LiftActor)
class ConditionalDispatcher(val eventName: String) {
var registration: EventRegistration = registerForEvent(eventName, execute)
val myConditions = new mutable.HashMap[(String, Any), mutable.HashSet[ConditionalRegistration]]
def add(c: ConditionalRegistration) {
logger.trace("[add] enter with condition {}", c.condition)
myConditions.get(c.condition) match {
case None =>
val callbacks = mutable.HashSet[ConditionalRegistration](c)
myConditions.put(c.condition, callbacks)
case Some(callbacks) =>
callbacks.add(c)
}
logger.trace("[EventService$ConditionalDispatcher.add] exit.")
}
def remove(c: ConditionalRegistration) {
logger.trace("[remove] enter with condition {}.", c.condition)
val so = myConditions.get(c.condition)
if (so == None) {
logger.warn("[remove] tried to remove conditional that did not exist.")
return
}
val callbacks = so.get
val result = callbacks.remove(c)
if (! result) {
logger.debug("[remove] remove of {} failed.", c.callback)
}
if (callbacks.isEmpty) {
logger.trace("[remove] removing set for condition {}.", c.condition)
myConditions.remove(c.condition)
}
if (myConditions.isEmpty) {
logger.trace("[remove] removing callback for event {}.", eventName)
registration.deregister()
}
logger.trace("[remove] exit.")
}
def execute(event: EFLEvent) {
logger.trace("[execute] enter.")
myConditions.foreach((a) => evaluate(event, a._1, a._2))
}
def evaluate(event: EFLEvent, condition: (String, Any), callbacks: mutable.HashSet[ConditionalRegistration]) {
val vOption = event.getProperty(condition._1)
logger.trace("[evaluate] property: {}, looking for: {}, found: {}", condition._1, condition._2, vOption)
vOption match {
case None => // automatic false, do nothing
case Some(value) => if (condition._2 == value) callbacks.foreach((callback: ConditionalRegistration) => callback.call(event))
}
}
}
/**
* Gets the exception stack trace as a string.
* @return String representation of exception.
*/
def getStackTraceAsString(exception: Exception): String = {
val sw = new StringWriter
val pw: PrintWriter = new PrintWriter (sw)
pw.print (" [ ")
pw.print (exception.getClass.getName )
pw.print (" ] ")
pw.print (exception.getMessage )
exception.printStackTrace (pw)
sw.toString
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T12:46:39.983",
"Id": "84642",
"Score": "0",
"body": "The [Netflix reactive programming library](https://github.com/Netflix/RxJava/tree/master/language-adaptors/rxjava-scala) does something similar. The whole approach is somewhat different since it is reactive programming, but you might want to look at it to get some ideas."
}
] | [
{
"body": "<p>Your whole design looks very mutable, but because I don't know your domain or the libraries you use I can't say to what extend it makes sense to functionalize it. Some thoughts while looking through the code:</p>\n\n<p>Always specify return types for public members (even consider <code>Unit</code>), especially in an interface definition:\n<code>def postEvent(event: EFLEvent)</code> → <code>def postEvent(event: EFLEvent): Unit</code>. This makes it easier to understand someone else code (sometimes the inferred types are nontrivial).</p>\n\n<hr>\n\n<p>The return types in subclasses need to be specified most of the time too (what you did). Scala allows covariant return types in override definitions which can be a problem because type inference makes use of this feature and therefore can result in compilation errors in some special cases where one only works with concrete subclasses and not the interfaces.</p>\n\n<hr>\n\n<p>Never initialize an instance field with a default value, always use the underscore:\n<code>var context: EFLContext = null</code> → <code>var context: EFLContext = _</code>. They have a different semantic meaning! The latter one leaves the initialization to the JVM, which does the thing one expects. The former one will initialize the field with <code>null</code> in the constructor, the JVM initialization is done before the constructor is even called. For subclass relationships this can make a huge difference:</p>\n\n<pre><code>scala> trait A { var x: String; init(); def init(): Unit = x = \"initialized\" }\ndefined trait A\n\nscala> class B extends A { override var x: String = null }\ndefined class B\n\nscala> class C extends A { override var x: String = _ }\ndefined class C\n\nscala> (new B).x\nres0: String = null\n\nscala> (new C).x\nres1: String = initialized\n</code></pre>\n\n<hr>\n\n<p><code>xs.foreach(n => {})</code> can be written as <code>xs.foreach { n => }</code></p>\n\n<hr>\n\n<p>I'm not familiar with Lift and therefore don't know their preferred coding style but when I see <code>def registerForEvent(name: String, callback: (EFLEvent) => Unit): EventRegistration</code> and an actor I can only think about callback hell. When I have actors then I prefer having only actors that send each other messages. Maybe a callback free and actor only solution makes sense for you too, think about it.</p>\n\n<hr>\n\n<p>Your try-catch blocks look cumbersome. They can be abstracted away with something like</p>\n\n<pre><code>def withErrorLogging(message: String)(f: => Unit) =\n try f catch { case t: Throwable => logger.error(message, t) }\n\nwithErrorLogging(\"[registerActorForEvent]\") { ... }\n</code></pre>\n\n<p>In fact, all of your register*/deregister* functions look the same. Try to move out the part which differ (which seems to be only the code in the try-block)</p>\n\n<hr>\n\n<p>Sometimes you use a <code>Thread.sleep(n)</code>, which shouldn't be used in an actor environment, because they block.</p>\n\n<hr>\n\n<p>I would never pass a mutable HashSet: <code>def evaluate(..., callbacks: mutable.HashSet[ConditionalRegistration])</code>. Do you know that it is not changed in this function, or is it intended to be changed by this function? In any case always prefer immutability to the outside, it makes it a lot easier to reason about control flow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T12:11:39.703",
"Id": "84637",
"Score": "0",
"body": "Thank you, @sschaef, very helpful. One thing that I'm not familiar with - you used the expression \"callback hell\" but I've never encountered a situation where callbacks were a problem. Can you please explain or provide a reference to an article, blog or such?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T12:44:35.033",
"Id": "84641",
"Score": "0",
"body": "I don't know good resources that describe the problem of callbacks, but it is not difficult to see these problems. You can name callbacks listeners, functions or whatever you want, they are async and therefore make it much harder to reason about control flow. There order of execution, the time of their execution, who executes them and the place of their execution are difficult to specify, especially if you have a lot of them. Actors make these problems far easier to reason about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T13:05:10.923",
"Id": "84644",
"Score": "0",
"body": "I made a comment in the OP about the Netflix reactive programming library. Its main goal is to get rid of \"callback hell\". Instead of thinking about callbacks, you think in terms of streams of events (Observables). The library allows the creation of new streams by splitting/merging, filtering, etc. other streams. I took the reactive programming class on Coursera; I don't know if you can register after the class is done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T04:19:36.087",
"Id": "86284",
"Score": "0",
"body": "@sschaef: After looking reading several articles that talk about callback hell in various contexts, I could not find a single problem described in those articles that apply to this design. Many of the problems are talking about any object being able to call any other object. None of my callbacks are like that, they are merely the glue between a distributor of events (the EventActor) and the consumer of events (a function within an object). Or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T10:33:15.850",
"Id": "86313",
"Score": "0",
"body": "Just try out your design. You will see if it works for you or if it starts making problems one day."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T14:54:42.537",
"Id": "86355",
"Score": "0",
"body": "@sschaef I have been using this design in production code, but I wrote most of this when I was just starting to learn Scala and I'm trying to do better. This version is MUCH better than the original (my event objects were mutable)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T09:27:42.253",
"Id": "48218",
"ParentId": "48210",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48218",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T04:58:19.427",
"Id": "48210",
"Score": "8",
"Tags": [
"scala"
],
"Title": "Event dispatcher"
} | 48210 |
<p>I'm creating a Space Invaders game, and graphics sprites in it are defined as 2D arrays of colors. </p>
<p>It seems like it's going to be cumbersome declaring these arrays the way I currently am:</p>
<pre><code>//This creates an inverting red/blue cross animation
public Sprite myFirstAnimation()
{
Sprite frame1 = new Sprite(new Color[,]
{{Color.Red, Color.Blue, Color.Red},
{Color.Blue, Color.Blue, Color.Blue},
{Color.Red, Color.Blue, Color.Red}});
Sprite frame2 = new Sprite(new Color[,]
{{Color.Blue, Color.Red, Color.Blue},
{Color.Red, Color.Red, Color.Red},
{Color.Blue, Color.Red, Color.Blue}});
AnimatedSprite myAnimatedSprite = new AnimatedSprite(new Sprite[] { frame1, frame2 });
return myAnimatedSprite;
}
</code></pre>
<p>Can you point me the the direction for a nicer way of doing this, as to make it more maintainable and readable, and less arduous? </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T05:21:45.287",
"Id": "84615",
"Score": "1",
"body": "... It seems like, using a bit of code that will convert bitmaps into my 2d array is what I'm going to want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T08:15:13.243",
"Id": "84622",
"Score": "0",
"body": ".... or just using the `System.Drawing.Image.Bitmap` class..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T08:31:26.837",
"Id": "84625",
"Score": "0",
"body": "Those sound like great ideas - go and implement them!"
}
] | [
{
"body": "<p>You're trying to store data in code. While that is not bad idea by itself, you shouldn't overuse it and I think that's what you're doing here.</p>\n\n<p>If your data is bitmaps, store them in some bitmap format (BMP or maybe PNG) and then load them into your program from that. As an additional advantage, you will be able to edit your images using normal image editing software (like Paint), instead of having to edit your code.</p>\n\n<p>If you want to keep having your bitmaps in code, you want to decrease the verbosity and you're willing to lose some type-safety, you could encode your bitmaps as strings and then transform them into 2D array using a helper function.</p>\n\n<p>It could look something like:</p>\n\n<pre><code>Color[,] frame1 = FormatMatrix(\"010 111 010\", Color.Red, Color.Blue);\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>Color[,] frame1 = FormatMatrix(@\"\n010\n111\n010\", Color.Red, Color.Blue);\n</code></pre>\n\n<p>The helper function would look something like this:</p>\n\n<pre><code>static T[,] FormatMatrix<T>(string format, params T[] values)\n{\n var formatParts = format.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);\n\n T[,] result = new T[formatParts.Length, formatParts[0].Length];\n\n for (int i = 0; i < formatParts.Length; i++)\n {\n var formatPart = formatParts[i];\n\n for (int j = 0; j < formatPart.Length; j++)\n {\n if (formatPart[j] >= '0' && formatPart[j] <= '9')\n result[i,j] = values[formatPart[j] - '0'];\n else\n throw new ArgumentException(\"format\");\n }\n }\n\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-14T15:45:58.360",
"Id": "49741",
"ParentId": "48211",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T05:11:40.903",
"Id": "48211",
"Score": "4",
"Tags": [
"c#",
"array"
],
"Title": "Declaring a large number of 2D arrays to be used as 2D graphic sprites"
} | 48211 |
<p>This code is for a simple 2D tile-based game. <code>x1</code> and <code>y1</code> are the mouse coordinates in the world. <code>entity->x1</code> and <code>entity->y1</code> is the point where the player is, the shot origin.</p>
<p>I would like to know how to keep the current output while simplifying the code and improving performance.</p>
<pre><code>void shoot(Map *map, Entity *entity, int x1, int y1)
{
float slope = (y1 - entity->y1) / (x1 - entity->x1);
float y = entity->y1; //Weapon position
Block *block;
if(x1 > entity->x1){
y += slope;
for(float x = entity->x1 + 1; x < map->width && y < map->height && y > 0; ++x){
//Get block at position x y. Check if found a hit
if((block = map_block_at(map, x, y))->type != EMPTY){
block_cause_damage(block, entity->hand_item->weapon.damage);
return;
}
y += slope;
}
}
else
if(x1 < entity->x1){
y -= slope;
for(float x = entity->x1 - 1; x > 0 && y < map->height && y > 0; --x){
//Get block at position x y. Check if found a hit
if((block = map_block_at(map, x, y))->type != EMPTY){
block_cause_damage(block, entity->hand_item->weapon.damage);
return;
}
y -= slope;
}
}
//When the player shoots up or down
else {
slope = (y1 > entity->y1) ? 1 : - 1;
y += slope;
while(y < map->height && y > 0){
//Get block at position x y. Check if found a hit
if((block = map_block_at(map, x1, y))->type != EMPTY){
block_cause_damage(block, entity->hand_item->weapon.damage);
return;
}
y += slope;
}
}
}
</code></pre>
<p>The code for <code>Entity</code> and <code>Map</code>:</p>
<pre><code>typedef struct Entity {
Renderable renderable;
plist_id render_id;
Point (*get_current_position)(struct Entity *, uint32_t);
int health, attack_damage, running, jumping;
float x0, y0, x1, y1;
uint32_t t0, t1;
enum {LEFT, RIGHT} side;
Image **texture;
Item *hand_item;
Backpack backpack;
} Entity;
typedef struct {
Renderable renderable;
plist_id render_id;
int width, height;
Block *blocks;
Camera *camera;
} Map;
</code></pre>
| [] | [
{
"body": "<p>I have a few remarks:</p>\n\n<ul>\n<li><p>You may have a problem with this line of code:</p>\n\n<pre><code>float slope = (y1 - entity->y1) / (x1 - entity->x1);\n</code></pre>\n\n<p>If <code>entity</code> is already at the longitude <code>x1</code>, this will cause a division by 0. Such a division is undefined behaviour. Anything can happen. A plane may crash on your house. You should check first whether <code>x1 == entity->x1</code> and handle this case properly. I see that the last <code>else</code> close of your program handles this case (<code>//When the player shoots up or down</code>), but the division by 0 appears <em>before</em> you handle it.</p></li>\n<li><p>I don't know whether <code>entity.x</code> and <code>entity.y</code> are <code>int</code> or <code>float</code> types. If they are <code>int</code> types, I guess that you can get rid of the <code>float</code> variables: the only thing that may need more precision than an integer is <code>slope</code>, and if <code>entity.x</code> and <code>entity.y</code> are integer types, then <code>slope</code> will contain an integer cast to a <code>float</code> (since it was initialized with an integer division).</p></li>\n</ul>\n\n<p>It lacks a bit of context to provide a complete review. You should post the code of at least <code>Map</code> and <code>Entity</code> so that we don't have to assume things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:32:38.773",
"Id": "84730",
"Score": "0",
"body": "Thank you for answering. I'll post the code for `entity` and `map`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T12:10:30.833",
"Id": "48223",
"ParentId": "48212",
"Score": "8"
}
},
{
"body": "<p>It's a little difficult to do a good review because there are so many pieces missing, but I've guessed at a number of things and I believe I can help.</p>\n\n<p>Specifically, it looks like your <code>Map</code> is a rectangular grid of <code>Block</code>s and that all <code>x</code> and <code>y</code> coordinates are integers. If so, then your <code>shot</code> routine is really doing the equivalent of drawing a line from the <code>entity</code> location to the passed <code>x1</code>,<code>y1</code> coordinates and one very efficient way to do that is to use <a href=\"https://stackoverflow.com/questions/10060046/drawing-lines-with-bresenhams-line-algorithm\">Bresenham's line-drawing algorithm</a>. Using a slight modification of that algorithm, since your <code>shot</code> routine seems to want to go until it either hits something or goes off the <code>Map</code>, we get a very efficient and very small routine:</p>\n\n<pre><code>void shoot(Map *map, Entity *entity, int x1, int y1)\n{\n int sx = entity->x1 < x1 ? 1 : -1;\n int sy = entity->y1 < y1 ? 1 : -1;\n int dx = abs(x1 - entity->x1);\n int dy = abs(y1 - entity->y1);\n int err = (dx>dy ? dx : -dy)/2;\n int e2;\n\n x1 = entity->x1;\n y1 = entity->y1;\n Block *block;\n while (inbounds(map,x1,y1)) {\n e2 = err;\n if (e2 > -dx) {\n err -= dy;\n x1 += sx;\n }\n if (e2 < dy) {\n err += dx; \n y1 += sy;\n }\n if((block = map_block_at(map, x1, y1))->type != EMPTY){\n block_cause_damage(block, entity->hand_item->weapon.damage);\n return;\n }\n }\n}\n</code></pre>\n\n<p>I've assumed that you have or can easily write an <code>inbounds</code> routine that returns <code>true</code> if the passed coordinates are within the <code>Map</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:31:23.417",
"Id": "84729",
"Score": "0",
"body": "Thank you for answering. I tried the code you provided and it works fine most of the time. But sometimes it gets stuck in the loop. I added another variable `get_out`, it's set to `0` on every iteration and incremented using `else` statements right after `if (e2 > -dx)` and `if (e2 < dy) `, then I check if `get_out == 2` and exit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:23:08.717",
"Id": "48262",
"ParentId": "48212",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "48262",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T06:23:30.467",
"Id": "48212",
"Score": "12",
"Tags": [
"optimization",
"algorithm",
"c"
],
"Title": "Optimize code to track player shot"
} | 48212 |
<p>The Greed game, from Ruby Koans, where you roll up to 5 dice:</p>
<blockquote>
<p>A set of three ones is 1000 points. A set of three numbers (other than ones) is worth 100 times the number.</p>
<p>A one (that is not part of a set of three) is worth 100 points. A five (that is not part of a set of three) is worth 50 points. Everything else is worth 0 points.</p>
</blockquote>
<p>I broke my solution into four methods.</p>
<pre><code>def score(dice)
(1..6).reduce(0) { |sum, n| sum + points(dice, n) }
end
def points(dice, num)
((dice.count(num) / 3) * triple(num)) + ((dice.count(num) % 3) * bonus(num))
end
def triple(num)
num == 1 ? 1000 : (num * 100)
end
def bonus(num)
[1, 5].include?(num) ? 50 + (50 * (num % 5)) : 0
end
</code></pre>
<p>I suspect there's a way to avoid having to pass the <code>dice</code> array into <code>points()</code>, but I can't figure it out. Maybe using a <code>yield</code> somewhere?</p>
| [] | [
{
"body": "<p>I think your code is very nice, succinct, and ruby-like.</p>\n\n<p>Two minor issues - </p>\n\n<p>Your <code>bonus</code> code is a bit over-sophisticated, which makes it not very readable, and quite brittle. Although it won't fit in one line - a <code>case</code> solution will be more suitable here:</p>\n\n<pre><code>def bonus(num)\n case num\n when 1 then 100;\n when 5 then 50;\n else 0;\n end\nend\n</code></pre>\n\n<p>Also, in <code>score</code> I personally think that separating the score calculation from its aggregation is more easy on the eyes:</p>\n\n<pre><code>(1..6).map { |n| points(dice, n) }.inject(:+)\n</code></pre>\n\n<p>although, I admit, it is more a matter of taste than anything else...</p>\n\n<hr>\n\n<p>As for your suspicion about not having to pass <code>dice</code> to <code>points</code>, I don't see a straight-forward way of doing that, or a proper motivation <em>for</em> doing it.</p>\n\n<p>Perhaps you want to be able to simplify your block into a straight forward method call (using a syntax like <code>.map(&some_method)</code>) - for that you can use proc's <a href=\"http://www.ruby-doc.org/core-2.1.1/Proc.html#method-i-curry\"><code>curry</code></a> method, but it actually results in a very awkward code, which does not seem to be worth it:</p>\n\n<pre><code>def score(dice)\n (1..6).map(&lambda(&method(:points)).curry[dice]).inject(:+)\nend\n</code></pre>\n\n<p>Perhaps you want to decouple the point calculation methods from the <code>dice</code> array altogether. This can be done easily enough by passing <code>dice.count(n)</code> instead of <code>dice</code>, as that is all the <code>points</code> actually cares about, although this solution will break as soon as point calculation will need more information...</p>\n\n<pre><code>def score(dice)\n (1..6).reduce(0) { |sum, n| sum + points(n, dice.count(n)) }\nend\n\ndef points(num, count)\n ((count / 3) * triple(num)) + ((count % 3) * bonus(num))\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T13:59:11.357",
"Id": "84647",
"Score": "0",
"body": "I agree on all counts! When I figured out a way to implement bonus() with modulus in a one-liner, I couldn't help myself. The case statement definitely makes more sense though. Thanks for the review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T07:57:03.053",
"Id": "48216",
"ParentId": "48213",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48216",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T06:43:10.810",
"Id": "48213",
"Score": "7",
"Tags": [
"ruby",
"dice"
],
"Title": "RubyKoans: Greed dice scoring"
} | 48213 |
<p>I'm trying to display data from Keen.io we're collecting from an iOS app where we report what devices of ours the app is used to communicate with. In particular I'm trying to find where there are more than one of our device.</p>
<p>An entry from the Keen collection looks like:</p>
<pre><code>{
"iOS_OpenUDID": "hexadecimal",
"iOS_CountryCode": "two-letter country code",
"Device": {
"SerialNumber": "numbers",
"Barcode": "numbers",
"IP": "IP address",
"Model": "string",
},
"iOS_Timezone": "name of timezone",
}
</code></pre>
<p>Most of this is adapted from various different examples and tutorials, and as far as I can tell, it works. Examples I remember using are:</p>
<ul>
<li><a href="https://developers.google.com/chart/interactive/docs/gallery/table" rel="nofollow noreferrer">Google Developers - Visualization: Table</a></li>
<li><a href="http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/" rel="nofollow noreferrer">Dreaming In Javascript - Eliminating Duplicates</a></li>
</ul>
<p>I have no idea though if it's 'good' code or 'awful', so please give constructive criticism:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Cache-Control" content="no-cache, mustrevalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<title>Multiple Devices</title>
<script type="text/javascript">
var Keen=Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};(function(){var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src=("https:"==document.location.protocol?"https://":"http://")+"dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)})();
Keen.configure({
projectId: "REMOVED",
readKey: "REMOVED"
});
// From http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
function eliminateDuplicates(arr) {
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
out.push(i);
}
return out;
}
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
function drawTable() {
var datatable = new google.visualization.DataTable();
datatable.addColumn('string', 'iOS OpenUDID');
datatable.addColumn('string', 'Models (Barcode, Serial Number, IP address)');
datatable.addColumn('string', 'App Brand');
datatable.addColumn('string', 'iOS Timezone');
var table = new google.visualization.Table(document.getElementById('table_div'));
var metric = new Keen.Metric("Devices", {
analysisType: "count_unique",
targetProperty: "Device.IP",
groupBy: "iOS_OpenUDID",
filters: [
{"property_name":"iOS_OpenUDID","operator":"exists","property_value":true},
]
});
metric.getResponse(function(response){
// console.log(response);
for (var id = 0; id < response.result.length; id++) {
if (response.result[id].result > 1) {
// console.log(response.result[id]);
var query = "https://api.keen.io/3.0/projects/REMOVED/queries/extraction?api_key=DEVICES&event_collection=Devices&timezone=43200&target_property=Device.Model&group_by=Device.Model&filters=%5B%7B%22property_name%22%3A%22iOS_OpenUDID%22%2C%22operator%22%3A%22eq%22%2C%22property_value%22%3A%22" + response.result[id].iOS_OpenUDID + "%22%7D%5D";
$.getJSON(query, function(data) {
// console.log(data);
var arr = [];
for (var i = 0; i < data.result.length; i++) {
if (data.result[i] !== undefined && data.result[i] !== null) {
var string = data.result[i].Device["Model"];
var string2 = "";
if (data.result[i].Device["Barcode"] !== undefined && data.result[i].Device["Barcode"] !== null) {
string2 += data.result[i].Device["Barcode"];
}
if (data.result[i].Device["SerialNumber"] !== undefined && data.result[i].Device["SerialNumber"] !== null) {
if (string2.length > 0) {
string2 += ", ";
}
string2 += data.result[i].Device["SerialNumber"];
}
if (data.result[i].Device["IP"] !== undefined && data.result[i].Device["IP"] !== null) {
if (string2.length > 0) {
string2 += ", ";
}
string2 += data.result[i].Device["IP"];
}
if (string2.length > 0) {
string += " (" + string2 + ")";
}
arr.push(string);
}
};
arr = eliminateDuplicates(arr);
var models = "";
for (var i = 0; i < arr.length; i++) {
if (models.length > 0) {
models += ", ";
}
models += arr[i];
}
datatable.addRow(
[data.result[0]["iOS_OpenUDID"], models, data.result[0]["Brand"], data.result[0]["iOS_Timezone"]]
);
table.draw(datatable, {showRowNumber: true});
})
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); });
}
}
});
table.draw(datatable, {showRowNumber: true});
}
</script>
<style type="text/css">
body { padding-top: 70px; }
</style>
</head>
<body>
<div id='table_div'></div>
</body>
</html>
</code></pre>
| [] | [
{
"body": "<p>Nice work, @parsley72! This is a really clever mashup, no reason to suspect it's \"not good\" or even \"awful\" :)</p>\n\n<p>[Keen IO employee here, fwiw]</p>\n\n<p>One characteristic worth considering is reusability, but since this seems to be a fairly specialized bit of code I wouldn't spend too much time there. If you do find yourself repeating operations, there might be the beginnings of a reusable utility hiding in there somewhere. And if that's the case, please let me know.. it may be handy enough for us to roll into the library.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:35:15.413",
"Id": "48443",
"ParentId": "48214",
"Score": "2"
}
},
{
"body": "<p>Entire <code>eliminateDuplicates()</code> function can be now replaced simply with <code>[...new Set(arr)]</code>.</p>\n\n<hr>\n\n<p>Callback of <code>$.getJSON</code> can be simplified. Instead of sea of <code>if</code>s to filter out <code>undefined</code>s and <code>null</code>s and to join elements with a comma, it can be done this way:</p>\n\n<pre><code>const models = new Set();\n\nfor (const result of data.result) {\n if (result === undefined || result === null) { continue; }\n\n const arr = [result.Device.Barcode, result.Device.SerialNumber, result.Device.IP]\n .filter(data => data !== undefined && data !== null).join(', ');\n\n models.add(result.Device.Model + (arr.length > 0 ? ` (${arr})` : ''));\n}\n</code></pre>\n\n<p>First all data get into an array, then <code>undefined</code>s and <code>null</code>s get filtered out, and all entries are joined with <code>,</code>. If there is anything in that array it get's appended to what will be added to <code>models</code>. Notice also, that since <code>models</code> is a <code>Set</code> and not an array, it does not have to be checked for duplicates.</p>\n\n<hr>\n\n<p>In your query, <code>response.result[id].iOS_OpenUDID</code> is not encoded, while another part of it is (value of <code>filters</code> param), worsening readability. Another approach:</p>\n\n<pre><code>const filters = encodeURIComponent(`[{\"property_name\":\"iOS_OpenUDID\",\"operator\":\"eq\",\"property_value\":\"${that.iOS_OpenUDID}\"}]`);\nconst query = '………' + filters;\n</code></pre>\n\n<hr>\n\n<h2>Rewrite</h2>\n\n<pre><code>var Keen=Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};(function(){var e=document.createElement('script');e.type='text/javascript',e.async=!0,e.src=('https:'==document.location.protocol?'https://':'http://')+'dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js';var t=document.getElementsByTagName('script')[0];t.parentNode.insertBefore(e,t)})();\n\nKeen.configure({\n projectId: 'REMOVED',\n readKey: 'REMOVED'\n});\n\ngoogle.load('visualization', '1', {packages:['table']});\ngoogle.setOnLoadCallback(drawTable);\n\nconst datatable = new google.visualization.DataTable();\n\ndatatable.addColumn('string', 'iOS OpenUDID');\ndatatable.addColumn('string', 'Models (Barcode, Serial Number, IP address)');\ndatatable.addColumn('string', 'App Brand');\ndatatable.addColumn('string', 'iOS Timezone');\n\nconst table = new google.visualization.Table(document.getElementById('table_div'));\n\nconst onFetch = data => {\n // console.log(data);\n\n const models = new Set();\n\n for (const result of data.result) {\n if (result === undefined || result === null) { continue; }\n\n const arr = [result.Device.Barcode, result.Device.SerialNumber, result.Device.IP]\n .filter(data => data !== undefined && data !== null).join(', ');\n\n models.add(result.Device.Model + (arr.length > 0 ? ` (${arr})` : ''));\n }\n\n datatable.addRow([\n data.result[0].iOS_OpenUDID,\n [...models].join(', '),\n data.result[0].Brand,\n data.result[0].iOS_Timezone\n ]);\n\n table.draw(datatable, {showRowNumber: true});\n};\n\nfunction drawTable() {\n const metric = new Keen.Metric('Devices', {\n analysisType: 'count_unique',\n targetProperty: 'Device.IP',\n groupBy: 'iOS_OpenUDID',\n filters: [{'property_name': 'iOS_OpenUDID', 'operator': 'exists', 'property_value': true}]\n });\n\n metric.getResponse(function(response) {\n // console.log(response);\n for (const that of response.result) {\n if (that.result <= 1) { continue; }\n // console.log(that);\n const filters = encodeURIComponent(`[{\"property_name\":\"iOS_OpenUDID\",\"operator\":\"eq\",\"property_value\":\"${that.iOS_OpenUDID}\"}]`);\n const query = 'https://api.keen.io/3.0/projects/REMOVED/queries/extraction?api_key=DEVICES&event_collection=Devices&timezone=43200&target_property=Device.Model&group_by=Device.Model&filters=' + filters;\n\n fetch(query).then(response => response.json()).then(onFetch).catch(reason =>\n alert(`fetch, JSONing or onFetch function failed. Reason: ${reason}`)\n );\n }\n });\n\n table.draw(datatable, {showRowNumber: true});\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-28T18:57:44.410",
"Id": "494579",
"Score": "0",
"body": "Ahoy! Do you ever intend to un-delete [this answer](https://codereview.stackexchange.com/a/175885/120114)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T21:35:15.450",
"Id": "505613",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ: done"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-19T10:33:45.277",
"Id": "196813",
"ParentId": "48214",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-26T07:37:35.130",
"Id": "48214",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "Detect multiple devices in Keen.io collection"
} | 48214 |
<p>I have a private method that is called from the constructor to instantiate a bunch of objects.</p>
<p>I can do it two ways.</p>
<pre><code> private Monster[,] createMonsters()
{
Monster[,] myMonsterArray = new Monster[8, 6];
for (int i = 0; i < 8; i++)
{
myMonsterArray[0, i] = new Monster(SpriteFactory.getMonster1Sprite());
myMonsterArray[1, i] = new Monster(SpriteFactory.getMonster2Sprite());
myMonsterArray[2, i] = new Monster(SpriteFactory.getMonster3Sprite());
myMonsterArray[3, i] = new Monster(SpriteFactory.getMonster1Sprite());
myMonsterArray[4, i] = new Monster(SpriteFactory.getMonster2Sprite());
myMonsterArray[5, i] = new Monster(SpriteFactory.getMonster3Sprite());
}
return myMonsterArray;
}
</code></pre>
<p>called with </p>
<pre><code>monsterArray = createMonsters();
</code></pre>
<p>or</p>
<pre><code> private void createMonsters()
{
monsterArray = new Monster[8, 6];
for (int i = 0; i < 8; i++)
{
monsterArray[0, i] = new Monster(SpriteFactory.getMonster1Sprite());
monsterArray[1, i] = new Monster(SpriteFactory.getMonster2Sprite());
monsterArray[2, i] = new Monster(SpriteFactory.getMonster3Sprite());
monsterArray[3, i] = new Monster(SpriteFactory.getMonster1Sprite());
monsterArray[4, i] = new Monster(SpriteFactory.getMonster2Sprite());
monsterArray[5, i] = new Monster(SpriteFactory.getMonster3Sprite());
}
}
</code></pre>
<p>called with</p>
<pre><code>createMonsters();
</code></pre>
<p>Is either better or worse?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T09:59:51.420",
"Id": "84633",
"Score": "2",
"body": "I was set off by the fact that you have *camelCase* method names, whereas I thought that they would be *PascalCase* in C#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T10:16:52.587",
"Id": "84634",
"Score": "0",
"body": "Huh is it? - I _had_ been noticing that the syntax was like that, in the API, and I wasn't sure why it was the case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T11:01:08.320",
"Id": "84635",
"Score": "0",
"body": "This is the first C# project I've worked on in a while, just to add it to my portfolio."
}
] | [
{
"body": "<p>Consider it is just an initializer and will only be used this once, there is no need to make it explicitly return the data when you can just set it directly.</p>\n\n<p>Therefore the second approach would be my approach as well.</p>\n\n<h1>Naming</h1>\n\n<p>Method names are UpperCamelCase in C# so this</p>\n\n<pre><code>createMonsters\n</code></pre>\n\n<p>should become</p>\n\n<pre><code>CreateMonsters\n</code></pre>\n\n<h1>Indices</h1>\n\n<p>You have your indices swapped: you define it as <code>[8, 6]</code> but you use it as <code>[6, 8]</code> which will lead to <code>IndexOutOfRangeExceptions</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T11:45:21.907",
"Id": "48222",
"ParentId": "48219",
"Score": "8"
}
},
{
"body": "<p><strong>It depends</strong></p>\n<p>I personally find a method that returns it more flexible and more of a separation-of-concerns approach. And by doing so, you could even move the method into another class, such as a <code>Factory</code> class that perhaps can provide you with other monster arrays.</p>\n<p>However, it is perfectly reasonable to use a method that returns <code>void</code> if:</p>\n<ul>\n<li>The reason for why you have this method in the first place is that you want to extract some code in your constructor into it's own method</li>\n<li>Your <code>myMonsterArray</code> is in a way "tightly coupled" with your class (i.e. it wouldn't make much sense to have the monster array without also having your class - think of a 8x8 chess grid without <em>the chess game itself</em> for example)</li>\n</ul>\n<p>In the end, which way you choose is up to you.</p>\n<h3>Other comments</h3>\n<p>Instead of numbering your <code>SpriteFactory.getMonster1Sprite()</code> methods, use <code>SpriteFactory.getMonsterSprite(1)</code>, this would allow you to write:</p>\n<pre><code>for (int i = 0; i < 8; i++)\n{\n for (int a = 0; a < 6; a++)\n {\n myMonsterArray[a, i] = new Monster(SpriteFactory.getMonsterSprite(a % 3));\n }\n}\n</code></pre>\n<p><strong>Magic numbers:</strong> Instead of using <code>8</code> and <code>6</code> (and perhaps even <code>3</code>) in the double-loop above, retreive the length of your array with <code>myMonsterArray.GetLength(0)</code> and <code>myMonsterArray.GetLength(1)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:05:09.293",
"Id": "84651",
"Score": "0",
"body": "The length of an array is retrieved with `myArray.Length` ...or did you think it was Java? ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:23:06.637",
"Id": "84654",
"Score": "0",
"body": "@Mat'sMug No, I'm aware it's C#. `GetLength` is what [MSDN says](http://msdn.microsoft.com/en-us/library/vstudio/system.array.getlength) and also what I used in [my C# Sudoku Solver](http://codereview.stackexchange.com/questions/37448/sudokusharp-solver-with-advanced-features) - have I missed anything?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:26:46.953",
"Id": "84655",
"Score": "0",
"body": "Nevermind, brainfart. Length wouldn't be useful for multidimentional arrays.. catxh you in chat later! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:19:12.100",
"Id": "84672",
"Score": "1",
"body": "An additional reason, related to the ones you cite, for preferring the version that returns the values: you could then extract an abstract superclass and defer creating the values to the subclass, and have the resulting variable remain private rather than needing to be changed to protected. A simpler variant of the Factory version you suggest."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T14:24:02.353",
"Id": "48226",
"ParentId": "48219",
"Score": "11"
}
},
{
"body": "<p>I would pick the method where you return an array of objects, because that makes it easier to unit test that method should you feel the need.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:47:42.443",
"Id": "84678",
"Score": "3",
"body": "`private` methods should not be unit tested considering they are not a part of the exposed API and thus, by definition, their internal definition is not reliable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T06:04:34.747",
"Id": "84758",
"Score": "1",
"body": "Many frameworks provide the ability to test private methods. Unit testing is usually done by the developers who are well aware of the functionality. In my opinion unit testing of private members will help to improve the quality."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:52:05.600",
"Id": "48244",
"ParentId": "48219",
"Score": "5"
}
},
{
"body": "<p>As far as I see no-one has mentioned temporal coupling yet, so here it is.</p>\n\n<p>The second one (which returns void) has this <a href=\"https://en.wikipedia.org/wiki/Code_smell\">code smell</a>. Consider the following constructor code:</p>\n\n<pre><code>createMonsters();\n...\ndoSomethingWithMonsters();\n</code></pre>\n\n<p>A maintainer easily could mix up the order of the called methods which breaks your class and might turn out only at runtime. It's not possible the following:</p>\n\n<pre><code>Monster[,] monsters = createMonsters();\n...\ndoSomethingWithMonsters(monsters);\n</code></pre>\n\n<p>Changing the order of the two methods simply would not compile.</p>\n\n<p>Another advantage of the first one is that your field could be <code>final</code> (or readonly, I'm not too familiar with C# but I guess it has something like that). The following constructor code also does not compile in Java if the <code>monsters</code> field is <code>final</code>:</p>\n\n<pre><code>doSomethingWithMonsters(monsters);\nmonsters = createMonsters();\n</code></pre>\n\n<p>Furthermore, having the array return value makes the code easier to read. It's obvious from the signature what the method does, readers don't have to check the method body to figure out its side-effects. Finally, you could call <code>createMonsters()</code> from other methods without side-effects.</p>\n\n<p>Anyway, having the separate factory class (as a constructor parameter) looks even better, it's less coupled, +1 to Simon.</p>\n\n<p>See also: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G31: Hidden Temporal Couplings</em>, p302</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T07:31:12.007",
"Id": "84768",
"Score": "1",
"body": "Yep, temporal coupling is the first thing that went through my mind when I read that question. This is a beautiful case for this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T20:46:04.517",
"Id": "48268",
"ParentId": "48219",
"Score": "16"
}
},
{
"body": "<p>TLDR: The first approach is better, pure functions are easier to understand.</p>\n\n<p>I would personally go with the first approach. As a general rule I prefer pure functions. While in this case I don't think it would make much difference, I have very rarely ever found that I was happier with a mutating function like this. I think pure functions are much easier to reason about, and reduce complexity. In general the creation of the object is best left to the function while the assignment should be left to the constructor.</p>\n\n<p>As with all code, if there was a single rule that could be easily applied, we wouldn't need programmers, as computers already excel at applying basic rules. What makes a programmer valuable is that there are many tools/patterns that can be applied, and they always have various trade offs. Our job is to understand where the tools/patterns give good value and apply them intelligently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:23:04.087",
"Id": "48290",
"ParentId": "48219",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T09:44:44.217",
"Id": "48219",
"Score": "23",
"Tags": [
"c#",
"constructor",
"comparative-review"
],
"Title": "When a constructor calls a helper function, should the helper mutate the object or return part of the object?"
} | 48219 |
<p>I need to implement some functionality of the otherwise monolithic application via DLL that is loaded at runtime. (Think about a customized DLL -- different for each customer.) </p>
<p>The Visual C++ from VS 2013 is used.</p>
<p>The application gets the full name name of the DLL. The function to be called has a fixed name (<code>convert</code> in my case) and fixed number and type of the arguments (a reference to a constant vector of strings -- see the <code>cref_vs</code> below). This means the function is implemented in C++.</p>
<p>I have modified the example from the MSDN doc, and it seems to work. However, I must be sure I did not overlooked something important. Here is the code (simplified) to load the DLL and call the function:</p>
<pre><code>typedef const std::vector<std::string> & cref_vs;
typedef int(*CONVERTPROC)(cref_vs vs);
</code></pre>
<p>Notice that unlike in the official example that mixes calling a C code in DLL from a C++ function, I do not use <code>__cdecl</code>. I guess that this way I can reliably pass a C++ object (like a vector of strings). Is it correct?</p>
<pre><code>int call_convert_from_dll(const std::string & dllname,
const std::vector<std::string> & vs)
{
HINSTANCE hinstLib;
CONVERTPROC convert;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
// Get a handle to the DLL module.
hinstLib = LoadLibrary(dllname.c_str());
// If the handle is valid, try to get the function address.
if (hinstLib != nullptr) {
convert = (CONVERTPROC)GetProcAddress(hinstLib, "convert");
// If the function address is valid, call the function.
if (convert != nullptr) {
(convert)(vs);
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
if (!fRunTimeLinkSuccess)
return 1;
return 0;
}
</code></pre>
<p>Now, because I want the unmangled name of the function inside the DLL, I need to use <code>extern "C"</code>, and it must be exported via <code>__declspec(dllexport)</code>. However, I do not want to use <code>__cdecl</code> calling convention:</p>
<pre><code>#include <windows.h>
#include <iostream>
using namespace std;
extern "C" {
__declspec(dllexport) int convert(const std::vector<std::string> & vs)
{
cout << "my.dll -- convert called with arguments:\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << endl;
return 0;
}
} // extern "C"
</code></pre>
<p>Can you confirm that I am doing it correctly?</p>
| [] | [
{
"body": "<p>Short answer: No, but I won't hold it against you. ;)</p>\n\n<p>I'd suggest reading up on using C++ with DLLs in a compatible fashion, and would suggest this <a href=\"http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL#CppMatureApproach\" rel=\"nofollow\">excellent article</a> as a good place to start. This article also touches on exporting STL types, which your code is doing.</p>\n\n<p>So, the question is, how portable/robust do you need/expect your approach to be? If you need developers from anywhere to be able to plug into your system, stick to a C interface if possible (avoiding STL types -- pass a <code>char**</code> across the boundary, and convert that on the C++ side to an STL <code>vector<string></code>). Otherwise, upgrade to a virtual class based system -- and make sure that you don't directly use STL, but instead use virtual class wrappers for those types as well. Note that this carries on -- e.g., if you want to use an iterator class used by the STL type you're wrapping, you'll need another abstract (iterator) class that your abstract (iterable) class references, so it can get a little ugly.</p>\n\n<p>Minor code notes...</p>\n\n<ul>\n<li><code>fFreeResult</code> is assigned, but never used.</li>\n<li><code>fRunTimeLinkSuccess</code> is not set (after initialization).</li>\n<li>The \"convert\" string might better be contained in a macro (or a small set of macros), so that your plugin clients can declare a convert function, and you can refer to that function name without the possibility of typo.</li>\n<li>Your example plugin refers to <code>argc</code> and <code>argv</code> that don't exist.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:07:02.990",
"Id": "84662",
"Score": "1",
"body": "@LokiAstari Good catch on fRunTimeLinkSuccess never changing from its initialized value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:35:11.320",
"Id": "84666",
"Score": "0",
"body": "For the `fRunTimeLinkSuccess` -- corrected. I did remove some other lines. This one should stay there. For the `argc` and `argv`. This was actually copied from another version of the code (my fault), that was passed the arguments from the command line (for testing). The newer version parses the string from a file (`StringTok` to `vector<string>`. So, I should do the opposite way -- to convert `vector<string>` to the `int` and `char*[]`, right? Thanks, I will be back after reading the article."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:22:18.697",
"Id": "84674",
"Score": "0",
"body": "Thanks for the article. It seems that it will be better to pass the `char*` (the string from a file) and wrap the function body to the `try`/`catch` to avoid exceptions bubble from DLL to the caller (returning integer error code)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:31:29.873",
"Id": "84691",
"Score": "0",
"body": "Please, have a look at the second version http://codereview.stackexchange.com/q/48260/16189"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:34:58.687",
"Id": "48235",
"ParentId": "48224",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48235",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T13:31:01.350",
"Id": "48224",
"Score": "4",
"Tags": [
"c++",
"windows"
],
"Title": "Calling a function from a dynamically loaded DLL"
} | 48224 |
<p>Let's say you want to increment the cells around the position <code>(x,y)</code> in a square matrix <code>m</code> of size <code>T</code>.</p>
<p>I've written the same code in a few languages. Here's the JS syntax version :</p>
<pre><code>if (x>0) {
if (y>0) m[x-1][y-1]++;
m[x-1][y]++;
if (y<T-1) m[x-1][y+1]++;
}
if (y>0) m[x][y-1]++;
if (y<T-1) m[x][y+1]++;
if (x<T-1) {
if (y>0) m[x+1][y-1]++;
m[x+1][y]++;
if (y<T-1) m[x+1][y+1]++;
}
</code></pre>
<p>I don't like this kind of code, those tests look redundant. What bothers me is less the clarity of the code than the fact it has to do so many times the same checks.</p>
<p>But I don't see anything better. Am I just missing an obvious solution or is there nothing better with the branching toolset we have ? A slower code isn't acceptable as an answer, performance is the essence of the question.</p>
| [] | [
{
"body": "<p>Create an array of the offsets you want to change in your code.</p>\n\n<pre><code>var offsets = new Array();\nfor (var x = -1; x <= 1; x++) {\n for (var y = -1; y <= 1; y++) {\n if ((x != 0) || (y != 0)) {\n offsets.push({ x: x, y: y });\n }\n }\n}\n</code></pre>\n\n<p>(There are probably better ways to do this, you could hard-code the values into the array for example, but I was lazy. It is very possible that this code needs to be reviewed itself)</p>\n\n<p>Now, loop through your <code>offsets</code> and check if your <code>x + offset.x</code> is within the <code>0</code> to <code>T - 1</code> range, and the same for <code>y</code>.</p>\n\n<p>Once you have the offsets array setup, you can loop through it like this and perform your <code>++</code> operation for the matrix:</p>\n\n<pre><code>for (var index in offsets) {\n var offset = offsets[index];\n var newX = x + offset.x;\n var newY = y + offset.y;\n\n if ((newX >= 0) && (newX < T) && (newY >= 0) && (newY < T))\n m[newX][newY]++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:03:20.993",
"Id": "84661",
"Score": "0",
"body": "This is a little cleaner but it adds a loop, some operations and it does much more checks in the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:10:28.690",
"Id": "84664",
"Score": "0",
"body": "@dystroy The loop is just a replacement for your code duplication, it won't have much of an impact on performance. The overall runtime complexity remains the same (constant time, `O(8)` --> `O(1)`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:53:10.100",
"Id": "84667",
"Score": "0",
"body": "You do 5 tests for each of the 8 neighbors (counting the loop one), while I was doing only one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:57:00.903",
"Id": "84669",
"Score": "1",
"body": "@dystroy That is a price I am willing to pay for cleaner code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:38:29.457",
"Id": "48237",
"ParentId": "48231",
"Score": "3"
}
},
{
"body": "<p>Like Simon I would store the directions into a data structure, though I would probably hard code it</p>\n\n<pre><code>//Array Index Constants\nvar X = 0 , Y = 1; \n//All 8 neighbours ( vectors )\nvar vectors = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];\n</code></pre>\n\n<p>The fun thing about JavaScript is that there is no <code>ArrayIndexOutOfBoundsException</code> in JavaScript, requesting a value out of bounds returns <code>undefined</code>.</p>\n\n<p>So, now, you can go for </p>\n\n<pre><code>for( int i = 0 ; i < vectors.length ; i++ ){\n var vector = vectors[i];\n if( m[x+vector[X]] && m[x+vector[X]][y+vector[Y]] !== undefined )\n m[x+vector[X]][y+vector[Y]]++; \n}\n</code></pre>\n\n<p>I did use for <code>m[x+vector[X]]</code> a falsey comparison, if the row X was defined it would pass the falsey evaluation ( it would be an Array ). For <code>m[x+vector[X]][y+vector[Y]]</code> I compared to <code>undefined</code>, since <code>0</code> is a realistic, acceptable value which would evaluate as false.</p>\n\n<p>If I had to do a lot of matrix magic, then I would have a dedicated function to check whether a point is part of the matrix. And a dedicated function to add a vector to a point.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:55:50.610",
"Id": "85101",
"Score": "2",
"body": "I'm apparently way too used to Java, I didn't even think about `undefined`!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T12:54:15.710",
"Id": "48395",
"ParentId": "48231",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:21:16.017",
"Id": "48231",
"Score": "6",
"Tags": [
"javascript",
"performance",
"matrix"
],
"Title": "Increment the neighbors of a cell in a matrix"
} | 48231 |
<p>I'm using MVP pattern for a payroll system as my final year project. There are about 16 entity classes (like <code>employee</code>, <code>client</code>, <code>salary</code> etc.) in the analyzed problem and I have designed the solution as follows…</p>
<ul>
<li>Number of UIs (Views) – 18 </li>
<li>Separate Presenters and Models for each UI ( 18+18)</li>
<li>One Data Service (repository) catering to all presenters</li>
</ul>
<p>Each view, model and the data service implement interfaces and use dependency injection (constructor Inj). </p>
<p>Already I have implemented one UI and below is the code. This code compiles and runs giving the desired output.</p>
<p>My questions are:</p>
<ol>
<li><p>What would be the consequences of applying this pattern, at the end of the project good? or bad? (As I don’t have a previous experience)</p></li>
<li><p>Any considerable flows in this pattern or in the code?</p></li>
<li><p>Is this pattern suitable for a project at this level?</p></li>
<li><p>Any advice on improving this? </p></li>
</ol>
<p>Please note that my final ambition is to finish the project with the schedule and to pass the evaluation. So actually now what I want is to build confidence that I’m going the right direction.</p>
<p><strong><em>View</em></strong></p>
<pre><code>namespace Payroll
{
public delegate void ViewEventHandler(object sender, EventArgs e);
public partial class frmNewClient : Form, IClientView
{
//Properties
public int CID
{
get {return Convert.ToInt32(txtCID.Text); }
set { txtCID.Text=value.ToString();}
}
public string ClientName
{
get { return txtCName.Text; }
set { txtCName.Text = value; }
}
.
.
.
public frmNewClient()
{
InitializeComponent();
}
//Raise events, first to update model and then to save data to database
private void cmdSave_Click(object sender, EventArgs e)
{
DataChanged(sender, e);
Save(sender, e);
}
//Even handlers
public event EventHandler DataChanged;
public event EventHandler Save;
public event EventHandler Search;
}
}
</code></pre>
<p><strong><em>Model</em></strong></p>
<pre><code>namespace Payroll
{
class Client: IClient
{
//Properties
public int CID { get; set; }
public string ClientName { get; set; }
public string ClientAdd { get; set; }
public string ContactPerson { get; set; }
public string ClientMob { get; set; }
public string ClientTel { get; set; }
public string Remarks { get; set; }
public DateTime EnteredDate { get; set; }
//Custom constructor with parameteres
public Client(int CID, string clientName, string clientAdd, string contactPerson, string clientMob, string clientTel, string Remarks, DateTime enteredDate)
{
this.CID = CID;
this.ClientName = clientName;
this.ClientAdd = clientAdd;
this.ContactPerson = contactPerson;
this.ClientMob = clientMob;
this.ClientTel = clientTel;
this.Remarks = Remarks;
this.EnteredDate = enteredDate;
}
//Default constructor
public Client()
{
}
}
}
</code></pre>
<p><strong><em>Presenter</em></strong></p>
<pre><code>namespace Payroll
{
class ClientPresenter
{
IClient _model;
IClientView _view;
IDataService _ds;
//Constructor
public ClientPresenter( IClient model,IClientView view, IDataService ds)
{
this._ds = ds;
this._model = model;
this._view = view;
this.SetViewPropertiesFromModel();
this.WireUpViewEvents();
}
//This will wire up the custom method provided to event
private void WireUpViewEvents()
{
this._view.DataChanged +=new EventHandler(_view_DataChanged);
this._view.Save += new EventHandler(_view_Save);
this._view.Search += new EventHandler(_view_Search);
}
//Following code snippet will sinc the parameters of the view with the parameters of the model and vice versa. (All text boxes in the UI are encapsulated in properties)
//======================================================================================
private void SetModelPropertiesFromView()
{
foreach (PropertyInfo viewProperty in this._view.GetType().GetProperties())
{
if (viewProperty.CanRead)
{
PropertyInfo modelProperty = this._model.GetType().GetProperty(viewProperty.Name);
if (modelProperty != null && modelProperty.PropertyType.Equals(viewProperty.PropertyType))
{
object valueToAssign = Convert.ChangeType(viewProperty.GetValue(this._view, null), modelProperty.PropertyType);
if (valueToAssign != null)
{
modelProperty.SetValue(this._model, valueToAssign, null);
}
}
}
}
}
private void SetViewPropertiesFromModel()
{
foreach (PropertyInfo viewProperty in this._view.GetType().GetProperties())
{
if (viewProperty.CanWrite)
{
PropertyInfo modelProperty = this._model.GetType().GetProperty(viewProperty.Name);
if (modelProperty != null && modelProperty.PropertyType.Equals(viewProperty.PropertyType))
{
object modelValue = modelProperty.GetValue(this._model, null);
if (modelValue != null)
{
object valueToAssign = Convert.ChangeType(modelValue, viewProperty.PropertyType);
if (valueToAssign != null)
{
viewProperty.SetValue(this._view, valueToAssign, null);
}
}
}
}
}
}
//======================================================================================
private void _view_DataChanged(object sender, EventArgs e)
{
this.SetModelPropertiesFromView(); // Updating the model properties when data in the view properties changed…
}
private void _view_Save(object sender, EventArgs e)
{
this.Save();
}
private bool Save()
{
return _ds.InsertClient(_model);
}
private void _view_Search(object sender, EventArgs e)
{
this.Search();
}
private void Search()
{
var obj = _ds.GetByCID(_model.CID);
if (obj != null)
{
_model = obj;
this.SetViewPropertiesFromModel(); //Updating the view properties from the model if an object returned from GetByCID() method
}
}
}
}
</code></pre>
<p><strong><em>DataService</em></strong></p>
<pre><code>namespace Payroll
{
class DataService :IDataService
{
public bool InsertClient(IClient newClient)
{
string InsertStatement = @"BEGIN INSERT INTO client(Client_Name, C_Add, Contact_Person, C_Mob_No, C_Tel_No, Remarks, Ent_Date)" +
" VALUES (@CName, @CAdd, @CPerson, @CMob, @CTel, @Remarks, @entDate) END";
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
using (SqlCommand SqlCom = new SqlCommand(InsertStatement,newCon))
{
try
{
SqlCom.Parameters.Add("@CName", SqlDbType.VarChar).Value = newClient.ClientName;
SqlCom.Parameters.Add("@CAdd", SqlDbType.VarChar).Value = newClient.ClientAdd;
SqlCom.Parameters.Add("@CPerson", SqlDbType.VarChar).Value = newClient.ContactPerson;
SqlCom.Parameters.Add("@CMob", SqlDbType.Char).Value = newClient.ClientMob;
SqlCom.Parameters.Add("@CTel", SqlDbType.Char).Value = newClient.ClientTel;
SqlCom.Parameters.Add("@Remarks", SqlDbType.VarChar).Value = newClient.Remarks;
SqlCom.Parameters.Add("@entDate", SqlDbType.Date).Value = newClient.EnteredDate;
SqlCom.Connection = newCon;
newCon.Open();
SqlCom.ExecuteNonQuery();
return true;
}
catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }
if (newCon.State == System.Data.ConnectionState.Open) newCon.Close();
return false;
}
}
}
public Client GetByCID(int CID)
{
string SelectStatement=@"SELECT * FROM client WHERE CID=@ID";
using (SqlConnection NewCon = new SqlConnection(db.GetConnectionString))
{
using (SqlCommand SqlCom = new SqlCommand(SelectStatement,NewCon))
{
SqlCom.Parameters.Add("@ID", SqlDbType.Char).Value = CID;
try
{
NewCon.Open();
using (SqlDataReader NewRdr = SqlCom.ExecuteReader())
{
if (NewRdr.Read())
{
return new Client
{
CID = NewRdr.GetInt32(0),
ClientName = NewRdr.GetString(1),
ClientAdd = NewRdr.GetString(2),
ContactPerson = NewRdr.GetString(3),
ClientMob = NewRdr.GetString(4),
ClientTel = NewRdr.GetString(5),
Remarks = NewRdr.GetString(6),
EnteredDate = NewRdr.GetDateTime(7)
};
}
return null;
}
}
catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }
if (NewCon.State == System.Data.ConnectionState.Open) NewCon.Close();
return null;
}
}
}
}
}
</code></pre>
<p><strong><em>Programme</em></strong></p>
<pre><code>private void btnClient_Click(object sender, EventArgs e)
{
IClient Client = new Client();
IClientView ClientView = new frmNewClient();
IDataService ds = new DataService();
new ClientPresenter(Client, ClientView, ds);
ClientView.ShowDialog();
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p><strong>View</strong></p>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code>//Even handlers \npublic event EventHandler DataChanged;\npublic event EventHandler Save;\npublic event EventHandler Search;\n</code></pre>\n</blockquote>\n\n<p>Comments like this only clutter up the code, they add nothing that the code doesn't say already. Avoid comments that say \"what\", do use comments that say \"why\". Don't use comments to \"sectionize\" code, use vertical whitespace instead.</p>\n\n<p>I've never implemented a MVP solution (switched to WPF/MVVM before I could!), but this definitely looks like it - your <em>view</em> is blissfully unaware of any business or data logic, and that's awesome; views should be exactly that. Your data service does nothing else, and the <em>presenter</em> coordinates everything... almost:</p>\n\n<pre><code>new ClientPresenter(Client, ClientView, ds);\nClientView.ShowDialog();\n</code></pre>\n\n<p>Since the <em>view</em> is a <em>dependency</em> for the <em>presenter</em>, I'd expect the <em>presenter</em> to pick up from its constructor and be responsible for displaying the <em>view</em>. It's also awkward that you're <code>new</code>ing up a <code>ClientPresenter</code> but don't care about the object reference you've just created. I'd do something like this instead:</p>\n\n<pre><code>var presenter = new ClientPresenter(Client, ClientView, ds);\npresenter.Show();\n</code></pre>\n\n<p>Where the <em>presenter</em>'s <code>Show</code> method could be implemented by calling <code>ShowDialog</code> on the <em>view</em>, making the presenter... <em>he who presents</em> ;)</p>\n\n<hr>\n\n<blockquote>\n <p><strong>DataService</strong></p>\n</blockquote>\n\n<p><code>IDataService</code> looks like some kind of <em>repository</em> - given that you're using ADO.NET, <em>actually</em> implementing a unit-of-work + repository pattern would have some benefits here, especially if you have more than just <code>Client</code> to deal with; you <em>might</em> be interested in a generic repository solution (there <em>are</em> caveats though):</p>\n\n<pre><code>public interface IRepository<T> where T : class\n{\n T Select(int id);\n}\n</code></pre>\n\n<p>Some entities may not be <em>insertable</em> or <em>deletable</em>, and some entities may not have an <code>int</code> key - that's why I'm not a fan of this pattern, but it can work in a lot of cases:</p>\n\n<pre><code>public interface IRepository<T> : IRepository<T> where T : class\n{\n T Select(int id);\n bool Insert(T entity);\n\n // ...\n}\n\npublic class ClientRepository : IRepository<Client>\n{\n public Client Select(int id)\n {\n // ...\n }\n\n public bool Insert(Client entity)\n {\n // ...\n }\n\n // ...\n}\n</code></pre>\n\n<p>A better solution would be to use Entity Framework's built-in unit-of-work and repositories, but I'm drifting. I like that you're using parameterized queries and properly disposing of <em>disposables</em>, but there's a nasty intrusion of a presentation concern in your data service:</p>\n\n<pre><code>catch (Exception e) \n{ \n MessageBox.Show((\"Error: \" + e.Message)); \n}\n</code></pre>\n\n<p>I've put the <code>catch</code> clause on multiple lines for readability: code reads much better/faster going down than going across. The problem with having a <code>MessageBox.Show</code> call here, is that despite all the efforts you've put into <em>dependency injection</em>, you have introduced tight coupling with the <code>MessageBox</code> class and made the service class implement a presentation concern.</p>\n\n<p>I'd just let whatever exception gets thrown in that class, bubble up to the <em>presenter</em>, who can then decide whether to display a potentially cryptic message to the user, or log the exception with its stack trace.</p>\n\n<hr>\n\n<blockquote>\n <p><strong>Presenter</strong></p>\n</blockquote>\n\n<p>I like that your private fields have an underscore prefix:</p>\n\n<pre><code> IClient _model;\n IClientView _view;\n IDataService _ds;\n</code></pre>\n\n<p>However I'd make the intent much clearer like this:</p>\n\n<pre><code> private IClient _model;\n private readonly IClientView _view;\n private readonly IDataService _ds;\n</code></pre>\n\n<p>This way whatever you do in the future, it's clear that the <code>_view</code> and <code>_ds</code> references cannot be tampered with, and that the <code>_model</code> reference <em>can</em> change during the object's lifetime, without even looking at the code.</p>\n\n<p>The underscode prefix makes the <code>this</code> qualifier perfectly redundant, and IMHO clutter up the constructor's code:</p>\n\n<pre><code> public ClientPresenter(IClient model,IClientView view, IDataService ds)\n {\n _ds = ds;\n _model = model;\n _view = view;\n\n SetViewPropertiesFromModel();\n WireUpViewEvents();\n }\n</code></pre>\n\n<p>Looking at <code>SetViewPropertiesFromModel</code> and <code>SetModelPropertiesFromView</code> implementations, I don't understand the need to use reflection cleverness. Such code would possibly be fine in a <code>PresenterBase</code> abstract class, but here you have a <code>ClientPresenter</code> that <em>knows</em> it's dealing with an <code>IClient</code> and an <code>IClientView</code>, both likely to expose properties that you can access directly. If you have 18 such presenters, it looks like you might have this code block copy+pasted 18 times... I'd look into refactoring some of it into a base abstract class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T05:32:22.897",
"Id": "84753",
"Score": "0",
"body": "In this case is it better to use separate repositories for each model (like ClientRepository,EmployeeRepository... ) over general one (DataService)? Dividing things in this way(16 presenters,16 DataServices etc.) would be a mess in future development or will it ease this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T05:33:55.963",
"Id": "84754",
"Score": "0",
"body": "Would you rather maintain 16 objects that do 1 thing, or 1 object that does 16 things? ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T09:48:38.837",
"Id": "84928",
"Score": "0",
"body": "One object that does one thing... ;) So if you have 16 things to do, so 16 objects. With regard to repository difficulty is to imagine whether it should be considered as doing one thing or 16 things as it is giving it's services to many clients?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:26:23.910",
"Id": "48263",
"ParentId": "48233",
"Score": "3"
}
},
{
"body": "<h2>Fragile SQL</h2>\n\n<pre><code>string SelectStatement=@\"SELECT * FROM client WHERE CID=@ID\";\n//....\nClientName = NewRdr.GetString(1),\nClientAdd = NewRdr.GetString(2),\n</code></pre>\n\n<p><code>SELECT *</code> is very fragile. It is even more so when used with column access by index. <code>SELECT *</code> is for human use only, do not use it in your applications.</p>\n\n<h2>Naming</h2>\n\n<p>Do not prefix the name of a class to its members' names. <code>Client.ClientName</code> etc. It reduces readability.</p>\n\n<p>Do not mangle names. <code>Client.ClientAdd</code> should be <code>Client.Address</code>.</p>\n\n<p><code>using (SqlDataReader NewRdr = SqlCom.ExecuteReader())</code>. Here <code>NewRdr</code> should start with lowercase because it's a local variable. It's not clear what is <code>New</code> about it. And <code>Rdr</code> is mangled. Since you are using it as a <code>IDataReader</code> mainly, you could name it <code>dataReader</code>. </p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>string selectStatement = @\"SELECT NAME, ADDRESS, ... FROM client WHERE CID=@ID\";\n//....\nName = (string) dataReader[\"NAME\"],\nAddress = (string) dataReader[\"ADDRESS\"],\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T08:11:47.137",
"Id": "48392",
"ParentId": "48233",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48263",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:27:40.023",
"Id": "48233",
"Score": "2",
"Tags": [
"c#",
".net",
"winforms",
"dependency-injection",
"mvp"
],
"Title": "MVP Pattern used in a payroll solution"
} | 48233 |
<p>I have some code:</p>
<pre><code> $matchingEvents = [];
foreach( $this->recurringEvents as $event ){
if( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth ){
array_push( $matchingEvents, $event );
} else if( $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek ){
array_push( $matchingEvents, $event );
}
}
</code></pre>
<p>Which duplicates the line: </p>
<pre><code>array_push( $matchingEvents, $event );
</code></pre>
<p>This is small duplication, but still duplication. I could reformat it as this:</p>
<pre><code> $matchingEvents = [];
foreach( $this->recurringEvents as $event ){
if( ( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth )
||
( $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek ) ){
array_push( $matchingEvents, $event );
}
}
</code></pre>
<p>But I feel like this drastically reduces the readability of the code.</p>
<p>In this type of situation, is DRY or simple more important?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:35:33.423",
"Id": "84693",
"Score": "1",
"body": "You can improve the readability of the (||) version by judicious use of white space to express the tree of connectives. Use the mathematical structure to your advantage. Don't fight the math. It will always win."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T07:12:29.310",
"Id": "85272",
"Score": "0",
"body": "@nomen: What _\"mathematical structure\"_ are you referring to? Care to elaborate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T16:48:48.633",
"Id": "85330",
"Score": "0",
"body": "@Elias: the tree of logical connectives."
}
] | [
{
"body": "<p>You could move the matching test to a separate method, like this:</p>\n\n<pre><code>private function is_matching_day( $event, $dayOfWeek, $dayOfMonth ) {\n\n if ( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth )\n return true;\n\n return $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek;\n}\n</code></pre>\n\n<p>Then your <code>foreach</code> statement would be more readable, and the duplicated <code>array_push()</code> is gone:</p>\n\n<pre><code>$matchingEvents = [];\nforeach( $this->recurringEvents as $event ) { \n if ( $this->is_matching_day( $event, $dayOfWeek, $dayOfMonth ) )\n array_push( $matchingEvents, $event );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:35:20.643",
"Id": "48241",
"ParentId": "48234",
"Score": "5"
}
},
{
"body": "<p>I think that this is a matter of preference.</p>\n\n<p>However, as a programmer, when I see that <code>||</code> it automatically translates to an \"OR\" in my head, so it's essentially the same thing as seeing <code>else if</code>. In fact, there's more spacing between the lines, so in my humble oppinion, the latter using <code>||</code> is actually easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:38:35.443",
"Id": "48242",
"ParentId": "48234",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>But I feel like this drastically reduces the readability of the code.</p>\n</blockquote>\n\n<p>I think it improves readability. If someone reads <code>... else if ...</code>, they will assume that different things happen in the two cases. It will take some time for them to understand that the same thing happens in two different conditions.</p>\n\n<p>The version with <code>... || ...</code>, on the other hand, clearly suggests that there are two different conditions for the same thing to happen.</p>\n\n<p>If you feel that the two-line condition is too long to be readable, toscho's suggestion to put it into a separate function is good. Maybe you even want to reuse the same function in other parts of the code?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:20:13.420",
"Id": "48249",
"ParentId": "48234",
"Score": "3"
}
},
{
"body": "<p>While I agree that is understandable enough with <code>||</code> symbols, I think it could be greatly improved with some well-named variables.</p>\n\n<p>For example:</p>\n\n<pre><code>$matchingEvents = [];\nforeach( $this->recurringEvents as $event ){\n $matchesMonth = $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth\n $matchesDayOfWeek = $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek\n\n if( $matchesMonth || $matchesDayOfWeek ){\n array_push( $matchingEvents, $event );\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T04:19:14.090",
"Id": "48299",
"ParentId": "48234",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48299",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:29:21.870",
"Id": "48234",
"Score": "3",
"Tags": [
"php"
],
"Title": "Complex boolean logic vs DRY"
} | 48234 |
<p>I wrote a solution to the popularized <a href="http://en.wikipedia.org/wiki/Fizz_buzz" rel="nofollow">FizzBuzz</a> problem in Haskell to see how a functional solution looks. I'm more or less happy with my solution, except for the definition of <code>list</code>. It just looks sort of contorted. </p>
<p><em>Are there any language features in Haskell which can improve the readability of this code, especially the definition of <code>list</code>, while preserving the extensibility that <code>table</code> provides?</em></p>
<pre><code>import Control.Arrow
main = mapM_ (putStrLn . fizzBuzzLogic) [1..100]
fizzBuzzLogic :: Int -> String
fizzBuzzLogic x
| null list = show x
| otherwise = foldl1 (++) list
where
list = map snd . filter ((==0) .fst) $ map (first (mod x)) table
table = [(3,"Fizz")
,(5,"Buzz")
] --add more modulo tokens if you wish
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:15:15.453",
"Id": "84688",
"Score": "1",
"body": "Instead of `foldl1 (++)` use `concat`"
}
] | [
{
"body": "<p>You write:</p>\n\n<pre><code>map snd . filter ((==0) .fst) $ map (first (mod x)) table\n</code></pre>\n\n<p>To make it clearer that we have three operations applied one after another, I would rather write:</p>\n\n<pre><code>map snd . filter ((==0) .fst) . map (first (mod x)) $ table\n</code></pre>\n\n<p>But I think this gets easier to read if we merge the <code>filter</code> and the second <code>map</code>:</p>\n\n<pre><code>map snd . filter ((== 0) . mod x . fst) $ table\n</code></pre>\n\n<p>Some people prefer pointful style, that is, they prefer <code>\\</code> over <code>.</code>:</p>\n\n<pre><code>map snd . filter (\\(number, text) -> x `mod` number == 0) $ table\n</code></pre>\n\n<p>Personally, I would prefer a list comprehension here:</p>\n\n<pre><code>[text | (number, text) <- table, x `mod` number == 0]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:26:17.733",
"Id": "84675",
"Score": "0",
"body": "I agree, the list comprehension is a much clean solution here! Thanks for the detailed input!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-25T19:50:51.887",
"Id": "136075",
"Score": "0",
"body": "Is there an official style guide statement for `op $ op $ op $ arg` vs `op . op . op $ arg`? I tend to prefer the former."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-13T18:14:34.430",
"Id": "176938",
"Score": "1",
"body": "@JanDvorak `$` is considered visually noisier than `.`. Also, `.` resembles mathematical operator ∘ for function composition. Since functional languages are largely about the composition of functions, the `.` operator is preferred also for academic reasons. Also `$` and `.` have different operator precedence so they are not always interchangeable!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:14:36.050",
"Id": "48246",
"ParentId": "48240",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T16:08:15.757",
"Id": "48240",
"Score": "3",
"Tags": [
"haskell",
"fizzbuzz"
],
"Title": "Improving a Haskell FizzBuzz Solution"
} | 48240 |
<p>I coded a php chat that stores the text in a txt file and retrieves it, and I want to know if XSS can get past it or if someone can replace <code>xhr.open("POST","uhh.php");</code> with something that contains the same php code but without <code>htmlspecialchars</code> or something like that. What are the vulnerabilities? (More specifically, I don't want people putting html elements through the chat, and that also leads to security issues.)</p>
<p>This is <code>uhh.php</code>:</p>
<pre><code><?php
$usr=$_POST["usr"];
$msg=$_POST["msg"];
if($usr&&$msg){
$txt="$usr: $msg";
$txt=htmlspecialchars(join("\n",str_split($txt,33)));
$split=explode("\n",file_get_contents("uhh.txt") . $txt);
while(count($split)>10){
$split=array_slice($split,1);
}
file_put_contents("uhh.txt",join("\n",$split) . "\n");
}
?>
watchu lookeen at???
</code></pre>
<p>And this is the code to the html page (JavaScript included):</p>
<pre><code><!DOCTYPE html>
<html><head>
<title>Chatting</title>
<style>
#chatlog {
text-align:left;
border:1px solid black;
width:300px;
height:200px;
}
#chatbar {
width:300px;
}
</style>
<style type="text/css"></style></head>
<body>
<center>
<div id="chatlog">Bagelhead: lol<br>Bagelhead: yes t is<br>Abe: ok proxy off now<br>Bagelhead: gtg<br>Bagelhead: :P<br>Test: Test<br>Abe: &lt;p&gt;Test&lt;/p&gt;<br>Abe: Test<br>TEST: ab<br>TEST: abe<br></div>
<input maxlength="9001" placeholder="Press / to chat" type="text" id="chatbar">
</center>
<script>
setInterval(function(){
var xhr=new XMLHttpRequest();
xhr.open("GET","uhh.txt?a="+Math.random());
xhr.onload=function(){
document.getElementById("chatlog").innerHTML=xhr.responseText.replace(/\n/g,"<br/>");
}
xhr.send();
},1000)
var cb=document.querySelector("#chatbar"),usr="";
function chat(m){
var xhr=new XMLHttpRequest();
xhr.open("POST","uhh.php");
var fd=new FormData();
fd.append("usr",usr);
fd.append("msg",m);
xhr.send(fd);
}
window.onkeyup=function(e){
if(e.keyIdentifier=="U+00BF"){
cb.focus();
}else if(e.keyIdentifier=="Enter"){
if(usr){
chat(cb.value);
cb.value="";
}else{
usr=cb.value;
cb.placeholder="Press / to chat";
cb.value="";
cb.maxLength=9001;
}
}
}
</script>
</body></html>
</code></pre>
<p><code>uhh.txt</code> is just a blank text file.</p>
| [] | [
{
"body": "<p>For the XSS part, here's some resources. It would be better off if I just referenced them rather than write the entire thing down. The second one might be the one you want:</p>\n\n<ul>\n<li><a href=\"https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet\" rel=\"nofollow\">https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet</a></li>\n<li><a href=\"https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\" rel=\"nofollow\">https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet</a></li>\n</ul>\n\n<p>By the definition of <a href=\"http://docs.php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow\"><code>htmlspecialchars</code></a>:</p>\n\n<blockquote>\n <p>Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.</p>\n</blockquote>\n\n<p>You might want to look at <a href=\"http://docs.php.net/manual/en/function.htmlentities.php\" rel=\"nofollow\"><code>htmlentities</code></a> instead.</p>\n\n<p>Also, in my experience, even if you are safe with just one input, you can still be victim of fragmented XSS, where an XSS attack is broken into parts which actually pass through preventive measures. The last time I did such was on a Wordpress plugin, which also happens to be a chat widget. What I did was carefully craft my XSS where the first half was injected to the username and the second continued on as the message. The first half commented out the code in between until the second half.</p>\n\n<p>For the JS part, mostly reusability and some notes:</p>\n\n<pre><code>// You could factor out the XHR to their own functions and make them handy\n// Notes:\n// - I haven't seen onload used in xhr. Read more about onreadystatechange event\n// and readystate properties for cross-browser compatibility. \nvar MyAJAX = {\n get : function (url, data,callback) {\n\n var xhr = new XMLHttpRequest();\n\n // Serialize\n var serializedData = Object.keys(data).reduce(function(serialized,key,index){\n if(index) serialized += '&';\n serialized += encodeURI(key + '=' data[key]);\n return serialized;\n },'?');\n\n xhr.open(\"GET\", url + serializedData); \n xhr.onload = function(e){\n callback.call(null,e.response);\n };\n xhr.send()\n },\n post: function (url, data,callback) {\n var formData = new FormData();\n var xhr = new XMLHttpRequest();\n\n // For each in data object, append\n Object.keys(data).forEach(function(key){\n fd.append(key,data[key]);\n });\n\n xhr.open(\"POST\", url);\n xhr.onload = function(e){\n callback.call(null,e.response);\n };\n xhr.send(formData);\n }\n}\n// Cache DOM elements\n// Notes:\n// - If you use an ID, you're better off with getElementById rather than querySelectorAll\nvar usr = \"\";\nvar cb = document.getElementById(\"chatbar\");\nvar chatLog = document.getElementById(\"chatlog\");\n\n// And your AJAX function looks as clean as this when used\nsetInterval(function(){\n MyAJAX.get('uhh.txt',{\n a : Math.random()\n },function(data){\n chatLog.innerHTML = data.replace(/\\n/g, \"<br/>\");\n });\n},1000);\n\n\nfunction chat(m) {\n MyAJAX.post('uhh.php',{\n \"usr\" : usr,\n \"msg\" : m\n },function(data){\n // Do something when sent\n });\n}\n\n// I suggest you don't place this event on window. Place it on the \n// element for efficiency.\n\ncb.addEventListener('keyup',function(e){\n var identifier = e.keyIdentifier;\n\n if (identifier == \"U+00BF\") {\n cb.focus();\n } else if (e.keyIdentifier == \"Enter\") {\n if (usr) {\n chat(cb.value);\n cb.value = \"\";\n } else {\n usr = cb.value;\n cb.placeholder = \"Press / to chat\";\n cb.value = \"\";\n\n // This only limits this on the browser. There's no one\n // stopping anyone sending more than this without using a browser\n cb.maxLength = 9001;\n }\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:57:41.107",
"Id": "84830",
"Score": "1",
"body": "Yeah, someone can just use the `chat` function in the console."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T18:46:03.327",
"Id": "84856",
"Score": "0",
"body": "@TheWobbuffet That's one issue that can't be solved in JS and should be addressed in the server. Encapsulating the function wouldn't help much. Anyone can replicate the request that `chat` does, even without a browser with tools like REST testers, curl, wget."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-02T13:48:55.397",
"Id": "105771",
"Score": "0",
"body": "Yeah, but I wouldn't call making chosen text appear cracking"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T18:38:22.700",
"Id": "48257",
"ParentId": "48254",
"Score": "1"
}
},
{
"body": "<p>Looks safe to me, but I would change the way you request the server. This way, you send many requests to the server and for more then few people using it, the server could be flooded by these requests. It would however require switching txt file for script file. Then you could use so called long poll.</p>\n\n<p>You are probably wondering what long poll is and how it works. Long poll is technique where client opens connection to the server and leaves it open. When new message comes, server sends it and closes the connection. Trick is, client immediately opens new connection. Same happens when old connection times out.</p>\n\n<p>Problem here is, when you use PHP on server side, it just executes some code and closes the connection. So, you have 2 possibilities: Best idea is to use server written in node.js, which is made for such things (and there are other advantages like that you don't have to store the message anywhere, you just recieve it and immediately send it to all clients and other...). If you want or have to use PHP, then you must use the sleep() function. Then, you have while loop, that each for example 200 miliseconds check for new message in database and either sends it or sleeps for another 200 miliseconds.</p>\n\n<p>If you want to try, here is part of my client code which takes care of server communication:</p>\n\n<pre><code>//function, that returns right kind of AJAX object based on browser\n//I don't have worst case scenario (AJAX not supported) here, because I usually check for required support at the beginning of the script\nfunction createAjax() {\n if (window.XMLHttpRequest) {\n return new XMLHttpRequest();\n } else {\n return new ActiveXObject('Microsoft.XMLHTTP');\n }\n}\n\n/*\nClass that takes care of receiving new messages from server\nPARAMS:\n longPollServerURL - string - URL of server file, which acts as long poll server\n lastIdGetURL - string - URL of txt file, where last message id is saved\n newMessageCallback - function - callback to get called when new message is received\n it is called with 4 params:\n id of the message, time when the message was sent as unix timestamp,\n nickname of the person who sent it, message text itself\n*/\nfunction ChatLongPoll(longPollServerURL, lastIdGetURL, newMessageCallback) {\n var mainContext = this,\n httpRequest = createAjax();\n\n //function that starts long poll and sets what should happen when connection ends\n this.startLongPoll = function() {\n httpRequest.onreadystatechange = function() {\n if (httpRequest.readyState == 4) {\n var _decodedResponse = JSON.parse(httpRequest.responseText);\n if (_decodedResponse.status == 'new') {\n for (var i = 0; i <_decodedResponse.messages.length; i++) {\n newMessageCallback(_decodedResponse.messages[i].id, _decodedResponse.messages[i].time, _decodedResponse.messages[i].from, _decodedResponse.messages[i].messageText);\n mainContext.lastMessageId = _decodedResponse.messages[i].id;\n }\n }\n mainContext.openLongPoll();\n }\n };\n mainContext.openLongPoll();\n };\n\n //function that opens connection to the server\n this.openLongPoll = function() {\n httpRequest.open('GET', longPollServerURL + '?lastId=' + mainContext.lastMessageId, true);\n httpRequest.send(null);\n };\n\n //function that downloads ID of last message sent\n this.getLastMessageId = function() {\n var _id = false;\n httpRequest.onreadystatechange = function() {\n if (httpRequest.readyState == 4) {\n _id = httpRequest.responseText;\n }\n };\n httpRequest.open('GET', lastIdGetURL, false);\n httpRequest.send(null);\n return _id;\n };\n\n this.lastMessageId = this.getLastMessageId();\n}\n\n\n/*\nClass that takes care of sending messages to server\nPARAMS:\n newMessageServerURL - string - URL of file, which saves and validates the message\n callback - function - function to handle response from server (ok / wrongFormat / noName / ... status etc... (that depends on how you make your server))\n*/\nfunction ChatSendMessage(newMessageServerURL, callback) {\n var httpRequest = createAjax();\n\n httpRequest.onreadystatechange = function() {\n if (httpRequest.readyState == 4) {\n callback(JSON.parse(httpRequest.responseText));\n }\n };\n\n //function that sends the message to server and saves it to httpRequest.lastMessage\n this.sendMessage = function (from, messageText) {\n var L_postData = 'from=' + encodeURIComponent(from) + '&messageText=' + encodeURIComponent(messageText);\n\n httpRequest.lastMessage = messageText;\n\n httpRequest.open('POST', newMessageServerURL, true);\n httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n httpRequest.send(L_postData);\n };\n}\n\n/*\nShort class that just simplifies access to those 2 classes before\nPARAMS:\n newMessageServerURL - string - URL of file, which saves and validates the message\n longPollServerURL - string - URL of server file, which acts as long poll server\n lastIdGetURL - string - URL of txt file, where last message id is saved\n messageReceivedCallback - function - callback to get called when new message is received, it is called with 4 params: id of the message, time when the message was sent as unix timestamp, nickname of the person who sent it, message text itself\n sentMessageCallback - function - function to handle response from server (ok / wrongFormat / noName / ... status etc... (that depends on how you make your server))\n*/\nfunction ServerCommunicator(newMessageServerURL, longPollServerURL, lastIdGetURL, messageReceivedCallback, sentMessageCallback) {\n var longPoll = new ChatLongPoll(longPollServerURL, lastIdGetURL, messageReceivedCallback);\n var sendMessage = new ChatSendMessage(newMessageServerURL, sentMessageCallback);\n\n this.sendMessage = sendMessage.sendMessage;\n this.startLongPoll = longPoll.startLongPoll;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:37:49.460",
"Id": "84710",
"Score": "0",
"body": "Could you go through your code and explain what you did differently than the OP? Right now this is more of just a code dump, with no explanation of what the OP should do and why. Once you make those changes you can have my upvote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:38:51.423",
"Id": "84823",
"Score": "0",
"body": "OK, I will add some comments to the code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:06:00.320",
"Id": "48272",
"ParentId": "48254",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48272",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T18:00:39.900",
"Id": "48254",
"Score": "3",
"Tags": [
"javascript",
"php"
],
"Title": "Can XSS or anything else get through this?"
} | 48254 |
<p>As many may know, I am developing a Trading Card Game for the <a href="https://codereview.meta.stackexchange.com/questions/1600/code-challenge-2">Coding Challenge</a>.</p>
<p>I have just completed the <code>Field</code> class and have not used it in practice yet, so all theoretical and looking for a review.</p>
<p>Using Java 8 and all custom classes will be included in this post as well, if you wish you can see all source on <a href="https://github.com/skiwi2/TCG" rel="nofollow noreferrer">GitHub</a>.</p>
<p>The field currently only consists of monsters that can be on the field, though in the future other types of cards may be added.</p>
<p>The Field class:</p>
<pre><code>public class Field {
private final MonsterCard[] monsters;
public Field(final int monsterCapacity) {
Arguments.requirePositive(monsterCapacity, "monster capacity");
this.monsters = new MonsterCard[monsterCapacity];
}
public void setMonster(final int index, final MonsterCard monsterCard) {
Arguments.requireIndexInRange(index, 0, monsters.length);
Objects.requireNonNull(monsterCard);
monsters[index] = monsterCard;
}
public MonsterCard getMonster(final int index) {
Arguments.requireIndexInRange(index, 0, monsters.length);
MonsterCard monsterCard = monsters[index];
States.requireNonNull(monsterCard, NoSuchElementException::new, "no monster exists on index: " + index);
return monsterCard;
}
public boolean hasMonster(final int index) {
Arguments.requireIndexInRange(index, 0, monsters.length);
return (monsters[index] != null);
}
public MonsterCard destroyMonster(final int index) {
Arguments.requireIndexInRange(index, 0, monsters.length);
MonsterCard monsterCard = monsters[index];
States.requireNonNull(monsterCard, NoSuchElementException::new, "no monster exists on index: " + index);
monsters[index] = null;
return monsterCard;
}
public Stream<MonsterCard> getMonsters() {
return Arrays.stream(monsters).filter(obj -> obj != null);
}
public int getMonsterCapacity() {
return monsters.length;
}
@Override
public String toString() {
return "Field(" + Arrays.toString(monsters) + ")";
}
}
</code></pre>
<p>The unit tests:</p>
<pre><code>public class FieldTest {
static {
assertTrue(true);
}
@Test
public void testConstructor() {
new Field(1);
new Field(6);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorZeroMonsterCapacity() {
new Field(0);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorNegativeMonsterCapacity() {
new Field(-1);
}
@Test
public void testSetMonster() {
Field field = new Field(6);
MonsterCard monsterCard = createMonsterCard();
field.setMonster(0, monsterCard);
assertEquals(monsterCard, field.getMonster(0));
MonsterCard monsterCard2 = createMonsterCard2();
field.setMonster(5, monsterCard2);
assertEquals(monsterCard2, field.getMonster(5));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetMonsterUnderRange() {
Field field = new Field(6);
field.setMonster(-1, createMonsterCard());
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetMonsterAboveRange() {
Field field = new Field(6);
field.setMonster(6, createMonsterCard());
}
@Test(expected = NullPointerException.class)
public void testSetMonsterMonsterCardNull() {
Field field = new Field(6);
field.setMonster(0, null);
}
@Test
public void testGetMonster() {
Field field = new Field(6);
MonsterCard monsterCard = createMonsterCard();
field.setMonster(0, monsterCard);
assertEquals(monsterCard, field.getMonster(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetMonsterUnderRange() {
Field field = new Field(6);
field.getMonster(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetMonsterAboveRange() {
Field field = new Field(6);
field.getMonster(6);
}
@Test(expected = NoSuchElementException.class)
public void testGetMonsterNoMonster() {
Field field = new Field(6);
field.getMonster(0);
}
@Test
public void testHasMonster() {
Field field = new Field(6);
field.setMonster(0, createMonsterCard());
assertTrue(field.hasMonster(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testHasMonsterUnderRange() {
Field field = new Field(6);
field.hasMonster(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testHasMonsterAboveRange() {
Field field = new Field(6);
field.hasMonster(6);
}
@Test
public void testDestroyMonster() {
Field field = new Field(6);
MonsterCard monsterCard = createMonsterCard();
field.setMonster(0, monsterCard);
assertEquals(monsterCard, field.destroyMonster(0));
assertFalse(field.hasMonster(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testDestroyMonsterUnderRange() {
Field field = new Field(6);
field.destroyMonster(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testDestroyMonsterAboveRange() {
Field field = new Field(6);
field.destroyMonster(6);
}
@Test(expected = NoSuchElementException.class)
public void testDestroyMonsterNoMonster() {
Field field = new Field(6);
field.destroyMonster(0);
}
@Test
public void testGetMonsters() {
Field field = new Field(6);
assertEquals(0, field.getMonsters().count());
assertFalse(field.getMonsters().anyMatch(m -> m == null));
MonsterCard monsterCard = createMonsterCard();
MonsterCard monsterCard2 = createMonsterCard2();
field.setMonster(0, monsterCard);
field.setMonster(1, monsterCard2);
List<MonsterCard> list = field.getMonsters().collect(Collectors.toList());
assertTrue(list.contains(monsterCard));
assertTrue(list.contains(monsterCard2));
}
@Test
public void testGetMonsterCapacity() {
Field field = new Field(6);
assertEquals(6, field.getMonsterCapacity());
}
@Test
public void testToString() {
Field field = new Field(5);
MonsterCard monsterCard = createMonsterCard();
MonsterCard monsterCard2 = createMonsterCard2();
field.setMonster(1, monsterCard);
field.setMonster(3, monsterCard2);
assertEquals("Field([null, " + monsterCard.toString() + ", null, " + monsterCard2.toString() + ", null])", field.toString());
}
private MonsterCard createMonsterCard() {
return new MonsterCard("Test", 5, 5, MonsterModus.HEALING);
}
private MonsterCard createMonsterCard2() {
return new MonsterCard("zzz", 7, 7, MonsterModus.OFFENSIVE);
}
}
</code></pre>
<p>The relevant <code>Arguments</code> and <code>States</code> snippets:</p>
<pre><code>public static int requirePositive(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value <= 0) {
throw new IllegalArgumentException("the " + name + " must be positive: " + value);
}
return value;
}
</code></pre>
<hr>
<pre><code>public static int requireIndexInRange(final int index, final int lowInclusive, final int highExclusive) throws IndexOutOfBoundsException {
if (index < lowInclusive || index >= highExclusive) {
throw new IndexOutOfBoundsException("the index must be in range: " + index + ", expected: [" + lowInclusive + ", " + highExclusive + ")");
}
return index;
}
</code></pre>
<hr>
<pre><code>public static <T, E extends RuntimeException> T requireNonNull(final T object, final Function<String, E> exceptionFunction, final String message) throws E {
Objects.requireNonNull(exceptionFunction);
Objects.requireNonNull(message);
if (object == null) {
throw exceptionFunction.apply(message);
}
return object;
}
</code></pre>
<p>A few notes:</p>
<ul>
<li>In the unit tests I explicitely create a <code>new Field(6)</code> every time, as the arguments are important to know.</li>
<li>The <code>static { assertTrue(true); }</code> is there such that Netbeans stop annoying me, it is standard in all my unit tests.</li>
<li>I use an experimental approach of providing a <code>Stream<E></code> as <em>view</em> of a class as opposed to the Java 7-and-below standard of <code>Collection<E></code>. The Java 8 developers encourage working with streams over the old collections API for writing API's.</li>
</ul>
| [] | [
{
"body": "<p>First, I don't think <code>Field</code> is a good name – it is really generic and doesn't reveal any information.</p>\n\n<p>Now a few notes on your unit tests:</p>\n\n<p>Instead of duplicating the setup <code>Field field = new Field(6)</code> in every test, you could use a <code>@Before</code> annotated setup method:</p>\n\n<pre><code>public class FieldTest {\n private Field field;\n\n @Before\n public void before() {\n field = new Field( 6 );\n }\n\n // …\n}\n</code></pre>\n\n<p>I would also recommend getting rid of <code>@Test(expected = XyzException.class)</code> and instead using the <code>ExpectedException</code> rule. This way, you can ensure that the exception is thrown exactly in the place you expect it to be thrown – and not, for example, in the test setup. This especially holds for standard exceptions such as <code>IllegalArgumentException</code> and <code>NullPointerException</code>. You should also assert for the message if you really want to make sure you are asserting the correct exception:</p>\n\n<pre><code>public class FieldTest {\n @Rule\n public ExpectedException thrown = ExpectedException.none();\n\n @Test\n public void someTest() {\n // some setup\n\n thrown.expect( IllegalArgumentException.class );\n thrown.expectMessage( \"Your custom message\" );\n\n // execute the behavior that is to be tested\n }\n}\n</code></pre>\n\n<p>For <a href=\"https://stackoverflow.com/questions/2588265/when-to-use-custom-exceptions-vs-existing-exceptions-vs-generic-exceptions\">application specific exceptions</a> you should also use custom exceptions such as <code>MonsterNotFoundException</code> or similar (that you can derive from the built-in classes if you like). It makes stack-traces easier to read and allows error handling that is both more understandable and more flexible:</p>\n\n<pre><code>try {\n // a few lines of code\n} catch( NoSuchElementException e ) {\n // reader: no such element of what? and where?\n}\n\ntry {\n // a few lines of code\n} catch( MonsterNotFoundException e ) {\n // reader: oh, no monster found. I see what happened here!\n}\n</code></pre>\n\n<p>This is more of a personal thing, but I would try to avoid allowing any kind of <code>NullPointerException</code> for expected behavior. </p>\n\n<p>Something I like to do to counter this is using <code>Optional</code>s which before Java 8 would be using <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\">Google's Guava</a>, but as of Java 8 it is a built-in functionality (though I still like Guava's implementation better).</p>\n\n<p>One major upside to this is that it forces the user of the class to think about handling these cases, while <code>null</code> values are easily forgotten about and then cause bugs.</p>\n\n<p>This also applies to your <code>getMonster</code> – if you just return <code>Optional<MonsterCard></code>, the caller doesn't need to do either one of these</p>\n\n<ul>\n<li>call <code>hasMonster</code> and if it returns <code>true</code>, call <code>getMonster</code></li>\n<li>call <code>getMonster</code> and wrap it in <code>try .. catch</code>.</li>\n</ul>\n\n<p>Instead, it is up to them and they can handle it in a more flexible way:</p>\n\n<pre><code>MonsterCard monster = field.getMonster( 1 ).orNull();\n// or:\nMonsterCard monster = field.getMonster( 2 ).or( defaultMonster );\n// or:\nOptional<MonsterCard> monster = field.getMonster( 3 );\nif( monster.isPresent() ) {\n // …\n}\n</code></pre>\n\n<p>For example, <code>getMonster</code> and <code>hasMonster</code> would look like this:</p>\n\n<pre><code>public Optional<MonsterCard> getMonster( final int index ) {\n Arguments.requireIndexInRange( index, 0, monsters.length );\n return Optional.fromNullable( monsters[index] );\n}\n\npublic boolean hasMonster( final int index ) {\n return getMonster( index ).isPresent();\n}\n</code></pre>\n\n<p>Two more things: </p>\n\n<ul>\n<li>In your <code>toString</code> method, instead of hard-coding <code>\"Field\"</code>, you could use <code>Field.class.getSimpleName()</code>. This has the benefit of automatically adapting to any kind of refactoring. Boilerplate methods like <code>toString</code> are very prone to being forgotten.</li>\n<li>I wouldn't obsess over making all arguments <code>final</code>. There is little to no benefit in it. I like making fields final whenever possible because looking at the class it becomes clear that this object will be assigned no more than once. Making classes final is fine if you are providing a library, otherwise it's somewhat pointless. Making arguments final really only makes sense to me if you are forced to do so (because you want to use it in a callback etc.). But this really is just a personal opinion and you should feel free to do so if you judge it differently.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:10:07.450",
"Id": "84782",
"Score": "1",
"body": "Overall, this is a great answer. Welcome to Code Review! One note though, `Optional<MonsterCard>[]` is problematic since such an array can not be created because it is of a generic type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:13:03.627",
"Id": "84783",
"Score": "0",
"body": "Fair points on most cases, few notes: 1) I intend the calling class (for example from within a GUI) to know about which monsters are where, therefore I do not expect the calling code to ever encounter `null` if designed properly, hence some of my design decisions; 2) I'm explicitely defining `Field field = new Field(6)` everywhere, because the `6` argument is relevant for testing bounds. Overall a very good answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:15:50.273",
"Id": "84786",
"Score": "0",
"body": "@SimonAndréForsberg D'oh, my bad. I usually stick with `List`s, but in a fixed-size scenario an array makes sense. :) Using a common array isn't too bad here anyway, I edited the answer accordingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:29:56.310",
"Id": "84802",
"Score": "0",
"body": "A minor minor note: I couldn't find any `orNull` method, I guess `orElse(null)` should be used? And the same for `orElse(defaultMonster)`. I happened to have use for some `Optional` things as well :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:20:19.677",
"Id": "84818",
"Score": "0",
"body": "@SimonAndréForsberg I was using Guava's `Optional` API. Unfortunately, Java 8 did sort of a half-assed job on the new APIs (imho)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:21:54.693",
"Id": "84819",
"Score": "0",
"body": "Ah, OK. That explains the difference!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:59:37.380",
"Id": "48321",
"ParentId": "48255",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T18:02:33.970",
"Id": "48255",
"Score": "5",
"Tags": [
"java",
"game",
"community-challenge"
],
"Title": "Field class used by my trading card game"
} | 48255 |
<p><a href="http://projecteuler.net/problem=33" rel="nofollow">Problem 33</a> in Project Euler asks:</p>
<blockquote>
<p>The fraction 49/98 is a curious fraction, as an inexperienced
mathematician in attempting to simplify it may incorrectly believe
that 49/98 = 4/8, which is correct, is obtained by canceling the 9s.</p>
<p>We shall consider fractions like, 30/50 = 3/5, to be trivial examples.</p>
<p>There are exactly four non-trivial examples of this type of fraction,
less than one in value, and containing two digits in the numerator and
denominator.</p>
<p>If the product of these four fractions is given in its lowest common
terms, find the value of the denominator.</p>
</blockquote>
<p>This is the code I came up with, which solves the problem pretty handily. But, I'm concerned that this is messy and unreadable, even with the comments - and I simply hate using magic numbers/indices littered throughout the code. Also, I do not want a procedural ("C" style) solution - I'm learning how to write idiomatic (read "functional") programming with Ruby, and I'd like to learn how to write cleaner functional code.</p>
<pre><code>a = 10.upto(99).to_a.map(&:to_s) # Create array of integers 10 - 99
puts a.product(a) # Form cartesion product [a,b] for all 2 digit numbers a,b
.reject{|x| x.any? {|y| y.chars.include? '0'}} # Numbers inlcuding '0' are the trivial matches
.reject{|x| x.first == x.last || # Reject pairs where a = b
x.first.to_f/x.last.to_f > 1 || # Reject fractions greater than 1
(x.first.chars & x.last.chars).size != 1} # Reject pairs in which no digits are common
.map{|x| [x.first.to_f / x.last.to_f, x.first.chars, x.last.chars, x.first.chars & x.last.chars]} # Ex: [0.5, ["4", "9"], ["9", "8"], ["9"]]
.map{|x| [x.first, x[1] - x.last, x[2] - x.last, x[1], x[2]]} # Ex: [0.5, ["4"], ["8"], ["4", "9"], ["9", "8"]]
.select{|x| x.length == 5 && x.first == x[1].join.to_f/x[2].join.to_f} # Select only the tuples which match the condition
.map{|x| Rational(x[-2].join.to_i, x[-1].join.to_i)} # Convert each such tuple to rational numbers
.reduce(:*)
</code></pre>
| [] | [
{
"body": "<p><strong>Array multiple assignment</strong><br>\nYou pass arrays around, and you find yourself calling for <code>x[1]</code> and <code>x.last</code> - this is very unreadable, and brittle.<br>\nRuby allows you to implicitely assign elements of the array to parameters in your block according to its location, so you could write the same \"maps\" like this:</p>\n\n<pre><code> .map do|numerator, denominator| \n [numerator.to_f / denominator.to_f, numerator.chars, denominator.chars, \n numerator.chars & denominator.chars] \n end.map do |result, numerator_digits, denominator_digits, mutual_digit| \n [result, numerator_digits - mutual_digit, denominator_digits - mutual_digit, \n numerator_digits, denominator_digits] \n end.select do|result, new_numerator_digits, new_denominator_digits| \n result == new_numerator_digits.join.to_f/new_denominator_digits.join.to_f \n end.map do |_, _, _, numerator_digits, denominator_digits| \n Rational(numerator_digits.join.to_i, denominator_digits.join.to_i) \n end.reduce(:*)\n</code></pre>\n\n<p>Note that unneeded array elements at the end of the array are truncated, so you don't have to write them. For the unneeded elements at the beginning of the array I've used the <code>_</code> idiom which tells the method that I expect these parameters, but I won't need them.</p>\n\n<p><strong>If it deserves a comment - it deserves a method</strong><br>\nInstead of commenting your code, consider refactoring it into methods. Each method will do <em>one</em> thing, and, given the proper name, will be descriptive when used, and easily read in itself:</p>\n\n<pre><code>def trivial?(pair)\n pair.any? {|y| y.chars.include? '0'}\nend\n\ndef identical?(numerator, denominator)\n numerator == denominator\nend\n\ndef larger_than_one?(numerator, denominator)\n numerator.to_i > numerator.to_i\nend\n\ndef has_common_digits?(numerator, denominator)\n (numerator.chars & numerator.chars).size > 0\nend\n\na = 10.upto(99).to_a.map(&:to_s) \nputs a.product(a) \n .reject(&method(:trivial?)) \n .reject(&method(:identical?)) \n .reject(&method(:larger_than_one?)) \n .select(&method(:has_common_digits?))\n</code></pre>\n\n<p><strong>Make your steps logical</strong><br>\nThe last few steps you take look like they are held out with gum, and that you made some acrobatics to stay one-line and \"idiomatic\". It is better to make your methods do something you can explain, than simply adding and removing temp-variables:</p>\n\n<pre><code>def reduced_fraction(numerator, denominator)\n mutual_digit = numerator.chars & denominator.chars\n (numerator.chars - mutual_digit).join.to_f / (denominator.chars - mutual_digit).join.to_f\nend\n\n\na = 10.upto(99).to_a.map(&:to_s)\nputs a.product(a) \n .reject(&method(:trivial?)) \n .reject(&method(:identical?)) \n .reject(&method(:larger_than_one?)) \n .select(&method(:has_common_digits?))\n .select do |numerator, denominator| \n numerator.to_f / denominator.to_f == reduced_fraction(numerator, denominator)\n end.map { |fraction| Rational(*fraction) }\n .reduce(:*)\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong><br>\nYes, it seems that using <code>&method(:something)</code> in <code>map</code> and multiple assignment are mutually exclusive... :(</p>\n\n<p>I can suggest a few strategies where you don't have to fall back to using <code>pair.first</code>, <code>pair.last</code>:</p>\n\n<ol>\n<li><p>Use multiple assignment in the first line of your method:</p>\n\n<pre><code>def identical?(pair)\n numerator, denominator = pair\n ...\nend\n</code></pre></li>\n<li><p>Use a hash to hold your values, and use <a href=\"http://blog.marc-andre.ca/2013/02/23/ruby-2-by-example/\" rel=\"nofollow\">keyword arguments</a> in your method</p>\n\n<pre><code>def identical?(numerator: nil, denominator: nil)\n numerator == denominator\nend\n\na = 10.upto(99).to_a.map(&:to_s)\nputs a.product(a) \n .reject(&method(:trivial?)) \n .map { |numerator, denominator| {numerator: numerator, denominator: denominator } }\n .reject(&method(:identical?)) \n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T20:47:49.393",
"Id": "84702",
"Score": "0",
"body": "Are you sure that works? I'm using Ruby 2.0, and I'm seeing identical errors as below:\n033.rb:9:in `larger_than_one?': wrong number of arguments (1 for 2) (ArgumentError)\n from 033.rb:26:in `reject'\n from 033.rb:26:in `<main>'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T20:48:54.430",
"Id": "84703",
"Score": "0",
"body": "This is because it is expecting 2 arguments instead of one that is being sent - I replaced (num,denum) with (pair) and then used pair.first, pair.last to make it work - what am I missing here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:01:11.287",
"Id": "84704",
"Score": "0",
"body": "I've been able to refactor my code and get rid of the syntax errors - Thanks a lot for teaching me about the &method syntax!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T07:59:34.063",
"Id": "84770",
"Score": "0",
"body": "@TCSGrad - yeah, sorry for the confusion - I added some more options so you could keep using named variables instead of an array..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T20:22:55.343",
"Id": "48266",
"ParentId": "48256",
"Score": "2"
}
},
{
"body": "<p>(This is less a review of the code itself, and more a suggestion for an alternative approach.)</p>\n\n<p>In my opinion, the most idiomatic thing you can do in Ruby is to keep it readable :)</p>\n\n<p>So if being strictly functional interferes with that, well, don't be strictly functional. Ruby can indeed be very functional, and more power to you for learning it - but Ruby can also be a lot of other things. No reason to disregard that on purpose (<a href=\"http://signalvnoise.com/posts/3034-remember-a-real-engineer-doesnt-want\" rel=\"nofollow\">sort of relevant quote here</a>).</p>\n\n<p>That being said, the int-to-string-to-float-to-int conversion seems sketchy to me, and seems to play a big part in complicating your code.</p>\n\n<p>That got me thinking that it'd be easier to start with the digits 1-9 rather than the numbers 10-99.</p>\n\n<p>We know that neither numerator or denominator can contain a zero, so we only have to look at 1-9. Furthermore, we can start by looking at the \"simplified\" fractions with single-digit components, and discarding those that are >= 1. That leaves 36 fractions.</p>\n\n<p>From there, we need only mix in an extra digit in both numerator and denominator; i.e. 4 \"expanded\" fractions to check per extra digit.</p>\n\n<p>First pass, I get this, if I try to keep chaining things</p>\n\n<pre><code># this'll be useful - could even be a constant\ndigits = (1...10).to_a\n\n# n and d are numerator and denominator, respectively I've pared\n# them down here to keep the line-lengths down a bit.\nresult = digits.product(digits) # 2-digit combinations of numbers 1-9\n .reject { |n, d| n >= d } # skip those where the numerator >= denominator\n .map do |n, d|\n fraction = Rational(n, d) # our 1-digit fraction\n digits.map do |digit| # add in another digit top and bottom\n numerators = [n, digit].permutation(2).map { |a, b| 10 * a + b }\n denominators = [d, digit].permutation(2).map { |a, b| 10 * a + b }\n numerators.product(denominators)\n .map { |n, d| fraction if Rational(n, d) == fraction }\n end\n end.flatten.compact.inject(&:*).denominator\n\np result # => 100\n</code></pre>\n\n<p>I'm sure this can be cleaned up further.</p>\n\n<p>The chaining feels forced. I'd probably do less chaining and use more local variables</p>\n\n<pre><code>digits = (1...10).to_a\n\n# a helper\ndef numbers_for_digits(a, b)\n [a, b].permutation(2).map { |a, b| 10 * a + b }\nend\n\nfractions = digits.product(digits).map do |numerator, denominator|\n next if numerator >= denominator\n fraction = Rational(numerator, denominator)\n digits.map do |digit|\n numerators = numbers_for_digits(numerator, digit)\n denominators = numbers_for_digits(denominator, digit)\n fractions = numerators.product(denominators)\n fractions.map do |numerator, denominator|\n fraction if Rational(numerator, denominator) == fraction\n end\n end\nend\n\nresult = fractions.flatten.compact.inject(&:*).denominator\n</code></pre>\n\n<p>p.s. For those curious:</p>\n\n<blockquote>\n <p>16 / 64 == 1 / 4 == 0.25<br>\n 19 / 95 == 1 / 5 == 0.2<br>\n 26 / 65 == 2 / 5 == 0.4<br>\n 49 / 98 == 4 / 8 == 0.5</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T23:21:56.510",
"Id": "48281",
"ParentId": "48256",
"Score": "1"
}
},
{
"body": "<p>As others have said, use logical groupings and aim for readability. I also suggest to use the standard library as much as possible. In Ruby there's a class <code>Rational</code> which has a wonderful feature of reducing any fraction. For example, if <code>r=Rational(4,10)</code>, then <code>r.numerator</code> is equal to 2, and <code>r.denominator</code> is equal to 5. Using this, we can plan our attack:</p>\n\n<pre><code>#params are 2-digit numerator and 2-digit denominator\ndef curious? n,d\n rat = Rational(n,d) #reduced fraction\n return false if rat.numerator==n #not reducible\n\n n0, n1 = n/10, n%10 #split into tens and ones digits\n d0, d1 = d/10, d%10\n return false if ([n0, n1] & [d0, d1]).empty? #no common digits\n\n #we know at least one digit repeats; try all combinations\n n0==d0 && !d1.zero? && Rational(n1,d1)==rat ||\n n0==d1 && !d0.zero? && Rational(n1,d0)==rat ||\n n1==d0 && !d1.zero? && Rational(n0,d1)==rat ||\n n1==d1 && !d0.zero? && Rational(n0,d0)==rat\nend\n\nlist=[]\n(10..98).each {|n|\n next if (n%10).zero? #comment this line if you want \"trivial\" as well\n (n+1..99).each {|d|\n list<<\"#{n}/#{d}\" if curious?(n,d)\n }\n}\np list #[\"16/64\", \"19/95\", \"26/65\", \"49/98\"]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-24T22:43:49.143",
"Id": "57988",
"ParentId": "48256",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48266",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T18:34:57.063",
"Id": "48256",
"Score": "3",
"Tags": [
"ruby",
"functional-programming",
"mathematics",
"programming-challenge",
"combinatorics"
],
"Title": "Curious fractions in functional Ruby"
} | 48256 |
<p><em>Lately, I've been, I've been losing sleep<br>
Dreaming about the things that we could be<br>
But baby, I've been, I've been praying hard,<br>
Said, no more counting dollars<br>
We'll be counting stars, yeah we'll be counting stars</em><br>
(<a href="https://www.youtube.com/watch?v=hT_nvWreIhg" rel="noreferrer">One Republic - Counting Stars</a>)</p>
<p><a href="http://chat.stackexchange.com/rooms/8595/the-2nd-monitor">The 2nd Monitor</a> is known to be a quite star-happy chat room, but exactly how many stars is there? And who are the most starred users? I decided to write a script to find out.</p>
<p>I chose to write this in Python because:</p>
<ul>
<li>I've never used Python before</li>
<li><a href="https://codereview.stackexchange.com/a/41210/31562">@200_success used it and it didn't look that hard</a></li>
<li>I found <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer">Beautiful Soup</a> which seemed powerful and easy to use</li>
</ul>
<p>The script performs a number of HTTP requests to the <a href="http://chat.stackexchange.com/rooms/info/8595/the-2nd-monitor/?tab=stars">list of starred messages</a>, keeps track of the numbers in a <code>dict</code> and also saves the pure HTML data to files (to make it easier to perform other calculations on the data in the future, and I had the opportunity to learn file I/O in Python).</p>
<p>To be safe, I included a little delay between some of the requests (Don't want to risk getting blocked by the system)</p>
<p>Unfortunately there's no way to see which user starred the most messages, <a href="https://codereview.meta.stackexchange.com/a/1667/31562">but we all know who that is anyway...</a></p>
<p>The code:</p>
<pre><code>from time import sleep
from bs4 import BeautifulSoup
from urllib import request
from collections import OrderedDict
import operator
room = 8595 # The 2nd Monitor (Code Review)
url = 'http://chat.stackexchange.com/rooms/info/{0}/the-2nd-monitor/?tab=stars&page={1}'
pages = 125
def write_files(filename, content):
with open(filename, 'w', encoding = 'utf-8') as f:
f.write(content)
def fetch_soup(room, page):
resource = request.urlopen(url.format(room, page))
content = resource.read().decode('utf-8')
mysoup = BeautifulSoup(content)
return mysoup
allstars = {}
def add_stars(message):
message_soup = BeautifulSoup(str(message))
stars = message_soup.select('.times').pop().string
who = message_soup.select(".username a").pop().string
# If there is only one star, the `.times` span item does not contain anything
if stars == None:
stars = 1
if who in allstars:
allstars[who] += int(stars)
else:
allstars[who] = int(stars)
for page in range(1, pages):
print("Fetching page {0}".format(page))
soup = fetch_soup(room, page)
all_messages = soup.find_all(attrs={'class': 'monologue'})
for message in all_messages:
add_stars(message)
write_files("{0}-page-{1}".format(room, page), soup.prettify())
if page % 5 == 0:
sleep(3)
# Create a sorted list from the dict with items sorted by value (number of stars)
sorted_stars = sorted(allstars.items(), key=lambda x:x[1])
for user in sorted_stars:
print(user)
</code></pre>
<p>The results, you ask? Well, here they are: <strong>(Spoiler warning!)</strong> (I'm only showing those who have \$> 50\$ stars here, to keep the list shorter)</p>
<blockquote class="spoiler">
<p> ('apieceoffruit', 73)<br>
('ChrisW', 85)<br>
('Edward', 86)<br>
('Yuushi', 93)<br>
('Marc-Andre', 98)<br>
('nhgrif', 112)<br>
('amon', 119)<br>
('James Khoury', 126)<br>
('Nobody', 148)<br>
('Jerry Coffin', 150)<br>
('BenVlodgi', 160)<br>
('Donald.McLean', 174)<br>
('konijn', 184)<br>
('200_success', 209)<br>
('Vogel612', 220)<br>
('kleinfreund', 229)<br>
('Corbin', 233)<br>
('Morwenn', 253)<br>
('skiwi', 407)<br>
('lol.upvote', 416)<br>
('syb0rg', 475)<br>
('Malachi', 534)<br>
('retailcoder', 749)<br>
("Mat's Mug", 931)<br>
('Simon André Forsberg', 1079)<br>
('Jamal', 1170)<br>
('The Mug with many names', 2096) (Mat's Mug, retailcoder and lol.upvote is the same user)<br>
('rolfl', 2115)<br></p>
</blockquote>
<p>It feels strange to do <code>.pop()</code> to fetch data from the select soup, is there another approach available here? However, as this is the first time I'm using Python, any comments are welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:44:17.810",
"Id": "84711",
"Score": "3",
"body": "Malachi only has 534? That surprised me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T14:44:26.493",
"Id": "86185",
"Score": "1",
"body": "@syb0rg that is how many of my messages have been starred, not how many stars I have given."
}
] | [
{
"body": "<p>I can't see any reason why you would need to pop elements off the arrays returned from <code>.select()</code> -- you could just do something like </p>\n\n<pre><code> message_soup.select('.times')[0].string\n</code></pre>\n\n<p>Either approach will throw an exception if the message doesn't contain a <code>.times</code> class, so you could add some exception handling:</p>\n\n<pre><code>try:\n stars = message_soup.select('.times')[0].string\nexcept IndexError:\n stars = None\n</code></pre>\n\n<p>Having said that, I don't think it's particularly <em>wrong</em> to use a <code>.pop()</code> -- it depends other factors that may come down to judgement. A co-worker I respect seems to think using <code>pop()</code> in python is a bit unpythonic. Another coworker who is more Lisp inflected likes it. Personally, I think I would leave it out, <em>unless</em> there was something compelling about mutating the data structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T20:16:37.927",
"Id": "48265",
"ParentId": "48258",
"Score": "8"
}
},
{
"body": "<p>That's a beautiful excuse for writing code, and the final product is quite nice as well.</p>\n\n<p>★ First of all, congrats to your Java-ridden mind for not forcing classes into Python where they aren't needed.</p>\n\n<p>★ You import but do not use <code>OrderedDict</code> and <code>operator</code>. Remove unused imports.</p>\n\n<p>★ It is customary to write your code in a way that allows it to be used as either a module, or a script. For this, the <code>if __name__ == '__main__'</code> trick is used:</p>\n\n<pre><code>if __name__ == '__main__':\n # executed only if used as a script\n</code></pre>\n\n<p>★ You declare a few variables like <code>room</code>, <code>url</code>, and <code>pages</code> up front. This hinders code reuse:</p>\n\n<ul>\n<li><p>The <code>room</code> variable should not be declared up front as a global variable, but in your main section. From there, it can be passed down through all functions.</p></li>\n<li><p>The <code>url</code> specifically but unnecessarily mentions <code>the-2nd-monitor</code>. This isn't harmful, but unnecessary as only the ID is relevant. Furthermore, <code>url</code> is an awfully short name for such a large scope. Something like <code>star_url_pattern</code> would be better – except that global “constants” should be named all-uppercase:</p>\n\n<pre><code>STAR_URL_PATTERN = 'http://chat.stackexchange.com/rooms/info/{0}/?tab=stars&page={1}'\n</code></pre></li>\n<li><p>Reserve plural names for collections. <code>pages</code> should rather be <code>page_count</code>. But wait – why are we hardcoding this rather than fetching it from the page itself? Just follow the <code>rel=\"next\"</code> links until you reach the end.</p></li>\n</ul>\n\n<p>★ That last idea could be implemented with a <em>generator function</em>. A Python generator function is similar to a simple iterator. It can <code>yield</code> elements, or <code>return</code> when exhausted. We could build such a generator function that yields a beautiful soup object for each page, and takes care of fetching the next one. As a sketch:</p>\n\n<pre><code>from urllib.parse import urljoin\n\ndef walk_pages(start_url):\n current_page = start_url\n while True:\n content = ... # fetch the current_page\n soup = BeautifulSoup(content)\n yield soup\n # find the next page\n next_link = soup.find('a', {'rel': 'next'})\n if next_link is None:\n return\n # urljoin takes care of resolving the relative URL\n current_page = urljoin(current_page, next_link.['href'])\n</code></pre>\n\n<p>★ Please don't use <code>urllib.request</code>. That library has a horrible interface and is more or less broken by design. You might notice that the <code>.read()</code> method returns raw bytes, rather than using the charset from the <code>Content-Type</code> header to automatically decode the content. This is useful when handling binary data, but a HTML page is <em>text</em>. Instead of hardcoding the encoding <code>utf-8</code> (which isn't even the default encoding for HTML), we could use a better library like <a href=\"http://docs.python-requests.org/en/latest/\"><code>requests</code></a>. Then:</p>\n\n<pre><code>import requests\nresponse = requests.get(current_page)\nresponse.raise_for_status() # throw an error (only for 4xx or 5xx responses)\ncontent = response.text # transparently decodes the content\n</code></pre>\n\n<p>★ Your <code>allstars</code> variable should not only be named something like <code>all_stars</code> (notice the separation of words via an underscore), but also not be a global variable. Consider passing it in as a parameter to <code>add_stars</code>, or wrapping this dictionary in an object where <code>add_stars</code> would be a method.</p>\n\n<p>★ I don't quite understand why you write each page to a file. I suspect this was intended as a debugging help, but it doesn't add any value to a user of that script. Instead of cluttering the current working directory, make this behavior optional.</p>\n\n<p>★ Do not compare to <code>None</code> via the <code>==</code> operator – this is for general comparison. To test for identity, use the <code>is</code> operator: <code>if stars is None</code>. Sometimes, it is preferable to rely on the boolean overload of an object. For example, arrays are considered falsey if they are empty.</p>\n\n<hr>\n\n<p><em>Talking is easy,<br>\ncoding is hard.<br>\nIs this refactoring<br>\nequally bad?</em></p>\n\n<pre><code>import time\nfrom bs4 import BeautifulSoup\nimport requests\nfrom urllib.parse import urljoin\n\nSTAR_URL_TEMPLATE = 'http://chat.{0}/rooms/info/{1}/?tab=stars'\n\ndef star_pages(start_url):\n current_page = start_url\n while True:\n print(\"GET {}\".format(current_page))\n response = requests.get(current_page)\n response.raise_for_status()\n soup = BeautifulSoup(response.text)\n yield soup\n # find the next page\n next_link = soup.find('a', {'rel': 'next'})\n if next_link is None:\n return\n # urljoin takes care of resolving the relative URL\n current_page = urljoin(current_page, next_link['href'])\n\ndef star_count(room_id, site='stackexchange.com'):\n stars = {}\n for page in star_pages(STAR_URL_TEMPLATE.format(site, room_id)):\n for message in page.find_all(attrs={'class': 'monologue'}):\n author = message.find(attrs={'class': 'username'}).string\n\n star_count = message.find(attrs={'class': 'times'}).string\n if star_count is None:\n star_count = 1\n\n if author not in stars:\n stars[author] = 0\n stars[author] += int(star_count)\n\n # be nice to the server, and wait after each page\n time.sleep(1)\n return stars\n\nif __name__ == '__main__':\n the_2nd_monitor_id = 8595\n stars = star_count(the_2nd_monitor_id)\n # print out the stars in descending order\n for author, count in sorted(stars.items(), key=lambda pair: pair[1], reverse=True):\n print(\"{}: {}\".format(author, count))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T14:04:37.403",
"Id": "49074",
"ParentId": "48258",
"Score": "28"
}
},
{
"body": "<p>There are also some possible <code>BeautifulSoup</code> related improvements:</p>\n\n<ul>\n<li><p>It is highly recommended to specify an underlying parser that <code>BeautifulSoup</code> would use under the hood:</p>\n\n<pre><code>soup = BeautifulSoup(response.text, \"html.parser\")\n# soup = BeautifulSoup(response.text, \"lxml\")\n# soup = BeautifulSoup(response.text, \"html5lib\")\n</code></pre>\n\n<p>If you don't specify a parser, <code>BeautifulSoup</code> would pick one automatically from what is available in the current Python environment - and it may work differently on different machines and environments leading to surprising consequences. See also <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser\" rel=\"nofollow noreferrer\">Installing a parser</a> documentation section.</p></li>\n<li>Instead of doing <code>.select()</code> and <code>.pop()</code>, you can call <code>.select_one()</code> method directly which would return a single element or <code>None</code> (if no elements found)</li>\n<li>The <code>soup.find_all(attrs={'class': 'monologue'})</code> can be replaced with a more concise CSS selector call: <code>soup.select('.monologue')</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-13T13:15:41.880",
"Id": "175571",
"ParentId": "48258",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "49074",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:14:16.450",
"Id": "48258",
"Score": "44",
"Tags": [
"python",
"python-3.x",
"stackexchange",
"web-scraping",
"beautifulsoup"
],
"Title": "We'll be counting stars"
} | 48258 |
<p>Please, have a look at the previous (bad) implementation and the review <a href="https://codereview.stackexchange.com/q/48224/16189">here</a>.</p>
<p>After reading the suggested article at <a href="http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL#CppMatureApproach" rel="nofollow noreferrer" title="HowTo: Export C++ classes from a DLL">HowTo: Export C++ classes from a DLL</a>, I have decided to use a plain C function approach. However, I want to use C++ code inside the DLL later. Anyway, the exported one will be a plain C function with the <code>const char *</code> argument.</p>
<p>In my earlier attempt, I tried to pass reference to the <code>vector<string></code> argument, which is not possible or at least safe. The vector of strings was the result of parsing the line from a text file. Now, I am passing the line itself, and the parsing is done inside the DLL. The code of the caller and the type of the called function look like this:</p>
<pre><code>typedef __declspec(dllimport) int (__cdecl *CONVERTPROC)(const char *);
int call_convert_from_dll(const std::string & dllname, const char * line)
{
HINSTANCE hinstLib;
CONVERTPROC convert;
BOOL fRunTimeLinkSuccess = FALSE;
// Get a handle to the DLL module.
hinstLib = LoadLibrary(dllname.c_str());
// If the handle is valid, try to get the function address.
if (hinstLib != nullptr)
{
convert = (CONVERTPROC)GetProcAddress(hinstLib, "convert");
// If the function address is valid, call the function.
if (convert != nullptr)
{
fRunTimeLinkSuccess = TRUE;
(convert)(line);
}
else {
DWORD err = GetLastError();
if (err == ERROR_PROC_NOT_FOUND)
cerr << "procedure convert() was not found" << endl;
else
cerr << "runtime link failed: " << err << endl;
}
// Free the DLL module.
FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (!fRunTimeLinkSuccess) {
cerr << "Failed when using '" << dllname << "' library." << endl;
return 1;
}
return 0;
}
</code></pre>
<p>The name of the called function (from the DLL) is passed as a string. Because of that, the <code>extern "C"</code> must be used to avoid identifier mangling.</p>
<p>The mentioned article also says that no exception should cross the boundary of the DLL module (if it is not the special case when both parts are written in C++ and compiled by the same version of the compiler). Because of that, the <code>try/catch</code> wraps the body of the called function. Any exception is transformed to the error code equal to 1:</p>
<pre><code>extern "C" { // we need to export the C interface
__declspec(dllexport) int __cdecl convert(const char * line)
{
int err = 0;
try {
cout << "my.dll: '" << line << "'" << endl;
vector<string> vs;
StringTok(vs, line, " \t\n");
err = xmain(vs);
}
catch (...) {
return 1;
}
return err;
}
} // extern "C"
</code></pre>
<p>Can you see any other flaw in the code?</p>
| [] | [
{
"body": "<p>Certainly a better approach that the original. Only one 'flaw' that I noticed:</p>\n\n<ul>\n<li>You ignore the return value from your <code>convert</code> function.</li>\n</ul>\n\n<p>But I do have a couple of comments:</p>\n\n<ul>\n<li>You may want to consider making <code>line</code> a <code>const char * const</code> (with associated other changes).</li>\n<li><p>Put the type declaration next to the first use. i.e., rather than</p>\n\n<pre><code>HINSTANCE hinstLib;\n// several lines\nhinstLib = LoadLibrary(dllname.c_str());\n</code></pre>\n\n<p>do</p>\n\n<pre><code>HINSTANCE hinstLib = LoadLibrary(dllname.c_str());\n</code></pre></li>\n<li><p>Since you're in C++, use <code>bool</code> \\ <code>false</code> etc rather than <code>BOOL</code>. </p></li>\n<li>Depending on how frequently this would be called, you may want to adopt a RAII approach similar to <a href=\"https://codereview.stackexchange.com/questions/15848/windows-dll-module-class\">Windows DLL Module Class</a>. This could lead to some simplifications in the main flow of the code.</li>\n<li><code>LoadLibrary</code> and <code>GetProcAddress</code> are documented as returning <code>NULL</code> rather than <code>std::nullptr</code>. It may be totally silly, but I'd stick with the documentation.</li>\n<li>You don't deal with the error case of <code>LoadLibrary</code> failing, with respect to <code>GetLastError</code> and giving a sensible error.</li>\n<li>Consider using a <code>reinterpret_cast<CONVERTPROC></code> rather than <code>(CONVERTPROC)</code>.</li>\n<li>You only return 1 or 0 from <code>call_convert_from_dll</code> - should it have a <code>bool</code> or enumerated return type?</li>\n<li>Depending on what the effect of failure is, you may want to consider using exceptions, catching them further up the chain rather than handling failure in this function.</li>\n</ul>\n\n<p>For your <code>convert</code> function:</p>\n\n<ul>\n<li>The code implies the use of <code>using namespace std</code>. Please don't.</li>\n<li>Rather than using an <code>err</code> variable, you could return immediately. The function is short enough to be understandable.</li>\n<li><p>If any exceptions are likely to be thrown by inner code, catch them separately in the catch block and give details rather than 'catch all and dump'. Perhaps something like:</p>\n\n<pre><code>catch (const std::exception& e) {\n std::cerr << \"Convert exception: \" << e.what() << std::endl;\n return 1;\n}\ncatch (...) {\n std::cerr << \"Convert unspecified exception\" << std::endl;\n return 1;\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T11:34:09.290",
"Id": "48768",
"ParentId": "48260",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48768",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:20:41.313",
"Id": "48260",
"Score": "4",
"Tags": [
"c++",
"windows"
],
"Title": "Calling a function from a dynamically loaded DLL (version 2)"
} | 48260 |
<p>I'm new at Caliburn Micro and the MVVM pattern.</p>
<p>I have 3 views (with its corresponding viewmodels):</p>
<ul>
<li><code>AppView</code></li>
<li><code>ClientsView</code></li>
<li><code>EditClientView</code></li>
</ul>
<p><code>AppView</code> is my main page with a <code>TabControl</code> inside. The child views (WPF <code>UserControls</code>) are loaded in new tabs.</p>
<p>In <code>ClientsView</code> I have a grid with filtered clients. I select one, and when the <code>Modify</code> button is clicked I need to load a new tab with the <code>editClientView</code> and load its data. Here is my code:</p>
<pre><code>public class EventAggregationProvider
{
static EventAggregator _eventAggregator = null;
public static EventAggregator EventAggregator
{
get
{
if (_eventAggregator == null)
_eventAggregator = new EventAggregator();
return _eventAggregator;
}
}
}
</code></pre>
<p>Function on <code>ClientsViewModel</code>:</p>
<pre><code>public void ModificarCliente()
{
AppViewModel myParent = (AppViewModel)this.Parent;
myParent.OpenTab(typeof(modClienteViewModel));
EventAggregationProvider.EventAggregator.Publish(_selectedclient);
}
</code></pre>
<p><code>MainViewModel</code> <code>OpenTab</code> function:</p>
<pre><code>public void OpenTab(Type TipoVista)
{
bool bFound = false;
if (TipoVista != null)
{
Screen myScreen = (Screen)Activator.CreateInstance(TipoVista as Type);
myScreen.DisplayName = myScreen.ToString();
foreach (Screen miItem in Items)
{
if (miItem.ToString() == myScreen.ToString())
{
bFound = true;
ActivateItem(miItem);
}
}
if (!bFound) ActivateItem(myScreen);
}
}
</code></pre>
<p><code>EditClientViewModel</code>:</p>
<pre><code>class modClienteViewModel : Screen, IHandle<vw_ClientesFull>
{
private OhmioService.OhmioServiceClient serviceClient =
new OhmioService.OhmioServiceClient();
public Clientes Cliente { get; set; }
public modClienteViewModel()
{
EventAggregationProvider.EventAggregator.Subscribe(this);
Cliente = new Clientes();
}
public void Handle(vw_ClientesFull myClient)
{
Cliente = serviceClient.Cliente_GetById(myClient.ID_Cliente);
NotifyOfPropertyChange("Cliente");
}
}
</code></pre>
<p>So what's your opinion on this? Especially about how I open the edit view (<code>ClientsView</code> becomes aware of the existence of <code>MainWindowViewmodel</code> and <code>EditClientViewModel</code>) from clients' viewmodel, and how I use <code>eventaggregator</code> to exchange the selected client between <code>clientsViewModel</code> and <code>EditClientViewModel</code>.</p>
| [] | [
{
"body": "<p><strong>Naming</strong></p>\n\n<p>You should use PascalCase to name methods and types. You do this most of the time, but slip up with <code>modClienteViewModel</code></p>\n\n<p>Your parameters should be in camelCase. Again, you do this most of the time, but slip up with <code>TipoVista</code> in your <code>OpenTab</code> method.</p>\n\n<p>Avoid Hungarian notation, with a modern IDE it's not necessary, and it just makes types harder to read.</p>\n\n<p><code>bool bFound = false;</code></p>\n\n<p>should be</p>\n\n<p><code>var found = false;</code></p>\n\n<p>The same probably goes for <code>miItem</code> which can just be <code>item</code> without any loss of meaning.</p>\n\n<p><strong>Var</strong></p>\n\n<p>Prefer to use <code>var</code> in a declaration when the right-hand side makes the type obvious.</p>\n\n<p>e.g.</p>\n\n<p><code>AppViewModel myParent = (AppViewModel)this.Parent;</code></p>\n\n<p>is obvious because of the cast, so we write</p>\n\n<p><code>var myParent = (AppViewModel)this.Parent;</code></p>\n\n<p>The reasoning behind this is that if you wanted to change a type, you would have to do so in two places in one line. With <code>var</code>, it is only one change.</p>\n\n<p>You should also use <code>var</code> when defining the loop variable in a foreach loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-04T13:58:10.223",
"Id": "68867",
"ParentId": "48261",
"Score": "2"
}
},
{
"body": "<p>For the <code>EventAggregator</code> property in your <code>EventAggregationProvider</code> class you should use the <a href=\"http://msdn.microsoft.com/en-us/library/ms173224.aspx\" rel=\"nofollow\"><strong>?? (null-coalescing) operator</strong></a>.</p>\n\n<p>Definition:</p>\n\n<blockquote>\n <p>The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.</p>\n</blockquote>\n\n<p>Your <code>get</code> will now look much cleaner:</p>\n\n<pre><code>public class EventAggregationProvider\n{\n static EventAggregator _eventAggregator = null;\n\n public static EventAggregator EventAggregator\n {\n get\n {\n return _eventAggregator ?? new EventAggregator();\n }\n }\n}\n</code></pre>\n\n<h2>Casing:</h2>\n\n<p>From the <a href=\"http://msdn.microsoft.com/en-us/library/ms229043.aspx\" rel=\"nofollow\"><strong>Capitalization Conventions</strong></a> on MSDN:</p>\n\n<blockquote>\n <ul>\n <li>Do use PascalCasing for all <strong><em>public</em></strong> member, type, and namespace names consisting of multiple words.</li>\n <li>Do use camelCasing for parameter names.</li>\n </ul>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-04T15:41:14.943",
"Id": "68871",
"ParentId": "48261",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T19:22:33.360",
"Id": "48261",
"Score": "5",
"Tags": [
"c#",
"mvvm"
],
"Title": "Caliburn Micro communication between list and edit viewmodels"
} | 48261 |
<p>I just started learning about the MVC architecture. And I started to create my own MVC framework to how I like it the most.</p>
<p>Here I've got the index.php, indexcontroller.php and view.php. I'm not too sure if what I am doing is right, or with best practices. So I would like to know if there is anything I missed so far, or what I could improve?</p>
<p><strong>Index.php</strong> (updated)</p>
<pre><code>//report all php errors
error_reporting(E_ALL);
//define site root path
define('ABSPATH', dirname(__FILE__));
//include functions
foreach(glob(ABSPATH . '/functions/*.php') as $filename) {
require $filename;
}
//set config array
$config = parse_ini_file(ABSPATH . '/config.ini', true);
$config = json_decode(json_encode($config));
//auto load classes
spl_autoload_register('autoloadCore');
spl_autoload_register('autoloadController');
spl_autoload_register('autoloadModel');
//url to class router
Glue::stick((Array) $config->routes);
</code></pre>
<p><strong>IndexController</strong></p>
<pre><code>class IndexController extends BaseController {
private $_view;
public function GET() {
$this->index();
}
public function POST() {
//don't handle post
}
public function __construct() {
$this->_view = new View();
}
public function index() {
$this->_view->welcome = 'Welcome!';
$this->_view->render('index');
}
}
</code></pre>
<p><strong>View</strong></p>
<pre><code>class View {
private $_vars = [];
public function __set($index, $value) {
$this->_vars[$index] = $value;
}
function render($fileView) {
$path = ABSPATH . '/view/' . $fileView . '.php';
if(!file_exists($path)) {
throw new Exception('View not found: '. $path);
}
foreach($this->_vars as $key => $value) {
$$key = $value;
}
include ($path);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:43:19.177",
"Id": "84896",
"Score": "0",
"body": "Best way to see if it's up to standard is to see how easy it is to add new views."
}
] | [
{
"body": "<p>MVC approaches differ between languages, platforms and frameworks. They are usually termed \"MV* frameworks\" because they don't exactly follow <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">strict MVC</a>. But we call them MVC nonetheless.</p>\n\n<h1>Separate core logic from configurable logic</h1>\n\n<p>The way I understand your code, it looks like you've gone over CodeIgniter (or something similar). I assume all your requests run through <code>index.php</code> where the initial logic runs, like the helper loading, routing etc. For that, I suggest you separate the autoloader list and routing list to different files. You can load them via something like <code>include</code>. That way, you don't accidentally modify the core logic.</p>\n\n<pre><code>// autoload.php\n$autoload = array(\n 'autoloadCore',\n 'autoloadController',\n 'autoloadModel'\n);\n\n// routes.php\n$routes = array(\n '/' => 'Index',\n '/signup' => 'SignUp',\n '/login' => 'Login'\n);\n</code></pre>\n\n<p>Additionally, the word \"Controller\" might not be necessary for the routing. You already know that they always go to controllers. You might want to do that in the underlying logic instead, and keep it easy on the configurable parts.</p>\n\n<h1>Route lists cons</h1>\n\n<p>One thing to note with this routing strategy is that whenever you add a controller, you always need to list down the route. This approach is not that nice, especially when you are going to be handling a hundred routes (and trust me, it ain't a walk in the park).</p>\n\n<h3>Auto-route + custom routes</h3>\n\n<p>Why not automatically look for controllers based on a predefined convention (like CodeIgniter). A route of <code>/foobar/bam</code> would route to <code>FoobarController</code> and execute the <code>bam</code> method. As for custom routes, you can map it like so:</p>\n\n<pre><code>$routes = array(\n 'autobam' => 'foobar/bam` // A route of `/autobam` executes the same as `foobar/bam`\n);\n</code></pre>\n\n<p>And the flow goes like:</p>\n\n<pre><code>- Parse route\n- Check for match under custom\n - If match, convert to equivalent route\n- Use non-custom/equivalent route for locating the controller\n - If none, throw error\n - Else, load and execute\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:03:34.763",
"Id": "84771",
"Score": "0",
"body": "Why would I put the autoload callbacks in an array and different file? I don't consider those configurable logic, but core logic as they will never be changed. As far as the route list, I have made a config.ini file for everything that's configurable and placed it there alongside other settings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:20:30.367",
"Id": "84840",
"Score": "0",
"body": "@KidDiamond You have to think about scaling and extensibility the system, not just code cleanliness and efficiency. Also, you can just use `require`/`include` and PHP arrays for routes. Saves you the effort of parsing the ini file."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T04:10:21.243",
"Id": "48297",
"ParentId": "48269",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48297",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T20:53:36.860",
"Id": "48269",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"design-patterns",
"mvc"
],
"Title": "Is my first MVC architecture set up to standards?"
} | 48269 |
<p>(Method signature is given with parameters)</p>
<p>Try to visualize me writing this code at an interview, and please be brutal while judging it.</p>
<blockquote>
<p><strong>Problem:</strong></p>
<p>Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.</p>
<p>For example, given</p>
<pre><code>s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"]
</code></pre>
<p>A solution is</p>
<pre><code>["cats and dog", "cat sand dog"]
</code></pre>
</blockquote>
<p><strong>Time complexity:</strong> I don't know how to analyze it, \$O(n)\$, since I visit each char of the string for sure, but since I am backtracking, I visit it again constant time. I don't know, so please explain</p>
<p><strong>Space Complexity:</strong> \$O(n)\$</p>
<pre><code>public ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String> sentences = new ArrayList<String>();
wordBreakHelper(s, dict, 0, new StringBuilder(), sentences);
return sentences;
}
private static void wordBreakHelper(String givenSentence, Set<String> dictionary, int index, StringBuilder path, ArrayList<String> results){
if(givenSentence.length() == 0){
results.add(path.toString());
}
if(index > givenSentence.length()){
return;
}
for(int i = index; i < givenSentence.length(); i++){
boolean isSpace = false;
if(dictionary.contains(givenSentence.substring(0, i+1))){
if(i+1 == givenSentence.length()){
path.append(givenSentence.substring(0, i+1));
}else{
path.append(givenSentence.substring(0, i+1) +" ");
isSpace = true;
}
wordBreakHelper(givenSentence.substring(i+1), dictionary, 0, path, results);
if(isSpace == true){
path.replace(path.length() - givenSentence.substring(0, i+2).length() , path.length(), "");
}else{
path.replace(path.length() - givenSentence.substring(0, i+1).length() , path.length(), "");
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>I don't believe you program is \\$O(n)\\$ because you recursively call <code>wordBreakHelper</code> in a loop, which I believe actually makes this an exponential time algorithm. This is because your \\$O(n)\\$ loop potentially run \\$O(n)\\$ times (\\$O(n^n)\\$).</p>\n\n<p>Two quick comments on the code, though:</p>\n\n<ul>\n<li><p>Be consistent in your parameter names. For example, you have both <code>dict</code> and <code>dictionary</code>.</p></li>\n<li><p>There's no reason to require <code>ArrayList</code> parameter types over simple <code>List</code> types.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T22:15:14.043",
"Id": "84720",
"Score": "0",
"body": "The method signature was provided in the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T22:22:17.823",
"Id": "84721",
"Score": "1",
"body": "That doesn't necessarily mean you have to keep it, as any calling code wouldn't be affected. It's a trivial point though, and you demonstrate the use of descriptive variable names in the `wordBreakHelper` signature."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:58:55.910",
"Id": "48277",
"ParentId": "48274",
"Score": "4"
}
},
{
"body": "<p>For the time and space complexity, think about how many sentences are possible with:</p>\n\n<pre><code>s = \"aaaaaaaaaaa...\"\ndict = [\"a\", \"aa\"]\n</code></pre>\n\n<p>Any solutation that creates all of these sentences would need to have exponential complexity.</p>\n\n<pre><code>path.append(givenSentence.substring(0, i + 1) + \" \");\n</code></pre>\n\n<p>If you are using a StringBuilder, you should use its append method instead of the '+' operator as it's more efficient.</p>\n\n<p>The index parameter is always 0. This can be removed.</p>\n\n<p><code>givenSentence.substring(0, i + 1)</code> is used multiple times. You can assign this to a variable and reuse it instead.</p>\n\n<pre><code>if(isSpace == true)\n</code></pre>\n\n<p>There's no need to compare with true. Just use <code>if(isSpace)</code></p>\n\n<pre><code>givenSentence.substring(0, i + 2).length()\n</code></pre>\n\n<p>Calling <code>substring</code> just to get the length of the String is unnessesary. This is the same as <code>i + 2</code>.</p>\n\n<p>The handling of <code>isSpace</code> adds some complexity. There is some code duplication and extra if statements needed. I would try to remove the need for this.</p>\n\n<p>Changing the bounds of the for-loop can remove the need for adding one to <code>i</code> each time it's used.</p>\n\n<p>With these changes, you have something like:</p>\n\n<pre><code>private static void wordBreakHelper(String givenSentence, Set<String> dictionary, StringBuilder path, List<String> results) {\n if(givenSentence.length() == 0) {\n return;\n }\n\n if(dictionary.contains(givenSentence)) {\n results.add(path.toString() + givenSentence);\n }\n\n for(int i = 1; i < givenSentence.length(); i++) {\n String nextWord = givenSentence.substring(0, i);\n if(dictionary.contains(nextWord)) {\n path.append(nextWord).append(\" \");\n wordBreakHelper(givenSentence.substring(i), dictionary, path, results);\n path.replace(path.length() - nextWord.length() - 1, path.length(), \"\");\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T23:45:08.697",
"Id": "84725",
"Score": "0",
"body": "can you explain the worst case complexity of the code in broader detail; I can see how it is expnonential but have a hard time grasping an upper bound on it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:23:07.017",
"Id": "84728",
"Score": "0",
"body": "@bazang If there are `w` words in dict, and `n` letters in `s`: a sentence can contain at most `n` words. There's\n`w` possibilities for each word: So at most `O(w^n)` sentences. Each sentence will require at least `O(n^2)`\ntime because the calls to `substring` for each word (substring is `O(n)`, can be called `n` times for each\nsentence). The calls to append and replace aren't any more than that. I'm not sure if the loop adds anything here or if it's already accounted for. That adds up\nto `O(w^n * n^2)` time, `O(w^n * n)` space."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-08T03:17:59.050",
"Id": "190214",
"Score": "0",
"body": "This is giving me wrong output. I am getting: cat sand dog,\n catcats and dog"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-08T12:18:35.897",
"Id": "190279",
"Score": "0",
"body": "@GobSmack I've updated a line to: `results.add(path.toString() + givenSentence);` - so that path keeps its original value instead of being modified."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T23:17:38.517",
"Id": "48280",
"ParentId": "48274",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48280",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:32:28.590",
"Id": "48274",
"Score": "9",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Breaking of a sentence"
} | 48274 |
<p>I'm writing a simple xHTML parser which parses a data without nested tags.</p>
<p>Example input code will look like:</p>
<pre><code><h2>Header</h2>
<p> atsatat </p>
<h2>asdsaad</2><p>s32532235</p>
</code></pre>
<p>I've wrote the following code:</p>
<pre><code>#include <node.h>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
using namespace v8;
enum Tags {
Closing = 0,
Paragraph,
Heading
};
int tagDetect(char *ptr){
if (*ptr == '/') {
return Tags::Closing;
}
if (*ptr == 'p') {
return Tags::Paragraph;
}
if (*(ptr + 1) == '2' || *(ptr + 1) == '3')
return Tags::Heading;
return -1;
}
Handle<Value> Callback(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsString() || !args[1]->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("Invalid arguments! First parameter must be [string], second must be a callback [function].")));
}
Local<Function> callback = Local<Function>::Cast(args[1]);
String::Utf8Value param1(args[0]->ToString());
std::string input = std::string(*param1);
static Persistent<String> data_symbol = NODE_PSYMBOL("data");
static Persistent<String> tag_symbol = NODE_PSYMBOL("tag");
std::string::size_type pos = 0, closePos = 0;
int openPos;
int tagID, lastTag, id = 0, lastAppended = 0, clearStartPos;
Local<Array> nodes = Array::New();
Local<Object> node_obj;
while ((pos = input.find('<', pos)) != std::string::npos) {
pos++;
switch (tagID = tagDetect(&input[pos])) {
case Tags::Closing:
tagID = tagDetect(&input[pos + 1]);
if (tagID == lastTag && (pos - openPos > 10 || lastTag != Tags::Paragraph)) {
/* Concat tags */
if (lastAppended == lastTag) {
if (lastTag == Tags::Heading) { /* Dont concat heading tags */
continue;
}
node_obj = nodes->Get(id - 1)->ToObject();
node_obj->Set(data_symbol, String::Concat(node_obj->Get(data_symbol)->ToString(), String::New(input.substr(openPos + (lastTag > 1 ? 3 : 2), pos - openPos - (lastTag > 1 ? 3 : 2) - 1).c_str())));
continue;
}
node_obj = Object::New();
node_obj->Set(data_symbol, String::New(input.substr(openPos + (lastTag > 1 ? 3 : 2), pos - openPos - (lastTag > 1 ? 3 : 2) - 1).c_str()));
node_obj->Set(tag_symbol, Integer::New(lastTag));
nodes->Set(id, node_obj);
id++;
lastAppended = lastTag;
continue;
}
/* Clear useless tags */
input.erase(pos - 1, input.find('>', pos - 1) - pos + 2);
break;
case Tags::Paragraph:
case Tags::Heading:
openPos = pos;
lastTag = tagID;
break;
default:
/* Clear useless tags */
input.erase(pos - 1, input.find('>', pos - 1) - pos + 2);
break;
}
}
/* Remove last element from array if its heading */
if (lastTag == Tags::Heading) {
nodes->Delete(id - 1);
}
const unsigned argc = 2;
Local<Value> argv[argc] = {
Local<Value>::New(Null()),
nodes
};
callback->Call(Context::GetCurrent()->Global(), argc, argv);
return Undefined();
}
void RegisterModule(Handle<Object> target) {
target->Set(String::NewSymbol("parse"),
FunctionTemplate::New(Callback)->GetFunction());
}
NODE_MODULE(smartparser, RegisterModule);
</code></pre>
<p>I'm using this as Native NodeJS module. Since I'm really new in the C++ world, any tips on how to optimize/improve my code will be greatly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T22:36:35.013",
"Id": "84723",
"Score": "1",
"body": "Too many pointers. You should try to replace them by standard library classes whenever possible :p"
}
] | [
{
"body": "<ul>\n<li><p>Although optional, you can keep your <code>#include</code>s organized (alphabetically, for instance) so that it's easier to locate an individual one or to determine if you've already included a particular one.</p></li>\n<li><p>You've included <code><sstream></code>, but I don't see any use of stringstreams. If you're not utilizing this library, then remove it.</p></li>\n<li><p>Avoid <code>using namespace X</code> in global scope as it will expose it to the entire program or file, which can break code in cases such as name-clashing (using the same name for something in which something <em>doesn't</em> belong to the <code>namespace</code>). It could also make it difficult for readers to tell what is part of a particular <code>namespace</code> (I cannot tell what belongs to <code>v8</code>, so I'm having a bit more trouble reviewing this). If you insist on keeping a <code>using</code>, then keep it local, such as in a function.</p></li>\n<li><p>For this <code>enum</code>:</p>\n\n<pre><code>enum Tags {\n Closing = 0,\n Paragraph,\n Heading\n};\n</code></pre>\n\n<p>You don't need to explicitly set it to <code>0</code>. This is already the default starting value for <code>enum</code>s.</p></li>\n<li><p>You don't need a <code>char*</code> here:</p>\n\n<pre><code>int tagDetect(char *ptr){\n</code></pre>\n\n<p>Looking at the calling code, you're passing in an <code>std::string</code>. You should just pass this object by itself. Also, because it's not being modified, pass it by <code>const&</code> to avoid a needless copy and any accidental modification:</p>\n\n<pre><code>int tagDetect(std::string const& str){\n</code></pre>\n\n<p>In C++ in general, you should avoid passing raw pointers to functions as you cannot keep track of ownership with them (C++11 smart pointers helps with that for when points are necessary). But in this case, you shouldn't need to deal with pointers.</p>\n\n<p>With this change, you will need to modify the function code (I'll use different names for clarity):</p>\n\n<p>This is accessing the first character:</p>\n\n<pre><code>if (*ptr == 'p')\n</code></pre>\n\n<p>so use <code>front()</code>:</p>\n\n<pre><code>if (str.front() == 'p')\n</code></pre>\n\n<p>This is accessing the second one:</p>\n\n<pre><code>*(ptr + 1)\n</code></pre>\n\n<p>so you can use indices to make it more clear (while they <em>are</em> technically the same thing; yours is doing pointer arithmetic):</p>\n\n<pre><code>str[1]\n</code></pre></li>\n<li><p>I'd keep these on separate lines for readability:</p>\n\n<pre><code>int tagID, lastTag, id = 0, lastAppended = 0, clearStartPos;\n</code></pre>\n\n<p>They aren't entirely related to each other, and there could be some maintenance issues since some are declared and the others initialized.</p>\n\n<pre><code>int tagID;\nint lastTag;\nint id = 0;\nint lastAppended = 0;\nint clearStartPos;\n</code></pre>\n\n<p>You should also have these declared/initialized as close to their scope as possible. This will help determine if any variable is no longer used (keeping around unused variables will clutter the code). But if you cannot put them any closer, then do have each one on separate lines.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T22:03:10.487",
"Id": "84715",
"Score": "0",
"body": "Thanks! I really appreciate this. Just 1 more thing: Is there a way to improve the algorithm of finding tags?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T22:12:41.683",
"Id": "84717",
"Score": "0",
"body": "@Deepsy: I haven't quite looked at it yet, but I still can. I'm not too great with algorithms, so someone else may address that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:53:26.397",
"Id": "48276",
"ParentId": "48275",
"Score": "2"
}
},
{
"body": "<p>I'm not that familiar with C++, so I can't comment too much on how idiomatic it is and such, but that said, there are a few concerns I've got.</p>\n\n<h1>Reading over the end of a buffer</h1>\n\n<p>Consider this input: <code><</code>. You'll find that left angle bracket and then call <code>tagDetect</code>, passing it a pointer to the <code>NUL</code> terminator. In that function, you then compare that <code>NUL</code> against a few values (specifically, <code>/</code> and <code>p</code>), and then move on to checking the value after the <code>NUL</code>. By doing that, you're reading past the end of the string. In C, that would be undefined behavior. I imagine it's undefined behavior in C++ as well.</p>\n\n<h1>Using uninitialized variables</h1>\n\n<p>Consider this input: <code></p></code>. You'll go to your <code>case Tags::Closing</code> bit and compare to see if <code>tagID</code> (0) is equal to <code>lastTag</code> (uninitialized). That could be true or it could be false. Either way, it's not deterministic, and that's bad.</p>\n\n<p>Later in the same condition, you check to see if <code>pos - openPos > 10</code>. Well, first I wonder why you chose 10, since it seems rather arbitrary, but <code>openPos</code> is similarly uninitialized. Again, you'll want to make sure that's initialized somehow and that it acts as expected.</p>\n\n<p>Last in that condition, you compare <code>lastTag</code> against <code>Tags::Paragraph</code>. Again, <code>lastTag</code> was uninitialized, so the result could be either true or false.</p>\n\n<h1>Potential concatenation bug</h1>\n\n<p>If <code>lastAppended == lastTag</code> and <code>lastTag == Tags::Heading</code>, you <code>continue</code> without appending <em>or</em> concatenating. I imagine this is a bug.</p>\n\n<h1>Synchronous functions shouldn't use a callback</h1>\n\n<p>There's no reason a parser (this one, at least) should be asynchronous, and if it is synchronous (as it is here), there's no reason to use a callback. Just return the result instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T22:03:36.540",
"Id": "48278",
"ParentId": "48275",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48276",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T21:38:34.553",
"Id": "48275",
"Score": "5",
"Tags": [
"c++",
"optimization",
"beginner",
"parsing",
"node.js"
],
"Title": "Optimizing simple xHTML parser"
} | 48275 |
<p>I was doing this easy challenge "Counting Minutes I" from Coderbyte.com where you just calculate the number of minutes between two given times. </p>
<p>The second time is always after the first, although it may look to be before but mean it's during the next day. </p>
<p>The format of their test cases is <code>"hour1:minute1-hour2:minute2"</code> such as <code>"12:30am-12:00pm"</code> where the difference would be 11.5 hours = <code>1425</code> minutes.</p>
<p>In converting different parts of the <code>string</code> containing the times to <code>int</code>s I've been using <code>istringstream</code> but creating a new one each time I call the function to set the <code>int</code>s. It seems like this is a sloppy way of accomplishing this, is there a better way like creating one <code>istringstream</code> in my main <code>CountingMinutesI</code> function and passing that as an argument to <code>getNum</code> then clearing it out after setting each particular <code>int</code>? Or is this also a bad idea?</p>
<pre><code>#include <iostream>
#include <sstream>
using namespace std;
void getNum (string timeString, int& pos, int& result) {
string temp;
while (isdigit(timeString[pos])) {
temp += timeString[pos];
pos++;
}
istringstream iss (temp);
iss >> result;
}
void to24HourTime(string timeString, int& pos, int& hourToConvert) {
if (timeString[pos] == 'p' && hourToConvert != 12)
hourToConvert += 12;
if (timeString[pos] == 'a' && hourToConvert == 12)
hourToConvert = 0;
}
int CountingMinutesI(string str) {
int hour1int, hour2int, min1int, min2int, minDifference;
int stringPos = 0;
getNum(str, stringPos, hour1int);
stringPos++;
getNum(str, stringPos, min1int);
to24HourTime(str, stringPos, hour1int);
stringPos += 3;
getNum(str, stringPos, hour2int);
stringPos++;
getNum(str, stringPos, min2int);
to24HourTime(str, stringPos, hour2int);
if (hour2int < hour1int) //second time is the during the next day
hour2int += 24;
if (hour1int == hour2int && min1int > min2int) //time difference would look negative, but is really between 23 and 24 hours
hour2int += 24;
if (min2int < min1int) { //simplify subtracting minutes to add to total difference
min2int += 60;
hour2int--;
}
minDifference = (hour2int - hour1int) * 60 + (min2int - min1int);
return minDifference;
}
int main() {
// keep this function call here
cout << CountingMinutesI(gets(stdin));
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-07T14:48:32.930",
"Id": "532554",
"Score": "0",
"body": "how come 11.5 hours = 1425 minutes. ?"
}
] | [
{
"body": "<p>In <code>to24HourTime()</code>, <code>pos</code> doesn't need to be passed by reference as it's not being modified. Just pass it by value.</p>\n\n<p>Instead of passing <code>hourToConvert</code> by reference (which <em>is</em> being modified), you can just pass by value and then return the result. It may also increase readability as it'll be clear that the third argument is to be reassigned by the function.</p>\n\n<p>Final changes:</p>\n\n<pre><code>hour1int = to24HourTime(str, stringPos, hour1int);\n\n// ...\n\nint to24HourTime(string timeString, int pos, int hourToConvert) {\n if (timeString[pos] == 'p' && hourToConvert != 12)\n hourToConvert += 12;\n if (timeString[pos] == 'a' && hourToConvert == 12)\n hourToConvert = 0;\n\n return hourToConvert;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:30:54.727",
"Id": "84885",
"Score": "0",
"body": "Didn't realize I wasn't even changing `pos` in that function, must have just been copying the input types from `getNum`. Will make the function changes though I wasn't sure whether to keep them void+pass by reference or just return the values I wanted change, but it does seem more readable this way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:27:26.723",
"Id": "48286",
"ParentId": "48284",
"Score": "5"
}
},
{
"body": "<pre><code>using namespace std;\n</code></pre>\n\n<p>I don't do much C++, but one thing I've learned from the many reviews I've upvoted on this site, I'm 100% positive, it isn't a good idea to import <code>std</code> in the global namespace; instead, refer to <code>std::cout</code>, <code>std::string</code> and <code>std::istringstream</code>.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this Stack Overflow answer</a> for more details about why it's best to avoid potential name clashes by not importing that namespace.</p>\n\n<p>Also <code>return 0</code> at the end of the <code>main()</code> procedure is redundant, the compiler should take care of it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:32:11.333",
"Id": "84886",
"Score": "0",
"body": "Never knew you didn't need to return 0, is it considered bad practice to leave the return out though? Only kept the namespace import because the site automatically put it in there, usually I leave it out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:35:43.503",
"Id": "84887",
"Score": "1",
"body": "@Instinct: No, it shouldn't be considered bad practice. It is already known that `main()` will always return 0 at the end, and any knowledgeable C++ programmer should know this. Leaving it in is still okay; it's just redundant if the compiler can already do this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:40:07.683",
"Id": "48287",
"ParentId": "48284",
"Score": "4"
}
},
{
"body": "<p>First, you should be aware that although you probably don't care about them in this specific case, there are <em>lots</em> of bits of ugliness to deal with if you try to deal with this issue in general. Time-keeping has so many strange little corner cases it's an absolute nightmare to get it really correct in general. Just for example, if a time crosses a daylight savings time (aka "summer time") boundary, the amount of time could be one hour longer or shorter than this will compute. For the moment, I'm going to assume you don't want to deal with any issues like that though.</p>\n<p>Second, the standard library has functions that attempt to make tasks like this quite a bit easier. If you don't want to implement everything on your own, a combination of <code>mktime</code> and <code>difftime</code> will reduce the amount of code you need to write by a fairly substantial factor.</p>\n<p>Third, for this particular case, I'd at least consider using <code>scanf</code> instead of using iostreams at all. Given the formatting of the input data, you can consolidate nearly all the data reading down to something on this order:</p>\n<pre><code>scanf("%d%:%dc%*c-%d:%d%c%*c", &hour1, &minute1, &ampm1, &hour2, &minute2, &ampm2);\n</code></pre>\n<p>Although <code>scanf</code> can be somewhat tricky to use well (especially to read strings safely), in this case the use is pretty safe--certainly a <em>lot</em> safer than the <code>gets</code> you used to read the input (in fact, you'd be better off if you never used <code>gets</code> again--for anything, under any circumstances).</p>\n<p>From there, I'd write a small function that takes an hour and AM/PM indicator, and converts that to hours since midnight:</p>\n<pre><code>int to24hour(int hour, char ampm) { \n if (hour == 12)\n hour -= 12;\n return ampm == 'a' ? hour : hour+12;\n}\n</code></pre>\n<p>This gives clearly-defined boundaries between different parts of the code. In <code>main</code>, you read the input from the stream, and get a time as hour (in 12-hour format), minute, and AM/PM indicator.</p>\n<p>The next step takes 12-hour format input and produces 24-hour format as output. As your code is written, nearly all the code has to work with the input string as a string, and cooperate in keeping track of a current position in the string. This (for one example) makes it much more difficult for any of the code from being put to other uses--nearly all the code deals directly with the input string, so using it with input in a different format is likely to be difficult.</p>\n<h3>Summary:</h3>\n<ol>\n<li>Try to isolate code that deals with details like specific input formats into one place.</li>\n<li>Don't use <code>gets</code>. Ever. For any reason.</li>\n<li>Outside very strict boundaries, computations involving time get ugly in a hurry. Avoid them if humanly possible.</li>\n<li>In a few cases (possibly including this one) it's worth considering alternatives to using iostreams directly. They're great for some purposes, but can get ugly for others.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:37:10.430",
"Id": "84777",
"Score": "0",
"body": "I would even add that `gets` has been deprecated for a long time and has been removed from C/C++ in both the C11 and C++14 standards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:45:25.367",
"Id": "84778",
"Score": "1",
"body": "I think you have your format string wrong. Currently it will read `12am:30` I think it should read `12:30am`. `\"%d:%d%c%*c-%d:%d%c%*c\"` (don't forget to move the parameters appropriately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:57:39.903",
"Id": "84890",
"Score": "0",
"body": "Oh that's awesome have actually never used scanf before, but definitely seems appropriate here, I'm assuming `%*c` means \"skip this character\"? So it reads in the a or p but disregards the m? Also very clean converting function using only one if, thanks for the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:59:42.723",
"Id": "84891",
"Score": "1",
"body": "@Instinct: Yes, `%c` means `read a character`, and the `*` means \"read but ignore\" (so \"%*d\" means read and ignore a decimal integer, and so on). Note that printf also uses `*`, but entirely differently (one of the few places the two are entirely different)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:01:44.840",
"Id": "48289",
"ParentId": "48284",
"Score": "4"
}
},
{
"body": "<p>I think your whole approach is very C like.</p>\n\n<p>Personally I would define classes that represent the fundamental things you are representing and define input operators for these things so that they can be read directly from the input stream.</p>\n\n<p>This is what I would do:</p>\n\n<p>Note: I am assuming extra white space is acceptable. If it is not then modifying the code to use <code>std::noskipws</code> is trivial.</p>\n\n<h3>AMPM</h3>\n\n<pre><code>class AMPM\n{\n bool am;\n public:\n operator bool isAM() const {return am;}\n operator bool isPM() const {return !am;}\n\n friend std::istream& operator>>(std::istream& str, AMPM& data)\n {\n std::string ampmval(2, ' ');\n str >> std::ws; /* Skip leading whitespace */\n str.read(&ampmval[0], 2);\n\n if (ampmval == \"am\") { data.am = true;}\n else if (ampmval == \"pm\") { data.am = false;}\n else { str.setstate(std::ios::badbit);}\n return str;\n }\n};\n</code></pre>\n\n<h3>Time-Thing</h3>\n\n<pre><code>class TimeInMin\n{\n int minutesFromMidnight;\n public:\n void add(int minutes)\n {\n minutesFromMidnight += minutes;\n }\n friend std::istream& operator>>(std::istream& str, TimeInMin& data)\n {\n int hour;\n int min;\n char colon;\n AMPM ampm;\n\n if (str >> hour >> colon >> min >> ampm)\n {\n if (colon != ':')\n {\n str.setstate(std::ios::badbit);\n }\n else\n {\n if (hour == 12)\n { hour = 0;\n }\n if (ampm.isPM())\n { hour += 12;\n }\n data.minutesFromMidnight = hour * 60 + min;\n }\n }\n return str;\n }\n friend int operator-(TimeInMin const& lhs, TimeInMin const& rhs)\n {\n return lhs.minutesFromMidnight - rhs.minutesFromMidnight;\n }\n friend bool operator<(TimeInMin const& lhs, TimeInMin const& rhs)\n {\n return lhs.minutesFromMidnight < rhs.minutesFromMidnight;\n }\n};\n</code></pre>\n\n<h3>Now main() is trivial.</h3>\n\n<pre><code>int main(int argc, char* argv[])\n{\n TimeInMin first;\n TimeInMin second;\n char minus;\n\n if ((std::cin >> first >> minus >> second) && (minus == '-'))\n {\n /* It worked */\n if (second < first)\n { second.add(60*24);\n }\n std::cout << (second - first) << \"\\n\";\n }\n}\n</code></pre>\n\n<h3>Other comments:</h3>\n\n<p>Yes you are converting to and from string/stream way to much.</p>\n\n<pre><code> // reading from string\n // tracking position\n // and copying into another string\n // which will then be copied into a stream\n string temp;\n while (isdigit(timeString[pos])) {\n temp += timeString[pos];\n pos++;\n }\n</code></pre>\n\n<p>That's way to much work. The problem arises from converting your input from a stream into a string and then trying to parse a string manually and keep track of the position. The original stream would have kept track of your position for you.</p>\n\n<p>If you want to do line based input (a good idea). Then you should read a line into a string. Then convert that to a stream and just use the stream from that point on.</p>\n\n<pre><code> std::string line;\n std::getline(std::cin, line);\n std::stringstream linestream(line); // now just use this.\n // it will keep track of the position\n // for you.\n</code></pre>\n\n<p>The other thing you don't do is validate your input. What happens if the input is bad? You should at least attempt to detect bad input. Otherwise your code will go haywire when it sees something it does not expect.</p>\n\n<p>When you use streams this is easy; just set the badbit on the stream. Any other input operation will then just silently do nothing; and any test you use the stream in (<code>if statement condition</code> or <code>loop statement condition</code>) will auto convert the stream to a false value (technically a value that will convert to false) and thus not do that code (see my <code>main()</code> above for an example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:47:48.787",
"Id": "84898",
"Score": "0",
"body": "Interesting, hadn't thought of using classes in this way for a time difference problem. Seems to be a lot more clear and would be easier to troubleshoot, good advice!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:34:36.783",
"Id": "48318",
"ParentId": "48284",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48318",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:06:31.043",
"Id": "48284",
"Score": "6",
"Tags": [
"c++",
"strings",
"datetime",
"converting",
"stream"
],
"Title": "Better way to repeatedly use istringstream in \"counting minutes\" challenge"
} | 48284 |
<p>I'm trying to improve my understanding of recursive and iterative
processes. I've started with SICP, but have branched off to try and
find a few exercises when I started having difficulty. Currently I've
been looking at a series of posts on the subject by <a href="http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html" rel="nofollow">Tom
Moertel</a>.</p>
<p>Tom's <a href="https://github.com/tmoertel/recursion-to-iteration" rel="nofollow">code</a>
defines a node object for binary search trees and a search function:</p>
<blockquote>
<pre><code>class BSTNode(object):
"""Binary search tree node."""
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return '(%s, %r, %r)' % (self.val, self.left, self.right)
def find_val_or_next_smallest(bst, x):
""" Get the greatest value <= x in a binary search tree. Returns
None if no such value can be found. """
if bst is None:
return None
elif bst.val == x:
return x
elif bst.val > x:
return find_val_or_next_smallest(bst.left, x)
else:
right_best = find_val_or_next_smallest(bst.right, x)
if right_best is None:
return bst.val
return right_best
</code></pre>
</blockquote>
<p>The exercise asks us to transform the search function into an
iterative process and gives a general
<a href="http://blog.moertel.com/posts/2013-05-14-recursive-to-iterative-2.html" rel="nofollow">procedure</a>
for doing so: refactor all recursive calls into tail calls using
accumulators and then create a loop structure.</p>
<p>I've refactored the <code>else</code> clause in the search function into:</p>
<pre><code> else:
return work(find_val4(bst.right, x), bst)
def work(child_node, parent_node):
if child_node is None:
return parent_node.val
return child_node
</code></pre>
<p>But I've been having trouble figuring out how to move the logic done
in the 'work' function into an accumulator. Any advice, hints, or ways
to think about this would be totally appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:30:27.953",
"Id": "84738",
"Score": "2",
"body": "To understand recursion, click here: https://codereview.stackexchange.com/questions/48288/understand-recursion"
}
] | [
{
"body": "<p>Ahhhh. Okay.</p>\n\n<p>That the issue here is that if the process takes a right branch at node Foo, it needs to store a reference to Foo in the event that it fails to find a child node which is less-than or equal. That reference effectively lives in the stack-calls which occur in inside the calls to the <code>work</code> function. </p>\n\n<p>There can be an arbitrary number of these calls, so we need an internal, private stack:</p>\n\n<pre><code>def find_val_iterative(parent_node, x):\n right_branch = []\n def _inner(parent_node, x):\n if parent_node is None:\n if right_branch:\n return right_branch.pop().val\n return None\n elif parent_node.val == x:\n return x\n elif parent_node.val > x:\n return _inner(parent_node.left, x)\n else:\n right_branch.append(parent_node)\n return _inner(parent_node.right, x)\n return _inner(parent_node, x)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:53:38.440",
"Id": "48296",
"ParentId": "48288",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48296",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:59:07.243",
"Id": "48288",
"Score": "1",
"Tags": [
"python",
"recursion",
"iteration"
],
"Title": "Understand recursion"
} | 48288 |
<p>I have an Excel sheet with lot of rows with data. I am separating it into 2 sheets with some condition satisfies.</p>
<p>This is taking too much time. How can I improve the speed? Please suggest any changes to my code.</p>
<pre><code>Dim bmver As Object(,) = New Object(i20, 36) {}
Dim bmhor As Object(,) = New Object(i20, 36) {}
Dim ik As Integer = 0
Dim ij As Integer = 0
With oWs
For i As Integer = 2 To i20 - 1
If (.range("E" & i).value = .range("L" & i).value) Then
For j As Integer = 0 To 36
bmhor(ij, j) = .cells(i, j + 1).value
Next
ij = ij + 1
End If
Next
For k As Integer = 2 To i20 - 1
If (.range("C" & k).value = .range("J" & k).value) Then
For j1 As Integer = 0 To 36
bmver(ik, j1) = .cells(k, j1 + 1).value
Next
ik = ik + 1
End If
Next
End With
oWs = oBook.Worksheets("beamhor")
oWs.activate()
Dim r6 As Range = oWs.Range("A2").Resize(bmhor.GetLength(0), 37)
r6.Value2 = bmhor
With oWs
.Range("A2:AE" & i20).Sort(Key1:=.range("E2"), Order1:=Excel.XlSortOrder.xlAscending, _
Key2:=.range("L2"), Order2:=Excel.XlSortOrder.xlAscending, _
Key2:=.range("C2"), Order2:=Excel.XlSortOrder.xlAscending, _
Key2:=.range("J2"), Order2:=Excel.XlSortOrder.xlAscending, _
Orientation:=XlSortOrientation.xlSortColumns, _
Header:=Excel.XlYesNoGuess.xlNo, _
SortMethod:=XlSortMethod.xlPinYin)
End With
oWs = oBook.Worksheets("beamver")
oWs.activate()
Dim r7 As Range = oWs.Range("A2").Resize(bmver.GetLength(0), 37)
r7.Value2 = bmver
With oWs
.Range("A2:AE" & i20).Sort(Key1:=.range("E2"), Order1:=Excel.XlSortOrder.xlAscending, _
Key2:=.range("L2"), Order2:=Excel.XlSortOrder.xlAscending, _
Key2:=.range("C2"), Order2:=Excel.XlSortOrder.xlAscending, _
Key2:=.range("J2"), Order2:=Excel.XlSortOrder.xlAscending, _
Orientation:=XlSortOrientation.xlSortColumns, _
Header:=Excel.XlYesNoGuess.xlNo, _
SortMethod:=XlSortMethod.xlPinYin)
End With
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:41:40.943",
"Id": "84741",
"Score": "0",
"body": "What's `i20`'s value?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:48:51.677",
"Id": "84963",
"Score": "0",
"body": "If I remember, it's possible to pull a range directly in an array instead of reading each cells at a time using sheet.get_Range and range.Cells.Value. This might be faster since it'll do less call to the interopt."
}
] | [
{
"body": "<p>Excel interoperability is inherently slow - you have the .NET runtime talking to a COM object model through COM interop, there's a performance penalty just for doing that.</p>\n\n<p>Hence, you should strive to reduce the number of times you're accessing the worksheet cells, be it to read or to write.</p>\n\n<p>Before going into the algorithm, I'd like to point out the naming issues. Bad names make the code harder to read and longer to parse. Typing code is 20% of the job - the other 80% is spent <em>reading</em> code, so when the first 20% makes a good job at being <em>readable</em>, the 80% can be more productive.</p>\n\n<p>Avoid single-letter identifiers (for-loop variable is ok though) and disemvoweling. Use comments - don't write code that assumes the reader is also looking at the worksheet in question: name things so that we know what columns C, E, J and L are, or comment to that effect.</p>\n\n<p>Now. We have two loops, both iterating from <code>2 To i20 - 1</code>. Round one would be to merge them:</p>\n\n<pre><code>For i As Integer = 2 To i20 - 1\n\n If (.range(\"E\" & i).value = .range(\"L\" & i).value) Then\n\n For j As Integer = 0 To 36\n bmhor(ij, j) = .cells(i, j + 1).value\n Next\n\n ij = ij + 1\n\n End If\n\n If (.range(\"C\" & i).value = .range(\"J\" & i).value) Then\n\n For j As Integer = 0 To 36 'I'd believe identifier j can be reused here\n bmver(ik, j) = .cells(i, j + 1).value\n Next\n\n ik = ik + 1\n\n End If\n\nNext\n</code></pre>\n\n<p>Just doing that has reduced the number of iterations by half. Now these two blocks look awfully similar. Let's see if we can <em>extract a method</em> here:</p>\n\n<pre><code>Sub NameMe(Value1 As String, Value2 As String, Row As Long, TheWorksheet As Worksheet, TheArray As Object(,))\n\n Dim Counter As Integer\n If (Value1 = Value2) Then\n\n For i As Integer = 0 To 36\n TheArray(Counter, i) = TheWorksheet.Cells(Row, i + 1).Value\n Next\n\n Counter += 1\n\n End If\n\nEnd Sub\n</code></pre>\n\n<p>Then the loop can look like this:</p>\n\n<pre><code>Dim ValueForColumnE As String\nDim ValueForColumnL As String\nDim ValueForColumnC As String\nDim ValueForColumnJ As String\n\nFor i As Integer = 2 To i20 - 1\n\n ValueForColumnE = .range(\"E\" & i).Value.ToString()\n ValueForColumnL = .range(\"L\" & i).Value.ToString()\n ValueForColumnC = .range(\"C\" & i).Value.ToString()\n ValueForColumnJ = .range(\"J\" & i).Value.ToString()\n\n NameMe ValueForColumnE, ValueForColumnL, i, ows, bmhor\n NameMe ValueForColumnC, ValueForColumnJ, i, ows, bmver\n\nNext\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T05:40:42.373",
"Id": "84755",
"Score": "0",
"body": "i20 is no. or rows in that sheet. thanks for your words. i am improving my programing skills day by day. i tested with the code you suggested. But its also taking same time as much as mine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T05:42:42.397",
"Id": "84756",
"Score": "0",
"body": "`SheetRows` would be a *slightly* more descriptive name ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:26:52.487",
"Id": "48293",
"ParentId": "48291",
"Score": "3"
}
},
{
"body": "<p>Here are a few tips that I have used often to speed up macros and code that runs against excel sheets:</p>\n\n<ol>\n<li>Turn off screen updating in excel.</li>\n<li>Set the calculation mode to manual if you have other formulas and you are changing range values.</li>\n<li>If possible load all the data into an array and only write it to the sheet once.</li>\n</ol>\n\n<p>I have had significant speedups when doing those from inside Excel using VBA and outside over COM using python. Here are a few snippets on how it is done, I used the Excel VBA syntax although you would want to adjust them for your code.</p>\n\n<pre><code>' Turn off updates in excel\nApplication.ScreenUpdating = False\nApplication.Calculation = xlCalculateManual\n</code></pre>\n\n<p>The other part is a little trickier but in my experience is extremely fast when doing it inside Excel. Perhaps this concept could be applied to your code.</p>\n\n<pre><code>' Setup and load a range into an array\nDim ColumnAValues As Variant\nDim EndNum as Long\n\n' Find the end of the used data range and copy the data into an array.\nEndNum = ActiveSheet.UsedRange.Rows.Count\nColumnAValues = ActiveSheet.Range(Cells(1, 1), Cells(EndNum, 1)).Value\n\n' Do all the calculations on the data using the array.\n\n' Save your array back into the range.\nActiveSheet.Range(Cells(1, 1), Cells(EndNum, 1)) = ColumnAValues\n</code></pre>\n\n<p>When I am done I turn both the screen and calculation back on.</p>\n\n<pre><code>' Turn back on updates\nApplication.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True\n</code></pre>\n\n<p>For speed comparison, I did an example sheet with ~ 16000 rows, I read two cells, added them together and wrote them into another... it took about 4 seconds (Excel VBA). When I convert using the mentioned array method it completed in far less than a second...</p>\n\n<p>To show it using com, here is an example using python, the set each 'cell' method takes about 27 seconds on my machine, the set a 'range' method takes about 5.3 seconds, ignoring the 5 second wait so you can see the sheet, the 'range' method is many times faster:</p>\n\n<pre><code>import time\nimport win32com.client as win32\n\n\ndef excel(method):\n \"\"\" Open Excel using COM \"\"\"\n starttime = time.time()\n # http://msdn.microsoft.com/en-us/library/ee861528.aspx\n xlCalculationManual = -4135\n xlCalculationAutomatic = -4105\n\n xl = win32.gencache.EnsureDispatch('Excel.Application')\n wb = xl.Workbooks.Add()\n sh = wb.ActiveSheet\n\n xl.Visible = True\n time.sleep(5) # So that you can see the sheet\n xl.Calculation = xlCalculationManual\n xl.ScreenUpdating = False\n\n if method == 'cell':\n for i in range(1, 15000):\n sh.Cells(i, 1).Value = 'ABC'\n\n if method == 'range':\n cells = []\n for i in range(1, 15000):\n cells.append(('ABC',))\n sh.Range(xl.Cells(1, 1), xl.Cells(len(cells), 1)).Value = cells\n\n xl.ScreenUpdating = True\n xl.Calculation = xlCalculationAutomatic\n print(\"Runtime \" + \"{:.2f}\".format(round(time.time() - starttime, 1)))\n\nif __name__ == \"__main__\":\n excel('cell')\n excel('range')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:01:44.777",
"Id": "48873",
"ParentId": "48291",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:56:07.707",
"Id": "48291",
"Score": "4",
"Tags": [
"performance",
"vb.net",
"excel"
],
"Title": "Excel sheet code is taking too much time"
} | 48291 |
<blockquote>
<p>Given set of words that are lexicographically sorted, return
lexicographic order.</p>
<p>E.g:</p>
<pre><code>abc
acd
bcc
bed
bdc
dab
</code></pre>
<p>The order of letters for the given example would be</p>
<pre><code>a->b->c->e->d
</code></pre>
<h1>Time:</h1>
<p><strong>Part-1:</strong></p>
<p>Complexity of constructing graph: \$O(n * m)\$, where \$n\$ is number
of words and \$m\$ is max length of any word.</p>
<p><strong>Part-2:</strong></p>
<p>Topological sort: \$O(V + E)\$, where \$V\$ is number of vertices and
\$E\$ is number of edges</p>
<h1>Space:</h1>
<p>\$O(V + E)\$ - entire graph is stored</p>
</blockquote>
<p>Looking for request code review, optimizations and best practices.
Also verifying if how would final answer for complexity look like.</p>
<p>E.g: Would it be \$O(n*m + E + V)\$?</p>
<pre><code>class GraphLexico<T> implements Iterable<T> {
/* A map from nodes in the graph to sets of outgoing edges. Each
* set of edges is represented by a map from edges to doubles.
*/
private final Map<T, List<T>> graph = new HashMap<T, List<T>>();
/**
* Adds a new node to the graph. If the node already exists then its a
* no-op.
*
* @param node Adds to a graph. If node is null then this is a no-op.
* @return true if node is added, false otherwise.
*/
public boolean addNode(T node) {
if (node == null) {
throw new NullPointerException("The input node cannot be null.");
}
if (graph.containsKey(node)) return false;
graph.put(node, new ArrayList<T>());
return true;
}
/**
* Given the source and destination node it would add an arc from source
* to destination node. If an arc already exists then the value would be
* updated the new value.
*
* @param source the source node.
* @param destination the destination node.
* @param length if length if
* @throws NullPointerException if source or destination is null.
* @throws NoSuchElementException if either source of destination does not exists.
*/
public void addEdge (T source, T destination) {
if (source == null || destination == null) {
throw new NullPointerException("Source and Destination, both should be non-null.");
}
if (!graph.containsKey(source) || !graph.containsKey(destination)) {
throw new NoSuchElementException("Source and Destination, both should be part of graph");
}
/* A node would always be added so no point returning true or false */
graph.get(source).add(destination);
}
/**
* Given a node, returns the edges going outward that node,
* as an immutable map.
*
* @param node The node whose edges should be queried.
* @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null.
* @throws NoSuchElementException If node is not in graph.
*/
public List<T> edgesFrom(T node) {
if (node == null) {
throw new NullPointerException("The node should not be null.");
}
List<T> edges = graph.get(node);
if (edges == null) {
throw new NoSuchElementException("Source node does not exist.");
}
return Collections.unmodifiableList(graph.get(node));
}
/**
* Returns the iterator that travels the nodes of a graph.
*
* @return an iterator that travels the nodes of a graph.
*/
@Override public Iterator<T> iterator() {
return graph.keySet().iterator();
}
}
public final class LexicographicalSort {
private LexicographicalSort() {}
/**
* Returns the list of characters in lexicographically sorted order.
*
* Note that if entire information needed to determine lexicographical
* order is not present then results are unreliable.
*
* @param dictionary the list of words ordered in lexicographical order
*/
public static List<Character> lexigoGraphicOrder(List<String> dictionary) {
final GraphLexico<Character> graph = new GraphLexico<Character>();
for (int i = 0; i < dictionary.size() - 1; i++) {
createGraph(dictionary.get(i), dictionary.get(i + 1), graph);
}
return topologicalSort(graph);
}
/**
* Creates a DAG based on the lexicographical order.
*
*
* @param string1 the first string with higher placement/priority in dictionary
* @param string2 the second string with lesser placement/priority in dictionary
* @param graph the DAG to be constructed.
*/
private static void createGraph(String string1, String string2, GraphLexico<Character> graph) {
char[] ch1 = string1.toCharArray();
char[] ch2 = string2.toCharArray();
// pick the smaller length
int minLength = ch1.length > ch2.length ? ch2.length : ch1.length;
for (int i = 0; i < minLength; i++) {
if (ch1[i] != ch2[i]) {
graph.addNode(ch1[i]);
graph.addNode(ch2[i]);
graph.addEdge(ch1[i], ch2[i]);
return;
}
}
}
/**
* Running the topological sort, on the constructed graph
*
*
* @param graph the DAG determining priority of characters
* @return the characters in lexicographic order
*/
private static List<Character> topologicalSort(GraphLexico<Character> graph) {
final GraphLexico<Character> reverseGraph = reverseGraph(graph);
final List<Character> result = new ArrayList<Character>();
final Set<Character> visited = new HashSet<Character>();
final Set<Character> finished = new HashSet<Character>();
for (Character node : reverseGraph) {
explore(node, result, visited, finished, reverseGraph);
}
return result;
}
private static void explore (Character node, List<Character> result, Set<Character> visited,
Set<Character> finished, GraphLexico<Character> reverseGraph) {
if (visited.contains(node)) {
if (finished.contains(node)) return;
else throw new IllegalArgumentException("Cycle detected. ");
}
visited.add(node);
for(Character currNode : reverseGraph.edgesFrom(node)) {
explore(currNode, result, visited, finished, reverseGraph);
}
finished.add(node);
result.add(node);
}
private static GraphLexico<Character> reverseGraph(GraphLexico<Character> graph) {
final GraphLexico<Character> graphRev = new GraphLexico<Character>();
for (Character node : graph) {
graphRev.addNode(node);
}
for (Character node : graph) {
for (Character neighbors : graph.edgesFrom(node)) {
graphRev.addEdge(neighbors, node);
}
}
return graphRev;
}
}
</code></pre>
<p>Followed by testing</p>
<pre><code>public class LexicographicalSortTest {
@Test
public void testLexicoGraphicalSort() {
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("acd");
list.add("bcc");
list.add("bed");
list.add("bdc");
list.add("dab");
List<Character> expectedList = new ArrayList<Character>();
expectedList.add('a');
expectedList.add('b');
expectedList.add('c');
expectedList.add('e');
expectedList.add('d');
assertEquals(expectedList, LexicographicalSort.lexigoGraphicOrder(list));
}
}
</code></pre>
| [] | [
{
"body": "<p>You code has lots of strengths. Its main weakness is the lack of explanation for the algorithm. </p>\n\n<ol>\n<li><p>Why are you building the reverse graph? A reverse post order visiting of the graph is a topo sort order. Just get the post order and then reverse it! Saves lots of effort and space.</p></li>\n<li><p>I can't grok how your topo sort is finding DAG roots. You can't afford to start searching at nodes that don't have zero parents. Keeping a parent count for each character makes it super-easy to find the roots.</p></li>\n<li><p>Your cycle detection is too complex. A cycle occurs if and only if a recursive call to <code>explore</code> encounters a node that's already on the stack. Just keep an \"active\" set. Add a node before a recursive call to <code>explore</code> and remove it afterward. If you encounter a node that's active, you've found a cycle. The active set will generally be much smaller than the node set, so this is a tiny performance win as well.</p></li>\n</ol>\n\n<p>Additional things to think about:</p>\n\n<ol>\n<li><p>You can use a <code>LinkedHashSet</code> to maintain the post order of visits and keep track of already-visited nodes efficiently with one data structure instead of two.</p></li>\n<li><p>Using sets instead of lists of successors in the graph removes a run time dependency on graph degree. This is a small thing.</p></li>\n<li><p>Learn how to use JavaDoc format comments. It's worth the time in the long run.</p></li>\n<li><p>A few of your names are deceptive. A <code>dictionary</code> in code usually refers to a hash of strings. Etc., etc.</p></li>\n<li><p>Not sure why you broke strings into character arrays. </p></li>\n<li><p>It's simpler to have the graph edge adder create missing nodes than to deem\nmissing nodes an error condition.</p></li>\n</ol>\n\n<p>I liked this problem so well I coded my own version to check some of the ideas above:</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\npublic class LexiDetective {\n\n /**\n * A little unit test of the lexicographic detective.\n */\n public static void main(String[] args) {\n String [] words = { \"abc\", \"acd\", \"bcc\", \"bed\", \"bdc\", \"dab\" };\n CharacterGraph graph = new CharacterGraph();\n graph.insertWordList(words);\n try {\n List<Character> order = graph.topoSort();\n for (Character ch : order) {\n System.out.print(ch);\n }\n System.out.println();\n } catch (Exception ex) {\n // Topo sort might find cycle and raise this exception.\n System.err.println(ex.getMessage());\n }\n }\n}\n\n/**\n * Symbol graph specialized for characters and enhanced to deal\n * with lexicographically ordered word lists.\n */\nclass CharacterGraph extends SymbolGraph<Character> {\n\n /**\n * Insert a lexicographically ordered word pair into the\n * character graph using the first non-equal character pair to\n * add an edge.\n * \n * @param x first word in lexicographic order\n * @param y second word\n */\n void insertWordPair(String x, String y) {\n int len = Math.min(x.length(), y.length());\n for (int i = 0; i < len; i++) {\n char cx = x.charAt(i);\n char cy = y.charAt(i);\n if (cx != cy) {\n addEdge(cx, cy);\n break;\n }\n }\n }\n\n /**\n * Insert a lexicographically ordered word list into the character\n * graph by inserting each adjacent word pair.\n * \n * @param list lexicographically ordered word list\n */\n void insertWordList(String [] list) {\n for (int i = 0; i < list.length - 1; i++) {\n insertWordPair(list[i], list[i + 1]);\n }\n }\n}\n\n/**\n * A class for graphs with symbols as nodes. Includes topological sort\n * in symbol order.\n * \n * @param <Symbol> ordered symbol type\n */\nclass SymbolGraph<Symbol> {\n\n /**\n * Information about a symbol and its successors in the graph.\n *\n * @param <T> symbol type\n */\n static class NodeData<T> {\n\n /**\n * Count of symbols with this one as successor.\n */\n int parentCount = 0;\n /**\n * Set of successor symbols.\n */\n final Set<T> successors = new HashSet<>();\n }\n\n /**\n * Graph adjacencies stored as a map from symbols to node data. The node\n * data stores information about the symbol and its successors.\n */\n Map<Symbol, NodeData> adjacencies = new HashMap<>();\n\n /**\n * Add a node to the graph unless it's already there.\n *\n * @param a datum for node\n * @return node, either existing or newly created\n */\n NodeData<Symbol> addNode(Symbol a) {\n NodeData<Symbol> data = adjacencies.get(a);\n if (data == null) {\n data = new NodeData<>();\n adjacencies.put(a, data);\n }\n return data;\n }\n\n /**\n * Add an edge to the graph unless it's already there.\n *\n * @param a edge origin\n * @param b edge destination\n */\n void addEdge(Symbol a, Symbol b) {\n NodeData<Symbol> aData = addNode(a);\n if (!aData.successors.contains(b)) {\n aData.successors.add(b);\n NodeData<Symbol> bData = addNode(b);\n ++bData.parentCount;\n }\n }\n\n /**\n * Visit the graph rooted at given symbol in post order, accumulating an\n * ordered set of visited symbols.\n *\n * @param a the symbol for the (sub)graph to search\n * @param visited an ordered set that gives the post visit order\n */\n void postOrderVisit(Symbol a, Set<Symbol> ancestors, LinkedHashSet<Symbol> visited) \n throws Exception {\n if (ancestors.contains(a)) {\n throw new Exception(\"Cycle detected. No post order exists.\");\n }\n if (!visited.contains(a)) {\n NodeData<Symbol> data = adjacencies.get(a);\n if (data != null) {\n ancestors.add(a);\n for (Symbol aSuccessor : data.successors) {\n postOrderVisit(aSuccessor, ancestors, visited);\n }\n visited.add(a);\n ancestors.remove(a);\n }\n }\n }\n\n /**\n * Topologically sort the symbol graph and return the result.\n *\n * @return topological sort of symbols\n */\n List<Symbol> topoSort() throws Exception {\n Set<Symbol> ancestors = new HashSet<>();\n LinkedHashSet<Symbol> visited = new LinkedHashSet<>();\n // Loop through all the symbols and their data.\n for (Entry<Symbol, NodeData> pair : adjacencies.entrySet()) {\n // Search each root (symbol with no parents).\n if (pair.getValue().parentCount == 0) {\n postOrderVisit(pair.getKey(), ancestors, visited);\n }\n }\n // Reverse the post order visit to get a topo sort.\n List<Symbol> order = new ArrayList<>(visited);\n Collections.reverse(order);\n return order;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T04:44:46.983",
"Id": "48300",
"ParentId": "48292",
"Score": "6"
}
},
{
"body": "<p>I would make a small change to the test case, to make it more concise:</p>\n\n<pre><code>public class LexicographicalSortTest {\n\n @Test\n public void testLexicoGraphicalSort() {\n List<String> list = Arrays.asList(\"abc\", \"acd\", \"bcc\", \"bed\", \"bdc\", \"dab\");\n\n List<Character> expectedList = Arrays.asList(\"abced\".toCharArray());\n\n assertEquals(expectedList, LexicographicalSort.lexigoGraphicOrder(list));\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:16:29.883",
"Id": "48343",
"ParentId": "48292",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48300",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:11:13.400",
"Id": "48292",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings"
],
"Title": "Return the lexicographic order"
} | 48292 |
<p>Let's say that I have a view, whose purpose is to show a table with some information about a person entity. The view contains a form with an input element that the user can use to add a new person to the table by entering its name. </p>
<p>My question is: In this scenario, is there a convention about where to put hidden fields that are needed to retrieve the data in the server again? </p>
<p>In my code, I put them in the table definition; but maybe it's best to put all those fields together inside a <code>div</code> or something. Maybe it just doesn't matter where you put those as long as the code works. I'm just curious because I like to generate the best HTML possible.</p>
<p>I understand that this type of operation is very expensive to archive using a full post-back to the server, and an Ajax request will be better in this scenario, but still the question remains valid.</p>
<p>This is the model for the view:</p>
<pre><code>class IndexViewModel
{
public string Query { get;set; }
public IList<Person> People { get;set; }
}
</code></pre>
<p>And the view:</p>
<pre><code><form action="home/index">
<input id="query" name="query"/>
<input type="submit" value"Add"/>
<table>
<tbody>
<tr>
<th>Name</th>
<th></th>
</tr>
@for (int i = 0; i < Model.People.Count; ++i)
{
<tr>
<td>
@Html.HiddenFor(m=>m.People[i].Id)
@Html.ActionLink(Model.People[i].Name, "Details", "Person", new { id = Model.People[i].Id }, null)
</td>
<td>
@Html.ActionLink("Remove", "RemovePerson", "Home", new { id = Model.People[i].Id }, null)
</td>
</tr>
}
</tbody>
</table>
</form>
</code></pre>
<p>In the Action I receive the model and get the list of people again from the database and add the new person.</p>
<pre><code>[HttpPost]
public ActionResult Index(IndexViewModel model)
{
// Here I load again all people in the view and add the new that was queried.
for (int i = 0; i < model.People.Count; ++i)
model.People[i] = db.FindById(model.People[i].Id);
var newPerson = db.FindByName(model.Query);
if (newPerson != null)
model.People.Add(newPerson);
return View(model);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:55:02.773",
"Id": "84742",
"Score": "3",
"body": "It is preferable that you do not undo edits unless they vandalize the post or modify the original code. Since that was not the case here, I'm going to rollback to the previous edit that contained the grammatical corrections."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:58:06.117",
"Id": "84743",
"Score": "0",
"body": "@syb0rg Sorry. It wont happen again. I got confused because a made a refresh and thought that I undo your edit some how then I edit it myself but I write the errors back again instead of fix them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:59:16.607",
"Id": "84744",
"Score": "3",
"body": "No harm done `:)`. Us [cheery regulars](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) are just trying to keep the site as tidy as possible!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T03:05:49.803",
"Id": "84745",
"Score": "0",
"body": "@agarwaen: If that's the case, then I apologize for not waiting the first five minutes (the poster's edit grace period). The edit system does frustrate me at times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T03:15:40.263",
"Id": "84747",
"Score": "0",
"body": "@Jamal I really appreciate the work you guys do. I'm not English native, I enjoy a lot learning at this site and hope it will help me to improve my English too."
}
] | [
{
"body": "<p>When you are iterating over the collection of people, it probably does make sense to keep the hidden fields within the loop. I would try to keep them grouped together in that first td, with a hidden field per line, so that they are easily noticeable when scanning the source.</p>\n\n<p>If I weren't iterating (meaning that I was using some field at the top of my model, not in an array), I generally stuff my hidden inputs immediately following the opening tag.</p>\n\n<p>When iterating, within the td, a hidden element should have no effect on the rendering. You might consider wrapping them in a or with display:none applied. I believe there are some (older) browsers that will render white space if you have line breaks between your hidden inputs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T16:33:06.867",
"Id": "51227",
"ParentId": "48294",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:42:32.467",
"Id": "48294",
"Score": "5",
"Tags": [
"c#",
"asp.net-mvc-4"
],
"Title": "Where to put hidden fields when displaying entities properties in a table?"
} | 48294 |
<p>I have snapshots (photos) that I load off my camera's memory card, and store in a folder. Sometimes I have videos, and occasionally plain audio too (the camera can record just sound).</p>
<p>Additionally, my wife, and kids have their point-and-shoots too.</p>
<p>I have a workflow where I dump the photos on to a designated folder on a linux samba share, and then run this script which identifies the photos, auto-rotates the portrait picturs, and renames them according to the date and time the picture was taken (rather than a sequential number from the camera).</p>
<p>This way, assuming the various cameras have the correct clock-time set, the different cameras all have photos that are named similar things (and can be sorted alphabetically to get them in chronological order too.</p>
<p><strong>Notes</strong>:</p>
<ul>
<li>the jhead program the script calls will rename/rotate the photos, and the name will become something like: <code>Img20140217-164850.20.jpg</code></li>
<li>the jhead also identifies that some pictures may have 'raw' partners, for example, my Nikon camera takes a picture called <code>DSC1234.JPG</code> and simultaneously the picture <code>DSC1234.NEF</code> (the raw photo). The command <code>jhead -aNEF -ft -autorot -n DSC*.JPG</code> will identify the JPG photo, strip the .JPG extensions, and, because there is also the <code>-aNEF</code> argument, will rename the matching NEF file to the same base-name (<code>Img*</code>) as the JPG.... in other words, for the files <code>DSC1234.JPG</code> and <code>DSC1234.JPG</code>, the jhead program will produce, for example, both <code>Img20140217-164850.20.jpg</code> and <code>Img20140217-164850.20.NEF</code></li>
<li>the script deals with both Canon, and Nikon raw files (<code>RW2</code> and <code>NEF</code> respectively)</li>
</ul>
<p>The script is relatively simple, but has a fair amount of repetition. Any suggestions for how to improve it?</p>
<pre><code>#!/usr/bin/tcsh -f
#cd /valuable/picxfer
# Do the .jpg first because the jhead program will write .jpg even for .JPG input.
echo 'Checking DSC*.jpg'
if ( `tcsh -f -c "ls -1 DSC*.jpg >& /dev/null" && echo yes` == "yes" ) then
jhead -anef -ft -autorot -n DSC*.jpg
else
echo no Nikon jpg files
endif
echo 'Checking DSC*.JPG'
if ( `tcsh -f -c "ls -1 DSC*.JPG >& /dev/null" && echo yes` == "yes" ) then
jhead -aNEF -ft -autorot -n DSC*.JPG
else
echo no Nikon JPG files
endif
echo 'Checking *.jpg'
if ( `tcsh -f -c "ls -1 p*.jpg >& /dev/null" && echo yes` == "yes" ) then
jhead -arw2 -ft -autorot -n p*.jpg
else
echo no Canon jpg files
endif
echo 'Checking *.JPG'
if ( `tcsh -f -c "ls -1 P*.JPG >& /dev/null" && echo yes` == "yes" ) then
jhead -aRW2 -ft -autorot -n P*.JPG
else
echo no Canon JPG files
endif
echo Setting permissions
chmod ugo=r Img*
</code></pre>
| [] | [
{
"body": "<p>Your <code>if</code> conditions can be simplified. Instead of this:</p>\n\n<pre><code>if ( `tcsh -f -c \"ls -1 DSC*.jpg >& /dev/null\" && echo yes` == \"yes\" ) then\n</code></pre>\n\n<p>You could write like this:</p>\n\n<pre><code>if ( `ls DSC*.jpg >& /dev/null && echo x` != \"\" ) then\n</code></pre>\n\n<p>That is:</p>\n\n<ul>\n<li>you don't need to spawn a <code>tcsh</code> sub-shell</li>\n<li>you don't need the <code>-1</code> for <code>ls</code> to list files in a single column because you redirect that to <code>/dev/null</code> anyway</li>\n<li>the <code>`...`</code> part will only output anything if there were files, so you don't need <code>yes == yes</code>, it's enough to check for emptiness</li>\n</ul>\n\n<p>If you don't mind using Bash instead of Tcsh, then the ifs can be even more simple:</p>\n\n<pre><code>if ls DSC*.jpg &> /dev/null; then\n</code></pre>\n\n<p>A lot less useless fluff.</p>\n\n<p>With Bash you could simplify the repetitive blocks with a function, for example:</p>\n\n<pre><code>check_files() {\n glob=$1\n flags=$2\n nomsg=$3\n echo Checking \"$glob\"\n if ls $glob &>/dev/null; then\n jhead -a$flags -ft -autorot -n $glob\n else\n echo $nomsg\n fi\n echo\n}\n\ncheck_files 'DSC*.jpg' nef 'no Nikon jpg files'\ncheck_files 'DSC*.JPG' NEF 'no Nikon JPG files'\ncheck_files 'p*.jpg' rw2 'no Canon jpg files'\ncheck_files 'P*.JPG' RW2 'no Canon JPG files'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:57:34.260",
"Id": "48311",
"ParentId": "48295",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T02:43:12.770",
"Id": "48295",
"Score": "6",
"Tags": [
"image",
"shell",
"tcsh"
],
"Title": "Directory of Snapshots"
} | 48295 |
<p>I've the following code:</p>
<pre><code> protected Dictionary<NpInfoHelper, object> Informer;
protected override void OnInit(EventArgs e)
{
if (Session.Keys.Count == 1)
{
Session.Abandon();
Response.RedirectPermanent("~/Pages/Login?e=true", true);
}
else
{
Informer = (Dictionary<NpInfoHelper, object>)Session["Informer"];
}
base.OnInit(e);
}
</code></pre>
<p>in every backend <code>.cs</code> file of the <code>.aspx</code> file.</p>
<p>I think this is repetitive. Note that I'll be using <code>Informer</code> in every <code>.aspx.cs</code> file.</p>
<p>The above code is repeated 19 times. Can I make it just one?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T04:47:32.673",
"Id": "84750",
"Score": "3",
"body": "Well, I can't say much about ASP.NET, but that kind of repetition implies you should either have the backend classes all derive from one class (whose OnItit does what your init does above)."
}
] | [
{
"body": "<p>Per the comment, what you probably want is an abstract class <code>MyAppPage</code>:</p>\n\n<pre><code>abstract class MyAppPage : Page {\n protected Dictionary<NpInfoHelper, object> Informer;\n protected override void OnInit(EventArgs e)\n {\n if (Session.Keys.Count == 1)\n {\n Session.Abandon();\n Response.Redirect(\"~/Pages/Login?e=true\", true);\n }\n else\n {\n Informer = (Dictionary<NpInfoHelper, object>)Session[\"Informer\"];\n }\n base.OnInit(e);\n }\n}\n</code></pre>\n\n<p>then your other pages would extend <code>MyAppPage</code> instead of <code>Page</code>.</p>\n\n<p>Finally, you'll notice I took the liberty of changes <code>Response.RedirectPermanent</code> to <code>Response.Redirect</code>. Permanent redirections return the 301 response \"Moved Permanently\" and signify that the current page no longer exists at this position and has been moved elsewhere. Using it to redirect someone who hasn't logged in might confuse crawlers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T05:22:03.180",
"Id": "48301",
"ParentId": "48298",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48301",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T04:13:35.843",
"Id": "48298",
"Score": "5",
"Tags": [
"c#",
"asp.net"
],
"Title": "Can my code be made into one?"
} | 48298 |
<p>I have a form that requires the user to select photos to be included in their portfolio before they can proceed to use the app for the first time.</p>
<p>I don't want to spend the rest of my life implementing a custom file browser, so I've decided to just use the FolderBrowserDialog to allow them to select a folder containing photos. I've also decided to let them browse as many times as they need in case they have photos scattered in other locations.</p>
<p>I can't think of a better way to write this, but it seems like there would be a better way. I'd appreciate any thoughts/suggestions on how to improve this piece or advice on a better way to write it:</p>
<pre><code> private void Main_Shown(object sender, EventArgs e)
{
/* Let them select photos to be included in the portfolio
* and move them to the permanent Photo Collection folder,
* and display them on the form.
*/
bool selectingPhotos = true;
while (selectingPhotos) {
using (FolderBrowserDialog folderPicker = new FolderBrowserDialog())
{
folderPicker.Description = "Please browse to, and select the folder containing the files you'd like to add.";
if (folderPicker.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
// Add files to list for processing later.
// Ask if they want to add more files from another directory.
if (MessageBox.Show("Do you want to select more photos from another location?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
selectingPhotos = true;
}
else
{
selectingPhotos = false;
}
}
else
{
selectingPhotos = false;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T06:08:03.570",
"Id": "84759",
"Score": "1",
"body": "Since it is a winform application so I would rather change its UI. Most of the applications that I have come across offers a \"Add More\" button to do the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T06:20:44.607",
"Id": "84760",
"Score": "0",
"body": "Thank you @Sandeep for your suggestion. Good suggestion :-)"
}
] | [
{
"body": "<p>I'm typically not a user of the <code>continue</code> statement but here is one alternative using this method. In this case it may be a simpler implementation and removes the need for any extra local variable.</p>\n\n<pre><code>private void Main_Shown(object sender, EventArgs e)\n{\n /* Let them select photos to be included in the portfolio\n * and move them to the permanent Photo Collection folder,\n * and display them on the form.\n */\n\n using (FolderBrowserDialog folderPicker = new FolderBrowserDialog())\n {\n folderPicker.Description = \"Please browse to, and select the folder containing the files you'd like to add.\";\n\n while (true) \n { \n if (folderPicker.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)\n {\n // Add files to list for processing later.\n\n // Ask if they want to add more files from another directory.\n if (MessageBox.Show(\"Do you want to select more photos from another location?\", \"Confirmation\", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)\n {\n continue;\n }\n }\n\n break;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T06:24:19.813",
"Id": "84762",
"Score": "1",
"body": "@spike.y no problem. Just a suggestion. If you leave the question un-accepted for a few days you are more likely to get a few more comments, many of which may be better suggestions than mine :) Many ways to skin a cat so to speak...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T07:23:47.267",
"Id": "84765",
"Score": "0",
"body": "Lol. Cool, I'm using your code right now and it's working out great plus it's a bit easier to manage. I will wait a few days and see if anything else comes along. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T07:26:14.500",
"Id": "84766",
"Score": "1",
"body": "@spike.y you can always upvote for now :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T07:41:49.157",
"Id": "84769",
"Score": "0",
"body": "I did try :-) But I don't have enough reputation to up-vote. I'm looking for answers that I can answer so I can. I will be back."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T06:00:16.940",
"Id": "48303",
"ParentId": "48302",
"Score": "3"
}
},
{
"body": "<p>Since you have a task you want to repeat at least once, the do-while is the most suitable. How about the following:</p>\n\n<pre><code>private void Main_Shown(object sender, EventArgs e)\n{\n /* Let them select photos to be included in the portfolio\n * and move them to the permanent Photo Collection folder,\n * and display them on the form.\n */\n\n using (FolderBrowserDialog folderPicker = new FolderBrowserDialog())\n {\n folderPicker.Description = \"Please browse to, and select the folder containing the files you'd like to add.\";\n\n do\n { \n if (folderPicker.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)\n {\n // Add files to list for processing later.\n }\n else\n {\n break;\n }\n\n } while (MessageBox.Show(\"Do you want to select more photos from another location?\", \"Confirmation\", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:22:12.873",
"Id": "48307",
"ParentId": "48302",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T05:32:49.723",
"Id": "48302",
"Score": "5",
"Tags": [
"c#",
"optimization",
".net",
"winforms"
],
"Title": "Keep asking the user [after performing an action] until they wish to stop"
} | 48302 |
<p>I have been attempting to learn Scala lately and so have produced a couple of different sorting algorithms to build up my basics.</p>
<p>I think I have been lucky with the methods returning exactly what I have wanted, but for MergeSort I have implemented recursive methods that could return one of two different values and could logically be placed into two different values of the same type (as I believe Scala does)</p>
<p>In order to get my program to sort properly I have put a temp variable in order to grab the returning value and then be able to use it.</p>
<p>Is there a better way to return the values that will not need me to create these temporary values or should I have been doing something else?</p>
<hr>
<p>Example:</p>
<pre><code>def merge(left: ArrayBuffer[Int], right: ArrayBuffer[Int]): ArrayBuffer[Int]
</code></pre>
<p>returns an ArrayBuffer, how does the scala language figure out which value to put the returned value into or does it need a variable on the returning end to capture the value that is being returned?</p>
<pre><code>merge(left, right)
</code></pre>
<p>This does nothing while, </p>
<pre><code>var tempResult = merge(left, right)
</code></pre>
<p>Solves the problem.</p>
<p>Am I doing something wrong in the first instance (due to my experience with single parameter methods returning to the proper variable), or is this the standard way to return the values, by returning to a variable?</p>
<hr>
<p>MergeSortClass.scala</p>
<pre><code>import scala.collection.mutable.ArrayBuffer
class MergeSortClass {
def mergeSort(array: ArrayBuffer[Int]): ArrayBuffer[Int] = {
if (array.size <= 1) {
array
} else {
var left = ArrayBuffer[Int]()
var right = ArrayBuffer[Int]()
var middle = array.size / 2
for (i <- 0 until middle) {
left += array(i)
}
for (i <- middle until array.size) {
right += array(i)
}
</code></pre>
<p>//-->>>TheseValues Below</p>
<pre><code> var leftTemp = mergeSort(left);
var rightTemp = mergeSort(right);
var result = merge(leftTemp, rightTemp)
result
}
}
def merge(left: ArrayBuffer[Int], right: ArrayBuffer[Int]): ArrayBuffer[Int] = {
var result = ArrayBuffer[Int]()
while (left.size > 0 || right.size > 0) {
if (left.size > 0 && right.size > 0) {
if (left(0) <= right(0)) {
result += left(0)
left.remove(0)
} else {
result += right(0)
right.remove(0)
}
} else if (left.size > 0) {
result += left(0)
left.remove(0)
} else if (right.size > 0) {
result += right(0)
right.remove(0)
}
}
result
}
}
</code></pre>
<p>MergeSortObject.scala</p>
<pre><code>import scala.collection.mutable.ArrayBuffer
object MergeSortObject {
def main(args: Array[String]): Unit = {
val array = ArrayBuffer(10, 5, 15, 25, 7, 11, 17, 35, 34, 16)
for (i <- 0 to array.length - 1) {
print(array(i))
if (i == array.length - 1) {
} else {
print(", ")
}
}
println()
var ms = new MergeSortClass()
</code></pre>
<p>//-->>>TheseValues Below</p>
<pre><code>var temp = ms.mergeSort(array)
//ms.test(array) (not shown here)
for (i <- 0 to temp.length - 1) {
print(temp(i))
if (i == temp.length - 1) {
} else {
print(", ")
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:39:37.953",
"Id": "84793",
"Score": "1",
"body": "I don't understand what you mean with \"temporary values\". Can you highlight the lines you mean and explain more how the code should look in the end?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T21:35:32.437",
"Id": "84879",
"Score": "0",
"body": "I think he is talking about using array buffers to simulate sequential data streams. This is bound to be inefficient. @BoydyBoydy If you want a reasonably efficient sort, give up on array buffers and use simple arrays, passing indices to identify subarrays in the usual manner. See for example the http://www.scala-lang.org/old/node/57.html quicksort code on the Scala web site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:27:31.487",
"Id": "84893",
"Score": "0",
"body": "@sschaef What I was talking about was how scala differentiates between what values to return and how it returns those values. In order to get my Merge Sort to work I had to create values that would receive the returned values and not just pass the value into an already created variable but into a new one. Is there an easier way to grab the values that are being returned or is that how I should get all of my returned values(by creating a new variable and keeping the value in that variable)? Also I do not care about the efficiency as I do about being able to maintain/OO design code later!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:30:42.567",
"Id": "84894",
"Score": "0",
"body": "I have also updated my question, with broken lines so that you can see where the \"temporary values\" are."
}
] | [
{
"body": "<p>The expression <code>merge(x,y)</code> will always return a value. <code>val r = merge(x,y)</code> stores the value so that you can use it again.</p>\n\n<p>You could write your code </p>\n\n<pre><code>var leftTemp = mergeSort(left);\nvar rightTemp = mergeSort(right);\n\nvar result = merge(leftTemp, rightTemp)\n\nresult\n</code></pre>\n\n<p>as</p>\n\n<pre><code>merge(mergeSort(left),mergeSort(right))\n</code></pre>\n\n<p>It is a matter of preference if you wish to use <code>leftTemp</code> and <code>rightTemp</code> like this, but the use of <code>result</code>, and then returning it on the next line is not idiomatic Scala.</p>\n\n<p>You must assign values to an identifier when you want to use them more than once (as you do with <code>temp</code> in your final example). But as I said above you may want to do this for other reasons such as readability and keeping down line lengths.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T00:43:16.980",
"Id": "85371",
"Score": "0",
"body": "Thankyou, all I really needed was a simple answer and I got that. Sorry can't upvote."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T12:54:46.490",
"Id": "48570",
"ParentId": "48305",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48570",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:16:28.133",
"Id": "48305",
"Score": "3",
"Tags": [
"scala",
"sorting",
"mergesort"
],
"Title": "Is there a better way to return values with merge sort?"
} | 48305 |
<p>Can you please verify my approach?</p>
<pre><code>using System;
/*
* In Factory pattern, we create object without exposing the creation logic.
* In this pattern, an interface is used for creating an object,
* but let subclass decide which class to instantiate.
* */
namespace FactoryMethod
{
</code></pre>
<p><strong>Product (abstract)</strong></p>
<pre><code> /*
* Faza Class ITree
*
* */
public interface ITree
{
string GetTreeName();
}
</code></pre>
<p><strong>Products (concrete)</strong></p>
<pre><code> /*
* The Concrete class which implements ITree
*
* */
public class BananaTree : ITree
{
public string GetTreeName()
{
return "My Name Is Banana Tree";
}
}
/*
* The Concrete class which implements ITree
*
* */
public class CoconutTree : ITree
{
public string GetTreeName()
{
return "My Name Is Coconut Tree";
}
}
</code></pre>
<p><strong>Factory (abstract)</strong></p>
<pre><code> /*
* Faza Class TreeType
* If you want you can add abstract class instad of faza class
*
* */
public interface TreeType
{
ITree GetTree(string tree);
}
</code></pre>
<p><strong>Factory (concrete)</strong></p>
<pre><code> /*
* Concrete class which implements faza or concrete class
*
* */
public class ConcreteTreeType : TreeType
{
public ITree GetTree(string tree)
{
if (tree == "COCONUT")
return new CoconutTree();
else
return new BananaTree();
}
}
</code></pre>
<p><strong>Client code</strong></p>
<pre><code> /*
* main app.
*
* */
class Program
{
static void Main(string[] args)
{
TreeType oTreeType = new ConcreteTreeType();
ITree banana = oTreeType.GetTree("COCONUT");
Console.WriteLine(banana.GetTreeName());
Console.ReadKey();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:13:12.893",
"Id": "84957",
"Score": "0",
"body": "You can also choose to use exceptions to make it more robust. Like in your code anyone can ask for \"Rose\" tree and still get banana tree."
}
] | [
{
"body": "<p>I personally would not rely on using magic strings.</p>\n\n<blockquote>\n <p>Magic strings are where you have taken something like a class/method/variable name and written it within a string, which is then used to identify the appropriate class/method/variable</p>\n</blockquote>\n\n<p>This makes it hard to refactor later on if you change a class name, it is too easy to miss instances etc. Furthermore, the code that you currently have is case-sensitive. This might be by design, however, consider the following:</p>\n\n<pre><code>var actuallyABananaTree = oTreeType.GetTree(\"Coconut\");\n</code></pre>\n\n<p>Even though the developer is specifying a coconut tree, he actually gets a banana tree. If the construction logic was changed to:</p>\n\n<pre><code>if (tree.Equals(\"coconut\", StringComparison.OrdinalIgnoreCase))\n</code></pre>\n\n<p>You would then get the right tree type back. <em>See <a href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparison%28v=vs.110%29.aspx\">StringComparison Enum</a> for the comparison options.</em></p>\n\n<p>In that same construction logic, you are also not checking to see whether or not the parameter <code>tree</code> is a null reference. This might be something that you wish to consider adding, especially if you use the approach suggested above.</p>\n\n<h1>Use of Enums</h1>\n\n<p>A better approach would be to use enums instead of magic strings. For example:</p>\n\n<pre><code>enum MyTreeTypes {\n Coconut,\n Banana\n}\n</code></pre>\n\n<p>Then in your construction logic, you can have: </p>\n\n<pre><code>public ITree GetTree(MyTreeTypes tree)\n{\n switch (tree)\n {\n case MyTreeTypes.Coconut:\n return new CoconutTree();\n default:\n return new BananaTree();\n }\n}\n</code></pre>\n\n<p>Using this approach ensures type safety and prevents problems of magic strings when refactoring etc. Also, you will compile time errors if you spell the tree type incorrectly</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T04:21:12.897",
"Id": "84911",
"Score": "0",
"body": "Hi @Stuart Blackler,\nthanks for your reply. my doubt is instead of abstract class I’ve used faza class. is it creates any issue? ,, regd. enum i agree with your point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:41:54.340",
"Id": "84944",
"Score": "1",
"body": "+1 excellent point. I'd call the enum type `TreeType` though (singular), and find another name for the abstract factory interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:11:33.737",
"Id": "84956",
"Score": "0",
"body": "@Mat'sMug I agree, that's what I would normally do. I try and steer clear of changing variable names in reviews and stick with what the OP has as it will correlate better for them, imo. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:27:48.850",
"Id": "84960",
"Score": "0",
"body": "Good point. Don't forget that *bad naming* can be part of a fruitful peer review - feel free to join us in [The 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)/[chat] ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:18:15.413",
"Id": "48316",
"ParentId": "48308",
"Score": "11"
}
},
{
"body": "<p>This pattern looks very much like a creational pattern called <em>Abstract Factory</em>.</p>\n\n<p>What's nice about design patterns, is that they're a very effective mean of <em>communication</em> with fellow programmers; provided that they know the patterns, when you say <code>TreeFactory</code> it should be clear what the type is for.</p>\n\n<blockquote>\n <p>You've called your abstraction <code>TreeType</code>, which is less clear. The\n naming you're using makes things quite confusing, especially in the\n client code - compare this:</p>\n\n<pre><code>TreeType oTreeType = new ConcreteTreeType();\n\nITree banana = oTreeType.GetTree(\"COCONUT\");\nConsole.WriteLine(banana.GetTreeName());\n</code></pre>\n \n <p>To this:</p>\n\n<pre><code>ITreeFactory factory = new CoconutTreeFactory();\n\nITree tree = factory.Create();\nConsole.WriteLine(tree.GetTreeName());\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>In C# it's common practice to name interface starting with a capital <code>i</code>, so this:</p>\n\n<pre><code>public interface TreeType\n{\n ITree GetTree(string tree);\n}\n</code></pre>\n\n<p>I'd write like this:</p>\n\n<pre><code>public interface ITreeFactory\n{\n // follow @Stuart's advice here, don't rely on magic strings!\n ITree Create(TreeType treeType);\n }\n</code></pre>\n\n<p><code>TreeType</code> would be a much better name for an <code>enum</code> type (enum names should be singular):</p>\n\n<pre><code>public enum TreeType\n{\n Banana,\n Coconut,\n Apple,\n Orange\n}\n</code></pre>\n\n<p>What you have here, however, isn't <em>quite exactly</em> an abstract factory, because the client code, despite working against an <code>ITree</code>, <em>knows exactly what type he's getting</em>... which is weird:</p>\n\n<p><img src=\"https://yuml.me/07cc1891\" alt=\"abstract factory actors\"></p>\n\n<p>The client code can know about <code>ITreeFactory</code> and <code>ITree</code>, but the point of an abstract factory is that he doesn't need to know/care about the exact implementation of <code>ITree</code> that the factory is producing, so your client code can be provided with an <code>ITreeFactory</code> and call its <code>Create()</code> method to get an <code>ITree</code> - whatever implementation that is.</p>\n\n<p>If the client code needs to use the same abstract factory to create multiple instances of different <code>ITree</code> implementations, then I'd go with a <em>generic abstract factory</em>:</p>\n\n<pre><code>public interface ITreeFactory<TTree> where TTree : ITree\n{\n ITree Create<TTree>();\n}\n</code></pre>\n\n<p>If <code>TTree</code> has a parameterless constructor, you can add a <em>generic type constraint</em> to ensure <code>TTree</code> always has a default constructor, and implement a generic concrete factory class like this:</p>\n\n<pre><code>public class TreeFactory<TTree> : ITreeFactory<TTree> \n where TTree : ITree, new()\n{\n public ITree Create<TTree>()\n {\n return new TTree();\n }\n}\n</code></pre>\n\n<p>That can be called like this:</p>\n\n<pre><code>ITree appleTree = factory.Create<AppleTree>();\nITree orangeTree = factory.Create<OrangeTree>();\n</code></pre>\n\n<p>I don't like this very much though, because it allows the client code to control the exact implementation type he's getting out of the factory - this smells of <em>Control Freak</em>, a <em>Dependency Injection Anti-Pattern</em>... but sometimes it's just what's needed.</p>\n\n<hr>\n\n<p>If <code>TTree</code> doesn't have a parameterless constructor, then the generic concrete factory has a problem:</p>\n\n<pre><code>public class TreeFactory<TTree> : ITreeFactory<TTree> \n where TTree : ITree\n{\n public ITree Create<TTree>()\n {\n return new ????(); // so, what type is TTree? how do we pass ctor parameters?\n }\n}\n</code></pre>\n\n<p>That can't work! This is where the enum type kicks in, when the <em>type of the factory's product</em> is unknown at compile-time - now because each tree type might have different constructor arguments, abstracting them into their own type can simplify things:</p>\n\n<pre><code>public class TreeFactory : ITreeFactory\n{\n private readonly IDictionary<TreeType, Func<ITreeArgs,ITree>> _create;\n\n public TreeFactory(IDictionary<TreeType, Func<ITreeArgs,ITree>> factoryMethods)\n {\n _create = factoryMethods;\n }\n\n public ITree Create(TreeType treeType, ITreeArgs args)\n {\n return _create[treeType](args);\n }\n}\n</code></pre>\n\n<p>Where <code>ITreeArgs</code> could perhaps encapsulate an <code>object</code> that merely exposes an array of constructor arguments, whatever they are. Notice that the factory class itself doesn't even know/care how each <code>TreeType</code> gets created - it receives a <em>dictionary</em> of factory methods (one for each <code>TreeType</code>) and simply calls into it in the <code>Create</code> method; this means if you want to modify how this factory class generates such or such <code>ITree</code> implementation, you don't even need to change the factory class's code!</p>\n\n<p>This is probably overkill for your example code however, since all your <code>ITree</code> implementations seem to have a default constructor, therefore the generic factory would work.</p>\n\n<hr>\n\n<p>It's often best to leave the client code oblivious of implementation details:</p>\n\n<pre><code>public class ClientObject\n{\n private readonly ITreeFactory _factory;\n\n public ClientObject(ITreeFactory factory)\n {\n _factory = factory;\n }\n\n public void DoSomething()\n {\n var tree = _factory.Create();\n Console.WriteLine(tree.Name); // assuming a \"Name\" property on `ITree` here\n }\n} \n</code></pre>\n\n<p>All <code>ClientObject</code> knows, is that he's getting an <code>ITree</code>. The exact implementation type is completely irrelevant, and <code>ClientObject</code> is completely <em>decoupled</em> from any specific <code>ITree</code> and <code>ITreeFactory</code> implementations.</p>\n\n<p>From the very first comment at the top of your code, I believe this is what you're trying to achieve.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:22:12.980",
"Id": "48401",
"ParentId": "48308",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48316",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:31:54.073",
"Id": "48308",
"Score": "8",
"Tags": [
"c#",
"factory-method"
],
"Title": "Factory Method implementation"
} | 48308 |
<p>I'm working through Yet Another Haskell Tutorial. One of the exercises is to prompt the user to enters numbers, entering a 0 to quit. The program should then both sum and multiply all the given numbers, and then display the factorial of each. </p>
<p>It works, but it's obviously sloppy, with some functions doing more than what is obvious. My main concern is whether it's better to try to format output in the nonpure IO functions, or to do it in the pure functions. Should I separate out calculating the data and formatting the output? Any other tips for how I could tighten this up?</p>
<pre><code>module Main
where
import System.IO
main = do
hSetBuffering stdin LineBuffering
putStrLn "Enter a number, or 0 to quit: "
numList <- getNumbers
putStrLn (my_sum numList)
putStrLn (my_product numList)
putStrLn (factorial numList)
getNumbers = do
number <- getLine
let n = read number :: Int
if n == 0
then do
return []
else do
numList <- getNumbers
return (n : numList)
my_sum [] = "The sum is 0"
my_sum xs = "The sum is " ++ show (foldr (+) 0 xs)
my_product [] = "The product is 0"
my_product xs = "The product is " ++ show (foldr (*) 1 xs)
factorial (x:xs) = show x ++ " factorial is " ++ show (fac x) ++ "\n"
++ factorial xs
factorial [] = ""
fac 1 = 1
fac x = x * fac (x - 1)
</code></pre>
| [] | [
{
"body": "<p>You should definitely separate the calculation from formatting the output. One of Haskell's key strengths is being able to compose functions. By confounding the definition of your function with the presentation of it's return value, you lose the ability to reuse it elsewhere. For instance, if you wanted to use <code>my_sum</code> to sum all of the numbers you were given, and then find the factorial of the sum, you couldn't with your code as-is without reimplementing both functions! Here's a composable definition of <code>my_sum</code>.</p>\n\n<pre><code>my_sum xs = foldr (+) 0 xs\n</code></pre>\n\n<p>Now when you want to write out to the command line what operation your program has performed, you can format the output in IO, or call a formatting operation (that's what <code>show</code> is).</p>\n\n<pre><code>main = do\n ...\n putStrLn $ \"The sum of the numbers you entered is \" ++ show (sum numList)\n ...\n</code></pre>\n\n<p>Now more general advice, you should include a type signature for all of your top-level definitions. This is important for a few reasons. One, it acts as a check on your understanding of what your functions are doing, the compiler will complain if your signature doesn't match what your function really does. Two, it serves as a surprisingly powerful form of documentation for readers of your code. And three, it can help the compiler infer more of the types you use within functions without needing annotations.</p>\n\n<p>As an example of that last point, look at how you had to annotate the line <code>let n = read number</code> with <code>:: Int</code>. If you had given the compiler enough information to go on elsewhere in your program, it would have been able to deduce that on its own. Here's how.</p>\n\n<pre><code>getNumbers :: IO [Int] -- 1) Type signature for the IO action\ngetNumbers = do\n number <- getLine\n let n = read number -- 3) The type checker sees that n is a part of the returned list, so it must be an Int\n if n == 0\n then do \n return []\n else do\n numList <- getNumbers\n return (n : numList) -- 2) Here's the list of Ints we're returning per the type signature\n</code></pre>\n\n<p>You shouldn't have to set <code>stdin</code> to <code>LineBuffering</code> mode at the start of <code>main</code>. <code>getLine</code> will work correctly by default.</p>\n\n<p><code>getNumbers</code> isn't properly tail-recursive, the recursive call to <code>getNumbers</code> is followed by that <code>return</code> action. In this example it won't make much of a difference, but in a real program where you can expect a large amount of data this would end up blowing up the stack.</p>\n\n<p>Here's the version I ended up producing taking all of the above into account. Read closely and try to make note of all the differences between both versions!</p>\n\n<pre><code>module Main where\n\nmain :: IO ()\nmain = do\n putStrLn \"Enter one number per line, or 0 to stop: \"\n numbers <- getNumbers\n putStrLn \"The sum of your numbers is \" ++ show (my_sum numbers)\n putStrLn \"The product of your numbers is \" ++ show (my_sum numbers)\n forM_ numbers $ \\n -> putStrLn \"The factorial of \" ++ show n ++ \" is \" ++ show (fac n)\n\ngetNumbers :: IO [Int]\ngetNumbers = do\n number <- getLine\n let n = read number\n if n == 0\n then return []\n else fmap (n:) getNumbers\n\nmy_sum :: [Int] -> Int\nmy_sum = foldr (+) 0\n\nmy_product :: [Int] -> Int\nmy_product = foldr (*) 1\n\nfac :: Int -> Int\nfac 1 = 1\nfac n = n * fac (n - 1)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T06:22:58.823",
"Id": "49119",
"ParentId": "48309",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T08:32:39.203",
"Id": "48309",
"Score": "1",
"Tags": [
"haskell",
"io"
],
"Title": "Idiomatic IO in Haskell"
} | 48309 |
<pre><code>public class DataBaseHandler extends SQLiteOpenHelper {
private static String DATABASE_NAME = "UnitDatabase";
private static String MEASUREMENT_TYPE_TABLE = "measurement_types";
private static String idCol = "id";
private static String typeCol = "type";
private static int DATABASE_VERSION = 1;
private static String[] measurementType = new String[] {"acceleration", "angles", "area", "astronomical",
"density", "energy", "force", "frequency", "length/distance", "power", "pressure", "speed",
"temperature", "torque", "volume", "weight"};
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " + MEASUREMENT_TYPE_TABLE +
"(" + idCol + " integer primary key autoincrement " +
typeCol + " varchar(255) not null ";
db.execSQL(create_table);
}
/**
* Populate the table containing measurement types
* @param db
*/
public void populateMeasurementTable(SQLiteDatabase db) {
db = this.getWritableDatabase();
for(int i = 0; i < measurementType.length; i++) {
ContentValues values = new ContentValues();
values.put(typeCol, measurementType[i]);
db.insert(MEASUREMENT_TYPE_TABLE, null, values);
}
}
}
</code></pre>
<p>I thought I would post my code first and then ask the question. My question is with my implementation of the last method (<code>populateMeasurementTable()</code>). I wanted to be able to insert multiple values in to the table and this is the way I am going to do it, however I don't think it is an efficient way of doing it especially if I have larger arrays such as:</p>
<pre><code>private static String[] densityUnitTypes = new String[] { "grain/cubic foot", "grain/cubic inch",
"grain/gallon [UK]", "grain/gallon [US]", "grain/ounce [UK]", "grain/ounce [US]", "grain/quart [UK]",
"grain/quart [US]", "gram/cubic centimeter", "gram/cubic kilometer", "gram/cubic meter",
"gram/cubic millimeter", "gram/kiloliter", "gram/liter", "gram/litre", "gram/microliter", "gram/milliliter",
"hectogram/cubic centimeter", "hectogram/cubic kilometer", "hectogram/cubic meter",
"hectogram/cubic micrometer", "hectogram/cubic millimeter", "hectogram/hectoliter", "hectogram/kiloliter",
"hectogram/liter", "hectogram/litre", "hectogram/microliter", "hectogram/milliliter",
"kilogram/cubic centimeter", "kilogram/cubic kilometer", "kilogram/cubic meter",
"kilogram/cubic micrometer", "kilogram/cubic millimeter", "kilogram/kiloliter", "kilogram/liter",
"kilogram/litre", "kilogram/microliter", "kilogram/milliliter", "kiloton/cubic mile [UK]",
"kiloton/cubic mile [US]", "kiloton/cubic yard [UK]", "kiloton/cubic yard [US]", "kilotonne/cubic meter",
"kilotonne/kiloliter", "kilotonne/liter", "kilotonne/litre", "microgram/cubic centimeter",
"microgram/cubic kilometer", "microgram/cubic meter", "microgram/cubic micrometer",
"microgram/cubic millimeter", "microgram/cubic nanometer", "microgram/kiloliter", "microgram/liter",
"microgram/litre", "microgram/microliter", "microgram/milliliter", "milligram/cubic centimeter",
"milligram/cubic kilometer", "milligram/cubic meter", "milligram/cubic millimeter",
"milligram/kiloliter", "milligram/liter", "milligram/litre", "milligram/microliter", "milligram/milliliter",
"nanogram/cubic centimeter", "nanogram/cubic kilometer", "nanogram/cubic meter",
"nanogram/cubic millimeter", "nanogram/kiloliter", "nanogram/liter", "nanogram/litre",
"nanogram/microliter", "nanogram/milliliter", "ounce/cubic foot", "ounce/cubic inch", "ounce/gallon [UK]",
"ounce/gallon [US]", "pound/cubic foot", "pound/cubic inch", "pound/cubic mile", "pound/cubic yard",
"pound/gallon [UK]", "pound/gallon [US]", "tonne/cubic kilometer", "tonne/cubic meter", "tonne/kiloliter",
"tonne/liter", "tonne/litre", "water [0°C, solid]", "water [20°C]", "water [4°C]" };
</code></pre>
<p>I had thought about using the <code>bulkInsert(Uri uri, ContentValues[] values)</code> method from the <code>ContentResolver</code> class in the API however, I felt that writing own provider class to extend the <code>ContentProvider</code> class and then writing my own implementation of the <code>bulkInsert()</code> method was a little nuclear for this - although it would allow me to use transactions which I have read a far more efficient way to carry out the task. </p>
<p>So my questions are:</p>
<ul>
<li>How efficient is the way I have chosen to do it?</li>
<li>Would I be better of writing my own implementation of the <code>bulkInsert()</code> method?</li>
<li>Is there a different more efficient way? (for example writing the raw SQL out to insert multiple values)</li>
</ul>
| [] | [
{
"body": "<p>You have some constants in your code. Why are they not final? Also the naming for <code>idCol</code> and <code>typeCol</code> is confusing me. Why not <code>ID_COLUMN</code> and <code>TYPE_COLUMN</code>. </p>\n\n<p>Same also goes for <code>measurementTypes</code> these all are constants. Name and use them as such.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T10:36:52.003",
"Id": "84774",
"Score": "0",
"body": "the final that is missing is my mistake as for naming the variables...we think differently? I don't know...perhaps a suggestion for my real question? thank you for pointing out the discrepancies though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T10:37:49.920",
"Id": "84775",
"Score": "0",
"body": "Well the are factual constants, right? Why not name them as constants then?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:57:31.887",
"Id": "84779",
"Score": "0",
"body": "As I said, it was a mistake..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T21:58:10.447",
"Id": "84881",
"Score": "0",
"body": "But this is still not an answer to the real question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:11:50.350",
"Id": "84882",
"Score": "2",
"body": "@user2405469: CR is a little different than other sites in this regard. Reviewers are free to comment on anything in the code, not just the specific questions. If a reviewer doesn't answer them, then that probably means that they don't know how to answer them, but still have other things to point out. Others may still come along to answer these questions if the first reviewer doesn't."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T10:30:06.833",
"Id": "48315",
"ParentId": "48312",
"Score": "3"
}
},
{
"body": "<p>For exact knowledge about finding out which is the most effective, the best way to find that out is to time using:</p>\n<pre><code>long start = System.nanoTime();\n... perform operations ...\nlong stop = System.nanoTime();\ndouble milliSecondsElapsed = (stop - start) / 1000000.0;\n</code></pre>\n<p>I think your way of doing it currently is quite good.</p>\n<p>I found that there is <a href=\"https://stackoverflow.com/questions/15613377/insert-multiple-rows-in-sqlite-error-error-code-1\">another way of doing it</a> but it seems to involve writing a seemingly SQL query that looks like this:</p>\n<pre><code>INSERT INTO Contacts \nSELECT 'ae0caa6a-8ff6-d63f-0253-110b20ac2127' AS ID, 'xxx' AS FirstName, 'xxx' AS LastName, '9008987887' AS PhoneNumber, 'xxx@gmail.com' AS EmailId, 'Yes' AS Status \nUNION SELECT '9afab56e-a18a-47f2-fd62-35c78d8e0d94', 'yyy', 'yyy', '7890988909', 'yyy@gmail.com', 'Yes' \nUNION SELECT '378d757a-ee60-07a4-e8bc-396b402c3270', 'zzz', 'zzz', '9000898454', 'zzz@gmail.com', 'Yes'\n</code></pre>\n<p>Unless that alternative way of inserting rows to the database improves performance significantly, I would stick to the way that you are doing it now. I imagine that the code required to write this SQL statement would be quite ugly (if you would want to transform your current <code>String[]</code>/<code>ContentValues</code> approach into this SQL statement). Especially considering that I assume you only perform this mass-insertion once. Besides, the code required to transform into SQL also takes time to execute of course, which might neglect the performance increase you would get from doing the mass-insertion with a single SQL statement.</p>\n<p>Also, your current approach is very easy to read and understand.</p>\n<p>As for whether or not you should write a <code>bulkInsert()</code> method, you could do it just for the challenge of it... if you don't have anything better to do :)</p>\n<h3>Summary</h3>\n<p>Stick to what you are using right now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:14:36.297",
"Id": "84915",
"Score": "0",
"body": "Thank you, I will stick to doing it this way for now, maybe I will have a go at implementing the other method at a later time for the sheer fun of it :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:32:11.390",
"Id": "48370",
"ParentId": "48312",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48370",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T09:42:02.023",
"Id": "48312",
"Score": "6",
"Tags": [
"java",
"android",
"database",
"sqlite"
],
"Title": "Database data insertion"
} | 48312 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.