body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've been running through <em>The Little Schemer</em>, and have hit the example of Peano multiplication. The solution is given in TLS (reproduced below) -- however what interests me is the order of the algorithm. </p>
<pre><code>(define mX
(lambda (n m)
(cond
((zero? m) 0)
(else
(+ n (mX n (1- m))))
)))
</code></pre>
<p>My understanding is that this sort of operation is to be avoided, as the order of the operation is unnecessarily large. </p>
<p>To that end I've been trying to think of how to convert this to a linear operation (I was able to do so in the case of addition). Nesting two functions occurred to me, but once i do this i am unsure how to measure the order of the function. </p>
<pre><code>(define (mX n m)
(define (mX-aux n m product)
(if (zero? m)
product
(mX-aux n (1- m) (+ product n))))
(mX-aux n m 0))
</code></pre>
<p>Is this approach linear or recursive? Is there a another way to do this? In particular, is it possible to do this without setting variables?</p>
|
[] |
[
{
"body": "<p>Let's look at a simpler problem first: counting the length of a list. Here's the recursive way to do it:</p>\n\n<pre><code>(define (length lst)\n (if (null? lst)\n 0\n (+ 1 (length (cdr lst)))))\n</code></pre>\n\n<p>Okay, so, what would it look like if instead of recursing, we kept a running count of the length instead?</p>\n\n<pre><code>(define (length lst)\n (length-aux lst 0))\n\n(define (length-aux lst count)\n (if (null? lst)\n count\n (length-aux (cdr lst) (+ 1 count))))\n</code></pre>\n\n<p>Here, <code>length-aux</code> tail-recurses into itself over and over with a new running count until we hit the end of the list, at which point we return the count.</p>\n\n<p>This idiom is common enough that Scheme has a concept called named <code>let</code>, which you can use like this:</p>\n\n<pre><code>(define (length lst)\n (let loop ((lst lst)\n (count 0))\n (if (null? lst)\n count\n (loop (cdr lst) (+ 1 count)))))\n</code></pre>\n\n<p>You can use a similar approach for solving your problem iteratively:</p>\n\n<pre><code>(define (mX n m)\n (let loop ((m m)\n (product 0))\n (if (zero? m)\n product\n (loop (- m 1) (+ product n)))))\n</code></pre>\n\n<p>Notice that we are not setting variables here. We are doing a tail recursion into <code>loop</code>, which is passed the new <code>m</code> and <code>product</code> values as arguments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T19:17:50.707",
"Id": "61054",
"Score": "0",
"body": "i asked a related follow up question on Peano Exponents [here](http://codereview.stackexchange.com/questions/37018/lexical-scope-v-let-in-scheme-functions)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T02:39:11.330",
"Id": "37009",
"ParentId": "37008",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37009",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T02:00:11.447",
"Id": "37008",
"Score": "1",
"Tags": [
"recursion",
"scheme"
],
"Title": "Linear Peano multiplication in Scheme?"
}
|
37008
|
<p>Several of my Python 2.7 programs need to access server tasks via our server Apache instance.
The 'client' programs will run on Windows in various environments. They may be run on systems that do not use a proxy, or on systems that use a proxy with no authentication, or enterprise systems that use an authenticated proxy server.</p>
<p>The function below is meant to address all three proxy situations.</p>
<p>My main question is whether I have coverage for requirement for all scenarios - i.e. for all possible proxy configurations. I am not familiar with, for example, the kind of proxy authentication that might be used on Windows Active Directory systems - is it different than what my code can handle?</p>
<p>I'm also interested in suggestions for general improvement of the code. The exception handlers are incomplete - I'll work on them once I'm sure the code is ok.</p>
<pre class="lang-python prettyprint-override"><code>def openUrl(url, data=None):
""" General purpose URL opener
Handles no proxy - un-authenticated proxy and authenticated proxy
urlencoding of the data argument to be performed prior to invoking this function
:param url: The url to access
:param data: Post data to accompany the url request
:return: an open urllib object
"""
# case 1: Proxy not required as no PROXY_URL found in environment. Fall through to urlopen
if os.getenv('PROXY_URL') is None:
pass
# case 2: un-authenticated proxy, just load the proxy handler and then fall through to urlopen
elif os.getenv('PROXY_USER') is None:
proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
# case 3: Authenticated proxy. Load password manager and proxyHandler, the fall through to urlopen
else:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, os.getenv('PROXY_URL'), os.getenv('PROXY_USER'), os.getenv('PROXY_PASSWORD'))
auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
# Access url using proxy defined above (or no proxy at all)
try:
connection = urllib2.urlopen(url, data)
except urllib2.URLError, err:
print(repr(err))
exit()
except urllib2.HTTPError, err:
print(repr(err))
exit()
return connection
</code></pre>
|
[] |
[
{
"body": "<p>I know you said the error handlers weren't done, but don't use <code>except Exception, err</code>. It's syntax that was removed in Python 3.x because it muddied the waters when you want to accept multiple exceptions, ie. <code>except ValueError, IndexError</code>. It is possible to do that, but you have to manually wrap them in parentheses to prevent the ambiguity. When you want to <code>except</code> an error and store it with a name, use the explicit syntax <code>except Exception as err</code>, so it's fully clear what you mean.</p>\n\n<p>Also, you might be able to just catch both exceptions in one go, if you don't intend to treat them differently. As I said above, you just need to put both exceptions in a tuple, like this:</p>\n\n<pre><code>except (urllib2.URLError, urllib2.HTTPError) as err:\n print(repr(err))\n exit()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-22T13:49:41.963",
"Id": "108382",
"ParentId": "37010",
"Score": "0"
}
},
{
"body": "<ul>\n<li>The function should be called <code>open_url</code> according to Python coding\nconventions.</li>\n<li>The <code>if</code>/<code>pass</code> combination isn't so nice, it's just more to read.\nI'd nest the conditions instead.</li>\n<li>I don't get the exception handler. Why exit hard? Maybe there's a\nshort network outage and then the program just shuts down? Let other\nparts of the program handle those scenarios. They need to deal with\n<code>urllib2</code> exceptions anyway.</li>\n<li><code>PROXY_PASSWORD</code> isn't verified, does <code>None</code> work as a value?</li>\n</ul>\n\n<p>Otherwise looks fine; I'd suggest caching those handlers and only\ninstalling them once, e.g.:</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>def install_open_url_handlers():\n # case 1: Proxy not required as no PROXY_URL found in environment. Fall through to urlopen,\n # otherwise:\n proxy_url = os.getenv('PROXY_URL')\n if proxy_url is not None:\n proxy_user = os.getenv('PROXY_USER')\n\n # case 2: un-authenticated proxy, just load the proxy handler and then fall through to urlopen\n if proxy_user is None:\n handler = urllib2.ProxyHandler({})\n # case 3: Authenticated proxy. Load password manager and proxyHandler, the fall through to urlopen\n else:\n password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\n password_mgr.add_password(None, proxy_url, proxy_user, os.getenv('PROXY_PASSWORD'))\n handler = urllib2.ProxyBasicAuthHandler(password_mgr)\n\n urllib2.install_opener(urllib2.build_opener(handler))\n\n\nHANDLER_INSTALLED = False\n\n\ndef open_url(url, data=None):\n \"\"\" General purpose URL opener\n Handles no proxy - un-authenticated proxy and authenticated proxy\n\n urlencoding of the data argument to be performed prior to invoking this function\n\n :param url: The url to access\n :param data: Post data to accompany the url request\n :return: an open urllib object\n \"\"\"\n global HANDLER_INSTALLED\n if not HANDLER_INSTALLED:\n HANDLER_INSTALLED = False\n install_open_url_handlers()\n\n # Access url using proxy defined above (or no proxy at all)\n return urllib2.urlopen(url, data)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-22T15:24:08.297",
"Id": "108398",
"ParentId": "37010",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T05:10:49.230",
"Id": "37010",
"Score": "3",
"Tags": [
"python",
"networking",
"python-2.x"
],
"Title": "urllib proxy access function"
}
|
37010
|
<p>I've just stumbled upon something today that seemed "unethical" in PHP. What I originally thought as malpractice, turned out to work just fine. Basically what I was wondering is if pushing an instantiated class in an array was considered proper?</p>
<p>Example:</p>
<pre><code>$array = array();
array_push($array, new myClass());
foreach($array as $i => $class)
{
$class->doSomething();
}
</code></pre>
<p>Although this example is quite vague, the idea is there. Any input or alternatives on this matter would be great.</p>
|
[] |
[
{
"body": "<p>That example looks like a very simple \"chain of command\" implementation.\nLooks fine to me, nothing unusual (though YYMV depending on the code-base).</p>\n\n<p>You'll see things like this as an alternative to long blocks of procedural code, often when there's a bunch of distinct actions to perform that have no relation to one another. It's a nice way to clean up and cut up large classes to keep things \"SRP\"'d.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:05:56.750",
"Id": "61028",
"Score": "0",
"body": "Great stuff. Reason for asking was due to the fact I've recently picked up PHP, migrating from Java where you'd see a lot of this stuff."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:16:25.220",
"Id": "37039",
"ParentId": "37012",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37039",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T05:25:59.530",
"Id": "37012",
"Score": "1",
"Tags": [
"php",
"array"
],
"Title": "Pushing instantiated class in an array"
}
|
37012
|
<p>I have written this code which adds a <code>querystring</code> to a URL:</p>
<pre><code>exports.addQueryString = function(url, queryString) {
var isQuestionMarkPresent = url && url.indexOf('?') !== -1,
separator = '';
if (queryString) {
separator = isQuestionMarkPresent ? '&' : '?';
url += separator + queryString;
}
return url;
};
</code></pre>
<p>Is there any way I can write this better?</p>
<p>Usage:</p>
<pre><code>addQueryString('http://example.com', 'q=1&val=3&user=me');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T14:27:04.737",
"Id": "65068",
"Score": "0",
"body": "Have you considered proper encoding of query string values? From your code it looks like it might be a separate operation since you already pass in a full query string but may be relevant overall."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T14:48:21.730",
"Id": "65069",
"Score": "0",
"body": "@PeterMonks Yes..That is indeed a great point but I handled this case later (after I posted the question here). Once again thanks."
}
] |
[
{
"body": "<p>What happens when you just want to add a single <code>queryString</code> to and already long <code>queryString</code>? You would need to know the entire <code>queryString</code> to do that, just to add a single new value.</p>\n\n<p>What your function should do is take a single <code>queryString</code> value and if it already exists it should update it and if it doesn't exist it should append it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T08:27:59.657",
"Id": "37017",
"ParentId": "37013",
"Score": "1"
}
},
{
"body": "<p>I think that is ok, only that i see not necesary make <code>url.indexOf('?')</code> if queryString is empty, because you are not going to use it.</p>\n\n<pre><code>exports.addQueryString = function(url, queryString) { \n if (queryString) {\n var isQuestionMarkPresent = url && url.indexOf('?') !== -1,\n separator = isQuestionMarkPresent ? '&' : '?';\n url += separator + queryString;\n }\n\n return url;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T10:28:00.450",
"Id": "38895",
"ParentId": "37013",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T06:15:42.050",
"Id": "37013",
"Score": "2",
"Tags": [
"javascript",
"url"
],
"Title": "Add query string to a URL"
}
|
37013
|
<p>I've tried using CRTP, but the forces the class to befriend CRTP Base.</p>
<pre><code>template <typename T>
class SharedConstructable
: public std::enable_shared_from_this<T>
{
typedef std::shared_ptr<T> ptr_type;
public:
struct Ptr
: ptr_type
{
template<typename... Args>
Ptr(Args&&... args)
: ptr_type(new T(args...))
{
}
};
};
class SharedOnly
: SharedConstructable<SharedOnly>
{
private:
friend class SharedConstructable<SharedOnly>;
SharedOnly(int) {}
}
</code></pre>
<p>Usage:</p>
<pre><code>SharedOnly x(5); // Error Constructor is private
SharedOnly::Ptr(5); // Correct usage;
</code></pre>
<p>Is there a cleaner/better way of doing this (without the friendship)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T03:44:24.510",
"Id": "61317",
"Score": "0",
"body": "To do what exactly - inherit privately from `SharedConstructable<T>` (more or less as given) and not expose a constructor? Or was that just an attempted means to accomplish another goal?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T05:06:26.357",
"Id": "61320",
"Score": "0",
"body": "To allow construction only through shared_ptrs - It needs to inherit publicly to expose the nested Ptr class"
}
] |
[
{
"body": "<p>If I follow you correctly, you're looking for a clean way to have a private constructor that can only be invoked by std::make_shared or std::allocate_shared. Unfortunately this does not appear to be <a href=\"http://www.drdobbs.com/befriending-templates/184403853\" rel=\"nofollow\">portable</a> or <a href=\"http://herbsutter.com/2012/01/20/gotw-103-smart-pointers-part-1-difficulty-310/#comment-4782\" rel=\"nofollow\">easy</a>, and I don't see a way to avoid your request to avoid friendship. However you can make the friend something that other people cannot easily co-opt. I'd call this mildly better, but it definitely has some downsides.</p>\n\n<p>As this is not portable, the scenario I'm showing here is specific to the compiler I had handy: Visual Studio 2012. First I created a class like this:</p>\n\n<pre><code>class SomeClass\n{\npublic:\n int GetValue() const { return m_val; }\n // optionally provide Ptr like yours?\n // static std::shared_ptr<SomeClass> Ptr(int val) { return std::make_shared<SomeClass>(val); }\n\nprivate:\n SomeClass(int val) { m_val = val; }\n SomeClass(const SomeClass&); // = delete;\n SomeClass(SomeClass&&); // = delete;\n ~SomeClass() {}\n\n int m_val;\n};\n</code></pre>\n\n<p>This is enough to prevent usage like <code>SomeClass thing(5);</code> Then I wanted to try to befriend std::make_shared. When I tried to compile code using this definition and <code>std::make_shared<SomeClass>(5)</code>, I got an error pointing to what needed access:</p>\n\n<blockquote>\n <p>error C2248 [...] cannot access private member [SomeClass::~SomeClass ...]\n while compiling class template member function 'void std::_Ref_count_obj<_Ty>::_Destroy(void)'</p>\n</blockquote>\n\n<p>After befriending <code>class std::_Ref_count_obj<SomeClass></code> (I first tried befriending the specific method, but that created worse problems), I also decided to fix the warning by befriending <code>std::_Get_align<SomeClass></code>:</p>\n\n<blockquote>\n <p>warning C4624: 'std::_Get_align<_Ty [= SomeClass]>' : destructor could not be generated because a base class destructor is inaccessible</p>\n</blockquote>\n\n<p>This left me with the following additions to this class that allows <code>std::make_shared<SomeClass>(5)</code> but not <code>SomeClass obj(5)</code>.</p>\n\n<pre><code>class SomeClass\n{\n : : : \n // Allow use in VS2012 implementation of std::make_shared\n friend class std::_Ref_count_obj<SomeClass>;\n friend struct std::_Get_align<SomeClass>;\n : : :\n};\n</code></pre>\n\n<p>I'll leave other compilers up to you as you need them. It may be worth collecting a series of macro alternatives that you can put in any class that needs this capability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:46:05.797",
"Id": "61525",
"Score": "0",
"body": "1K! Congratulations!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T03:02:58.163",
"Id": "61572",
"Score": "0",
"body": "Thats an interesting approach, but unfortunately much less portable or clean... thanks for trying though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:44:52.277",
"Id": "61657",
"Score": "0",
"body": "@nishantjr The portability is definitely its biggest weakness. However if you hide that behind a `#define BEFRIEND_MAKE_SHARED(ClassName) ...` it should be easy to clean up in a single shared header."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T01:35:33.730",
"Id": "61740",
"Score": "0",
"body": "eeek, macros are evil, especially for something as trivial as this. And how is that any beeter than the original solution I gave?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T05:51:12.980",
"Id": "61743",
"Score": "0",
"body": "The use of `make_shared<T>(...)` is preferable to `shared_ptr<T>(new T{...})` for its memory layout, and I prefer the friend statements over creating two helper classes. But as for the macro, to each his own."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:11:25.550",
"Id": "37248",
"ParentId": "37014",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T06:56:39.287",
"Id": "37014",
"Score": "0",
"Tags": [
"c++",
"c++11",
"pointers"
],
"Title": "Extract code that makes class shared_ptr construct-able only"
}
|
37014
|
<p>Thanks for taking the time to read this.
I submitted a code screening for a company I really wanted to work for and spent a decent amount of time on their programming assignment. Pretty bummed when they just said thanks but no thanks. </p>
<p>Could you guys take a look and see why that might be? I was hoping to at least talk to an engineer. Thank you again. </p>
<pre><code>DICTIONARY_INPUT="/usr/share/dict/words"
declare -A DICTIONARY
while read word; do
word=${word,,}
DICTIONARY[$word]=1
done < $DICTIONARY_INPUT
#for j in "${!DICTIONARY[@]}"; do
# echo "$j"
#done
while read -p"> " input_word; do
#echo "You entered $input_word"
input_word=${input_word,,}
#echo "Lowercased: $input_word"
found=false
# If the input is a word in the dictionary, you're done!
if [[ ${DICTIONARY[$input_word]} ]]; then
echo "$input_word";
found=true
else
# Else, use DUPLICATE as a queue and enqueue permutations of reduced
#+words. Use ALL_DUPLICATE as a set which removes duplicate words.
declare -a DUPLICATE=($input_word)
declare -A ALL_DUPLICATE
ALL_DUPLICATE=()
ALL_DUPLICATE[$input_word]=$input_word
while [ ${#DUPLICATE[@]} -gt 0 ]; do
for (( i=0; i<${#DUPLICATE}-1; i++ )); do
if [[ ${DUPLICATE:$i:1} == ${DUPLICATE:$i+1:1} ]]; then
twochars=${DUPLICATE:$i:2}
#echo $twochars
removed_dup=${DUPLICATE:0:$i}${DUPLICATE:$((i+1))}
#echo $removed_dup
ALL_DUPLICATE[$removed_dup]=$removed_dup
if [[ ${DICTIONARY[$removed_dup]} ]]; then
echo "$removed_dup"
found=true
break 2
else
DUPLICATE=( "${DUPLICATE[@]}" $removed_dup)
#echo "New size is ${#DUPLICATE[@]}"
fi
fi
done
DUPLICATE=(${DUPLICATE[@]:1})
#echo "Removed size is ${#DUPLICATE[@]}"
done
#for j in "${!ALL_DUPLICATE[@]}"; do
# echo "$j"
#done
# If we didn't find the word yet, go through the set of duplicates
#+and stack words with changed vowels in VOWELS.
# Each stack in VOWELS belongs to a particular word in ALL_DUPLICATES.
# Iterate through the length of the word since we don't need to check
#+earlier letters of newly created words.
if ! $found; then
#echo "Found: $found"
declare -a VOWELS
for j in "${!ALL_DUPLICATE[@]}"; do
VOWELS=( $j )
num_letters=${#VOWELS}
for (( i=0; i<$num_letters; i++ )); do
for k in "${VOWELS[@]}"; do
if [[ ${k:$i:1} == [aeiou] ]]; then
change_a=${k:0:$i}a${k:$((i+1))}
change_e=${k:0:$i}e${k:$((i+1))}
change_i=${k:0:$i}i${k:$((i+1))}
change_o=${k:0:$i}o${k:$((i+1))}
change_u=${k:0:$i}u${k:$((i+1))}
#echo $change_a
#echo $change_e
#echo $change_i
#echo $change_o
#echo $change_u
VOWELS=( "${VOWELS[@]}" $change_a )
VOWELS=( "${VOWELS[@]}" $change_e )
VOWELS=( "${VOWELS[@]}" $change_i )
VOWELS=( "${VOWELS[@]}" $change_o )
VOWELS=( "${VOWELS[@]}" $change_u )
if [[ ${DICTIONARY[$change_a]} ]]; then
echo "$change_a"
found=true
break 3
elif [[ ${DICTIONARY[$change_e]} ]]; then
echo "$change_e"
found=true
break 3
elif [[ ${DICTIONARY[$change_i]} ]]; then
echo "$change_i"
found=true
break 3
elif [[ ${DICTIONARY[$change_o]} ]]; then
echo "$change_o"
found=true
break 3
elif [[ ${DICTIONARY[$change_u]} ]]; then
echo "$change_u"
found=true
break 3
fi
fi
done
done
VOWELS=($VOWELS[@]:1})
done
fi
fi
if ! $found; then
echo "NO SUGGESTION"
fi
done
</code></pre>
<p><a href="https://github.com/mrlamroger/spellcheck/tree/afdde006ea2a7e703303bf1bdfd1211dc7e5b9e9" rel="nofollow">https://github.com/mrlamroger/spellcheck</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:07:04.940",
"Id": "60995",
"Score": "0",
"body": "What was the specification of the task?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:22:41.673",
"Id": "60998",
"Score": "2",
"body": "why bash? Did they ask for it in bash?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:14:20.270",
"Id": "61033",
"Score": "1",
"body": "@GarethRees The task was this \"Write a program that reads a large list of English words (e.g. from /usr/share/dict/words on a unix system) into memory, and then reads words from stdin, and prints either the best spelling suggestion, or \"NO SUGGESTION\" if no suggestion can be found. The program should print \">\" as a prompt before reading each word, and should loop until killed.\" \nMore info can be found in the link about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:16:48.597",
"Id": "61034",
"Score": "0",
"body": "@WinstonEwert I've been playing around with bash recently and wanted to learn more about it. In hindsight, Python would have been cleaner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T19:59:22.143",
"Id": "61066",
"Score": "0",
"body": "For the purpose of screening job candidates, the quality of the code was not the deciding factor. Picking the wrong tool made your solution impractical, leading to immediate disqualification. Had you proposed a Bash solution that involved piping the words to `aspell -a`, then claimed that you had achieved a superior (but incompatible) product with less code, an enlightened interviewer _might_ like your ingenuity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:26:46.230",
"Id": "61072",
"Score": "0",
"body": "@200_success That's a bummer. Thanks for the insight."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T06:46:58.200",
"Id": "61151",
"Score": "0",
"body": "Yeah... If I got code sent to me in bash my immediate response would be: WTF? That's just not the response you want."
}
] |
[
{
"body": "<p>First, I'd start with </p>\n\n<pre><code>#!/usr/bin/env bash\n</code></pre>\n\n<p>to indicate the shell.</p>\n\n<p>Next, I don't know how much bash you must use, but I think you can at least replace a serious portion of the code by using some other tools (i.e. more UNIX style).</p>\n\n<p>E.g. check if a word is in the dictionary:</p>\n\n<pre><code>if grep \"^${input_word}$\" $DICTIONARY_INPUT; then\n found=true\nfi\n</code></pre>\n\n<p><code>^${input_word}$</code> will match exactly that word (use the -i flag for case insensitivity). <code>grep</code> returns 1 if the regular expression is not found in the input file, else 0, which is why this if-expression works.</p>\n\n<p>Then, a bit further you seem to try to replace all vowels with all other vowels; a oneliner for this could be</p>\n\n<pre><code>eval echo $(echo \"$input_word\" | sed 's/[aeiou]/{a,e,i,o,u}/g')\n</code></pre>\n\n<p>This makes use of a very useful feature in bash: bracket expansion. \nE.g. \"a{b,c}d\" expands to \"ab cd\".\nSo here, we use a regular expression that replaces every vowel in a word with {a,e,i,o,u}. E.g. hello gets <code>sed</code>'d to h{a,e,i,o,u}ll{a,e,i,o,u}. Applying bracket expansion results in a lot of words, all the combinations of vowels.</p>\n\n<p>The <code>eval</code> applies this bracket expansion; the echo is needed to pass the string to eval (else it would interpret it as a command).</p>\n\n<p>So, in short, this can be replaced by</p>\n\n<pre><code>for word in $(eval echo $(echo $input_word | sed 's/[aeiou]/{a,e,i,o,u}/g')); do\n if grep \"^${word}$\" $DICTIONARY_INPUT; then\n found=true\n break\n fi\ndone\n</code></pre>\n\n<p>You also have another section of code that checks for duplicate letters (I first wrote previous section, so that's why the order differs with your code). It can also be replaced by something like</p>\n\n<pre><code>eval echo $(echo \"$input_word\" | sed 's/\\([a-z]\\)\\1/{\\1,\\1\\1}/g')\n</code></pre>\n\n<p>It works similarly to previous code, but now we use backreferences in <code>sed</code> to check for duplicate letters.</p>\n\n<p>These results can be combined with the for loop above to get all your combinations.\nOr, at least I think so :)</p>\n\n<p>I think this code is better because</p>\n\n<ul>\n<li>it uses some specialized tools like <code>sed</code> and <code>grep</code> which is more UNIXy</li>\n<li>it has less number of lines, and I think more clear (after some study) to understand and modify</li>\n<li>I think performance should be better, as grep is quite fast at reading input and filtering (just a guess, not really tested it)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:18:17.887",
"Id": "61035",
"Score": "0",
"body": "Thanks @jerous! I'll implement changes tonight and compare performance."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:04:52.903",
"Id": "37048",
"ParentId": "37015",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37048",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T07:15:11.563",
"Id": "37015",
"Score": "2",
"Tags": [
"interview-questions",
"bash"
],
"Title": "Spell check interview problem in Bash"
}
|
37015
|
<p>I've been chewing through a bit of <em>The Little Schemer</em> and the Peano examples got me thinking about operation size and time. </p>
<p>I got some <a href="https://codereview.stackexchange.com/questions/37008/linear-peano-multiplication-in-scheme">help</a> on making Peano Multiplication linear -- however <code>(time ...)</code> didn't show much difference between a lexically scoped version and the <code>let-loop</code> version. </p>
<p>I do however find a <em>massive</em> difference between the lexically scoped and <code>let-loop</code> versions when minting a Peano Exponent function. </p>
<p>The obvious question is why it makes such a difference (or perhaps it does not and my attempt at a lexically scoped Peano Exponent has some fatal error)? </p>
<p>-- i had thought i understood what the <code>let-loop</code> was doing in terms of storing the value in the parent enclosure (making the two roughly equivalent); in which way is this wrong? </p>
<pre><code>;; lexically scoped version of Peano Exp
(define (exxp-lex b ex)
(define (exxp-aux ex prod)
(cond
((zero? ex) 1)
((= ex 1) (mX-let b prod))
(else
(exxp-aux (- ex 1) (mX-lex b prod)))))
(exxp-aux ex 1))
;; let version of Peano Exp
(define (exxp-let b ex)
(let loop ((ex ex)
(prod 1))
(cond
((zero? ex) 1)
((= ex 1) (mX-let prod b))
(else
(loop (- ex 1) (mX-let prod b))))
))
</code></pre>
<p>If it's relevant, I am using petite-chez scheme. </p>
<p>For reference, here are the Peano Multiplication functions. </p>
<pre><code>;; a lexically scoped version Peano Multiplication
(define (mX-lex n m)
(define (mX-aux m product)
(if (zero? m)
product
(mX-aux (- m 1) (+ product n))))
(mX-aux m 0))
;; using let for Peano Mult
(define (mX-let n m)
(let loop ((m m)
(product 0))
(if (zero? m)
product
(loop (- m 1) (+ product n)))))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:10:31.433",
"Id": "61134",
"Score": "1",
"body": "This doesn't address your question, but just as a point of interest: all the functions above are lexically scoped and in fact Scheme is always lexically scoped. What distinguishes the ones you're referring to as lexically scoped is that they use \"internal definitions\" whereas the others use \"named `let`\". As I said, this is neither here nor there regarding the question; I only mention it since you seem interested in learning more about Scheme."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T06:14:31.490",
"Id": "61150",
"Score": "0",
"body": "@jbm thanks. I am very interested - is there a major difference between function operation/execution in either case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:20:33.570",
"Id": "61249",
"Score": "0",
"body": "They should be the same in this case, as would an equivalent use of `letrec`. (In fact, many implementations translate named `let` to `letrec`, and may do something similar with internal definitions). However, locally scoped mutually recursive procedures can be expressed with internal definitions and `letrec` but not with named `let`. I see it as coming down to what best fits the logic and flow of your function(s), there shouldn't be a big performance difference between otherwise equivalent binding forms."
}
] |
[
{
"body": "<p>In <code>exxp-aux</code>, you call <code>(mX-let b prod)</code> and <code>(mX-lex b prod)</code>. You probably meant the two calls to be identical.</p>\n\n<p>In <code>exxp-let</code>, you call <code>(mX-let prod b)</code>.</p>\n\n<p><code>mX-lex</code> and <code>mX-let</code> are both implemented such that they would be faster if you call them with the larger multiplicand first and the smaller one second, because the second parameter controls the number of additions. Since <code>prod</code> is likely to be larger than <code>b</code>, your <code>exxp-aux</code> will be slower.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T10:24:43.867",
"Id": "61165",
"Score": "0",
"body": "+1, accepted. wow, i changed the order of the `(mX-fun b prod)` calls to (mX-fun prod b)` and the speed difference disappeared. Had no idea. Now the only thing that's different is the byte size of the operation -- why is the `let-loop` so much smaller?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T10:28:57.913",
"Id": "61167",
"Score": "0",
"body": "Funny how you had a 50-50 chance of getting the fast version, being oblivious to the performance difference due to the parameter ordering. I have no idea how to explain the difference in code size, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:46:06.310",
"Id": "61243",
"Score": "0",
"body": "How costly is testing parameter size and setting the order so as to maximise performance? I mean, at what point does it generally become worth it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:52:45.193",
"Id": "61245",
"Score": "0",
"body": "Probably not costly. However, the point of the exercise was to implement Peano arithmetic, not performance. Would you still consider it a valid implementation if you conditionally swapped the arguments? If you wanted speed, you would just do `(* b prod)`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:27:25.427",
"Id": "37072",
"ParentId": "37018",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37072",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T08:38:08.143",
"Id": "37018",
"Score": "2",
"Tags": [
"performance",
"recursion",
"scheme",
"iteration"
],
"Title": "lexical scope v let in scheme functions"
}
|
37018
|
<p>In this, we are given an array of numbers, say 1 2 3 4.</p>
<p>We start from a given position, let's say the 1st position.
We cancel that number and move forward that many non-cancelled numbers. The number on which we stop again has the same procedure.This is repeated until only one number is left. That is the lucky number.</p>
<p><strong>1</strong> 2 3 4</p>
<p><strong>2</strong> 3 4</p>
<p>3 <strong>4</strong></p>
<p><strong>3</strong></p>
<p>My code:</p>
<pre><code>import java.util.*;
class ln
{
public static void main(String[] ar)throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.print("How many nos. will you enter: ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.print("Enter the nos.: ");
for(int i = 0; i < a.length; i++)
a[i] = sc.nextInt();
System.out.print("From which position do you want to start: ");
int st = sc.nextInt();
for(int i = 0; i < a.length - 1; i++)
{
int j = a[st - 1];
a[st - 1] = 0;
int s = (int)Math.signum(j);
while(j != 0)
{
if(a[st-1] != 0)
j -= s;
st += s;
if(st > a.length)
st = 1;
else if(st < 1)
st = a.length;
}
}
for(int i = 0; i < a.length; i++)
{
if(a[i] != 0)
{
System.out.println("Final no.: " + a[i]);
break;
}
}
}
}
</code></pre>
<p>Please tell if there is a more elegant way of doing this .</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T11:01:55.933",
"Id": "60960",
"Score": "0",
"body": "Your current code doesn't work as you have described. The array `1 2 3 4` and the starting number `1` returns `2`, not `3` as you have described."
}
] |
[
{
"body": "<p>Yes, there is a more elegant way of doing this. (That's all you wanted to know, isn't it?)</p>\n\n<p>First of all, here's some general comments about your code:</p>\n\n<ul>\n<li>Your <code>Scanner</code> should be closed when you are done with it. <code>sc.close();</code></li>\n<li>You use in total six different names for variables. All of these have a variable name of one or two single characters. It is hard to understand their purpose because of the short variable names you have given them. Possible better names could be <code>currentIndex</code>, <code>sign</code>, <code>currentNumber</code>...</li>\n<li><p>Use methods. A method should do one thing and it should do that one thing well. Your main method currently does:</p>\n\n<ul>\n<li>Receive user input and put it into an array</li>\n<li>Determine the \"final number\" according to your rules for this array</li>\n<li>Display result to user</li>\n</ul>\n\n<p>At least make a separate method for determining the final number for an array. The method could be something like this: <code>public static int finalNumber(int[] inputArray)</code></p></li>\n</ul>\n\n<p>Use an if-statement to check if you are currently processing the last number. This will get rid of the last for-loop in your current code, which only loops through the array and shows the non-zero number it encounters.</p>\n\n<p>There is some things that can be simplified within your algorithm as well.</p>\n\n<ul>\n<li>loop x number of times, where x equals array size</li>\n<li>get the value at the current index</li>\n<li>get the sign of the current value</li>\n<li>modify the current index by + current value</li>\n<li>while the value at the current index is zero, modify the current index by the value of sign</li>\n</ul>\n\n<p>When modifying the index, you can use the modulo <code>%</code> operator to make sure that it is within the bounds of the array.</p>\n\n<p>Here is what I would do:</p>\n\n<pre><code>public static int luckyNumber(int[] a, int index) {\n List<Integer> ints = new ArrayList<Integer>(a.length);\n for (int i = 0; i < a.length; i++) {\n // Add the values to a list so that it is easy to remove them later\n ints.add(a[i]);\n }\n int lastValue = 0;\n while (!ints.isEmpty()) {\n // Save the index that should be removed later\n int oldIndex = index;\n int currentNumber = ints.get(index);\n index = index + currentNumber;\n\n // Make sure that the index is within a valid range\n if (index < 0)\n index += ints.size() * Math.abs(index);\n index = index % ints.size();\n\n // Remove the old index and adjust the index value if the index removed was before the current index.\n lastValue = ints.remove(oldIndex);\n if (oldIndex <= index) index--;\n }\n // Once the list is empty, return the last value that was removed\n return lastValue;\n}\n</code></pre>\n\n<p>All these tests will print the lovely number 42:</p>\n\n<pre><code>System.out.println(luckyNumber(new int[]{ 1, 2, 42, 4 }, 0));\nSystem.out.println(luckyNumber(new int[]{ 1, -1, 42, 4 }, 0));\nSystem.out.println(luckyNumber(new int[]{ 1, -1, 2, 42, -4 }, 1));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:25:44.233",
"Id": "62711",
"Score": "0",
"body": "\"9 9 8 1\" , starting with '0' gives error"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T10:15:25.177",
"Id": "37024",
"ParentId": "37019",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37024",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T08:49:42.217",
"Id": "37019",
"Score": "3",
"Tags": [
"java",
"array"
],
"Title": "Optimising Lucky Number Program"
}
|
37019
|
<p>I have this query:</p>
<pre><code>SELECT * FROM
(SELECT u.id,u.email,u.verified,u.verified_on,u.created_on,ca.html AS age,cg.html AS gender,cs.html AS state
FROM users u
LEFT JOIN combo ca ON ca.combo_group='age' AND ca.value =u.age
LEFT JOIN combo cg ON cg.combo_group='gender' AND cg.value =u.gender
LEFT JOIN combo cs ON cs.combo_group='state' AND cs.value =u.state ORDER BY created_on DESC) users ORDER BY email ASC;
</code></pre>
<p>I am using sub query because I want sort <code>created_on DESC</code> and <code>email ASC</code>.</p>
<p>Would using sub query affect performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T12:23:16.477",
"Id": "60972",
"Score": "5",
"body": "Cross-posted from http://stackoverflow.com/q/20492709/398670. Please do NOT duplicate your questions across multiple sites; if you really feel you must, link between them to avoid wasting everybody's time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T12:29:25.963",
"Id": "60974",
"Score": "0",
"body": "yes my friend have posted there because i was not getting response from here and i banned from asking question in SO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T12:33:24.310",
"Id": "60975",
"Score": "5",
"body": "@user20907171 Guess why you're banned on Stack Overflow? If you copy and paste posts, you'll get banned here pretty quickly too. Consider changing whatever behavior is getting you banned instead."
}
] |
[
{
"body": "<p>Your query doesn't do what you think it does. It discards the original ordering when it re-sorts. It might, depending on the sorting algorithm chosen, happen to come out how you want, but there's no guarantee.</p>\n\n<blockquote>\n <p>I am using sub query because i want sort created_on DESC and email ASC</p>\n</blockquote>\n\n<p>If that's what you want, just write:</p>\n\n<pre><code>ORDER BY created_on DESC, email ASC\n</code></pre>\n\n<p>Your bigger worry with performance is that <code>combo</code> side table, which appears to be <a href=\"http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model\">EAV</a> and thus likely to be painful in performance terms. Consider using a <code>hstore</code> or <code>json</code> field instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T12:19:24.577",
"Id": "37031",
"ParentId": "37025",
"Score": "5"
}
},
{
"body": "<p>Nested query is unnecessary in this case, you can rewrite the query as,</p>\n\n<pre><code>SELECT \n u.id\n ,u.email\n ,u.verified\n ,u.verified_on\n ,u.created_on\n ,ca.html AS age\n ,cg.html AS gender\n ,cs.html AS state\nFROM users u\n LEFT JOIN combo ca ON ca.combo_group='age' AND ca.value =u.age\n LEFT JOIN combo cg ON cg.combo_group='gender' AND cg.value =u.gender\n LEFT JOIN combo cs ON cs.combo_group='state' AND cs.value =u.state \nORDER BY u.created_on DESC, u.email ASC\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T13:42:16.007",
"Id": "37036",
"ParentId": "37025",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37031",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T10:40:06.380",
"Id": "37025",
"Score": "2",
"Tags": [
"performance",
"sql",
"mysql",
"sorting",
"postgresql"
],
"Title": "Query of users for some age, gender, and state, using a subselect"
}
|
37025
|
<p>I have a pretty simple problem. A large set of unique strings that are to various degrees not clean, and in reality they in fact represent the same underlying reality. They are not person names, but they could be. So for example Dr. John Holmes and Dr. Jon Holms are more than likely the same person. From the list of unqiue strings I want to cluster together those that possibly match the same underlying reality. There is no restrictions on the size of the cluster (i.e. I am not expecting only one match per string). </p>
<p>I calculate the distance between strings using the Jaro-Distance with jellyfish in python. But then I wondered how I cluster them together? I was unable to figure out how to do this using scipy clusters as I am working with strings, not floats, so I decided to work according to the following algorithm. </p>
<ol>
<li>Make the first object the centroid for the first cluster</li>
<li>For the next object, calculate the similarity with each existing cluster centroid
If the highest calculated similarity is over some threshold value then add the object to the relevant cluster and re-determine the centroid of that cluster, otherwise use the object to initiate a new cluster. </li>
<li>If any object remains to be clustered then return to step </li>
</ol>
<p>Also, I decided to strip out generic components of the strings to improve the matches. In the name example above, this would give Dr. John Holmes, and J. Holmes a better chance of matching if 'Dr' is stripped out as a generic component.</p>
<p>I created a Stripped Class that has an attribute that is the original unique string, and then attribute that is a stripped version (stripped of the generic components). This is becasue once stripped many of the strings could have exactly the same values, and I need to be able to identify which original string they identify. </p>
<p>The code is posted below. It works well, except that the size/number of clusters is not independent of the order in which the strings are evaluated. So the results do differ. </p>
<p>In the final function, the SLink fucntion is called inside another function</p>
<p>I would specifically like to know if anyone knows of a better way to implement this type of clustering? If anyone has comments on how I could improve my code, and if anyone has any information about clustering strings in scipy.</p>
<p>In an IPython notebook I go through in more detail how I could refine this system, including using another function to verify the clusters using alternate data points relating to each string (such as age). If anyone would like to view that and offer guidance, then please see the following link:</p>
<p><a href="http://nbviewer.ipython.org/gist/MajorGressingham/7876252">http://nbviewer.ipython.org/gist/MajorGressingham/7876252</a></p>
<p>I think as the functions were somewhat trial and error and unplanned, they may have got a bit out of control. Any guidance appreciated. I am a researcher living in Bangladesh, a total programming data tripper sadly, but trying to get better every day. </p>
<pre><code>class Stripped:
'Common base class for all stripped stings'
def __init__(self, original, GenericAll, GenericWhite = None, DelWhite = False):
# Class attribute that is the string in its original format
self.original = original
StrVal = original.lower()
StrVal = re.sub('[^A-Za-z0-9 ' ']+', ' ', StrVal)
#strip out all occurences of sub-strings from GenericAll list that appear anywhere in the string
for word in GenericAll:
RegEx1 = re.compile('' + word)
StrVal = re.sub(RegEx1, '', StrVal)
# If provided as argument strip out all occurences of sub-string when that sub string is surrounded by
# whitespace (i.e. is not part of another substring-sequence)
if not GenericWhite == None:
for word in GenericWhite:
RegEx2 = re.compile(r'\b' + word + r'\b')
StrVal = re.sub(RegEx2, '', StrVal)
# Removes special characters, removes all whitespace
if DelWhite == True:
StrVal = StrVal.replace(' ', '')
# Class attribute that is the stipped string
self.stripped = StrVal
</code></pre>
<p>GenericAll is a list of substrings to be stripped from each string wherever the sub string appears in the string. GenericWhite is a list of substrings that are stripped only if they are surrounded by whitespace. </p>
<p>And the function that implements the clustering</p>
<pre><code>def SlinkSC(ClassList, Threshold):
#1
random.shuffle(ClassList)
Clusters = []
ClustersStripped = []
Centroid = []
Scores = []
for StrippedClass in ClassList:
SPScores = []
Matched = 0
if len(Clusters) == 0:
Clusters.append([StrippedClass.original])
ClustersStripped.append([StrippedClass.stripped])
Centroid.append([StrippedClass.stripped, StrippedClass.original])
Scores.append([])
continue
for ClustNum in xrange(len(Clusters)):
Dist = jf.jaro_distance(StrippedClass.stripped, Centroid[ClustNum][0])
SPScores.append(Dist)
MaxVal = max(SPScores)
MaxInd = SPScores.index(max(SPScores))
if MaxVal >= Threshold:
Clusters[MaxInd].append(StrippedClass.original)
ClustersStripped[MaxInd].append(StrippedClass.stripped)
if len(Scores[MaxInd]) == 0:
Scores[MaxInd].append(MaxVal)
else:
if MaxVal > Scores[MaxInd][0]:
Scores[MaxInd][0] = MaxVal
Centroid[MaxInd][0] = StrippedClass.stripped
Centroid[MaxInd][1] = StrippedClass.original
Matched = 1
if Matched ==0:
Clusters.append([StrippedClass.original])
ClustersStripped.append([StrippedClass.stripped])
Centroid.append([StrippedClass.stripped, StrippedClass.original])
Scores.append([])
return [Clusters, ClustersStripped, Centroid]
</code></pre>
<p>ClassList is a list of Stripped Class obejcts created from the unique strings that are to be clustered. Threshold is the threshold above which strings will be clustered when distance between the centorid and the string being evaluated is calcuated as the jaro-distance. </p>
<p>Lastly I wrote a function that sort of combines all of the above, but also clusters the clusters, and calls the clustering function recursively until no more clusters are found. It also references the data frame from which the strings are pulled. In theory, if two non-indentical strings represent the same undelying reality, this third data point should be equal for the non-identical stings that are above the Jaro-Distance threshold. This function directly modifies the data frame from which both the list of unqiue strings and the verifying data point are drawn, until no more modifications are possible. </p>
<p>That looks like this:</p>
<pre><code> def ClustersRecursive2(Threshold, df, col1, col2, GenericAll, GenericWhite = None, DelWhite = False):
Styles = df[col1].unique()
ClassList = [Stripped(style, GenericAll, GenericWhite, DelWhite) for style in Styles]
ClustersDict = {}
Clusters = SlinkSC(ClassList, Threshold)
ClustersOriginal = Clusters[0]
ClustersCentroid = Clusters[2]
IndList = [x for x in xrange(len(ClustersOriginal)) if len(ClustersOriginal[x]) > 1]
MultiClusters = [ClustersOriginal[Ind] for Ind in IndList]
MultiCentroid = [ClustersCentroid[Ind] for Ind in IndList]
if len(MultiClusters) == 0:
return
else:
Counter = 0
for cluster in xrange(len(MultiClusters)):
MultiSMV = list(itertools.chain(*[df[df[col1] == elem][col2].unique() for elem in MultiClusters[cluster]]))
if len(set(MultiSMV)) == 1:
ClustersDict[MultiCentroid[cluster][1]] = MultiClusters[cluster]
Counter +=1
else:
if len(MultiSMV) == len(MultiClusters[cluster]):
for smv in list(set(MultiSMV)):
if MultiSMV.count(smv) >= 2:
BoolList = [True if elem == smv else False for elem in MultiSMV]
StrList = [MultiClusters[cluster][x] for x in xrange(len(BoolList)) if BoolList[x] == True]
StrList.sort(lambda x, y: cmp(len(x), len(y)))
ClustersDict[StrList[0]] = StrList
Counter +=1
#Cluster the Clusters
ClusClusList = [Stripped(style, GenericAll, GenericWhite, DelWhite) for style in ClustersDict.keys()]
ClusClusters = SlinkSC(ClusClusList, Threshold)
ClusClusOrig = ClusClusters[0]
ClusClusCentroid = ClusClusters[0]
IndList2 = [x for x in xrange(len(ClusClusOrig)) if len(ClusClusOrig[x]) > 1]
MultiClusClus = [ClusClusOrig[Ind] for Ind in IndList2]
if len(MultiClusClus) > 0:
for CCluster in xrange(len(MultiClusClus)):
MultiSMVCC = list(itertools.chain(*[df[df[col1] == elem][col2].unique() for elem in MultiClusClus[CCluster]]))
if len(set(MultiSMVCC)) == 1:
NewList = []
for x in xrange(1, len(MultiClusClus[CCluster])):
NewList.extend(ClustersDict[MultiClusClus[CCluster][x]])
del ClustersDict[MultiClusClus[CCluster][x]]
ClustersDict[MultiClusClus[CCluster][0]].extend(NewList)
StringMap = {}
for key, value in ClustersDict.iteritems():
for elem in value:
StringMap[elem] = key
if Counter == 0:
return
else:
for row in DF.index:
try:
df[col1][row] = StringMap[df[col1][row]]
except KeyError:
pass
ClustersRecursive(Threshold, df, col1, col2, GenericAll, GenericWhite = None, DelWhite = False)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T11:32:31.273",
"Id": "60962",
"Score": "1",
"body": "(i) Do you have any test data? (ii) Can you explain in more detail why you decided not to use any of the methods in [`scipy.cluster.hierarchy`](http://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:59:37.777",
"Id": "60994",
"Score": "0",
"body": "Actually I would love to use scipy, but didn't understand the mechanics of doing that. The jaro-distance does not obey triangulation rules, so I'm not sure it is possible. The Jaccard metric is available in scipy hierachy methods, but I kept getting a message saying that my strings could not become floats when creating the matrix. Backstory is I posted this on stackoverflow basically asking for help with scipy and I was referred here as I actually have code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:35:32.010",
"Id": "61002",
"Score": "0",
"body": "So it sounds as if you tried to use one of the SciPy clustering methods (which one?) but couldn't figure out how to use it, so you gave up and wrote your own. Is that right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:39:02.813",
"Id": "61003",
"Score": "0",
"body": "That pretty much sums it up! Basically I know little about clustering, and found the above simple program format and decided to write my own. I looked into hierarchical clustering but essentially got stuck even creating the matrix. I'm not familiar with the package, and don't fully understand the method. I was looking at hierarchical clustering as k-means seemed tough as I would have no idea how to specify k. Plus I can fully get my head around jaro distance (hamming etc. just does not seem as good) and that metric is not available with scipy. Should I go back and try with scipy you reckon?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:39:57.507",
"Id": "61004",
"Score": "0",
"body": "Also, could not work out how to do it with strings. Would I have to convert them to a float somehow? or to unicode?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:48:16.663",
"Id": "61009",
"Score": "0",
"body": "I recommend that you try again with SciPy, but this time read the documentation carefully. You don't pass your original strings to [`scipy.cluster.hierarchy.linkage`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage), instead you compute a \"condensed distance matrix\" and pass that instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:50:37.110",
"Id": "61010",
"Score": "0",
"body": "But I like my version! Haha, no you are right. I didn't give it enough time. In any case it was fun to try to work it our myself I guess....."
}
] |
[
{
"body": "<p>Here's a quick illustration of how to use <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage\" rel=\"noreferrer\"><code>scipy.cluster.hierarchy.linkage</code></a> to hierarchically cluster a group of strings according to their <a href=\"https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance\" rel=\"noreferrer\">Jaro score</a>. I'm not going to try to solve your actual problem, just show how to use the SciPy interface.</p>\n\n<p>If you read the documentation for <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage\" rel=\"noreferrer\"><code>scipy.cluster.hierarchy.linkage</code></a> you'll see that it takes as its first argument:</p>\n\n<blockquote>\n <p>A condensed or redundant distance matrix. A condensed distance matrix is a flat array containing the upper triangular [part] of the distance matrix.</p>\n</blockquote>\n\n<p>What does that mean? The idea is that if you have a matrix giving distances between your words, for example:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> │CHEESE CHORES GEESE GLOVES\n───────┼───────────────────────────\nCHEESE │ 0 0.222 0.177 0.444 \nCHORES │0.222 0 0.422 0.333\nGEESE │0.177 0.422 0 0.300\nGLOVES │0.444 0.333 0.300 0\n</code></pre>\n\n<p>Then the condensed distance matrix is a flattened array containing the numbers in the upper triangle: that is, the part of the matrix above the diagonal of zeroes. In this case, it's the array <code>[0.222, 0.177, 0.444, 0.422, 0.333, 0.3]</code>. Here's how to compute the condensed distance matrix:</p>\n\n<ol>\n<li><p>Define a distance function that takes coordinates \\$(i, j)\\$ and returns the distance between word \\$i\\$ and word \\$j\\$. Despite the function being named <code>jaro_distance</code>, this score is actually a measure of <em>similarity</em> rather than difference, so we need to subtract it from 1 to get a distance measure.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> from jellyfish import jaro_distance\n>>> words = 'CHEESE CHORES GEESE GLOVES'.split()\n>>> def d(coord):\n... i, j = coord\n... return 1 - jaro_distance(words[i], words[j])\n</code></pre></li>\n<li><p>Use <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.triu_indices.html\" rel=\"noreferrer\"><code>numpy.triu_indices</code></a> to get the coordinates of the upper triangle:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> import numpy as np\n>>> np.triu_indices(len(words), 1)\n(array([0, 0, 0, 1, 1, 2]), array([1, 2, 3, 2, 3, 3]))\n</code></pre></li>\n<li><p>Use <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html\" rel=\"noreferrer\"><code>numpy.apply_along_axis</code></a> to apply the distance function to the coordinates of the upper triangle just computed:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> np.apply_along_axis(d, 0, _)\narray([ 0.22222222, 0.17777778, 0.44444444, 0.42222222, 0.33333333,\n 0.3 ])\n</code></pre></li>\n</ol>\n\n<p>Pass this array to <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage\" rel=\"noreferrer\"><code>scipy.cluster.hierarchy.linkage</code></a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> import scipy.cluster.hierarchy\n>>> scipy.cluster.hierarchy.linkage(_)\narray([[ 0. , 2. , 0.17777778, 2. ],\n [ 1. , 4. , 0.22222222, 3. ],\n [ 3. , 5. , 0.3 , 4. ]])\n</code></pre>\n\n<p>What does this mean? The documentation says:</p>\n\n<blockquote>\n <p>A 4 by \\$n-1\\$ matrix \\$Z\\$ is returned. At the \\$i\\$th iteration, clusters with indices \\$Z[i, 0]\\$ and \\$Z[i, 1]\\$ are combined to form cluster \\$n + i\\$. A cluster with an index less than \\$n\\$ corresponds to one of the \\$n\\$ original observations. The distance between clusters \\$Z[i, 0]\\$ and \\$Z[i, 1]\\$ is given by \\$Z[i, 2]\\$. The fourth value \\$Z[i, 3]\\$ represents the number of original observations in the newly formed cluster.</p>\n</blockquote>\n\n<p>So at the first iteration, words 0 (CHEESE) and 2 (GEESE) are combined to form a new cluster (#4) containing 2 original observations.</p>\n\n<p>At the second iteration, word 1 (CHORES) and cluster #4 are combined to form a new cluster (#5) containing 3 original observations.</p>\n\n<p>And at the third iteration, word 3 (GLOVES) and cluster #5 are combined to form a new cluster (#6) containing all 4 original observations.</p>\n\n<p>This corresponds to the following hierarchical clustering:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> 6 \n ┌─────┴─────┐ \n 5 │\n ┌────┴────┐ │\n 4 │ │\n ┌──┴──┐ │ │\n CHEESE GEESE CHORES GLOVES\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:26:39.723",
"Id": "61242",
"Score": "0",
"body": "hey, thanks so much, ive not got round to looking at this yet today, but i will tomo. I see you edited my jellyfish question. Should i split out the jaro distance question? It turns out the levenshtein one is buggy, its been confirmed by the developer, the jaro distance bug has not been confirmed (i may have got it wrong)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-08T10:13:27.800",
"Id": "163425",
"Score": "0",
"body": "Amazing! Very short and useful, they probably should include similar functionality in any data-processing software like Excel, etc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-18T07:36:13.877",
"Id": "311088",
"Score": "0",
"body": "Do anyone know how implement this in javascript?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T17:30:23.783",
"Id": "37059",
"ParentId": "37026",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T10:59:07.433",
"Id": "37026",
"Score": "12",
"Tags": [
"python",
"strings",
"edit-distance",
"clustering"
],
"Title": "String Matching and Clustering"
}
|
37026
|
<p>I was trying to make my life easier making a class or something that would create HTML tags in a faster way. I ended up with something that I wouldn't consider the best practice. Take a look:</p>
<pre><code>/**
* Add HTML to the page
*
* Add HTML to the page based on arrays with the tag names. It's gonna open and close the tags.
*
* @param array tags The name of the tags
* @param array attributes The attributes of the tags if you want
* @param array The elements you want inside the tags
*/
function addHtml($tags = null, $attributes = null, $innerHtml = null)
{
for($i = 0; $i < count($tags); $i++) {
// Opens the tag
echo '<' . $tags[$i];
// If there're attribures, show them and close
// If not, just closes the tag
echo !empty($attributes) ? ' ' . $attributes[$i] . '>' : '>';
// Show something you wanna put inside the tag. Another tag, text, anything
echo $innerHtml[$i];
// Closes the tag
echo '</' . $tags[$i] . '>';
}
}
</code></pre>
<p>Is there someone with a better way of doing it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T11:43:22.683",
"Id": "68467",
"Score": "1",
"body": "This is very similar to http://codereview.stackexchange.com/questions/10809/code-readability-vs-code-length. I have an answer there which you might want to look at."
}
] |
[
{
"body": "<p>When it comes to outputting HTML from PHP, there are a couple of alternatives:</p>\n\n<ul>\n<li>Using a MVC framework which will separate the logic (Controller) from the data (Model) and the output (View).</li>\n<li>Include files that contains HTML, and that can use some PHP as well (\"Templates\"). MVC frameworks normally makes use of this.</li>\n<li>For short HTML, I believe there is nothing that beats using PHP's <code>echo</code> function and write the HTML you want manually.</li>\n</ul>\n\n<p>A big problem with your current function is that to output several HTML tags, you'd have to write things that actually belongs together very far apart. For example: </p>\n\n<pre><code>addHTML(array(\"p\", \"p\"), \n array('class=\"some\"', 'class=\"other\"'), \n array(\"Lorem ipsum\", \"dolor sit amet\"));\n</code></pre>\n\n<p>It's not very readable to see that one tag will become <code><p class=\"some\">Lorem ipsum</p></code> and the other <code><p class=\"other\">dolor sit amet</p></code>.</p>\n\n<p>If you really really want to have some self-written PHP function for this, then I suggest putting things that belong together, together. Something like this:</p>\n\n<pre><code>addHTML(array(array(\"p\", \"class\" => \"some\", \"Lorem ipsum\"), \n array(\"p\", \"class\" => \"other\", \"dolor sit amet\")));\n</code></pre>\n\n<p>However, simply writing this would be so much simpler, and a whole lot easier to read: (Especially for people who are used to reading HTML)</p>\n\n<pre><code>echo '<p class=\"some\">Lorem ipsum</p>';\necho '<p class=\"other\">dolor sit amet</p>';\n</code></pre>\n\n<p>(My PHP is a bit rusty but I hope you get the idea)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T11:57:34.490",
"Id": "37029",
"ParentId": "37027",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37029",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T11:40:03.577",
"Id": "37027",
"Score": "5",
"Tags": [
"php"
],
"Title": "Add HTML to the page using a PHP Class"
}
|
37027
|
<p>During work, I was given this task: to group elements with similar properties in the array.</p>
<p>In general, the problem is as follows:</p>
<pre><code>var list = [
{name: "1", lastname: "foo1", age: "16"},
{name: "2", lastname: "foo", age: "13"},
{name: "3", lastname: "foo1", age: "11"},
{name: "4", lastname: "foo", age: "11"},
{name: "5", lastname: "foo1", age: "16"},
{name: "6", lastname: "foo", age: "16"},
{name: "7", lastname: "foo1", age: "13"},
{name: "8", lastname: "foo1", age: "16"},
{name: "9", lastname: "foo", age: "13"},
{name: "0", lastname: "foo", age: "16"}
];
</code></pre>
<p>If I group this elements by <code>lastname</code> and <code>age</code>, I will get this result: </p>
<pre><code>var result = [
[
{name: "1", lastname: "foo1", age: "16"},
{name: "5", lastname: "foo1", age: "16"},
{name: "8", lastname: "foo1", age: "16"}
],
[
{name: "2", lastname: "foo", age: "13"},
{name: "9", lastname: "foo", age: "13"}
],
[
{name: "3", lastname: "foo1", age: "11"}
],
[
{name: "4", lastname: "foo", age: "11"}
],
[
{name: "6", lastname: "foo", age: "16"},
{name: "0", lastname: "foo", age: "16"}
],
[
{name: "7", lastname: "foo1", age: "13"}
]
];
</code></pre>
<p>After some experimentation, I came to the following solution:</p>
<pre><code> Array.prototype.groupByProperties = function(properties){
var arr = this;
var groups = [];
for(var i = 0, len = arr.length; i<len; i+=1){
var obj = arr[i];
if(groups.length == 0){
groups.push([obj]);
}
else{
var equalGroup = false;
for(var a = 0, glen = groups.length; a<glen;a+=1){
var group = groups[a];
var equal = true;
var firstElement = group[0];
properties.forEach(function(property){
if(firstElement[property] !== obj[property]){
equal = false;
}
});
if(equal){
equalGroup = group;
}
}
if(equalGroup){
equalGroup.push(obj);
}
else {
groups.push([obj]);
}
}
}
return groups;
};
</code></pre>
<p>This solution works, but is this a right and best way? It still looks a little ugly to me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-10T10:26:32.417",
"Id": "222507",
"Score": "0",
"body": "There is npm module named [group-array](https://www.npmjs.com/package/group-array) that matches the same requirement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-03T17:09:09.757",
"Id": "226870",
"Score": "0",
"body": "Why not just sort the array based on those values?"
}
] |
[
{
"body": "<p>I find the functional aspect of JavaScript to be a big advantage. When it comes to looping, <code>Array.prototype.forEach</code> and cousins can help your code be more descriptive:</p>\n\n<pre><code>Array.prototype.defineProperty('groupByProperties', {\n value : function(properties){ \n // will contain grouped items\n var result = []; \n\n // iterate over each item in the original array\n this.forEach(function(item){\n // check if the item belongs in an already created group\n var added = result.some(function(group){\n // check if the item belongs in this group\n var shouldAdd = properties.every(function(prop){\n return (group[0][prop] === item[prop]);\n });\n // add item to this group if it belongs \n if (shouldAdd) {\n group.push(item);\n }\n // exit the loop when an item is added, continue if not\n return shouldAdd;\n });\n\n // no matching group was found, so a new group needs to be created for this item\n if (!added) {\n result.push([item]);\n }\n });\n return result;\n }\n});\n</code></pre>\n\n<p>While i don't consider it a best practice to add custom functionality to predefined objects (<code>Array.prototype</code> in this case), i left that part of your solution in. However, I added <code>groupByProperties</code> as a non-enumerable property of <code>Array.prototype</code> so it doesn't appear in <code>for..in</code> enumerations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T13:03:15.053",
"Id": "60976",
"Score": "0",
"body": "Great! But some tests shows that forEach method much slower than for loop with predefined length. You disagree? =)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T13:38:31.533",
"Id": "60981",
"Score": "0",
"body": "Indeed, forEach may be about 5 times slower than a for loop. It's still pretty fast and I for one am a fan of writing clearly and optimizing the bottlenecks if needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:10:28.960",
"Id": "60983",
"Score": "0",
"body": "The same issue is with creating a local variable that stores the length of the array you're looping over. It is probably a lot faster to access local variable than array.length, but when you're iterating that is not the bottleneck, so a loop with saved variable is about as fast as a regular loop with array.length. (The exception to that rule is when length is not a static property, but computed on the fly, like in a live NodeList)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T12:55:49.557",
"Id": "37033",
"ParentId": "37028",
"Score": "10"
}
},
{
"body": "<p>The main problem with your function is quadratic time complexity in the worst case. Also, if we first implement a general <code>groupBy</code> function, grouping by properties becomes trivial.</p>\n\n<pre><code>function arrayFromObject(obj) {\n var arr = [];\n for (var i in obj) {\n arr.push(obj[i]);\n }\n return arr;\n}\n\nfunction groupBy(list, fn) {\n var groups = {};\n for (var i = 0; i < list.length; i++) {\n var group = JSON.stringify(fn(list[i]));\n if (group in groups) {\n groups[group].push(list[i]);\n } else {\n groups[group] = [list[i]];\n }\n }\n return arrayFromObject(groups);\n}\n\nvar result = groupBy(list, function(item) {\n return [item.lastname, item.age];\n});\n</code></pre>\n\n<p>You might want to add <code>hasOwnProperty</code> check into <code>arrayFromObject</code>, if your coding convention doesn't forbid extending object prototype.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T10:40:40.717",
"Id": "61168",
"Score": "0",
"body": "Perhaps you should consider passing a serialization function to your groupBy method. With toString there are several problems: `item1 = { lastName : [1,2], age : 3 }` and `item2 = { lastName : 1, age : [2,3] }` and `item3 = { lastName : '1,2', age : 3 }` will all be put in the same group in your example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T12:16:38.583",
"Id": "61177",
"Score": "0",
"body": "Tibos: you're right, that's a bug waiting to happen. I've changed `toString()` to `JSON.stringify()`. The speed is comparable, assuming that JSON is implemented natively."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T13:38:31.557",
"Id": "61182",
"Score": "3",
"body": "Using the stringify as the key is brilliant, +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T19:39:00.947",
"Id": "414624",
"Score": "0",
"body": "@AlexeyLebedev vey brilliant solution! Assumed I want to lowercase so to ignore case how to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T20:01:51.270",
"Id": "414627",
"Score": "1",
"body": "@loretoparisi `return [item.lastname.toLowerCase(), item.age];`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:27:37.043",
"Id": "37088",
"ParentId": "37028",
"Score": "25"
}
},
{
"body": "<p>I felt compelled to write that you probably should combine forEach and map with the answer of Alexey Lebedev. </p>\n\n<pre><code>function groupBy( array , f )\n{\n var groups = {};\n array.forEach( function( o )\n {\n var group = JSON.stringify( f(o) );\n groups[group] = groups[group] || [];\n groups[group].push( o ); \n });\n return Object.keys(groups).map( function( group )\n {\n return groups[group]; \n })\n}\n\nvar result = groupBy(list, function(item)\n{\n return [item.lastname, item.age];\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T14:06:19.523",
"Id": "37132",
"ParentId": "37028",
"Score": "64"
}
},
{
"body": "<p>Another way to do it is to use <a href=\"https://lodash.com/docs#groupBy\" rel=\"nofollow noreferrer\">_lodash.groupBy</a> or <a href=\"https://lodash.com/docs#keyBy\" rel=\"nofollow noreferrer\">_lodash.keyBy</a>:</p>\n\n<ol>\n<li><p>You will only have to write few lines of code to achieve same result:</p>\n\n<pre><code>const Results = _.groupBy(list, 'lastname')\n</code></pre>\n\n<p>This will group your results by last name. However in your case you need to group by multiple properties - you can use <a href=\"https://stackoverflow.com/questions/10022156/underscore-js-groupby-multiple-values/13869056#13869056\">this snippet</a> to enchant this function.</p></li>\n<li><p>Of course you can use this code multiple times.</p></li>\n<li>Lodash allows you to install its modules one-by-one (npm i lodash.groupby);</li>\n</ol>\n\n<p>I believe in this way you will get shorter, more maintainable code with clear functions. I guess this is an alternative.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-03T10:04:05.023",
"Id": "226807",
"Score": "0",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-03T10:05:07.250",
"Id": "226808",
"Score": "0",
"body": "It might not be a code solution, but right now you don't have any explanation for **why** those functions should be used, other than \"simply clean code\", which doesn't explain anything."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-03T09:30:00.327",
"Id": "121766",
"ParentId": "37028",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37132",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T11:44:11.493",
"Id": "37028",
"Score": "62",
"Tags": [
"javascript",
"sorting",
"properties"
],
"Title": "Grouping elements in array by multiple properties"
}
|
37028
|
<p>I need to write code for the given problem:</p>
<p>I'm provided with a word and I need to find all the possible combination of it that matches with a given list of words in a file.</p>
<p>Here's my code. Can I make it much better? I'm sure it can be done. Please offer suggestions.</p>
<pre><code>dict = {}
file = open("/usr/share/dict/words", "r")
for word in file: #Iterate through every word in the dictionary
word = word.strip().lower() #Strip newlines and send to lowercase
sorted_word = ''.join(sorted(word)) #Alphabetically sort the word
if sorted_word in dict: #Check if sorted_word is already a key
if word not in dict[sorted_word]: #Make sure word is not already in the list under the key sorted_word
dict[sorted_word].append(word) #Add to list under the key sorted_word
else: #If not in dictionary
dict[sorted_word] = [word] #Create new list with one entry
while(True): #Loop until quit is typed
jumble = raw_input("Enter a jumble to decode or 'quit': ") #Get input
jumble = jumble.lower() #Send jumble to lower
if(jumble == "quit"): #Quit if quit is typed
break
jumble = ''.join(sorted(jumble)) #Sort jumble alphabetical
if jumble in dict: #If sorted jumble exists in dictionary
results = dict[jumble] #Get list of words that match jumble
for result in results: #Loop through list printing results
print result, #Trailing , designates that there should be a space between entries
print "" #Print newlines
else: #Jumble not found in dictionary print message
print "Results for jumble not found"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:40:13.640",
"Id": "60990",
"Score": "0",
"body": "You may want to handle some special characters, like apostrophe, more directly. It's quite possible that you'd want to let `sit` find anagrams including both `its` and `it's`, and your code will not do so."
}
] |
[
{
"body": "<p>Hum, first of all, there are way too many comments. People simply won't read them, you should only keep the meaningful ones. For example, you could remove:</p>\n\n<pre><code>if sorted_word in dict: #Check if sorted_word is already a key\n</code></pre>\n\n<p>Anybody who knows how Python dictionaries work will know what this lign is doing, the code is explicit by itself. Instead of always repeating what your <code>dict</code> is doing, you should just explain once what it does when you declare it; the code will tell the rest. You should only explain once at the beginning how your algorithm work and let your code tell the rest. Honestly, you could remove almost <strong>all</strong> of your comments. Python is designed to be readable and it is.</p>\n\n<p>Second point, avoid to name a variable <code>dict</code>: it is already the name of a built-in type. It's bad pratice and can be confusing for people who will try to read your code.</p>\n\n<p>Also, you open your file once, but never close it. You should close it once you have filled your <code>dict</code>. You could use the <code>with open('...', 'r') as f:</code> construct to have your file closed automatically at the end of the <code>with</code> block, therefore, you won't even have to remember to close it. Also, <code>file</code>, like <code>dict</code> is also the name of a built-in type in Python, find another name :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:31:36.493",
"Id": "60989",
"Score": "0",
"body": "100% agreed about too many comments. My general advice here is similar to yours: the lines of code themselves tell the tiny details, so instead find blocks of code and explain what they accomplish together. E.g. \"Create a mapping from the sorted characters of a word to all the words made from those characters\" for the first block; and \"Look up and print all words created using all the same characters entered\" for the second block."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:03:12.060",
"Id": "37037",
"ParentId": "37034",
"Score": "6"
}
},
{
"body": "<p>On top of the comments from Morwenn : <code>setdefault</code> and <code>join</code> will do exactly what you want to do and make your code more expressive.</p>\n\n<p>Here what your code can become :</p>\n\n<pre><code>#!/usr/bin/python\n\nsorted_words = {}\n\nwith open(\"/usr/share/dict/words\", \"r\") as f:\n for word in f:\n word = word.strip().lower()\n sorted_word = ''.join(sorted(word))\n sorted_words.setdefault(sorted_word,[]).append(word)\n\nwhile True:\n jumble = raw_input(\"Enter a jumble to decode or 'quit': \").lower()\n if jumble == \"quit\":\n break\n sorted_jumble = ''.join(sorted(jumble))\n if sorted_jumble in sorted_words:\n print \", \".join(sorted_words[sorted_jumble])\n else:\n print \"Results for jumble not found\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:25:40.533",
"Id": "60987",
"Score": "2",
"body": "Big +1; I was halfway through writing a response with the same advice. However there is one important behavior change with the above: it doesn't filter duplicate words (say from a bad dictionary file). I was going to suggest `set` instead of `list` for this, but that changes the order printed later. Note as well that `collections.defaultdict(list)` lets you just call `sorted_words[sorted_word].append(word)`. There's also one typo change: use `\", \".join` to keep the spacing between resulting words."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:28:48.840",
"Id": "60988",
"Score": "0",
"body": "Thanks for pointing this out. I've edited my answer. As for the set, it completely went out of my mind. Given the source for words, I don't know if it is a big deal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:25:53.727",
"Id": "60999",
"Score": "0",
"body": "I agree with Michael Urman: [`collections.defaultdict`](http://docs.python.org/3/library/collections.html#collections.defaultdict) is clearly indicated here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:21:34.300",
"Id": "37041",
"ParentId": "37034",
"Score": "6"
}
},
{
"body": "<p>One thing to consider: by using <code>quit</code> as a magic word, you cannot look up anagrams of it. One approach you could use to enable looking up anagrams of <code>quit</code> is to instead loop until EOF (typically input by pressing ctrl+d or ctrl+z enter) by using something like this:</p>\n\n<pre><code>while True:\n try:\n jumble = raw_input(\"Enter a jumble to decode: \")\n except EOFError:\n break\n ...\n</code></pre>\n\n<p>Alternately you could exit on an empty string, which of course has no anagrams.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:39:53.187",
"Id": "37043",
"ParentId": "37034",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T13:08:51.303",
"Id": "37034",
"Score": "4",
"Tags": [
"python",
"algorithm"
],
"Title": "Jumble solver algorithm"
}
|
37034
|
<p>The goal of this code was to create a table from an associative array.</p>
<ul>
<li>I need to create horizontal rows where the keys need to be used as "headers" while the values are posted below each header. </li>
<li>I need to be able to reuse the code with associative arrays of unknown lengths and varying number of columns allowed in the tables.</li>
</ul>
<p>I realize this is not set up as a function. I'm just playing with the code for now.</p>
<p>The code that I have actually does work. I'm not sure if it's "proper" form especially here - <code>$startIndex = $index</code> in the for loop.</p>
<p>I create two rows at a time - one for the header, one for the values. After the end of these two rows, I'm re-setting the index on the for loop so it runs through the next group in the array. I'm trying to get better at coding and would like some input on what I've done. </p>
<pre><code> <h2>Print out a horizontal table with a capability to vary the number of cells across</h2>
<table class="<?php echo $tableClass; ?>">
<caption>Horizontal</caption>
<?php
$array = array(
"A" => 1,
"B" => 2,
"C" => 3,
"D" => 4,
"E" => 5,
"F" => 6,
"G" => 7,
"H" => 8,
"I" => 9,
"J" => 10,
"K" => 11,
"L" => 12,
"M" => 13
);
$maxColumns = 8;//set the number of columns allowed in the table
$arrayOfKeys = array_keys($array);//grab the keys from the initial array
$count = count($arrayOfKeys);//gets a count of the number of items in the array
$maxRows = ceil($count/$maxColumns) * 2;//takes the count and determines the number of rows based on the number of items and the maxColumns * 2 for total rows (need a "header" and value for each set of keys/values in the array
$endIndex = $maxColumns-1;//initialize the endIndex on the loop that runs the
$startIndex = 0;//initialize the start index for the second loop which will loop through the array assigning keys to first row - value to second
for ($row=1; $row<=$maxRows; $row++){//loops based on the number of rows required to generate the table for the number of cells required
echo '<tr>';//start the row
$rowEvenOdd = ($row % 2); //figures whether an even or odd row
for ($index=$startIndex; $index<=$endIndex; $index++){//creates the rows
if($rowEvenOdd == 1) {//if the row is odd, grab and display the key
if(array_key_exists($index, $arrayOfKeys))
{$thiskey = $arrayOfKeys[$index];}
else {$thiskey ="&nbsp;";}
echo "<td>$thiskey</td>";
}//end of odd rows
if($rowEvenOdd == 0) {//if the row is even, grab and display the value
if(array_key_exists($index, $arrayOfKeys))
{$thisvalue = $array[$arrayOfKeys[$index]];}
else {$thisvalue ="&nbsp;";}
echo "<td>". $thisvalue ."</td>";
}//end of odd rows
}//end of loop to generate content for the cells
echo '</tr>';//end the row
if($rowEvenOdd == 0) {$startIndex = $index; $endIndex = $index + $maxColumns-1;/* reset the index begin and end to loop through next group of rows */ }
}//end loops that creates the rows
?>
</table>
</code></pre>
|
[] |
[
{
"body": "<p>Use <a href=\"http://www.php.net/manual/en/function.array-chunk.php\" rel=\"nofollow\"><code>array_chunk()</code></a> to split <code>$rows</code> into rows. Each <em>row</em> will be double high <code>$doubleRows</code>, so store the values in a small multi-dimension array <code>$tablerows</code> before echoing the rows.</p>\n\n<pre><code>// One single row.\n$rows = array(\n \"A\" => 1,\n \"B\" => 2,\n \"C\" => 3,\n \"D\" => 4,\n \"E\" => 5,\n \"F\" => 6,\n \"G\" => 7,\n \"H\" => 8,\n \"I\" => 9,\n \"J\" => 10,\n \"K\" => 11,\n \"L\" => 12,\n \"M\" => 13\n);\n\n// Split into 1 or more rows of 8 columns each.\n$doubleRows = array_chunk( $rows, 8, true );\n\n// Rows are now double high.\n// Keys on the first row and values on the second.\nforeach ( $doubleRows as $columns ) {\n\n // Reset rows.\n $tableRows = array();\n foreach ( $columns as $key => $value ) {\n $tableRows['keys'][] = \"<td>$key</td>\";\n $tableRows['values'][] = \"<td>$value</td>\";\n }\n\n echo \"<tr>\", join( '', $tableRows['keys'] ), \"</tr>\";\n echo \"<tr>\", join( '', $tableRows['values'] ), \"</tr>\";\n}\n</code></pre>\n\n<p><strong>Style</strong></p>\n\n<p>You used a lot of end comments. I try to avoid them and I try to avoid obvious comments like, <code>// Start the row</code>. To me, the <code><tr></code> tag is pretty self explanatory, but if it is not to you, then I understand why you did it.</p>\n\n<p>Wrap long comments and use proper punctuation and capitalization. Comments are for humans. PHP strips them out. If you are the only person who ever sees your code, write your comments for the (different) person you will be in six months. The future you may appreciate comments that look like sentences and paragraphs. </p>\n\n<p>Be consistent with your indentation and white space. Always indent the same number of characters. This <code>foreach</code> is indented 4 spaces (or 1 tab). The conditional statement is indented 12 spaces (or 3 tabs).</p>\n\n<pre><code> for ($index=$startIndex; $index<=$endIndex; $index++){//creates the rows\n if($rowEvenOdd == 1) {//if the row is odd, grab and display the key\n</code></pre>\n\n<p>I would write it like this:</p>\n\n<pre><code> // Create table rows.\n for ( $index = $startIndex; $index <= $endIndex; $index++ ) {\n if ( $rowEvenOdd == 1 ) {\n // Row is odd. Grab and display the key.\n</code></pre>\n\n<p>I added some white space so it wouldn't look all scrunch up. I find it easier to read like that. The comment after the conditional tells you what the condition is instead of what the conditional does.</p>\n\n<p>If this is your style for writing one line conditionals, I guess it is fine, but it looks scrunch up and harder to read.</p>\n\n<pre><code>if(array_key_exists($index, $arrayOfKeys))\n {$thisvalue = $array[$arrayOfKeys[$index]];}\n else {$thisvalue =\"&nbsp;\";}\n</code></pre>\n\n<p>I prefer this:</p>\n\n<pre><code>if ( array_key_exists( $index, $arrayOfKeys ) ) {\n $thisvalue = $array[$arrayOfKeys[$index]];\n} else {\n $thisvalue =\"&nbsp;\";\n}\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>if ( array_key_exists( $index, $arrayOfKeys ) )\n $thisvalue = $array[$arrayOfKeys[$index]];\nelse\n $thisvalue =\"&nbsp;\";\n</code></pre>\n\n<p>I tend to not add white space near brackets <code>[]</code> and to add it in parenthesis <code>()</code>.</p>\n\n<p>Except for <code>$thisvalue</code> and <code>$thiskey</code> all your variable name use camel case. <code>$thisValue</code> and <code>$thisKey</code> would be more consistent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:47:21.810",
"Id": "37091",
"ParentId": "37035",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T13:16:32.183",
"Id": "37035",
"Score": "2",
"Tags": [
"php"
],
"Title": "Using a variable in a for loop: is it proper practice or is there a better approach"
}
|
37035
|
<p>Assume the server is sending data to our app at regular intervals, at least once per second. The received data is parsed and stored in memory as a POJO. A blocking queue is processing data in a worker thread.</p>
<p>Suppose I want to use a very simple object pool, so I don’t have to create a new POJO for each server response. I don’t want to use e.g. Apache Commons Pool.</p>
<p>Would the following implementation suffice? </p>
<pre><code>public abstract class ObjectPool<T> {
private final Stack<T> mPool;
public ObjectPool() {
mPool = new Stack<T>();
}
public T obtain() {
if (mPool.isEmpty()) {
return create();
} else {
return mPool.pop();
}
}
public void recycle(T object) {
if (null != object) {
destroy(object);
mPool.push(object);
}
}
public void clear() {
mPool.clear();
}
public int getSize() {
return mPool.size();
}
protected abstract T create();
protected abstract void destroy(T object);
}
</code></pre>
<p>Can I shoot myself in the foot using this? Any caveats I’m not seeing? </p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>I have to question whether this makes any sense in your application:</p>\n<blockquote>\n<p>Assume the server is sending data to our app at regular intervals, at least once per second</p>\n</blockquote>\n<p>Have you done any testing/metrics that indicate that the current system you have is actually a problem? I would be very surprised if it is.</p>\n<p>If the server is sending data as infrequently as that, there does not seem to be any reason to 'pool' the objects at all. The overhead of 'cleaning' an instance, storing it, recycling it, repopulating it, and repeating with it is probably just as overwhelming as simply creating a new instance and GC'ing the old one.</p>\n<p>Unless you can already identify 'specifically' that object creation is a significant part of an existing performance problem, I would suggest that you are looking in the wrong places for performance improvements.</p>\n<h1>EDIT - hypothetically...</h1>\n<p>Answering hypothetically: no, I don't believe your solution is enough...</p>\n<ul>\n<li>by the time you get to the frequency where object creation/reuse is a problem, you will be needing multiple concurrent threads to do the work anyway, and your solution is not synchronized (by the way, <code>new</code> and GarbageCollection <strong>are</strong> thread-safe)</li>\n<li>You have created an artificial latency in your program flow - see <a href=\"http://en.wikipedia.org/wiki/Amdahl%27s_law\" rel=\"nofollow noreferrer\">Ahmdahl's law</a> .. by <strong>adding</strong> to the critical path instead of taking work off the path (parallelizing things). As your system gets busier, you are making the problem <strong>worse</strong> and not better.</li>\n</ul>\n<p>Bottom line, is that, at low volumes your current solution is not going to make a difference, and that at high frequencies, your solution is only going to make things worse.</p>\n<p>One other thing to consider, and Android performance is not my strength, but on 'full' computers (I often work with systems with more than 128 cores in highly-threaded systems), the cost of having to bring the stack in to your system cache, and then replace it with the cache of your object is probably going to be more than just creating a new object would... Again, the more busy your system, the more this sort of issue 'hurts'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:54:26.603",
"Id": "60993",
"Score": "0",
"body": "You are right - brief tests show the current system is performing OK. The reason I’m asking is because the frequency could pick up at any time, growing at a polynomial rate. With older devices we support, this might be a problem. For the sake of argument, let’s assume pooling would be required. Would my implementation be enough?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:07:06.553",
"Id": "60996",
"Score": "0",
"body": "@curtisLoew - added an edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:40:16.723",
"Id": "37044",
"ParentId": "37040",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37044",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:20:31.700",
"Id": "37040",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "Simple object pool on Android"
}
|
37040
|
<p>Being new to raw JavaScript, intervals and times this was not the easiest script to come up with, and thus, although it seems to be working as I want it too the code looks very clunky.</p>
<p>The timer counts down to one of 4 times of day: 8am, 2pm, 8pm or 2am depending on which is the closest. Because they are at six hour intervals there can either be one or a maximum of 2 times that are currently in the future.</p>
<p>Can anyone suggest improvements to the code and how I might be able to make it more dynamic (more than 4 times of day for example)?</p>
<pre><code> <?php
// define times to count down to and the time now
$time1 = strtotime(gmdate("08:00:00")).'<br />';
$time2 = strtotime(gmdate("14:00:00")).'<br />';
$time3 = strtotime(gmdate("20:00:00")).'<br />';
$time4 = strtotime(gmdate("02:00:00")).'<br />';
$timeNow = strtotime('now').'<br />';
// Get the difference between times
echo $dif1 = $time1 - $timeNow.' 1<br>';
echo $dif2 = $time2 - $timeNow.' 2<br>';
echo $dif3 = $time3 - $timeNow.' 3<br>';
echo $dif4 = $time4 - $timeNow.' 4<br>';
?>
<script type="text/javascript">
// 4 reboot times
var time1 = "<?php echo $time1;?>"; // 8am
var time2 = "<?php echo $time2;?>"; // 2pm
var time3 = "<?php echo $time3;?>"; // 8pm
var time4 = "<?php echo $time4;?>"; // 2am
// time differences
var dif1 = parseInt("<?php echo $dif1;?>");
var dif2 = parseInt("<?php echo $dif2;?>");
var dif3 = parseInt("<?php echo $dif3;?>");
var dif4 = parseInt("<?php echo $dif4;?>");
// count how many times are above zero
var countDif = 0;
// Check whether the time differences are above 0 (in the future)
if(dif1>0){
countDif = countDif+1;
}
if(dif2>0){
countDif = countDif+1;
}
if(dif3>0){
countDif = countDif+1;
}
if(dif4>0){
countDif = countDif+1;
}
// if there is only one time in the future check which 1 it is
if(countDif == 1){
if(dif1>0){
// set countdown to this time difference
var secs = dif1;
}else if(dif2>0){
// set countdown to this time difference
var secs = dif2;
}else if(dif3>0){
// set countdown to this time difference
var secs = dif3;
}else if(dif4>0){
// set countdown to this time difference
var secs = dif4;
}
// run the timer
var counter1=setInterval(timer, 1000); //1000 will run it every 1 second
// if there are two counters in the future (max of two with 6 hour interval timers) check which two
}else if(countDif > 1){
// check if dif 1 is greater than zero
if(dif1>0){
//check if dif2 2 is greater than zero
if(dif2>0){
// check if dif1 is less than dif2
if(dif1<dif2){
// set countdown to this time difference
var secs = dif1;
}else{
// set countdown to this time difference
var secs = dif2;
}
}else if(dif3>0){
// check if dif1 is less than dif3
if(dif1<dif3){
// set countdown to this time difference
var secs = dif1;
}else{
// set countdown to this time difference
var secs = dif3;
}
}else if(dif4>0){
// check if dif1 is less than dif4
if(dif1<dif4){
// set countdown to this time difference
var secs = dif1;
}else{
// set countdown to this time difference
var secs = dif4;
}
}
}else if(dif2>0){
//check if dif2 2 is greater than zero
if(dif3>0){
// check if dif1 is less than dif2
if(dif2<dif3){
// set countdown to this time difference
var secs = dif2;
}else{
// set countdown to this time difference
var secs = dif3;
}
}else if(dif4>0){
// check if dif1 is less than dif3
if(dif2<dif4){
// set countdown to this time difference
var secs = dif2;
}else{
// set countdown to this time difference
var secs = dif4;
}
}
}else if(dif3>0){
//check if dif2 2 is greater than zero
if(dif4>0){
// check if dif1 is less than dif2
if(dif3<dif4){
// set countdown to this time difference
var secs = dif3;
}else{
// set countdown to this time difference
var secs = dif4;
}
}
}
// run the timer
var counter1=setInterval(timer, 1000); //1000 will run it every 1 second
}
var a = 10;
function timer()
{
if(secs == 0){
//clearInterval(counter1);
var announce=setInterval(announcement,1000);
counter=setInterval(timer, 1000); //1000 will run it every 1 second
}else{
var dh1 = Math.floor(secs/3600) % 24;
var dm1 = Math.floor(secs/60) % 60;
var ds1 = secs % 60;
secs=secs-1;
document.getElementById("timer").innerHTML=dh1+"hrs "+dm1+"mins "+ds1+"secs "+"("+secs+")";
}
}
function announcement()
{
if(a==0){
clearInterval(announce);
}else{
a=a-1;
document.getElementById("timer").innerHTML="Server is rebooting...";
}
}
</script>
<span id="timer"></span>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Because they are at six hour intervals there can either be one or a maximum of 2 times that are currently in the future.</p>\n</blockquote>\n\n<p>True, <em>BUT</em> there is still only 1 hour that is closes</p>\n\n<p>This should do the same thing, and you could add more hours to the <code>hours</code> array.</p>\n\n<p>What it will do is take the current hour (as of this writing: 16), compare it with the <code>hours</code> array and find whats next (in this case: 20), and then we start an interval which will check the time every 1 second.</p>\n\n<pre><code>var hours = [ 2, 8, 14, 20 ];\nvar currentHour = new Date().getHours();\nvar targetHour = 0;\n\nfor(var i = 0; i < hours.length; i++) {\n if(hours[i] > currentHour) { targetHour = hours[i]; break; }\n}\n\nvar intervalID = setInterval(function() {\n console.log(\"running timer...\");\n if(new Date().getHours() == targetHour) {\n alert(\"done\");\n //\n /* Here goes your logic for what should happen when your target hour hits */\n // \n clearInterval(intervalID); //stop the interval once the hour has been hit \n }\n}, 1000);\n</code></pre>\n\n<p><strong>edit</strong></p>\n\n<p>As Simon pointed out we need a way to either break out of the interval once the targeted hour has been hit or we need to make sure that the scope of <code>if(new Date().getHours() == targetHour)</code> is not executed every second once the targeted hour has been hit. In this case we invoke <code>clearInterval</code> on the interval ID returned by <code>setInterval</code>, effectively killing the interval.</p>\n\n<p>Another alternative would be to use a <code>var targetHourHit = false</code> variable and only execute the scope of the <code>if</code> when our variable is false, and at the end set our variable to true. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:33:50.177",
"Id": "61000",
"Score": "1",
"body": "I'd rather not see the same alert message once every second for one hour. But you're on the right track."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:35:05.807",
"Id": "61001",
"Score": "0",
"body": "@SimonAndréForsberg I'd rather not see an alert at all, or rarely - but it's a simple way of conveying a message to an user and it's a simple way of distinguishing when a unique or rare conditional has been met."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:40:16.213",
"Id": "61005",
"Score": "0",
"body": "This is great @Max thanks I assume I can use the same date class to easily display the current minutes and seconds, the same way you used `gethours`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:42:51.653",
"Id": "61006",
"Score": "0",
"body": "@SimonAndréForsberg - Oh, I see your point now... Yeah, you're right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:43:24.140",
"Id": "61007",
"Score": "0",
"body": "@crm - Yes you can! Check out http://www.w3schools.com/jsref/jsref_obj_date.asp for all functions in the Date object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:43:41.030",
"Id": "61008",
"Score": "0",
"body": "My point was that the way I see it, your code here will call some code once every second for an entire hour, while the original.... (sees that there is 1 new comment) yeah, exactly..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:52:41.317",
"Id": "61012",
"Score": "0",
"body": "@Max w3schools are also known as [w3fools](http://www.w3fools.com), when referencing to JavaScript references it is better to use an official documentation such as [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T16:13:57.833",
"Id": "61015",
"Score": "0",
"body": "So to display an actual count down do I put an `else` for when the current time doesn't match the targethour? and calculate the tiem difference in seconds here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T16:27:07.110",
"Id": "61017",
"Score": "0",
"body": "How can I account for GMT times using this date object?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T07:40:25.280",
"Id": "61153",
"Score": "0",
"body": "@crm - No, there may be that you don't need an `else` depending on what you want to do. You should give it a try and either update this post or create a new post. Let's see how you would implement it and we'll guide you along the way! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T07:41:20.940",
"Id": "61154",
"Score": "0",
"body": "@SimonAndréForsberg - <lazy>yupp I know, but it was the first link...</lazy>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T02:43:27.960",
"Id": "61310",
"Score": "0",
"body": "I recommend using `>` instead off `==` in `new Date().getHours() == targetHour` in case the browser pause the timer in background, and you may want the code to trigger even if it's delayed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:01:11.880",
"Id": "61325",
"Score": "0",
"body": "@Vitim.us - If I do that, then it won't trigger on the same hour. I could use `>=`, but it still means it will trigger on the same hour regardless of what minute. If it delays more than an hour there is something else that is wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T17:00:41.827",
"Id": "61407",
"Score": "0",
"body": "Yeah I meant `>=` your computer can always go to sleep or something, and when you wake it up, you should see the notification there."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:30:21.710",
"Id": "37049",
"ParentId": "37047",
"Score": "4"
}
},
{
"body": "<p>Adding to the things Max wrote, to make sure that you don't make the same mistakes again I wanted to point out several things regarding your current code:</p>\n\n<ul>\n<li>You're using both PHP and JavaScript. Why I am not exactly sure. You should be able to do everything with JavaScript only.</li>\n<li>You're <code>time</code> variables gets set to strings, with an additional HTML <code><br /></code> element. Then you're setting them to JavaScript variables. The JavaScript <code>time</code> variables are unused</li>\n<li>Your PHP <code>dif</code> variables are set to a string in PHP and then Parsed as an integer in JavaScript. Use only an integer variable and use it as part of an <code>echo</code> instead.</li>\n<li>If the time is <code>01:00:00</code>, won't all four times be in the future?</li>\n<li>You are using four numbered variables for each thing, the next time you find yourself doing this think: Would using an array help here? Most often the answer is yes.</li>\n<li><p>Whenever you write messy code like the <code>if(countDif > 1)</code> part, you are bound to miss a case, or forget to update one when you make a change, which is very likely to cause bugs. Since you wanted to get the lowest positive value, you could instead use this code:</p>\n\n<pre><code>var lowest = 2000000000; // initialize to a very high value\nif ((dif1 > 0) && (dif1 < lowest)) lowest = dif1;\nif ((dif2 > 0) && (dif2 < lowest)) lowest = dif2;\nif ((dif3 > 0) && (dif3 < lowest)) lowest = dif3;\nif ((dif4 > 0) && (dif4 < lowest)) lowest = dif4;\n</code></pre>\n\n<p>However, it is of course a lot better to use an array, as Max has used in his answer.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T15:50:58.040",
"Id": "37050",
"ParentId": "37047",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37049",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:52:53.063",
"Id": "37047",
"Score": "1",
"Tags": [
"javascript",
"php",
"timer"
],
"Title": "Countdown timer"
}
|
37047
|
<p><em>This is a copy of <a href="https://stackoverflow.com/questions/20498825/converting-a-32bit-number-in-a-proprietary-timestamp-with-php">a posting I made on SO</a>, it was suggested I post it here all I've changed from that post is I'm now doing the bitwise AND using a decimal number rather than using bindec("111") to create the mask. The output is identical.</em></p>
<p>I have a 32 bit number represented as a HEX string that I need to convert to a timestamp following these rules:</p>
<p><img src="https://i.stack.imgur.com/aPH8Y.png" alt="Timestamp specification"></p>
<p>What I want to check is that I'm not doing something glaringly stupid? Does my conversion look sane given the timestamp specification? </p>
<p>I've put together the following code to do this. I know PHP isn't the best for this sort of work but it's part of a larger legacy application all written in PHP.</p>
<p><code>$t</code> is taken from an XML file of readings, one every 5 mins.</p>
<pre><code> // convert the hex string to a string representation of the binary number
// sprintf pads leading zeros, for debugging only
$binStr = sprintf('%032s', base_convert($t, 16, 2));
//get a decimal representation so we can use the bitwise operator on it
$decimal = base_convert($t, 16, 10);
// get the first 6 bits
$min = $decimal & 63; // 111111 in binary
// drop the first 8 bits then apply a mask to the next 5
$hour = ($decimal >> 8) & 31; // 11111 in binary
// drop the first 15 bits then apply a mask to the next 1
$daylightSaving = ($decimal >> 15) & 1;
// etc
$day = ($decimal >> 16) & 31; // 11111
$yearLsb = ($decimal >> 21) & 7; //111
$month = ($decimal >> 24) & 15; //1111
$yearMsb = ($decimal >> 28) & 15; //1111
Logger::debug(
"Incoming timestamp " . $t . " \n" .
" (as binary " . $binStr . ") converted to: \n" .
" Day: " . $day . "\n" .
" Month: " . $month . "\n" .
" Year: " . $yearMsb . $yearLsb . "\n" .
" Hour: " . $hour . "\n" .
" Min: " . $min . "\n" .
" Daylight saving: ". $daylightSaving
);
</code></pre>
<p>The output for the last entry in the file is:</p>
<pre><code>Incoming timestamp 2DAC1B0A
(as binary 00101101101011000001101100001010) converted to
Day: 12
Month: 13
Year: 25
Hour: 27
Min: 10
Daylight saving: 0
</code></pre>
<p>I know the file was created at 11:25am on the 12th Nov 2013, the readings are for 11:10 to 11:25 with the last one in the file being the 11:10am one.</p>
<p>The mins match those in the file I get 10 through 25 in 5 min increments. The day is also accurate if I run it against other files.</p>
<p>There's a chance that the equipment manufacturer who wants us to purchase some expensive software to do this parsing has munged the timetamp specification but that being an option I've played with lots of possible combinations in that 32bit integer and I can't see how I can get all the numbers I require from the supplied timestamps.</p>
|
[] |
[
{
"body": "<p>Not being a PHP expert, but messing with bitwise operations a lot, I have some advice for you:</p>\n\n<p>First, the specification for your operations <strong>should be embedded with the code</strong> as a comment. Having to look up a specification that may or may not be the same as the one you used when programming it, is not useful... and changing between screens/pages to inspect the code vs. the specification is also not much fun. Something like:</p>\n\n<pre><code>// Input data is 4 bytes with following bit-specification:\n// Byte0 (least significant)\n// 0-5 : minutes\n// 6 : reserved\n// 7 : valid\n// Byte1\n// 0-4 : hours\n// ........\n</code></pre>\n\n<p>This makes it easier to compare/validate your code.</p>\n\n<p>My next suggestion is to shift the data as you pull values off... This way you don't need to do 'brain-mushing' thinking when doing the manipulation.</p>\n\n<pre><code>// get the first 6 bits\n$min = $decimal & 63; // 111111 in binary\n$decimal = $decimal >> 6; // get rid of those 6 bits,\n // now we only need to worry about low bits.\n</code></pre>\n\n<p>Then, the next suggestion is to set up some 'constants' for your masks:</p>\n\n<pre><code>$mask6bits = (1 << 6) - 1; // 00111111 in binary.\n</code></pre>\n\n<p>Now, the example above becomes:</p>\n\n<pre><code>// get the first 6 bits\n$min = $decimal & mask6bits;\n$decimal = $decimal >> 6; // shift off minutes\n</code></pre>\n\n<p>Then, I recommend you process the fields you don't need, and it helps you keep track of the specification:</p>\n\n<pre><code>// get the first 6 bits\n$min = $decimal & mask6bits;\n$decimal = $decimal >> 6; // shift off minutes\n\n$decimal = $decimal >> 1; // shift off reserved\n\n$decimal = $decimal >> 1; // shift off valid\n\n$hours = $decimal & mask5bits;\n$decimal = $decimal >> 5; // shift off the hours.\n</code></pre>\n\n<p>Follow the same pattern for the other bits...</p>\n\n<p>This is a relatively concise way to do things, actually, and you only need to keep one 'dimension' (the length of each data value) of the problem in your head, and you can ignore the offset.</p>\n\n<p>This leads to fewer bugs, and better understanding and readability.</p>\n\n<p>I cannot find a definitive reference whether PHP supports a definitive <code>>>=</code> assignment operator. If it does, the lines <code>$decimal = $decimal >> 5</code> can be replaced with <code>$decimal >>= 5</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T17:10:48.630",
"Id": "61022",
"Score": "0",
"body": "@rolfi thanks, great response. I already have the comment at the start of my method like you suggest, documenting the integer's make-up, but your other points I'll definitely take on board and apply. I'm starting to suspect that the timestamp doesn't follow this rule and it's a proprietary make-up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:20:08.503",
"Id": "61036",
"Score": "0",
"body": "I'm new to CR so after reading the About page for the site I'm marking this as an answer: I've been given assistance on improving my code both for my sake and any future maintainers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T17:02:33.820",
"Id": "37057",
"ParentId": "37051",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37057",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T16:06:28.253",
"Id": "37051",
"Score": "4",
"Tags": [
"php"
],
"Title": "Converting a 32bit number in a proprietary timestamp with PHP"
}
|
37051
|
<p>Think of a set of text lines starting with a common string, e.g. indented code.</p>
<pre><code>my $preamble = reduce {
my $len = min(length $a, length $b);
--$len while substr($a, 0, $len) ne substr($b, 0, $len);
return substr($a, 0, $len);
} @lines;
</code></pre>
<p>Note that after the first invocation chances are high that <code>$a</code> already has the final result.</p>
<p>I'm wondering if there is a better approach in comparing the two strings in the reduce block. The while loop does not seem to be the best approach. It's also less readable since it does not convey the intent of the code (find common preamble of <code>$a</code> and <code>$b</code>).</p>
<p><strong>Update:</strong>
After feedback from amon here is an alternative:</p>
<pre><code>my $preamble = reduce {
my $len = min(length $a, length $b);
my ($current_prefix, $string) = (substr($a, 0, $len), substr($b, 0, $len));
while($current_prefix ne $string) {
chop $current_prefix;
chop $string;
}
return $current_prefix;
} @lines;
</code></pre>
<p>I think this is an improvement in both performance and readability.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T17:23:30.453",
"Id": "61023",
"Score": "1",
"body": "Can you provide `@lines` and `$preamble` sample?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T19:31:04.340",
"Id": "61059",
"Score": "0",
"body": "Here is an example: http://ideone.com/3UVfcm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T22:10:01.300",
"Id": "61102",
"Score": "0",
"body": "Instead of starting from right side of the string (and then choping), you can start from left side of it. It will make fewer while loops when `$preamble` is shorter string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:31:06.103",
"Id": "61227",
"Score": "0",
"body": "@mpapec I agree, I'd still like to find a better solution there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:56:40.213",
"Id": "61233",
"Score": "0",
"body": "If performance is absolute requirement, replace `reduce` with foreach equivalent."
}
] |
[
{
"body": "<p>First of all, I think it is very good that you used <code>reduce</code>, as it clearly shows how the algorithm works. At least, to a reader who understands functional idioms.</p>\n\n<p>One problem in your code is that you keep using <code>$a</code> and <code>$b</code>. These two names do not convey any meaning. We could do instead:</p>\n\n<pre><code>my $prefix = reduce {\n my ($current_prefix, $string) = ($a, $b);\n ...\n</code></pre>\n\n<p>Then, I would shorten the <code>$current_prefix</code> until it is at the beginning of the other <code>$string</code>:</p>\n\n<pre><code>until (0 == index $string, $current_prefix) {\n chop $current_prefix;\n}\n</code></pre>\n\n<p>I did not use the statement modifier form of <code>until</code> or <code>while</code> – I don't believe that they make code much easier to read the way a postfix <code>if</code> or <code>for</code> can do. Note that the empty string occurs at the beginning of <em>any</em> string, so the termination condition of that loop is safe.</p>\n\n<p>If you do not like <code>index</code> or <code>chop</code>, you could equivalently use the less efficient</p>\n\n<pre><code>until ($string =~ /\\A\\Q$current_prefix/) {\n $current_prefix =~ s/.\\z//s;\n}\n</code></pre>\n\n<p>Either way, the concept of shortening the prefix by removing one character at a time until it fits should be easier to read than all the <code>substr</code>inging you used.</p>\n\n<p>Cutting the prefix to the length of the string would just be an optimization:</p>\n\n<pre><code>$current_prefix = substr $current_prefix, 0, length $string;\n</code></pre>\n\n<p>Put together, we would get the following code:</p>\n\n<pre><code>my $prefix = reduce {\n my ($current_prefix, $string) = ($a, $b);\n\n # the prefix cannot be longer than the string\n $current_prefix = substr $current_prefix, 0, length $string;\n\n # remove characters from the prefix until it occurs at the beginning.\n # \"\" is always a prefix, so the loop properly terminates.\n until (0 == index $string, $current_prefix) {\n chop $current_prefix;\n }\n\n return $current_prefix;\n} @strings;\n</code></pre>\n\n<p>The code might be easier to understand for people who don't know <code>reduce</code> if you express it in the imperative form:</p>\n\n<pre><code>my ($prefix, @strings) = @original_strings;\nfor my $string (@strings) {\n # the prefix cannot be longer than the string\n $prefix = substr $prefix, 0, length $string;\n\n # remove characters from the prefix until it occurs at the beginning.\n # \"\" is always a prefix, so the loop properly terminates.\n until (0 == index $string, $prefix) {\n chop $prefix;\n }\n}\n# now $prefix is the prefix of all @original_strings\n</code></pre>\n\n<p>Oh look, it's shorter too!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:41:12.460",
"Id": "61075",
"Score": "0",
"body": "`until (0 == index $string, $current_prefix)` is likely to perform worse than the original."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:47:09.793",
"Id": "61077",
"Score": "0",
"body": "@200_success You have a point there (even after a match failure, other positions are searched), and we could use `until($current_prefix eq substr $string, 0, length $current_prefix)` or `until (0 == rindex $string, $current_prefix, 0)` to get around that. My answer *only* optimized for readability, not for performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:01:14.797",
"Id": "61079",
"Score": "0",
"body": "Thanks for your answer. Performance is an issue here, that's why I used `substr` and `ne` instead of `index`. However your answer made me realize that I don't need to preserve `$a` and `$b` (this is not a for loop) so I'm thinking of chopping both to size and compare them instead of using `substr`. Since `$a` is unlikely to change after line 2 I don't mind to have two `chop`s in the loop body..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:06:45.963",
"Id": "61084",
"Score": "0",
"body": "Something like this: http://ideone.com/WvVX86 updating question..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:36:59.163",
"Id": "37074",
"ParentId": "37054",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37074",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T16:44:39.473",
"Id": "37054",
"Score": "4",
"Tags": [
"strings",
"perl"
],
"Title": "Find common preamble of a list of strings"
}
|
37054
|
<p>I'm new to Java and am trying to solve a scenario. Even though I've succeeded and it works, I've just wondered if there was a more practical way of doing this task. Is there a quicker or more efficient way of solving the task, or is this fine?</p>
<blockquote>
<p><strong>Task:</strong></p>
<p>Given a string, return a version without the first 2 chars. Except
keep the first char if it is 'a' and keep the second char if it is
'b'. The string may be any length. </p>
<pre><code>deFront("Hello") → "llo"
deFront("java") → "va"
deFront("away") → "aay"
</code></pre>
</blockquote>
<p><strong>Code:</strong></p>
<pre><code>public String deFront(String str) {
if(str.length() > 0) {
if(str.substring(0,1).equals("a") && !str.substring(1,2).equals("b")) {
return str.substring(0,1) + str.substring(2,str.length());
} else if(str.substring(1,2).equals("b") && !str.substring(0,1).equals("a")) {
return str.substring(1,2) + str.substring(2,str.length());
} else if(str.substring(0,1).equals("a") && str.substring(1,2).equals("b")) {
return str;
} else {
return str.substring(2,str.length());
}
} else {
return "";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T01:20:20.477",
"Id": "61118",
"Score": "0",
"body": "Worth noting, there's `charAt(int)` for the single char checks, which expresses your intent far clearer than `substring`."
}
] |
[
{
"body": "<p>Yes, some of the things you are doing is redundant and quite messy. As this seems to be a homework assignment I will only provide hints for you here.</p>\n\n<p>What you can do is:</p>\n\n<ul>\n<li>If the string is empty, return an empty string immediately</li>\n<li>Store the first character in a variable</li>\n<li>Store the second character in a variable, if it exists</li>\n<li>Store the rest of the string in a variable, if it exists</li>\n<li>Check if the second character is <code>'b'</code>, if it is then add it to the beginning of the string</li>\n<li>Check if the first character is <code>'a'</code>, if it is then add it to the beginning of the string</li>\n<li>Return the string</li>\n</ul>\n\n<p>A problem of your existing code is that it will fail for strings of length 1. So it is important to only use the first and second characters if they exist at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T16:54:02.457",
"Id": "37056",
"ParentId": "37055",
"Score": "17"
}
},
{
"body": "<p>First of all, thumbs up for solving this problem in a function rather than in <code>main()</code>. I would declare this as a <code>static</code> function, though, since it is a pure function that does not rely on any instance variables in an object.</p>\n\n<p>I see two main problems:</p>\n\n<ol>\n<li>If <code>str</code> has fewer than two characters, you'll get an <code>IndexOutOfBoundsException</code>.</li>\n<li>Your strategy doesn't \"scale\" well, since you are attempting to enumerate all possible combinations of how the string can begin. If you also took into consideration the possibility of <code>str</code> having fewer than two characters, you would end up with a combinatorial explosion.</li>\n</ol>\n\n<p>I recommend a different approach, which mimics the problem description more closely. As you analyze <code>str</code>, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html\" rel=\"noreferrer\">build</a> the string that you want to return. For example, if the string length exceeds 0 and the first character is <code>'a'</code>, then append <code>'a'</code> to your result.</p>\n\n<p>Instead of extracting substrings of length 1, I suggest fetching a character by calling <code>string.charAt(index)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:03:14.663",
"Id": "37064",
"ParentId": "37055",
"Score": "7"
}
},
{
"body": "<p>There are a few things I noticed right off of the bat:</p>\n\n<ul>\n<li>You never check to see if your input is <code>null</code>. This opens you up immediately to a <code>NullPointerException</code> if your API is misused.</li>\n<li>You don't handle the case of a 1-length <code>String</code> being passed in, which opens you up to an <code>IndexOutOfBoundsException</code>.</li>\n<li>You are constantly calling <code>.substring(1, 2)</code> or the like in order to retrieve one character of the <code>String</code>; this is less efficient than using the <code>.chatAt(1)</code> method, and you could simply store the character in a <code>char</code> variable for future reference.</li>\n<li>There's no need to use something like <code>str.substring(2, str.length())</code>; you can simply call this as <code>str.substring(2)</code>. <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring%28int%29\" rel=\"noreferrer\">The String API is actually pretty powerful.</a></li>\n</ul>\n\n<p>Here's my five minute rendition of it. Actually, my version uses inline <code>if</code> statements because I find that it makes the code more concise and readable, but I laid it out a bit more to make it more intuitive for you.</p>\n\n<pre><code>public static String deFront(String str) {\n\n if(str == null || (str.length() < 2) {\n return \"\";\n }\n\n boolean keepFirst = str.charAt(0) == 'a';\n boolean keepSecond = str.charAt(0) == 'b';\n\n if(keepFirst && keepSecond) {\n return str;\n }\n else if(!keepFirst && !keepSecond) {\n return str.substring(2);\n }\n else if(!keepFirst && keepSecond) {\n return str.substring(1);\n }\n else if(keepFirst && !keepSecond) {\n return str.charAt(0) + str.substring(2);\n }\n\n throw new IllegalArgumentException(\"Something weird happened.\"); \n}\n</code></pre>\n\n<p>Notice that I immediately check for <code>null</code> in the first line. Because <a href=\"http://en.wikipedia.org/wiki/Short-circuit_evaluation#Avoiding_the_execution_of_second_expression.27s_side_effects\" rel=\"noreferrer\">logical operators \"short-circuit\" in Java</a>, if <code>str == null</code>, the <code>str.length() < 2</code> condition will never even be evaluated since the <code>||</code> will evaluate to <code>true</code> regardless.</p>\n\n<p>Next, notice that I store whether or not to trim the associated characters in a <code>boolean</code> variable right off the bat. This prevents me from constantly having to examine and break up the passed in <code>str</code>, which not only makes my code slightly more efficient but, more importantly, makes it vastly more readable.</p>\n\n<p>Finally, the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html\" rel=\"noreferrer\">throwing Exceptions</a> bit at the end might be a bit more advanced than your level, but there's nothing like a taste of the fun stuff you'll get to do to keep you interested. :) At first I simply had the last line as <code>return null</code>, since every ending branch must return <em>something</em>. But because the code should never reach that line anyway (since I have an exhaustive list of all possibilities in my if/else-if blocks), I thought it was better to throw an Exception (i.e., raise an error the program) in case it ever happened for some reason, since it means something fundamentally broke.</p>\n\n<p>Note that I could have also just left the last <code>else if()</code> block as an <code>else</code> in order to avoid the need to do something like that, but I wanted to make the code as explicit as possible for you to read through and understand.</p>\n\n<p>For reference, here's how I originally wrote it:</p>\n\n<pre><code>public static String deFront(String str) {\n\n if(str == null || str.length() < 2) return \"\";\n\n boolean keepFirst = str.charAt(0) == 'a';\n boolean keepSecond = str.charAt(0) == 'b';\n\n if(!keepFirst && !keepSecond) return str.substring(2);\n else if(!keepFirst && keepSecond) return str.substring(1);\n else if(keepFirst && !keepSecond) return str.charAt(0) + str.substring(2);\n else return str;\n}\n</code></pre>\n\n<p>One last note: I could have just had them all be <code>if</code> statements as well, since each only returns and removes the method call from the stack anyway, but I find that it makes the code more readable to have <code>else if</code>s, since it means the conditionals are logically joined to the reader.</p>\n\n<p><strong>EDIT:</strong> I actually had to expand the initial checks slightly. Technically speaking, given your rules, if the <code>String</code> is passed in as <code>\"a\"</code>, it should return <code>\"a\"</code>, not the empty string.</p>\n\n<pre><code>public static String deFront(String str) {\n\n if(str == null) return \"\";\n else if(str.equals(\"a\")) return str;\n else if(str.length() < 2) return \"\";\n\n boolean keepFirst = str.charAt(0) == 'a';\n boolean keepSecond = str.charAt(0) == 'b';\n\n if(!keepFirst && !keepSecond) return str.substring(2);\n else if(!keepFirst && keepSecond) return str.substring(1);\n else if(keepFirst && !keepSecond) return str.charAt(0) + str.substring(2);\n else return str;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:50:16.737",
"Id": "61099",
"Score": "2",
"body": "I don't think it's the API's job to check whether the string is null, rather this looks like something that could hide nasty errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:54:58.607",
"Id": "84731",
"Score": "0",
"body": "I interpret the question to be: keep the second character if the _second_ character is `b`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:19:12.540",
"Id": "37065",
"ParentId": "37055",
"Score": "7"
}
},
{
"body": "<p>I would have solved it using a regular expression with a replace command. It might not be faster than a well written if-tree, but why write the if-tree yourself when the regex engine will do it for you?</p>\n\n<pre><code>(?:(a)|[^a])\n</code></pre>\n\n<p>For instance matches any one character, but only captures the character if it is <code>a</code>. Build the rest of that regex and you have a clean one-liner solution.</p>\n\n<p>Do remember the edge cases, as others have pointed out you forgot to handle the 1 character case in your code, and it is of course also something you need to think about with this method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T11:49:55.480",
"Id": "61355",
"Score": "0",
"body": "Although a nice suggestion and something I didn't think about originally, writing a good regex is hard, probably especially for the OP who is \"new to Java\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T19:03:16.017",
"Id": "61674",
"Score": "1",
"body": "@SimonAndréForsberg It is something to put on the to-learn list, knowing that markedly different methods exist is the first step towards utilizing them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T22:42:26.897",
"Id": "37084",
"ParentId": "37055",
"Score": "3"
}
},
{
"body": "<p>This seems to work:</p>\n\n<pre><code>public String deFront(String str) {\n return (str.startsWith(\"a\") ? \"a\" : \"\") + (str.matches(\".b.*\") ? \"b\" : \"\") + (str.length() > 2 ? str.substring(2) : \"\");\n}\n</code></pre>\n\n<p>Or even shorter with regex replaceAll:</p>\n\n<pre><code>public String deFront(String str) {\n return str.replaceAll(\"^((a)|[^a])((b)|[^b])?(.*)\", \"$2$4$5\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T01:50:23.357",
"Id": "84736",
"Score": "4",
"body": "Hi, and welcome to Code Review. Offering a suggested alternative to the original problem is a valuable contribution, but only if you add in why the alternative is better, or what problems it solves in the original code. Please consider updating your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:24:03.160",
"Id": "48285",
"ParentId": "37055",
"Score": "-1"
}
},
{
"body": "<p>You may do the following as well:</p>\n\n<ul>\n<li><p>Store the string without the first two characters in a variable say\nstr1.</p></li>\n<li><p>Check if the second character is 'b', if it is then add it to the\nbeginning of the string str1.</p></li>\n<li><p>Check if the first character is 'a', if it is then add it to the\nbeginning of the string str1.</p>\n\n<pre><code>String str = \"away\";\nString str1 = str.substring(2);\n\nif(str.substring(1).startsWith(\"b\"))\n str1 = \"b\" + str1;\nif(str.startsWith(\"a\"))\n str1 = \"a\" + str1;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-19T12:45:36.253",
"Id": "224475",
"Score": "1",
"body": "This is mostly a duplicate of Simon's answer, and you don't handle strings of length 0 or 1 - these would fail with `IndexOutOfBoundsException`. It's a good attempt at an implementation, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-19T12:39:10.507",
"Id": "120524",
"ParentId": "37055",
"Score": "2"
}
},
{
"body": "<p>I think this problem shouldn't be solved by using the <code>substring</code> method.\nThe reason why is that <code>substring</code> does to much things and is way too complicated.</p>\n\n<p>When you take a look to your code you can see the effect of this. The thing that annoys me the most is that you need to call <code>substring</code> multiple times.</p>\n\n<p>Even @asteri solution uses at least 3 <code>substring</code> calls.</p>\n\n<p>So I implemented a solution with a <code>StringBuilder</code></p>\n\n<pre><code>public String dePrefix(string prefix, string value){\n StringBuilder builder = new StringBuilder();\n for(int i = 0; i < value.length; ++i){\n if(i < prefix.length && value.charAt(i) != prefix.charAt(i)){\n continue;\n }\n builder.append(value.charAt(i));\n }\n return builder.toString();\n}\n\npublic static String deFront(String str) {\n return dePrefix(\"ab\", str);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-19T13:07:28.960",
"Id": "120531",
"ParentId": "37055",
"Score": "2"
}
},
{
"body": "<p>You could build your final string using ternary operators and avoid all the ifs. I think this is much more readable:</p>\n\n<pre><code>String firstChar = str.charAt(0) == 'a' ? \"a\" : \"\";\nString secondChar = str.charAt(1) == 'b' ? \"b\" : \"\";\nString remainingChars = str.substring(2, str.length());\nString finalString = firstChar + secondChar + remainingChars;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-19T14:52:09.417",
"Id": "461804",
"Score": "0",
"body": "Readability is important. What is the result for `str = \"a\"`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-19T12:59:37.593",
"Id": "235845",
"ParentId": "37055",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37056",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T16:48:38.130",
"Id": "37055",
"Score": "11",
"Tags": [
"java",
"strings",
"beginner",
"homework"
],
"Title": "Return a string without the first two characters"
}
|
37055
|
<p>I wrote this program for an assignment, thus I had some requirements as far as the format of the cfg.txt file and some basic other classes that we had to use. Other than that, I am curious if there is a way to drastically simplify this code. Although the program runs fine and produces the desired output, is there a better way to go about writing this? (What initially spurred my concern was the <code>iterateData</code> method. I did not like the code repetition and thought it may be convenient to "reuse" some of it. However, in doing so, I then introduced numerous class variables to prevent from having to pass in 7 instance variables to the method. I can't say that I'm all too thrilled about this...) Regardless, advice and suggestions appreciated.</p>
<p>Thank you. </p>
<pre><code>import java.util.Scanner;
import java.io.*;
import java.util.Random;
public class ContextFreeGrammar {
private static String nt, useExp = "";
private static int totalWeight = 0, randomNum;
private static ArrayUnsortedList<Production> data = new ArrayUnsortedList<Production>();
private static Production pObj;
public static void main(String[] args) throws IOException {
String result = "<S>";
File myFile = new File("cfg.txt");
Scanner fileScan = new Scanner(myFile);
// Read and process each line of the file
while (fileScan.hasNext()) {
Production p = new Production(fileScan.nextLine());
data.add(p);
}
// If the result string still contains non-terminals
while (result.contains("<")) {
// Get the non-terminal
nt = result.substring(result.indexOf('<')+1, result.indexOf('>'));
// Cannot condense because we have an ambiguous
// totalWeight. Hence, we need to iterate twice:
// 1. To generate appropriate random number from totalWeight
// 2. To determine when the totalWeight exceeds that random number.
iterateData(false);
Random rand = new Random(); // Generate a random number object
randomNum = rand.nextInt(totalWeight - 1) + 1; // Generate actual random number
// Resets
totalWeight = 0;
data.reset();
iterateData(true);
// Replace the non-terminal with the expression to use
result = result.replaceFirst("<" + nt + ">", useExp);
totalWeight = 0; // Reset totalWeight;
}
System.out.println(result);
}
public static void iterateData(boolean GETEXP) {
// Iterate through list again
for (int i = 0; i < data.size(); i++) {
// Get the current value
pObj = data.getNext();
// Keep track of weight
if (nt.equalsIgnoreCase(pObj.getNonTerminal())) {
totalWeight += pObj.getWeight();
if (GETEXP) {
if (totalWeight > randomNum) {
useExp = pObj.getExpression(); // This is expression to use
break;
}
}
}
}
}
}
</code></pre>
<p>My <code>cfg.txt</code> file is as such:</p>
<pre><code>80 <S> = My homework is late because <reason>.
20 <S> = I want to <action> instead of writing this program.
40 <reason> = <who> ate it
40 <reason> = I set it on fire because I was cold
20 <reason> = I didn't feel like doing it
30 <who> = Deep Shah
70 <who> = my pet <animal>
10 <animal> = dog
20 <animal> = narwhal
50 <animal> = python
20 <animal> = velociraptor
30 <action> = go on a vacation
30 <action> = indulge in a giant feast
40 <action> = frolic in the snow
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>It is said that \"a method should do one thing, and it should do that one thing well\". Your iterateData method is being used to do two separate things, depending on the parameter you send it.</p></li>\n<li><p>If your <code>ArrayUnsortedList</code> is <a href=\"https://github.com/ckoch786/Hashing/blob/master/src/lists/ArrayUnsortedList.java\" rel=\"nofollow\">this class</a> (which really could use a code review itself) then I don't really understand why you are using it. The way I see it is that you could use a regular <code>ArrayList</code>.</p></li>\n<li><p>What you are referring to as \"class variables\" are <strong>static</strong> variables. It would be better to use them as instance variables. Currently you can't have two <code>ContextFreeGrammar</code> objects at once, each with it's own state. Remove the <strong>static</strong> keyword and *create an instance of <code>ContextFreeGrammar</code> to properly use it as an instance (which is a lot better practice, although you might not have learned about such things yet. If you haven't learned about it yet, you should ask your teacher about it)</p></li>\n<li><p>Only create a new <code>Random</code> object once. <code>Random</code> objects are meant to be re-used. When they are initialized, they get a random seed set depending on the system clock time. Repeatedly creating a <code>Random</code> object gives a loss in randomness.</p></li>\n<li><p>Instead of your current <code>iterateData</code> method, consider using one method such as <code>int calculateTotalWeight(List<Production> list, String nonTerminal)</code> and one <code>String determineExpression(List<Production> list, String nonTerminal, int weightRandom)</code>. Determining such an important behavior of your method by sending it a true/false value makes your code harder to understand. You don't need to pass seven variables to the method when it only uses two or three.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T19:20:51.103",
"Id": "61055",
"Score": "0",
"body": "To address your second point, this is quite true; however, for my course, I must use this class because it comes from my professor's textbook...and he wants us to use it...Anyway, I appreciate the feedback and will make the necessary changes. You make some very good points. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:01:16.953",
"Id": "61080",
"Score": "0",
"body": "@JohnZ Send your professor and his textbook over here and we would gladly review him!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:04:05.157",
"Id": "61082",
"Score": "0",
"body": "You have no idea how much I would love that. To be honest, considering I've only ever learned Java in his particular class, I'm very interested to know what I'm being taught versus what I *should* be being taught. Makes me wonder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:06:58.270",
"Id": "61085",
"Score": "1",
"body": "@JohnZ It all depends on how much you're ready to learn at once I think. Whenever you create something you'd like a second opinion on, Code Review is your friend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:13:17.430",
"Id": "61087",
"Score": "0",
"body": "Well for what it's worth, your review was far more helpful than any other feedback I've received in class. I will definitely be using CodeReview more often."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T17:44:29.383",
"Id": "37060",
"ParentId": "37058",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T17:16:44.143",
"Id": "37058",
"Score": "3",
"Tags": [
"java",
"performance",
"design-patterns",
"parsing"
],
"Title": "Very basic Context Free Grammar in Java"
}
|
37058
|
<p>so this is my code and I just want to improve it, I'm a beginner so I think there are some better and short ways to do what I did here. Any Ideas?
The code:</p>
<pre><code>class Table:
def __init__(self,path,sep):
self.path=path
self.sep=sep
self.g=[]
self.count=0
self.headlines=[]
self.matrix=[]
self.headrows=[]
self.postionrow=0
self.postioncolmn=0
try:
f=open(self.path,'r')
read_file=f.read()
split_file=read_file.split()
for line in split_file:
list_the_line=line.split(self.sep)
self.g.append(list_the_line)
self.count=0
for z in range (len(self.g[0])):
self.count=0
for d in range(len(self.g[0])):
if self.g[0][z]==self.g[0][d]:
self.count+=1
if self.count>=2:
raise ValueError
num_first_line=len(self.g[0])
for k in range (len(self.g)):
if len(self.g[k])!= num_first_line:
raise ValueError
self.headlines=self.g[0]
self.g.remove(self.g[0])
self.count=0
for row_name1 in range (len(self.g)):
self.count=0
for row_name2 in range(len(self.g)):
if self.g[row_name1][0]==self.g[row_name2][0]:
self.count+=1
if self.count>=2:
raise ValueError
for i in range (len(self.g)):
self.headrows.append(self.g[i][0])
self.g[i].remove(self.g[i][0])
ezer=[]
for op in range (len(self.g)):
ezer=[]
for od in range (len(self.g[0])):
ezer.append(self.g[od][op])
self.matrix.append(ezer)
f.close()
except :
print "Check - Error..."
return
def len(self):
num_rows=len(self.g)
num_cols=len(self.g[0])
return num_rows*num_cols
def get_row(self,rowname):
for i in range (len(self.headlines)):
if rowname==self.headrows[i]:
self.postionrow=i
return self.g[i]
if not rowname in self.headrows :
raise ValueError
def get_column(self,colname):
for i in range (len(self.headlines)):
if colname==self.headlines[i]:
self.postioncolmn=i-1
return self.matrix[i-1]
if not colname in self.headlines :
raise ValueError
def get_value(self,rowname,colname):
self.get_row(rowname)
self.get_column(colname)
if not rowname in self.headrows :
raise ValueError
if not colname in self.headlines :
raise ValueError
return self.g[self.postionrow][self.postioncolmn]
def get_row_name_with_max_value(self,colname):
if not colname in self.headlines :
raise ValueError
max_colmn=max(self.get_column(colname))
for i in range (len(self.matrix)):
if max_colmn == self.g[i][self.postioncolmn]:
return self.headrows[i]
</code></pre>
<p>and what should be the result:</p>
<pre><code>>>> table = Table("table_examp1111111","\t")
Check - Error...
>>> table = Table("table_example1.txt","\t")
>>> print table.len()
12
>>> print table.get_row("Menny")
['M', '1', '1', '1']
>>> print table.get_column("Height")
['1', '2', '3']
>>> print table.get_value("Sami","Age")
3
>>> print table.get_row_name_with_max_value("Height")
Sami
>>> print table.get_row_name_with_max_value("Salary")
Sami
</code></pre>
<p>This code works but I want to make it more Pythonic. Please don't change the form, don't add or remove function just fix my syntax and make it better.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:56:34.003",
"Id": "61047",
"Score": "0",
"body": "Did you consider using the built-in [`sqlite3`](http://docs.python.org/3/library/sqlite3.html) module instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:59:46.783",
"Id": "61049",
"Score": "0",
"body": "Thank you for your idead, but sorry, I don't want to use this build-in function... just using the basic built in function like \"sum\" or \"len\"..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:24:27.250",
"Id": "61071",
"Score": "0",
"body": "anyone please? thanks"
}
] |
[
{
"body": "<p>Here are a number of suggestions that would help the readability and usability of your code. Most of these are fairly high level suggestions that apply almost anywhere, but some do get into the details of your implementation.</p>\n\n<ul>\n<li>Comment on the blocks that make up your <code>Table.__init__</code>, or even better, refactor them into helpers. For example the first six lines in the <code>try</code> initialize <code>self.g</code>, but the next several are verifying some unclear invariant (it seems to be checking for duplicates), and the next couple appear to verify that each line had the same number of items. These blocks would be much more clear with either a method name or comment describing what it was verifying.</li>\n<li>Avoid <code>for i in range(len(mylist)): ... mylist[i] ...</code> loops unless performance measurements have shown it to be necessary. Instead prefer loops starting with <code>for item in mylist:</code> or (if you need the index) <code>for i, item in enumerate(mylist): ...</code></li>\n<li><p>Don't use <code>mylist.remove(mylist[0])</code> where <code>del mylist[0]</code> or perhaps a slight rewrite and <code>mylist.pop(0)</code> would work better. The call to remove is more indirect, and thus requires more thought to assess its impact. For example, applying both of these points:</p>\n\n<pre><code> # original:\n for i in range (len(self.g)):\n self.headrows.append(self.g[i][0])\n self.g[i].remove(self.g[i][0])\n\n # better (if line is an appropriate name):\n for line in self.g:\n self.headrows.append(line.pop(0))\n</code></pre></li>\n<li><p>Avoid <code>try: ... except: ...</code> clauses that do not specify an exception type. These suppress exceptions like <code>KeyboardInterrupt</code> that you probably do not want to suppress. Also limit the length of the try block to as short as you can feasibly make it. This one covers at least two kinds of possible exceptions (a failure opening or reading the file, and a failure processing the file).</p></li>\n<li>Avoid just suppressing an important exception like <code>__init__</code> does; after all, exceptions are the only way for an <code>__init__</code> to signal an error. When an exception occurs in the middle of processing the file, the code prints a message, and returns with a partially initialized object. This means calling code can't tell there was an error, and may make invalid assumptions about the contents of the file. If you really need the partially initialized object, you can look into returning it on a custom exception type (this need is fairly rare).</li>\n<li>Looking past <code>__init__</code>, the various error cases across several methods all raise a <code>ValueError</code> when it looks like <code>KeyError</code> or <code>IndexError</code> would be more appropriate. You can get this for free if you slightly restructure your code to maintain a dict mapping names to column/row indices, and just let the code attempt to access things. If the key isn't in the mapping, the dict will raise the <code>KeyError</code>. You can also avoid your lookup loops. Win-win.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:22:02.890",
"Id": "37138",
"ParentId": "37067",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T18:46:01.780",
"Id": "37067",
"Score": "1",
"Tags": [
"python",
"database"
],
"Title": "Data table class"
}
|
37067
|
<p>I'm trying to write a simple game. I have an <code>Entity</code> object, that has a list of <code>Sprite</code> objects. Each <code>Sprite</code> has a position property where it is drawn on the screen. Sometimes, an entity can contain a lot of <code>Sprite</code>s in which case it is much easier to set the position property on the parent <code>Entity</code>.</p>
<p>Here's a simplified example of creating an <code>Entity</code> with a list of <code>Sprite</code>s:</p>
<pre><code>var player = new Entity( new List<Sprite>
{
new Sprite( "characters/walkcycle/body", new Vector2( 128, 128 ) ),
new Sprite( "characters/walkcycle/halo", new Vector2( 128, 120 ),
new Sprite( "characters/walkcycle/shirt", new Vector2( 128, 128 ) ),
new Sprite( "characters/walkcycle/pants", new Vector2( 128, 128 ) ),
new Sprite( "characters/walkcycle/shoes", new Vector2( 128, 128 ) )
} );
</code></pre>
<p>Most of the Sprites have the same position, so I do this instead:</p>
<pre><code>var player = new Entity( new Vector2( 128, 128 ),
new List<Sprite>
{
new Sprite( "characters/walkcycle/body" ),
new Sprite( "characters/walkcycle/halo", new Vector2( 128, 120 ),
new Sprite( "characters/walkcycle/shirt" ),
new Sprite( "characters/walkcycle/pants" ),
new Sprite( "characters/walkcycle/shoes" )
} );
</code></pre>
<p>Notice the halo sprite is in a different position. Later in the code, I call the <code>Load</code> method on <code>Entity</code>, which passes its position property on to the children <code>Sprite</code>s:</p>
<pre><code>public class Entity
{
// fields, constructor, properties ...
public void Load()
{
foreach ( var sprite in this.sprites )
{
sprite.Load( this.position );
}
}
}
</code></pre>
<p>The <code>Load</code> method on <code>Sprite</code> will set its own position property to the value passed in <em>if it doesn't already have one</em>:</p>
<pre><code>public class Sprite
{
// fields, constructor, properties ...
public void Load( Vector2 position )
{
if ( this.position == Vector2.Zero && position != Vector2.Zero )
{
this.position = position;
}
}
}
</code></pre>
<p>Is there a better way to do this? It smells a little to me.</p>
|
[] |
[
{
"body": "<p>Another approach would be to make the positions of sprites relative to the position of the entity. That way, the default of zero comes up naturally and when you move an entity, all of its sprites are automatically moved too.</p>\n\n<p>One more advantage is that this means position zero now becomes a valid one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:38:45.437",
"Id": "37080",
"ParentId": "37069",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T19:19:32.693",
"Id": "37069",
"Score": "7",
"Tags": [
"c#",
"design-patterns",
"collections"
],
"Title": "Cascading a property for a game"
}
|
37069
|
<p>Coming from an imperative background, I have written the following code in Scala. I need to attempt to find a value in a map. If the value exists, I need to pass the value to another function and return the result, otherwise I need to return None.</p>
<pre><code>def foo(index: Int): Option[FooBar] = {
val mylookup: Map[Int, String] = this.generateMap()
var out: Option[String] = None
if (mylookup.containsKey(index)) {
out = Some(mylookup(index))
} else if (mylookup.containsKey("static_value")) {
out = Some(mylookup("static_value"))
}
if (!out.getOrElse("").isEmpty) {
return this.doSomeCall(out.get).makeFooBar()
} else {
return None
}
}
</code></pre>
<p>I don't feel like this is the best way to accomplish this in Scala. Any ideas on how to approach this using the idiomatic nature of the language?</p>
|
[] |
[
{
"body": "<pre><code>myLookup.get(index).orElse(myLookup.get(static_value)).map { doSomeCall(_).makeFooBar }\n</code></pre>\n\n<p>From the Scala doc of <a href=\"http://www.scala-lang.org/api/current/index.html#scala.Option\" rel=\"nofollow\"><code>Option.map</code></a>: </p>\n\n<blockquote>\n <p>Returns a scala.Some containing the result of applying f to this scala.Option's value if this scala.Option is nonempty. Otherwise return None.</p>\n</blockquote>\n\n<p>This is exactly the type of task functional programming is made for. This simple chaining of <code>Option</code>s using <code>map</code> is related to the fact that <code>Option</code> is a monad.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:44:08.743",
"Id": "61098",
"Score": "0",
"body": "That is indeed terse. However, how do I return a single value? I'll modify my code above to not be as implicit. I want to return the value from makeFooBar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:53:50.553",
"Id": "61100",
"Score": "0",
"body": "Ignore my last comment as I understand how that works now. However, how would I check for my static value if the index value doesn't exist?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T22:08:44.730",
"Id": "61101",
"Score": "0",
"body": "Sorry, I completely missed the part with `static_value`. I changed my post."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:27:36.557",
"Id": "37079",
"ParentId": "37070",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37079",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:21:54.683",
"Id": "37070",
"Score": "4",
"Tags": [
"scala"
],
"Title": "What is a better approach for operating on an arbitrary map value in Scala?"
}
|
37070
|
<p>I am trying to re-factor (improve design of existing working code) with the following principals:</p>
<ul>
<li>Switch statements removal.</li>
<li>Encapsulate Field</li>
<li>Extract Class</li>
<li>Extract Interface</li>
<li>Extract Method</li>
<li>Extract Subclass</li>
<li>Extract Super Class</li>
<li>Form Template Method - Before</li>
<li>Move Method - Before</li>
<li>Introduce Null Object</li>
<li>Replace Error Code with Exception</li>
<li>Replace Exception with Test</li>
<li>Nested Conditional with Guard</li>
<li>Replace Parameter with Explicit Method</li>
<li>Replace Temp with Query</li>
<li>Rename Variable or Method</li>
</ul>
<p>Here is my code. Any help or suggestions?</p>
<p>Class: <strong>TriviaData</strong></p>
<pre><code>import java.util.ArrayList;
public class TriviaData
{
private ArrayList<TriviaQuestion> data;
public TriviaData()
{
data = new ArrayList<TriviaQuestion>();
}
public void addQuestion(String q, String a, int v, int t)
{
TriviaQuestion question = new TriviaQuestion(q,a,v,t);
data.add(question);
}
public void showQuestion(int index)
{
TriviaQuestion q = data.get(index);
System.out.println("Question " + (index +1) + ". " + q.value + " points.");
if (q.type == TriviaQuestion.TRUEFALSE)
{
System.out.println(q.question);
System.out.println("Enter 'T' for true or 'F' for false.");
}
else if (q.type == TriviaQuestion.FREEFORM)
{
System.out.println(q.question);
}
}
public int numQuestions()
{
return data.size();
}
public TriviaQuestion getQuestion(int index)
{
return data.get(index);
}
}
public class TriviaQuestion
{
public static final int TRUEFALSE = 0;
public static final int FREEFORM = 1;
public String question; // Actual question
public String answer; // Answer to question
public int value; // Point value of question
public int type; // Question type, TRUEFALSE or FREEFORM
public TriviaQuestion()
{
question = "";
answer = "";
value = 0;
type = FREEFORM;
}
public TriviaQuestion(String q, String a, int v, int t)
{
question = q;
answer = a;
value = v;
type = t;
}
}
</code></pre>
<p>Class <strong>TriviaGame</strong></p>
<pre><code>import java.io.*;
import java.util.Scanner;
public class TriviaGame
{
public TriviaData questions; // Questions
public TriviaGame()
{
// Load questions
questions = new TriviaData();
questions.addQuestion("The possession of more than two sets of chromosomes is termed?",
"polyploidy", 3, TriviaQuestion.FREEFORM);
questions.addQuestion("Erling Kagge skiied into the north pole alone on January 7, 1993.",
"F", 1, TriviaQuestion.TRUEFALSE);
questions.addQuestion("1997 British band that produced 'Tub Thumper'",
"Chumbawumba", 2, TriviaQuestion.FREEFORM);
questions.addQuestion("I am the geometric figure most like a lost parrot",
"polygon", 2, TriviaQuestion.FREEFORM);
questions.addQuestion("Generics were introducted to Java starting at version 5.0.",
"T", 1, TriviaQuestion.TRUEFALSE);
}
// Main game loop
public static void main(String[] args)
{
int score = 0; // Overall score
int questionNum = 0; // Which question we're asking
TriviaGame game = new TriviaGame();
Scanner keyboard = new Scanner(System.in);
// Ask a question as long as we haven't asked them all
while (questionNum < game.questions.numQuestions())
{
// Show question
game.questions.showQuestion(questionNum);
// Get answer
String answer = keyboard.nextLine();
// Validate answer
TriviaQuestion q = game.questions.getQuestion(questionNum);
if (q.type == TriviaQuestion.TRUEFALSE)
{
if (answer.charAt(0) == q.answer.charAt(0))
{
System.out.println("That is correct! You get " + q.value + " points.");
score += q.value;
}
else
{
System.out.println("Wrong, the correct answer is " + q.answer);
}
}
else if (q.type == TriviaQuestion.FREEFORM)
{
if (answer.toLowerCase().equals(q.answer.toLowerCase()))
{
System.out.println("That is correct! You get " + q.value + " points.");
score += q.value;
}
else
{
System.out.println("Wrong, the correct answer is " + q.answer);
}
}
System.out.println("Your score is " + score);
questionNum++;
}
System.out.println("Game over! Thanks for playing!");
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>It's better to use <code>enum { TRUEFALSE, FREEFORM }</code> instead of hard coding arbitrary <code>int</code> values.</p></li>\n<li><p>It's better to declare your variables as <code>List<TriviaQuestion> data</code> and only use <code>ArrayList</code> when you instantiate them. You then have more freedom later if you want to change the type of list you are using. In general you always want to declare variables with the most general superclass/interface type possible.</p></li>\n<li><p>Use meaningful variable names, not <code>(String q, String a, int v, int t)</code>. Variables names are a form of documentation. On that same topic, instead of using the variable name \"data\" I would use \"questions\" or \"questionList\".</p></li>\n<li><p>I don't like the class <code>TriviaData</code>: it doesn't do anything more than using a plain <code>List<TriviaQuestion></code>. You can just <code>questions.add(new TriviaQuestion(...))</code>.</p></li>\n<li><p>It's better not to have the empty constructor <code>TriviaQuestion()</code>.</p></li>\n<li><p>Instead of making the members of <code>TriviaQuestion</code> public, it's better to keep them private and add getters (but no setters since they should only be set by the constructor).</p></li>\n</ol>\n\n<p>Your bracket indentation is from C/C++. Your code will run nonetheless, but maybe you should use the Java conventions if you are switching to Java.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:06:07.710",
"Id": "37076",
"ParentId": "37073",
"Score": "5"
}
},
{
"body": "<p>I think you missed a crucial refactoring: <a href=\"http://refactoring.com/catalog/replaceTypeCodeWithSubclasses.html\" rel=\"nofollow\">Replace Type Code With Subclasses</a>.</p>\n\n<pre><code>questions.add(new FreeformQuestion(3,\n \"The possession of more than two sets of chromosomes is termed?\",\n \"polyploidy\"));\nquestions.add(new TrueFalseQuestion(1,\n \"Erling Kagge skiied into the north pole alone on January 7, 1993.\",\n false));\n</code></pre>\n\n<p>Then, the game loop should be vastly simplified:</p>\n\n<pre><code>for (TriviaQuestion q : game.questions) {\n boolean isCorrect = q.promptAndVerify(keyboard, System.out);\n if (isCorrect) {\n System.out.format(\"That is correct! You get %d points.\\n\", q.getValue());\n score += q.getValue();\n } else {\n System.out.format(\"Wrong, the correct answer is %s\\n\", q.getAnswer());\n }\n System.out.format(\"Your score is %d\\n\", score);\n}\n</code></pre>\n\n<p>By delegating the prompting and verification to the question, you gain a lot of flexibility. You could add question subclasses for Daily Doubles, multiple choice questions, timed questions, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:10:00.573",
"Id": "37078",
"ParentId": "37073",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:36:03.967",
"Id": "37073",
"Score": "1",
"Tags": [
"java",
"game"
],
"Title": "Trivia game refactoring"
}
|
37073
|
<p>The context is Weekend Challenge #2 (Poker hand evaluation).</p>
<pre><code>Hand.prototype.isStraight = function()
{
for( var i = 1 ; i < this.cards.length ; i++ )
if( this.cards[i].value + 1 != this.cards[i-1].value )
return false;
return true;
}
</code></pre>
<p><code>cards</code> is an array with card objects <code>{ suit : "x" , value : "0->12" }</code>. The cards are sorted during the creation of the hand.</p>
<p>My approach to detect straightness seems like the hard way. Can anyone suggest something else?</p>
<p>Okay, Poker is tough. I will revise this question once I have my new <code>isStraight</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:13:25.200",
"Id": "61088",
"Score": "2",
"body": "Ugh. You have no idea how much I wish it were *that* simple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:15:55.523",
"Id": "61089",
"Score": "0",
"body": "Are the cards guaranteed to be maintained as sorted?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:17:40.207",
"Id": "61090",
"Score": "1",
"body": "Indeed the straight seems to be one of the hardest things about this week's challenge. I like your approach but remember that Ace can be used as both `1` and `14` in a straight (Ace - 5 and 10 - Ace). Also, why are you starting the loop at `i = 1` when arrays indexes tends to be 0-based?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:18:53.680",
"Id": "61091",
"Score": "0",
"body": "How many cards do you have in `this.cards`? Are you assuming a 5-card hand? Can you tell 5 consecutive cards in a 7-card hand? What if you have only 3 cards, is that a straight? As @SimonAndréForsberg has mentioned, what about aces low / aces high?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:22:21.183",
"Id": "61092",
"Score": "0",
"body": "@retailcoder Let's not make it too complicated for now. If he is assuming a 5-card hand, that's acceptable IMO :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:26:46.510",
"Id": "61094",
"Score": "1",
"body": "Although I have to add: If you don't want to handle both the low & high ace case, that's OK for now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:27:00.600",
"Id": "61095",
"Score": "1",
"body": "Wait a minute, a straight is 5 cards, even if your hand has 7 cards ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:31:17.353",
"Id": "61096",
"Score": "0",
"body": "@tomdemuyt that's what makes it a PITA!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:38:50.657",
"Id": "61097",
"Score": "0",
"body": "@tomdemuyt Depends on if you're playing Texas Hold 'em or one of the million other possible poker variations."
}
] |
[
{
"body": "<p>It's not that hard. </p>\n\n<p>Instead of sorting the cards, looping over them and skipping double results, let's convert them to a more useful format:</p>\n\n<pre><code>var bitmap = 0;\n\nfor(var i = 0; i < cards.length; i++)\n{\n var value = cards[i].value;\n\n // set i+1 bit in the bitmap\n bitmap |= 1 << (value + 1);\n\n // if it's an ace, also set the low bit\n if(value === 12)\n bitmap |= 1;\n}\n</code></pre>\n\n<p>Now, if there's a card of value <code>i</code> in your hand, the <code>i+1</code> bit will be set in the bitmap. An Ace is treated as two cards with values 13 and 0.\nNext, we scan the bitmap for 5 consecutive bits set, which is equivalent to 31 (<code>1 | 2 | 4 | 8 | 16</code>). We start with the highest straight, which is 9.\nThe lowest straight is 0, if there is no straight <code>i</code> is -1.</p>\n\n<pre><code>for(var i = 10; i--; )\n{\n if((bitmap & 31 << i) === (31 << i))\n {\n break;\n }\n}\n</code></pre>\n\n<p>The method works for games with more than 5 cards. Note that in any variant of Poker, 5 cards make a hand, so even in Omaha with 9 cards, 5 cards give you a straight.</p>\n\n<p><strong>Note:</strong> The method is roughly equivalent to creating a set (and checking for 5 consecutive elements). As you can see, with bit-wise operators it is much simpler to check for 5 consecutive cards. </p>\n\n<p><strong>Another note:</strong> There's a harder-to-understand but slightly faster method for testing a straight given the bitmap. I might add it later, but for now I think this method hard enough to understand for beginners.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:53:40.847",
"Id": "37082",
"ParentId": "37077",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "37082",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:08:42.387",
"Id": "37077",
"Score": "10",
"Tags": [
"javascript",
"playing-cards",
"weekend-challenge"
],
"Title": "isStraight evaluation function"
}
|
37077
|
<p>This is one of my Haskell solutions to a variation of the N-Queens problem, where the queens can move like knights in addition to their normal moves. It has been optimized somewhat to avoid investigating redundant combinations.</p>
<pre><code>place :: Int -> [[Int]]
place 0 = [[]]
place n = go $ take n $ repeat [1..n]
where go [] = [[]]
go (row:rest) = do
q <- row
qs <- go $ safe q rest
return (q : qs)
safe q = notK q . notD q . notC q
notC q = map (filter (/= q))
notD q = (map (\(x, r) -> filter (\y -> abs(y - q) /= x) r)) . (zip [1..])
notK q = map (\(f, r) -> filter f r) . (zip (kFilters q))
kFilters q = (\x -> abs (x - q) /= 2) : (\x -> abs (x - q) > 1) : (repeat (const True))
solutions = length . place
main = do
n <- readLn
putStrLn $ show $ solutions n
</code></pre>
<p>I am satisfied with the performance, but I feel there must be a more elegant way to apply a series of functions (in this case, filters) to a list.</p>
<p>In each iteration of the recursive function <code>go</code>, the top row of the board is selected and then for each position in sequence a queen is positioned and the function recurs with a filtered copy of the rest of the board, so that each iteration has only safe squares to choose from. The <code>safe</code> function applies three filters to the board:</p>
<ol>
<li><code>notC</code> removes all spaces in the same column as the new queen.</li>
<li><code>notD</code> removes any spaces on a diagonal from the new queen.</li>
<li><code>notK</code> removes knight moves from the next two lines.</li>
</ol>
<p>I feel that <code>notK</code> in particular could be implemented more cleanly and idiomatically but I couldn't see a better way to apply one function to the first item of a list, another to the second and something else to the rest. And using <code>zip</code> does save me from having to check for the end of the board.</p>
<p>I wouldn't be surprised if there is a better way to write <code>notD</code>. So I am looking for more expressive ways to apply a sequence of varying functions to successive list items.</p>
<p><strong>UPDATE</strong>:</p>
<p>I realise that I can use <code>uncurry</code> to clean up <code>notK</code>...</p>
<pre><code> notK q = map (uncurry filter) . (zip (kFilters q))
</code></pre>
<p>and the two filters in Kfilters can be written in dot notation...</p>
<pre><code> ((/= 2) . abs . subtract q) : ((/= 1) . abs . subtract q) : ...
</code></pre>
<p>which allows the kFilters line to be rendered as</p>
<pre><code> kFilters = (f 2) : (f 1) : (repeat (const True))
</code></pre>
<p>but this doesn't actually change my original question. I'm still looking for a better mechanism for applying a varying sequence of functions to a list.</p>
|
[] |
[
{
"body": "<pre><code>notK q = map (uncurry filter) . (zip (kFilters q))\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>notK q rows = zipWith filter (kFilters q) rows\n</code></pre>\n\n<p>Onto making above Haskell less <em>idiomatic</em> and less <em>pointfree</em> and more <em>readable</em>.</p>\n\n<pre><code>notC q = map (filter (/= q))\nnotD q = (map (\\(x, r) -> filter (\\y -> abs(y - q) /= x) r)) . (zip [1..])\nnotK q = map (\\(f, r) -> filter f r) . (zip (kFilters q))\n</code></pre>\n\n<p>These three are logically similar but structurally dissimilar. </p>\n\n<p>First let's factor out common components, give them meaningful names, and some comments to help those readers without the Developer's Manual.</p>\n\n<pre><code>-- a new queen placed in column q\n-- would take a piece placed in column x\n-- n rows down\n-- because (r, q) and (r+n, x)\n\n-- are on the same column\nsameColumn q n x = x == q\n\n-- are on the same diagonal\nsameDiagonal q n x = abs(x - q) == n\n\n-- or (n, |q - x|) is in [(1,2),(2,1)]\nonKnightMove :: Int -> Int -> Int -> Bool\nonKnightMove q n x = (n, abs(x - q)) `elem` [(1,2),(2,1)]\n</code></pre>\n\n<p>The last one needs a better name still, oh well. At least they are of the same form, with parameter name use consistent among them (and elsewhere).</p>\n\n<pre><code>rowFilterList :: Int -> (Int -> Int -> Int -> Bool) -> [Int -> Bool]\nrowFilterList q pred = map (\\n x -> not $ pred q n x) [1..]\n</code></pre>\n\n<p>such that <code>kFilters q = rowFilterList q onKnightMove</code></p>\n\n<pre><code>filterRows :: Int -> (Int -> Int -> Int -> Bool) -> [[Int]] -> [[Int]]\nfilterRows q pred rows = zipWith filter (rowFilterList q pred) rows\n</code></pre>\n\n<p>This way <code>notC q = filterRows q sameColumn</code> and <code>notD q = filterRows q sameDiagonal</code></p>\n\n<p><code>notK q . notD q . notC q</code> a repetition is evident. And we now can factor it out easily.</p>\n\n<pre><code>filterWithAll :: Int -> [[Int]] -> [Int -> Int -> Int -> Bool] -> [[Int]]\nfilterWithAll q rows preds = foldl (\\rows' pred -> filterRows q pred rows') rows preds\n</code></pre>\n\n<p>such that <code>safe q rows = filterWithAll q rows [sameColumn, sameDiagonal, onKnightMove]</code></p>\n\n<p>By factoring out <code>[sameColumn, sameDiagonal, onKnightMove]</code> as a parameter to <code>place n</code> one could easily generalize <code>place</code> from n super-queens to n queens or n rooks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:05:56.930",
"Id": "37236",
"ParentId": "37081",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T21:40:22.837",
"Id": "37081",
"Score": "9",
"Tags": [
"haskell",
"recursion",
"functional-programming",
"linked-list",
"higher-order-functions"
],
"Title": "Better or more idiomatic way to apply a sequence of functions in Haskell"
}
|
37081
|
<p>I'm working on <a href="https://github.com/benjamin-hodgson/Contexts" rel="nofollow">an open-source test framework</a> which needs to dynamically import Python source modules from a given directory.</p>
<p>I can't just use <code>importlib.import_module()</code> or <code>__import__()</code>, because it's a black box and I need to do some source-code-rewriting. On the other hand, I feel the <a href="http://www.python.org/dev/peps/pep-0302/" rel="nofollow">PEP 302 Import Hooks</a> to be overkill for what I'm trying to do (they seem to be designed with importing totally foreign file formats in mind), so I rolled my own:</p>
<pre><code>import os
import sys
import types
def import_module(dir_path, module_name):
if module_name in sys.modules:
return sys.modules[module_name]
filename = resolve_filename(dir_path, module_name)
with open(filename, 'r', encoding='utf-8') as f:
source = f.read()
# Here I do some AST munging
code = compile(source, filename, 'exec')
module = create_module_object(module_name, filename)
exec(code, module.__dict__)
sys.modules[module_name] = module
return module
def resolve_filename(dir_path, module_name):
filename = os.path.join(dir_path, *module_name.split('.'))
# I happen to know that the calling code will already have
# determined whether it's a package or not
if os.path.isdir(filename):
filename = os.path.join(filename, '__init__.py')
else:
filename += '.py'
return filename
def create_module_object(module_name, filename):
module = types.ModuleType(module_name)
module.__file__ = filename
if '__init__.py' in filename:
module.__package__ = module_name
module.__path__ = [os.path.dirname(filename)]
else:
if '.' in module_name:
module.__package__, _ = module_name.rsplit('.', 1)
else:
module.__package__ = ''
return module
</code></pre>
<p>To paraphrase <a href="http://en.wikipedia.org/wiki/Greenspun's_tenth_rule" rel="nofollow">Greenspun's Tenth Rule</a>:</p>
<blockquote>
<p>Any sufficiently complicated Python program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of the import system.</p>
</blockquote>
<p>So, does my code do everything it's supposed to? I wrote my tests against an implementation that used <code>importlib.import_module()</code> and then rewrote it as this one, which gives me some confidence, but I'm not sure whether I've missed any important steps.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T22:44:10.730",
"Id": "61103",
"Score": "0",
"body": "Did you consider subclassing [`importlib.SourceLoader`](http://docs.python.org/3/library/importlib.html#importlib.abc.SourceLoader) and providing an implementation of the `get_code` method? This looks to be exactly what you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T22:48:52.867",
"Id": "61105",
"Score": "0",
"body": "@GarethRees Could you elaborate on the advantages of that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:00:45.810",
"Id": "61106",
"Score": "0",
"body": "You'd only have to implement the bit of the import process that you want to change (not the whole of it as at present) and this would give you more confidence that what you had done was correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:17:25.513",
"Id": "61107",
"Score": "0",
"body": "@GarethRees But wouldn't I also have to write a 'finder' and install it onto `sys.meta_path`? Seems like I'd be trading simplicity in one part for complexity in another."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:24:01.807",
"Id": "61108",
"Score": "0",
"body": "Couldn't you just instantiate your class and call its `load_module` method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:30:38.167",
"Id": "61110",
"Score": "0",
"body": "Perhaps I've misunderstood the documentation, but I was under the impression that you were supposed to return a 'loader' from a 'finder' and let `importlib` call the relevant methods, not call them yourself. But, maybe I'm confused."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:40:47.037",
"Id": "61111",
"Score": "1",
"body": "That's what you have to do if you want `import foo` to call your code. But if you're prepared to call your code directly, you can shortcut some of the steps."
}
] |
[
{
"body": "<p>I took @GarethRees's advice and subclassed <code>importlib.abc.SourceLoader</code>. After reading <code>importlib</code>'s source code, I arrived at the following implementation:</p>\n\n<pre><code>import importlib.abc\n\ndef import_module(dir_path, module_name):\n filename = resolve_filename(dir_path, module_name)\n\n # I got test failures when I left this out, even though I thought it\n # was a responsibility of the loader.\n # If you know why this is, please enlighten me!\n if module_name in sys.modules:\n return sys.modules[module_name]\n\n return ASTFrobnicatingLoader(module_name, filename).load_module(module_name)\n\n\n# in importlib, this function would be the job of the 'finder'\ndef resolve_filename(dir_path, module_name):\n filename = os.path.join(dir_path, *module_name.split('.'))\n if os.path.isdir(filename):\n filename = os.path.join(filename, '__init__.py')\n else:\n filename += '.py'\n return filename \n\n\nclass ASTFrobnicatingLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader):\n def get_code(self, fullname):\n source = self.get_source(fullname)\n path = self.get_filename(fullname)\n\n parsed = ast.parse(source)\n self.frobnicate(parsed)\n\n return compile(parsed, path, 'exec', dont_inherit=True, optimize=0)\n\n def module_repr(self, module):\n return '<module {!r} from {!r}>'.format(module.__name__, module.__file__)\n</code></pre>\n\n<p><code>import_module</code> now creates an instance of my custom loader and calls its <code>load_module</code> template method, which is provided by the abstract base class. By inheriting from both FileLoader and SourceLoader, I get a 'free' implementation of the whole protocol and I only need to override <code>get_code</code>.</p>\n\n<p>In Python 3.4, SourceLoader provides a <code>source_to_code</code> method which you can override. It would've been ideal for my purposes (because the only thing I'm customising is the generation of the code object) but sadly I'm stuck with having to override the whole of <code>get_code</code> and calling <code>get_source</code> and <code>get_filename</code> manually.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:30:15.317",
"Id": "37167",
"ParentId": "37083",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37167",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T22:24:35.287",
"Id": "37083",
"Score": "4",
"Tags": [
"python",
"import"
],
"Title": "Dynamically importing Python source modules from a given directory"
}
|
37083
|
<p>My Game class has a property of type Player, which inherits from Entity:</p>
<pre><code>player = new Player( "knight.png" );
</code></pre>
<p>It also has a property of type World, which has a collection of Entities (Robot inherits from Entity):</p>
<pre><code>world = new World( new List<Entity>
{
new Robot( "guy_1.png" ),
new Robot( "guy_2.png", new MoveBehavior( Directions.Up ) )
};
</code></pre>
<p>Finally, it has a Physics object with which I register the Player and World properties:</p>
<pre><code>physics.Register( player );
physics.Register( world );
</code></pre>
<p>This is a typical observer pattern. The Register method on the Physics class adds each object to its own collection of Entities.</p>
<pre><code>public void Register( Entity entity )
{
if ( !entity.Collidable )
{
return;
}
entity.Physics = this;
entities.Add( entity );
}
public void Register( World world )
{
foreach ( var entity in world.Entities.Where( e => e.Collidable ) )
{
Register( entity );
}
}
</code></pre>
<p>In my game loop, I update each of the Entities:</p>
<pre><code>foreach ( var entity in Entities )
{
entity.Update( gameTime );
}
</code></pre>
<p>When Update is called on the Robot class, it will execute its behavior:</p>
<pre><code>private readonly IBehavior behavior;
public override void Update( GameTime gameTime )
{
if ( behavior != null )
{
behavior.DoIt( gameTime, this );
}
}
</code></pre>
<p>Since there are two Robots in the World (see above), one of them will stand still and one of them will move. Now, when DoIt is called on the MoveBehavior class is where I do some collision detection:</p>
<pre><code>private readonly Vector2 direction;
public bool DoIt( GameTime gameTime, Entity entity )
{
if ( entity.DetectCollision( direction ) )
{
// Do nothing
return false;
}
entity.Move( direction );
return true;
}
</code></pre>
<p>(By the way, this is a simplified example. I'll get to my question really soon.)</p>
<p>Remember, when I registered the Player and World properties they each got assigned to them the Physics object. This is the DetectCollision method on the Entity class:</p>
<pre><code>public bool DetectCollision( Vector2 direction )
{
var newPosition = position + direction;
if ( physics != null && physics.DetectCollision( newPosition, frame ) )
{
return true;
}
return false;
}
</code></pre>
<p>Finally we jump into the DetectCollision method on the Physics class. This method looks for a collision between any of the Entities that are registered with it:</p>
<pre><code>private IList<Entity> entities;
public bool DetectCollision( Vector2 position, Rectangle frame )
{
var collisions = entities.Count( e => e.Position.Y < position.Y + frame.Height
&& e.Position.X < position.X + frame.Width
&& e.Position.Y + e.Frame.Height > position.Y
&& e.Position.X + e.Frame.Width > position.X );
// An entity will always collide with itself
// We want to know if it will collide with another entity
return collisions > 1;
}
</code></pre>
<p>Whew! I have a few problems with this implementation that I need advice on:</p>
<ol>
<li><p>All of the properties of the Entity class are publicly exposed so they are accessible in the Physics class. e.g., I check <code>entity.Collidable</code> and I assign a value to <code>entity.Physics</code> inside the Register method, and I use <code>e.Position</code> and <code>e.Frame</code> in DetectCollision. I know I can change each of these to <code>e.getCollidable()</code>, <code>e.setPhysics()</code>, <code>e.getPosition()</code> and <code>e.getFrame()</code>, but I'm not sure what the point of doing that would be. Especially since I'm using C# auto-properties which does that for you anyways (I think).</p></li>
<li><p>It seems incredibly complicated. I realize collision detection is complicated no matter what you do but is there a better way to register all my objects with the physics engine?</p></li>
</ol>
<p>I'm sure my algorithm could be better, but my primary concern (at least regarding this question) is the game design and not the actual collision detection algorithm.</p>
<p><strong>Edit</strong></p>
<p>I will try to clarify my first question. My Entity class has the following properties:</p>
<pre><code>public bool Collidable { get; set; }
public Rectangle Frame { get; set; }
public IPhysics Physics { get; set; }
public Vector2 Position { get; set; }
</code></pre>
<p>I think I understand the principle of encapsulation enough. If anything I am probably confused about auto-properties. I believe the above will be compiled to something resembling this:</p>
<pre><code>private Rectangle _collidable;
public Rectangle GetCollidable()
{
return _collidable;
}
public void SetCollidable( Rectangle value )
{
_collidable = value;
}
</code></pre>
<p>for each of the properties with <code>{get; set;}</code>. So my first question is: what is the point of doing that manually? Just so I can say my code is encapsulated? I know I can also do this:</p>
<pre><code>public bool Collidable { get; private set; }
public Rectangle Frame { get; private set; }
public IPhysics Physics { get; private set; }
public Vector2 Position { get; private set; }
</code></pre>
<p>But doesn't that violate some principle of encapsulation? After some debate (with myself) my Entity class is looking like this:</p>
<pre><code>private readonly bool collidable;
private readonly Rectangle frame;
private IPhysics physics;
private Vector2 position;
public bool IsCollidable()
{
return collidable;
}
public void SetPhysics( IPhysics physics )
{
this.physics = physics;
}
</code></pre>
<p>Then I refactored the DetectCollision method on the Physics class to call an overload of DetectCollision on the Entity class:</p>
<pre><code>public bool DetectCollision( Vector2 position, Rectangle frame )
{
var collisions = entities.Count( e => e.DetectCollision( position, frame ) );
// An entity will always collide with itself
// We want to know if it will collide with another entity
return collisions > 1;
}
</code></pre>
<p>So now I have two versions of DetectCollision on Entity:</p>
<pre><code>public bool DetectCollision( Vector2 direction )
{
var newPosition = position + direction;
if ( physics != null && physics.DetectCollision( newPosition, frame ) )
{
return true;
}
return false;
}
public bool DetectCollision( Vector2 otherPosition, Rectangle otherFrame )
{
return position.Y < otherPosition.Y + otherFrame.Height
&& position.X < otherPosition.X + otherFrame.Width
&& position.Y + frame.Height > otherPosition.Y
&& position.X + frame.Width > otherPosition.X;
}
</code></pre>
<p>Is this better? I don't know! It seems to be a good compromise to me but it also seems insanely complicated. So the workflow goes something like this every time the game updates:</p>
<pre><code>Game.Update() -> Entity.Update() -> Robot.Update()
-> MoveBehavior.DoIt() -> Entity.DetectCollision()
-> Physics.DetectCollision() -> Entity.DetectCollision() (overload)
</code></pre>
<p>And it does this like a million times per second!</p>
|
[] |
[
{
"body": "<p>Your vision about what is an auto-property is correct. Your first question is essentially whether you should use an auto-property or a property instead, which I answer this way:</p>\n\n<p>Is the property implementation likely to change?</p>\n\n<p>Example:</p>\n\n<pre><code>public class Person{\n public int Age{get; set;}\n}\n</code></pre>\n\n<p>With this you are able to change the age to -1. To prevent that, you would change your code to the following:</p>\n\n<pre><code>public class Person{\n private int age;\n public int Age{\n get{return age;} \n set{\n if(age >= 0)age = value;\n else throw new Exception();\n }\n }\n}\n</code></pre>\n\n<p>You had to: Introduce a field, write get and set code. If you hadn't used an auto-property in the first place, you would have to write less. Although I leave up to you if you would rather use an auto-property or a property. For me there are some cases that I don't use them and they could fit. Properties do not disrespect the principle of encapsulation. In my example (in second code segment) if you exposed the field age you could set it to a negative number, but you couldn't do that if you used the property. Basically you can change the implementation of the property whenever you want, but you wouldn't have to change the code that references that property.</p>\n\n<p>Your re-factored code is actually better and I am glad that you improved it that way! With that code you are able to unit test the method <code>DetectCollision</code> in a better way, and separate the collision logic.</p>\n\n<p>Finally, if you have to register many objects on your physics object, you may have (at least) two approaches:</p>\n\n<ul>\n<li><p>Implement a fluent method call so you could write</p>\n\n<pre><code>physics.Register(player).Register(world);\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>physics.Register(player);\nphysics.Register(world);\n</code></pre></li>\n<li><p>Or write a new class that includes all possible Entities and register it in your physics object. This can be bothersome if you want to add a new type of entity in the future and adds an additional piece that you have to remember (know its purpose). This is also like returning to the same problem because now you would have to register all objects here!</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T00:25:01.117",
"Id": "37093",
"ParentId": "37085",
"Score": "7"
}
},
{
"body": "<p>One thing to consider with this design is that the <code>Physics</code> class seems to have a case of <a href=\"http://sourcemaking.com/refactoring/feature-envy\" rel=\"nofollow\">Feature Envy</a>. Perhaps the collision detection logic should live in the <code>Physics</code> class instead of the <code>Entity</code> class.</p>\n\n<p>Given:</p>\n\n<pre><code>Physics physics = new Physics();\nEntity[] surroundingEntities = ... ;\n</code></pre>\n\n<p>I may be speculating too much, but I think you want to be able to write in Entity:</p>\n\n<pre><code>var meInNewPosition = AfterSubmittedMove(this);\nvar anyCollisions = physics.Collisions(meInNewPosition, surroundingEntities).Any();\nif (!anyCollisions) {\n this.CompleteMove();\n} else {\n this.RejectMove();\n}\n</code></pre>\n\n<p>where <code>Collisions()</code> would call <code>DetectCollisions</code> on all possible entities pairs. <code>Any()</code> ensures that it will return after the first one detected.</p>\n\n<p>Think about the API you want between your classes, and then write methods to implement that API. Test Driven Development is invaluable here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:09:24.487",
"Id": "61506",
"Score": "1",
"body": "There are certainly some pros and cons about having collision detection logic in physics. One pro is that if you have it on your entities then they need to be aware of their behavior. One cons is (as I mentioned in my post) that you can unit test it in a better way (you don't have to add it to a physics object and you may test the behavior out of the context of physics). But in essence one should ask: does it make sense that my entity is aware of how do it collide?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:28:42.567",
"Id": "61516",
"Score": "0",
"body": "I agree, if an Entity can make different decisions based on projected collisions, then it should have access to that information, But I believe that it should still get that knowledge from a Physics object."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:48:51.103",
"Id": "37252",
"ParentId": "37085",
"Score": "2"
}
},
{
"body": "<p>OK, what I don't like about your pattern and what I feel leads you to complain about its overcomplicatedness, is your behavior pattern.</p>\n\n<p>The problem is that you want to have a generic DoIt() method on the behavior but a particular behavior has specific dependencies. In this case the physics object. You get around this by adding the physics object to Entity, but you can see how this can grow out of control. Say your robot either has wheels or hover propulsion, wheeled robots sink when they enter water, hover robots can move as normal. Now you need to add RobotFeet to your Entity so that the behavior can decide what to do.</p>\n\n<p>Adding the property to Entity is the wrong way to go. </p>\n\n<p>You could instead inject the Physics object into the Behavior when it is constructed</p>\n\n<p>OR</p>\n\n<p>Make a generic Behaviour so you can reference the subclass of entity in DoIt. ie. DoIt(Robot entity)</p>\n\n<p>OR</p>\n\n<p>Abandon the behavior pattern and put the move logic in the Robot class</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-05T09:57:09.940",
"Id": "88852",
"ParentId": "37085",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T22:53:11.373",
"Id": "37085",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"game",
"xna"
],
"Title": "Using the observer pattern with collision detection"
}
|
37085
|
<p>I started a Chess in Python for fun. I learned Python in my free time but I've been doing it for a while. The code works but I just want to know if there's anything non-pythonic in my code. The functions calculate all potentially possible moves (ignoring game state).</p>
<pre><code>from itertools import product
from itertools import chain
from functools import wraps
from math import atan2
_angle_to_direction = {90: "up", -90: "down", 180: "right", 0: "left", -135: "right_down", 135: "right_up",
45: "left_up", -45: "left_down"}
def move(f):
@wraps(f)
def wrapper(*args, **kwargs):
x, y = args
moves = f(x, y)
if (x, y) in moves: moves.remove((x, y))
return moves
return wrapper
def check_range(x:tuple) -> bool:
return x[0] >= 0 and x[1] >= 0 and x[0] < 8 and x[1] < 8
@move
def _knight(x:int, y:int) -> set:
moves = chain(product([x - 1, x + 1], [y - 2, y + 2]), product([x - 2, x + 2], [y - 1, y + 1]))
moves = {(x, y) for x, y in moves if check_range((x, y))}
return moves
@move
def _rook(x:int, y:int) -> set:
return {(x, i) for i in range(0, 8)}.union({(i, y) for i in range(0, 8)})
@move
def _bishop(x:int, y:int) -> set:
possible = lambda k: [(x + k, y + k), (x + k, y - k), (x - k, y + k), (x - k, y - k)]
return {j for i in range(1, 8) for j in possible(i) if check_range(j)}
def direction(start:tuple, end:tuple) -> str:
delta_a = start[1] - end[1]
delta_b = start[0] - end[0]
return _angle_to_direction[int(atan2(delta_a, delta_b) * 180 / 3.14)]
</code></pre>
|
[] |
[
{
"body": "<p>The implementation of your <code>move</code> decorator is a little schizophrenic. On the one hand, it carefully allows any and all arguments to be passed to it by declaring itself <code>def wrapper(*args, **kwargs)</code>. However it then requires exactly two positional arguments which it then passes on to the wrapped function. Keyword arguments are accepted but ignored and dropped. I would suggest changing this to be all at one end or all at the other end of this spectrum. Given the annotations elsewhere, I would expect you to prefer changing the function to <code>def wrapper(x, y)</code> (or maybe to <code>def wrapper(x, y, **kwargs)</code> but then also passing <code>**kwargs</code> to <code>f</code>).</p>\n\n<p>It might make sense to incorporate <code>check_range</code> into the wrapper as well, simplifying most of the move generators. It might also make sense to skip the decorator and instead call the filter in your move generators: <code>return filter_move((x, y), moves)</code>.</p>\n\n<p>As a side note, it would be interesting to see if there are any performance advantages to either the current approach of checking for <code>(x,y)</code> and conditionally removing it or to unconditionally doing a set difference: <code>return f(x, y) - {(x, y)}</code>.</p>\n\n<p>The rest of your code is fairly straightforward, if perhaps a bit too clever. Clever is typically bad for other readers, or for debugging misbehavior. The two things that stand out to me is the name of your lambda <code>possible</code> (which seems more like a <code>diagonal_moves_of_distance</code> or simply <code>diagonal</code>), and the approach used for <code>direction</code>. Given the limited number of possible move deltas, bringing in trigonometry to handle it seems like overkill; I'd almost expect a simple if/else tree instead. As is, it will have problems classifying a knight's move.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:01:02.047",
"Id": "61246",
"Score": "0",
"body": "thank you sir. i would agree with you being too clever is bad that was my main concern. very detailed answer much appreciated"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:20:28.373",
"Id": "37153",
"ParentId": "37089",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37153",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:34:32.487",
"Id": "37089",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"chess"
],
"Title": "Calculating potential Chess moves"
}
|
37089
|
<p>Here is some code of mine that prints out the relative date according to the current time:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, char *argv[])
{
int i = 1;
struct tm date = {0};
char relativeDays[80];
char* temp = strtok(argv[1], "/");
while(temp != 0)
{
switch(i++)
{
case 1:
date.tm_mon = atoi(temp) - 1;
break;
case 2:
date.tm_mday = atoi(temp);
break;
case 3:
date.tm_year = atoi(temp) - 1900;
}
temp=strtok(NULL, "/");
}
i = (int) difftime(time(NULL), mktime(&date))/86400;
sprintf(relativeDays, "%d", abs(i));
if (i > 0) printf("%s\n", strcat(relativeDays, " days ago."));
else if (i < 0) printf("%s\n", strcat(relativeDays, " days from now."));
else printf("Today\n");
return 0;
}
</code></pre>
<hr>
<p>Sample input and output:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>$ ./date 12/8/2013
2 days ago.
$ ./date 12/10/2013
Today
$ ./date 12/24/2013
13 days from now.
</code></pre>
</blockquote>
<p>Any thoughts on how to improve the code, specifically how to make it shorter?</p>
|
[] |
[
{
"body": "<p>I've commented your code: </p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(int argc, char *argv[])\n{\n int i = 1;\n struct tm date = {0};\n char relativeDays[80];\n</code></pre>\n\n<p>Check For Proper Input</p>\n\n<pre><code> if(argc != 2)\n {\n printf(\"Two arguments required!\\n\");\n return -1;\n }\n\n char *temp = strtok(argv[1], \"/\");\n</code></pre>\n\n<p><code>temp</code> will be <code>NULL</code> if empty. Also, add a <code>break</code> after <code>case 3:</code> for consistency. If you think you'll need to handle unexpected cases, use <code>default</code> at the end.</p>\n\n<pre><code> while(temp != NULL)\n {\n switch(i++)\n {\n case 1:\n date.tm_mon = atoi(temp) - 1;\n break;\n case 2:\n date.tm_mday = atoi(temp);\n break;\n case 3:\n date.tm_year = atoi(temp) - 1900;\n break;\n default:\n }\n</code></pre>\n\n<p>Be consistent with spacing.</p>\n\n<pre><code> temp = strtok(NULL, \"/\");\n }\n</code></pre>\n\n<p>Add comments so people know what your intentions are. Why are you dividing by 86400?</p>\n\n<pre><code> i = (int)difftime(time(NULL), mktime(&date)) / 86400;\n sprintf(relativeDays, \"%d\", abs(i));\n</code></pre>\n\n<p>Use spaces to make everything more readable.</p>\n\n<pre><code> if(i > 0)\n printf(\"%s\\n\", strcat(relativeDays, \" days ago.\"));\n else if(i < 0)\n printf(\"%s\\n\", strcat(relativeDays, \" days from now.\"));\n else\n printf(\"Today\\n\");\n\n return 0;\n}\n</code></pre>\n\n<p>Edit:</p>\n\n<p>This while block can be changed to the following. Though it doesn't change the operation, it may improve the aesthetics. </p>\n\n<pre><code>while(temp != NULL)\n{\n int num = atoi(temp); \n switch(i++)\n {\n case 1:\n date.tm_mon = num - 1;\n break;\n case 2:\n date.tm_mday = num;\n break;\n case 3:\n date.tm_year = num - 1900;\n break;\n default:\n printf(\"Unexpected input. Blowing up now!\\n\");\n break;\n }\n\n temp = strtok(NULL, \"/\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:24:52.490",
"Id": "61122",
"Score": "0",
"body": "`NULL` is `#define`d as `0`, so that shouldn't be the case. Perhaps a bug has been exposed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:26:58.207",
"Id": "61123",
"Score": "0",
"body": "You are right, it works. I thought putting it in as `!temp` would give the same result, but it didn't. Good advice overall (+1), but I was really looking for a way to shorten the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:31:21.980",
"Id": "61124",
"Score": "1",
"body": "Hi, I've upvoted your answer - however be careful with comment-in-code answers, they might eventually get flagged as *code-only* posts - which are frowned upon. Take the time to format your answer, make it look good, lay down your thoughts in plain text - and of course include improved code blocks if you want to :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:31:37.287",
"Id": "61125",
"Score": "0",
"body": "Probably can't be shortened and still be readable. Short code doesn't necessarily mean good code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:32:41.403",
"Id": "61126",
"Score": "0",
"body": "@retailcoder Thanks. I didn't know that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:34:33.217",
"Id": "61127",
"Score": "0",
"body": "@BitFiddlingCodeMonkey I agree, but if you look in the `while` loop I have, I convert a `char*` to an `int` every iteration of the loop instead of once outside of the loop. That could be a way to shorten it (I've tried to shorten it that way, but failed)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:40:38.427",
"Id": "61128",
"Score": "0",
"body": "@syb0rg You can add `int num = atoi(temp);` right at the start of the `while` loop, before the `switch` and replace all the `atoi(temp)`s in your code with `num`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:41:57.960",
"Id": "61129",
"Score": "0",
"body": "@BitFiddlingCodeMonkey It broke the code :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:24:22.677",
"Id": "61139",
"Score": "0",
"body": "@syb0rg Can you tell me what input you're giving your program? What is the string in `argv[1]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:29:12.493",
"Id": "61140",
"Score": "0",
"body": "@BitFiddlingCodeMonkey I edited in some working I/O into my answer. With your most recent edit, here is the I/O: `./clean 12/8/2013\n16050 days ago.`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:38:28.840",
"Id": "61141",
"Score": "0",
"body": "@syb0rg It's working for me. Add `printf(\"%s\\n\", argv[1]);` at the beginning of `main` and tell me what it says."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:41:05.900",
"Id": "61142",
"Score": "0",
"body": "@BitFiddlingCodeMonkey `12/8/2013`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:42:57.567",
"Id": "61143",
"Score": "0",
"body": "@syb0rg It's working for me. Wish I could help you more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T05:38:35.997",
"Id": "61149",
"Score": "4",
"body": "@BitFiddlingCodeMonkey: anyone working on this code will probably know, or easily deduce, that 86400 is the number of seconds in a day (60x60x24). Not sure it needs a comment. Making it a named constant on the other hand..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:55:06.460",
"Id": "61232",
"Score": "0",
"body": "@BitFiddlingCodeMonkey \"NULL is #defined as 0\" is incorrect for the language posted here (C). You may find it true in other languages such as C++."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:19:01.787",
"Id": "37097",
"ParentId": "37096",
"Score": "5"
}
},
{
"body": "<p>Concerns if <code>argv[1]</code> represents a <em>local</em> time</p>\n\n<ol>\n<li>Should add <code>date.tm_isdst = -1;</code>. Although the h:m:s are set to 0, can't think of a dst change that crossed a day, so this is pedantic.</li>\n</ol>\n\n<p>Other concerns.</p>\n\n<ol>\n<li>Should check range of year, easy for folks to enter only last 2 digits and expect 13 to be 2013.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:00:14.050",
"Id": "61195",
"Score": "0",
"body": "@syb0rg Alos: In effect, you are comparing the days elapsed since zero-hour of the supplied date (the first moment of that day) to \"now\". Then using `(int) difftime()`, you are rounding toward 0 that result. The asymmetry of using \"first moment\" and \"round toward 0\" may be of concern."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T06:04:39.920",
"Id": "37108",
"ParentId": "37096",
"Score": "4"
}
},
{
"body": "<p>Date-time handling is tricky to implement correctly. Unless you want to reinvent the wheel, use <code>strptime(3)</code> to parse dates. Your code will be simpler, and you should automatically get validation to reject dates like \"12/32/2013\".</p>\n\n<p>When converting the input date to a Unix epoch value using <code>mktime(&date)</code>, you always interpret the date as midnight in the UTC time zone. That leads to two bugs in calculating the date difference, in my opinion:</p>\n\n<ol>\n<li>The user would expect the input date to be interpreted in the local time zone.</li>\n<li>When specifying tomorrow's date (and interpreting it in the local time zone), the output will be <code>\"Today\"</code>, since 00:00:00 of the following day is less than 86400 seconds in the future.</li>\n</ol>\n\n<p>The output routines could also use some slight improvement. You need neither <code>abs()</code> nor <code>strcat()</code>. Also, it would be human-friendly to handle singular numbers.</p>\n\n<p>The magic number 86400 should be explained better.</p>\n\n<pre><code>#include <stdio.h>\n#include <time.h>\n\n#define SECONDS_PER_DAY (24 * 60 * 60L)\n\nint main(int argc, char *argv[]) {\n char *input_str;\n time_t now;\n struct tm input_tm = { 0 };\n long diff_days;\n\n if (argc <= 1) {\n fprintf(stderr, \"Need MM/DD/YYYY input\\n\");\n return 1;\n }\n input_str = argv[1];\n\n /* When calling difftime(), both arguments should have the same\n hr:min:sec, else you might get off-by-one-day errors depending on\n the time of day when you run the program. We could either use\n 00:00:00 midnight for both, or the current hr:min:sec for both.\n Let's use the current time for both. */\n time(&now);\n localtime_r(&now, &input_tm);\n\n /* strptime() will fill in MM/DD/YYYY, but leave the hr:min:sec and\n time zone fields from above alone. */\n if (!strptime(input_str, \"%m/%d/%Y\", &input_tm)) {\n fprintf(stderr, \"Bad date: %s\\n\", input_str);\n return 1;\n }\n diff_days = (long)difftime(now, mktime(&input_tm)) / SECONDS_PER_DAY;\n\n if (diff_days > 0) {\n printf(\"%ld day%s ago.\\n\", diff_days, (diff_days > 1 ? \"s\" : \"\"));\n } else if (diff_days < 0) {\n printf(\"%ld day%s from now.\\n\", -diff_days, (diff_days < -1 ? \"s\" : \"\"));\n } else {\n printf(\"Today\\n\");\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:47:40.727",
"Id": "61205",
"Score": "1",
"body": "Note: With 16-bit `int`, `86400` is recognized as needing a larger type, such as `long`. Thus the division occurs with `(long) 86400`. With the more understandably `(24 * 60 * 60)`, would such a compilation also come up with the same product or `(int) (24 * 60 * 60)` which is 20864?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:49:11.823",
"Id": "61244",
"Score": "0",
"body": "@chux Good observation. I've widened the data types accordingly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T09:18:34.333",
"Id": "37116",
"ParentId": "37096",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37116",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T02:04:56.980",
"Id": "37096",
"Score": "9",
"Tags": [
"performance",
"c",
"datetime"
],
"Title": "Printing out relative date from current time"
}
|
37096
|
<p>This code is supposed to delete every node from a linked list with a given value. </p>
<p>Are there any logical errors with this implementation? Did I do anything wrong or is there an area of this implementation that needs significant improvement. Any suggestions? </p>
<pre><code>public boolean delete(int d) {
Node tmpNode = head;
Node prevNode = null;
boolean deletedANode = false;
if (head == null) {
return deletedANode;
}
while (tmpNode != null) {
if (tmpNode.data == d) {
if (tmpNode == head) {
head = head.next;
}
else {
prevNode.next = tmpNode.next;
}
deletedANode = true;
}
prevNode = tmpNode;
tmpNode = tmpNode.next;
}
return deletedANode;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:20:26.830",
"Id": "61137",
"Score": "0",
"body": "You need to give some more detail on what the delete is supposed to do... like, at the moment it keeps searching even after it's deleted a node... is that intentional?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:21:16.607",
"Id": "61138",
"Score": "0",
"body": "yes, it is supposed to delete every node with the value"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:50:48.583",
"Id": "61253",
"Score": "0",
"body": "I suggest renaming the method to `deleteAll(value)`."
}
] |
[
{
"body": "<p>Your code is buggy, if you have two Nodes with the same value in succession it will corrupt the list.... </p>\n\n<p><code>prevNode</code> will be set to the deleted node <code>tempNode</code>, and if the next value also matches the input value you will be working with the wrong node as <code>prevNode</code>.</p>\n\n<p>Also, why is <code>d</code> a good name for the input search value?</p>\n\n<p>To avoid future bugs it is convenient to mark constant input values as <code>final</code>. It also can potentially help with performance</p>\n\n<p>You need to change some code:</p>\n\n<pre><code>// added final, change input to `searchValue`\npublic boolean delete(final int searchValue) {\n Node tmpNode = head;\n Node prevNode = null;\n boolean deletedANode = false;\n\n /*\n This code is redundant, the while-loop does the same effective thing.\n if (head == null) {\n return deletedANode;\n }\n */\n\n while (tmpNode != null) {\n if (tmpNode.data == searchValue) {\n if (tmpNode == head) {\n head = head.next;\n } else { // fixed indenting/newline\n prevNode.next = tmpNode.next;\n }\n // fixed indenting\n deletedANode = true;\n } else {\n // only advance the prevNode when there's no match.\n prevNode = tmpNode;\n }\n tmpNode = tmpNode.next;\n }\n\n return deletedANode;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T05:37:09.553",
"Id": "61863",
"Score": "0",
"body": "Good catch with bug of wrongly advancing tmpNode. Thanks for the help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:30:58.677",
"Id": "37101",
"ParentId": "37099",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "37101",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T03:00:40.717",
"Id": "37099",
"Score": "5",
"Tags": [
"java",
"linked-list"
],
"Title": "Linked List Delete Node Function"
}
|
37099
|
<p>I'm using PHP, MySQL, Smarty, jQuery, etc. for my website. I'm using an MVC architecture to develop the website. Now in one of the functionality I'm fetching a large amount of data and perform some processing on it. Then I'm returning the finally processed data from model to the controller and assigning it to the Smarty template for showing the result to the user.</p>
<p>But all this scenario is taking more time. The user has to wait for a long time to get the final output result. I've tried my best to optimize my code so the data could be fetched, processed and displayed to the user as early as possible but still the issue of loading time exists.</p>
<p>Can anyone please help me in optimizing the code in order to reduce the loading time?</p>
<p><strong>Controller (match_question.php)</strong>:</p>
<pre><code><?php
require_once("../../includes/application-header.php");
$objQuestionMatch = new QuestionMatch();
$request = empty( $_GET ) ? $_POST : $_GET ;
if($request['subject_id']!="")
$subject_id = $request['subject_id'];
if($request['topic_id']!="")
$topic_id = $request['topic_id'];
if($subject_id !='' && $topic_id !='')
$all_match_questions = $objQuestionMatch->GetSimilarQuestionsBySubjectIdTopicId($subject_id, $topic_id);
$smarty->assign('all_match_questions', $all_match_questions);
$smarty->display("match-question.tpl")
?>
</code></pre>
<p><strong>Model (QuestionMatch.php)</strong>:</p>
<pre><code><?php
class QuestionMatch {
var $mError = "";
var $mCheck;
var $mDb;
var $mValidator;
var $mTopicId;
var $mTableName;
function __construct() {
global $gDb;
global $gFormValidation;
$this->mDb = $gDb;
$this->mValidator = $gFormValidation;
$this->mTableName = TBL_QUESTIONS;
}
/**
* This function is used to get all the questions from the given subject id and topic id
*/
function GetSimilarQuestionsBySubjectIdTopicId($subject_id, $topic_id) {
/*SQL query to find out questions from given subject_id and topic_id*/
$sql = " SELECT * FROM ".TBL_QUESTIONS." WHERE question_subject_id=".$subject_id;
$sql .= " AND question_topic_id=".$topic_id;
$this->mDb->Query($sql);
$questions_data = $this->mDb->FetchArray();
/*Same array $questions_data is assigned to new array $questions to avoid the reference mismatching*/
$questions = $questions_data;
/*Array of words to be excluded from comparison process*/
$exclude_words = array('which','who','what','how','when','whom','wherever','the','is','a','an','and','of','from');
/*This loop removes all the words of $exclude_words array from all questions and
*converts all questions' text into lower case
*/
foreach($questions as $index=>$arr) {
$questions_array = explode(' ',strtolower($arr['question_text']));
$clean_questions = array_diff($questions_array, $exclude_words);
$questions[$index]['question_text'] = implode(' ',$clean_questions);
}
/*Now the actual comparison of each question with every other question stats here*/
foreach ($questions as $index=>$outer_data) {
/*Logic to find out the no. of count question appeared into tests*/
$sql = " SELECT count(*) as question_appeared_count FROM ".TBL_TESTS_QUESTIONS." WHERE test_que_id=";
$sql .= $outer_data['question_id'];
$this->mDb->Query($sql);
$qcount = $this->mDb->FetchArray(MYSQL_FETCH_SINGLE);
$question_appeared_count = $qcount['question_appeared_count'];
$questions_data[$index]['question_appeared_count'] = $question_appeared_count;
/*Crerated a new key in an array to hold similar question's ids*/
$questions_data[$index]['similar_questions_ids_and_percentage'] = Array();
$outer_question = $outer_data['question_text'];
$qpcnt = 0;
//foreach ($questions as $inner_data) {
/*This foreach loop is for getting every question to compare with outer foreach loop's
question*/
foreach ($questions as $secondIndex=>$inner_data) {
/*This condition is to avoid comparing the same questions again*/
if ($secondIndex <= $index) {
/*This is to avoid comparing the question with itself*/
if ($outer_data['question_id'] != $inner_data['question_id']) {
$inner_question = $inner_data['question_text'];
/*This is to calculate percentage of match between each question with every other question*/
similar_text($outer_question, $inner_question, $percent);
$percentage = number_format((float)$percent, 2, '.', '');
/*If $percentage is >= $percent_match only then push the respective question_id into an array*/
if($percentage >= 85) {
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['question_id'] = $inner_data['question_id'];
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['percentage'] = $percentage;
/*$questions_data[$secondIndex]['similar_questions_ids_and_percentage'][$qpcnt]['question_id'] = $outer_data['question_id'];
$questions_data[$secondIndex]['similar_questions_ids_and_percentage'][$qpcnt]['percentage'] = $percentage;*/
/*Logic to find out the no. of count question appeared into tests*/
$sql = " SELECT count(*) as question_appeared_count FROM ".TBL_TESTS_QUESTIONS." WHERE test_que_id=";
$sql .= $inner_data['question_id'];
$this->mDb->Query($sql);
$qcount = $this->mDb->FetchArray(MYSQL_FETCH_SINGLE);
$question_appeared_count = $qcount['question_appeared_count'];
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['question_appeared_count'] = $question_appeared_count;
$qpcnt++;
}
}
}
}
} //}
/*Logic to create the return_url when user clicks on any of the displayed matching question_ids*/
foreach ($questions_data as $index=>$outer_data) {
if(!empty($outer_data['similar_questions_ids_and_percentage'])) {
$return_url = ADMIN_SITE_URL.'modules/questions/match_question.php?';
$return_url .= 'op=get_question_detail&question_ids='.$outer_data['question_id'];
foreach($outer_data['similar_questions_ids_and_percentage'] as $secondIndex=>$inner_data) {
$return_url = $return_url.','.$inner_data['question_id'];
}
$questions_data[$index]['return_url'] = $return_url.'#searchPopContent';
}
}
/*This will return the complete array with matching question ids*/
return $questions_data;
}
}
?>
</code></pre>
<p><strong>View (match-question.tpl)</strong>:</p>
<pre><code><table width="100%" class="base-table tbl-practice" cellspacing="0" cellpadding="0" border="0">
<tr class="evenRow">
<th width="33%" style="text-align:center;" class="question-id">Que ID</th>
<th width="33%" style="text-align:center;" class="question-id">Matching Que IDs</th>
<th width="33%" style="text-align:center;" class="question-id">Percentage(%)</th>
</tr>
{if $all_match_questions}
{foreach from=$all_match_questions item=qstn key=key}
{if $qstn.similar_questions_ids_and_percentage}
{assign var=counter value=1}
<tr class="oddRow">
<td class="question-id" align="center" valign="top">
<a href="{$qstn.return_url}" title="View question" class="inline_view_question_detail">QUE{$qstn.question_id}</a>{if $qstn.question_appeared_count gt 0}-Appeared({$qstn.question_appeared_count}){/if}
</td>
{foreach from=$qstn.similar_questions_ids_and_percentage item=question key=q_no}
{if $counter gt 1}
<tr class="oddRow"><td class="question-id" align="center" valign="top"></td>
{/if}
<td class="question" align="center" valign="top">
{if $question.question_id!=''}
<a href="{$qstn.return_url}" title="View question" class="inline_view_question_detail">QUE{$question.question_id}</a>{if $question.question_appeared_count gt 0}-Appeared({$question.question_appeared_count}){/if}
{if $question.question_appeared_count eq 0}
<a id ="{$question.question_id}" href="#" class="c-icn c-remove delete_question" title="Delete question"> Delete</a>{/if}
{/if}
</td>
<td class="question" align="center" valign="top">
{if $question.percentage!=''}{$question.percentage}{/if}
{assign var=counter value=$counter+1}
</td>
</tr>
{/foreach}
{/if}
{/foreach}
{else}
<tr>
<td colspan="2" align="center"><b>No Questions Available</b></td>
</tr>
{/if}
</table>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T17:51:21.043",
"Id": "68759",
"Score": "0",
"body": "One note on `$request = empty( $_GET ) ? $_POST : $_GET ;` is that it's really bad practice to do this. It makes the `$_POST`/`$_GET` abstract, I would rather use (don't, really don't) use `$_REQUEST`. Even more, is it possible to have both POST and GET data."
}
] |
[
{
"body": "<p>I would remove your very performance heavy <code>GetSimilarQuestionsBySubjectIdTopicId</code> from PageLoad and call/load it asynchronously with AJAX.</p>\n\n<p>I would also try and redesign it so you do not execute a SQL query in a loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T10:09:11.027",
"Id": "61163",
"Score": "0",
"body": ":I thought and tired using AJAX but not able to called the AJAX request recursively. Can you please demonstrate your answer with some code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T10:20:57.207",
"Id": "61164",
"Score": "0",
"body": "@PHPLover - Sorry but I don't know enough PHP to effectively implement it. But here is a simple example (http://stackoverflow.com/a/5298493/1021726) which should hopefully get you started."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T10:06:57.630",
"Id": "37119",
"ParentId": "37105",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T04:56:47.157",
"Id": "37105",
"Score": "2",
"Tags": [
"performance",
"mysql",
"mvc",
"php5",
"smarty"
],
"Title": "Reducing the loading time of a page"
}
|
37105
|
<p>I'm new to Scala, and would appreciate any notes about a better approach, correctness, or style.</p>
<pre><code>/**
* Call proc(f) for each file in the directory tree rooted at dir.
*
* proc will not be called for directories, just for files.
*/
def traverse(dir: File, proc: File => Unit): Unit = {
dir.listFiles foreach { (f) => {
if(f.isDirectory) {
traverse(f, proc)
} else {
proc(f)
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is fine. Nevertheless, removing unnecessary braces can increase readability:</p>\n\n<pre><code>def traverse(dir: File, proc: File => Unit): Unit =\n dir.listFiles foreach { f => if (f.isDirectory) traverse(f, proc) else proc(f) }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T07:53:32.317",
"Id": "37110",
"ParentId": "37106",
"Score": "3"
}
},
{
"body": "<p>I prefer something like this:</p>\n\n<pre><code>def traverse(root: File): Iterator[File] =\n if (root.isDirectory)\n root.listFiles.iterator.map(traverse).fold(Seq(root).iterator)(_ ++ _)\n else\n Seq(root).iterator\n</code></pre>\n\n<p>You can use that iterator with a <code>foreach</code> (as you are doing), but you get a lot more of flexibility, you can do <code>map</code>, <code>filter</code>, and all the usual Scala awesomeness very easily. For example, this is what you were doing</p>\n\n<pre><code> def whatever(root:File, proc:File => Unit) = traverse(root) foreach proc\n</code></pre>\n\n<p>There may be more efficient (<code>@tailrec</code> maybe), lazy or better options. I'd be interested in seeing them, this was just the most immediate solution I could think of to put an example.</p>\n\n<p>PD: this doesn't filter the files that are directories, you can impose that constraint with something of the form:</p>\n\n<pre><code>def traverse(root: File): Iterator[File] =\n if (root.isDirectory)\n root.listFiles.iterator map traverse reduce (_ ++ _)\n else\n Seq(root).iterator\n</code></pre>\n\n<p>But I'd suggest <em>not</em> to do that.</p>\n\n<p>PD: perhaps the signature should be something like:</p>\n\n<pre><code>def toTraversable(root:File): Traversable[File]\n</code></pre>\n\n<p>Maybe its in the standard Scala API already...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-27T12:43:44.123",
"Id": "91933",
"ParentId": "37106",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37110",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T05:05:19.967",
"Id": "37106",
"Score": "3",
"Tags": [
"beginner",
"scala",
"file-system"
],
"Title": "Processing files in a directory tree"
}
|
37106
|
<p>I have an array of 1000 numbers, randomly generated. 10 of those numbers must be between 0-9 (including 0 and 9), and 10 of those numbers must be between 991 and 1000 (including 991 and 1000). This is what I came up with:</p>
<pre><code>arr = []
980.times do
arr << (11..989).to_a.sample
end
arr2 = []
10.times do
arr2 << rand(10)
end
arr3 = []
10.times do
arr3 << (990..1000).to_a.sample
end
arr4 = []
arr4 = arr + arr2 + arr3
arr4.shuffle
</code></pre>
<p>Is there a more elegant way to do this in ruby? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:45:17.720",
"Id": "61790",
"Score": "0",
"body": "Is it only 10 for ranges at the end or \"at least 10\"?"
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p>Try to learn some functional programming, you shouldn't write Ruby as it were a low-level language (like C). Favor expressions over statements. My 2-cents on the matter, I hope it helps: <a href=\"http://www.slideshare.net/tokland/functional-programming-with-ruby-9975242\" rel=\"nofollow\">http://www.slideshare.net/tokland/functional-programming-with-ruby-9975242</a></p></li>\n<li><p>Let me show a simple example of using FP. The first 4 lines of your code could be written like this: <code>arr = 980.times.map { (11..989).to_a.sample }</code></p></li>\n<li><p><code>arr4 = []</code>: Why? the next line assigns it to another expression. </p></li>\n<li><p><code>range.to_a.sample</code>. That's very inefficient, better <code>rand(range)</code>.</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>ranges = [0..9, 11..989, 990..1000]\noutput = ranges.flat_map do |range|\n range.map { rand(range) }\nend.shuffle\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T07:54:37.553",
"Id": "64837",
"Score": "0",
"body": "I can't improve on your \"I'd write:\", but here's a variant: `ranges.reduce([]) {|arr, range| arr + Array.new(range.size) {rand(range)}}.shuffle`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T09:38:42.170",
"Id": "64846",
"Score": "0",
"body": "@CarySwoveland: Not that efficiency is important here (those are small arrays), but note that `reduce` with `+` leads to O(n^2) code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T09:03:35.603",
"Id": "37114",
"ParentId": "37107",
"Score": "5"
}
},
{
"body": "<p>Be careful at the boundaries — you didn't implement what you wanted. The output will never contain 10, and it might include 990 among the [991, 1000] range.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T09:27:24.497",
"Id": "37117",
"ParentId": "37107",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37114",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T05:51:16.697",
"Id": "37107",
"Score": "2",
"Tags": [
"ruby",
"random"
],
"Title": "rand number generator with limits in ruby"
}
|
37107
|
<p>Please review the code and suggest better algorithm to efficiently extract key/value from files using multithread.</p>
<p><strong>Input</strong> : FormNGFAddTab:First add Tab control inside Tabs control.परीक्षण</p>
<p><strong>Output</strong> : </p>
<p><strong>Key</strong> : FormNGFAddTab</p>
<p><strong>Value</strong> : First add Tab control inside Tabs control.परीक्षण</p>
<p><strong>Separator</strong> : ':'</p>
<p><strong>DataHolder/DataStructure</strong> : Any[Dictionary/Hash Table/Array/Linked List]</p>
<p><strong>Solution 1:</strong></p>
<pre><code> public static ConcurrentDictionary<string, string> LoadActivityLookupParallelOptimized(string filePath)
{
Stopwatch sw = Stopwatch.StartNew();
var lineCollection = File.ReadAllLines(filePath);
var newLookup = new System.Collections.Concurrent.ConcurrentDictionary<string, string>();
int ParallelThreads = 100;
Parallel.ForEach(lineCollection, new ParallelOptions() { MaxDegreeOfParallelism = ParallelThreads }, currentLine =>
{
if (String.IsNullOrEmpty(currentLine))
{
return;
}
if (currentLine.Substring(0, 2) == "//")
{
return;
}
int iPos = currentLine.IndexOf(":", StringComparison.OrdinalIgnoreCase);
int iiPos = currentLine.IndexOf("::", StringComparison.OrdinalIgnoreCase);
string currentKey, currentValue;
if (iPos>0)
{
if (iiPos>0)
{
currentKey = currentLine.Substring(0, iiPos);
if ((iPos = currentLine.IndexOf(":", iiPos + 2, StringComparison.OrdinalIgnoreCase)) > 0)
{
if ((iPos + 1) <= currentLine.Length)
{
currentValue = currentLine.Substring(iPos + 1);
}
else
{
currentValue = string.Empty;
}
}
else
{
return;
}
}
else
{
currentKey = currentLine.Substring(0, iPos);
if ((iPos + 1) <= currentLine.Length)
{
currentValue = currentLine.Substring(iPos + 1);
}
else
{
currentValue = string.Empty;
}
}
newLookup.TryAdd(currentKey.Trim(), currentValue.TrimEnd());
}
});
sw.Stop();
Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);
return newLookup;
}
</code></pre>
<p>I am using Parallel.Foreach to process all lines.</p>
<p><strong>Solution 2:</strong></p>
<pre><code> private static Dictionary<string, string> ProcessLine(string SourceFile)
{
Stopwatch sw2 = Stopwatch.StartNew();
Dictionary<string, string> keyValue = new Dictionary<string, string>();
using (FileStream fs = new FileStream(SourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
string sLine = string.Empty;
string sKey = string.Empty, sValue = string.Empty;
try
{
while ((sLine = sr.ReadLine()) != null)
{
int iPos, iiPos;
sLine = sLine.Trim();
if (String.IsNullOrEmpty(sLine))
{
continue;
}
////Ignore comments
if (sLine.Substring(0, 2) == "//")
{
continue;
}
////Ignore if line does not contain :
if ((iPos = sLine.IndexOf(":", StringComparison.OrdinalIgnoreCase)) > 0)
{
if ((iiPos = sLine.IndexOf("::", StringComparison.OrdinalIgnoreCase)) > 0)
{
sKey = sLine.Substring(0, iiPos);
if ((iPos = sLine.IndexOf(":", iiPos + 2, StringComparison.OrdinalIgnoreCase)) > 0)
{
if ((iPos + 1) <= sLine.Length)
{
sValue = sLine.Substring(iPos + 1);
}
else
{
sValue = string.Empty;
}
}
else
{
continue;
}
}
else
{
sKey = sLine.Substring(0, iPos);
if ((iPos + 1) <= sLine.Length)
{
sValue = sLine.Substring(iPos + 1);
}
else
{
sValue = string.Empty;
}
}
keyValue.Add(sKey.Trim(), sValue.TrimEnd());
}
}
sw2.Stop();
Console.WriteLine("Time taken: {0}ms", sw2.Elapsed.TotalMilliseconds);
}
catch (Exception ex)
{
//Workflow.NET.Log logger = new Log();
//logger.LogError(ex, "Could not add key (" + sKey + ") from folder (" + SourceFile + "), Error:" + ex.Message);
}
}
}
return keyValue;
}
Main()
var filePath = @"M:\Dev3.0\Locales\hi-IN\NGF\NGFStandardMessages.txt";
var result = LoadActivityLookupParallelOptimized(filePath);
var result2 = ProcessLine(filePath);
Console.ReadLine();
Results:
Algo 1: 3.1717 ms
Algo 2: 0.6234
LinesCount : 196 lines to process
</code></pre>
<p>Please share your thoughts on writing better algorithms for File Processing.</p>
<p>My Thoughts:</p>
<p>--> Using <code>IndexOf</code> is costly but it is the most efficient.</p>
<p><strong>Sample Key/Value in a line</strong>:</p>
<p><strong>Line1</strong> : FormNGFAddTab:First add Tab control inside Tabs control.परीक्षण</p>
<p><strong>Key</strong> : FormNGFAddTab</p>
<p><strong>Value</strong> : First add Tab control inside Tabs control.परीक्षण</p>
<p><strong>Common string in key</strong> : FormNGF</p>
|
[] |
[
{
"body": "<ol>\n<li>You should use multithreading for reading if you are after performance, so solution which uses <code>Parallel.ForEach()</code> is definetely better.</li>\n<li>For really big files, you should not read all the text into memory. Instead you should create multiple file streams, split your file into reading sections and read those asynchroniously. For smaller files (200 lines is really small) your approach is fine.</li>\n<li><p>Your algorithm can be simplified if you'd use <code>Split</code> method. For example:</p>\n\n<pre><code>//remove comments\nvar lineWithoutComments = line.Split(new []{\"//\"}, StringSplitOptions.None).FirstOrDefault();\nif (String.IsNullOrWhitespace(lineWithoutComments)) continue;\n//split key and value\nvar split = lineWithoutComments.Split(new []{\":\"}, StringSplitOptions.None);\nif (split.Length < 2) continue;\nvar key = split[0].Trim();\nvar value = split[1].Trim();\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:07:40.717",
"Id": "61332",
"Score": "0",
"body": "Thank you for the comments. I am concerned about performance as file size is close to 10MB i.e generating close to 1,00,000 keys. I tried the string.split operation but it costly when it comes to performance. I am trying to avoid IndexOf method which is costly. Searching for better algo to extract Key/Value pair."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:15:01.730",
"Id": "61333",
"Score": "0",
"body": "Is it possible to write the algo in C++ and call it in c# to get best performance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:18:12.243",
"Id": "37123",
"ParentId": "37109",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T07:27:09.787",
"Id": "37109",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "How to efficiently extract Key Value and load to C# dictionary/HashMap from large files [File Size grows]?"
}
|
37109
|
<p>I'm writing a code for my application: you can create a task, and you can choose the moment when you want to send this task (to some kind of user):</p>
<ul>
<li>Send now</li>
<li>Send later</li>
<li>Repeat</li>
</ul>
<p><img src="https://i.stack.imgur.com/CdSLW.jpg" alt="Send options"></p>
<p>You can select from above options. If you choose <strong>send later</strong>, you'll be prompted for a date:</p>
<p><img src="https://i.stack.imgur.com/goDOj.jpg" alt="Send later"></p>
<p>And there are variety of options if you choose <strong>Repeat</strong>:</p>
<p><img src="https://i.stack.imgur.com/aeLZA.jpg" alt="Repeat daily"></p>
<p>(they're all <a href="http://imgur.com/U4Arkn7,YbkT4Z8,Kh6BtU0,mwddxfM,iR6o1ee,hZ9ETi9#0" rel="nofollow noreferrer">on imgur</a> if you're interested)</p>
<p>I use design-driven-development approach, and now I'm working on the <em>view model</em> for ASP.Net MVC application. Now it looks like this:</p>
<pre><code>public class TaskViewModel
{
// ... other properties (title, etc...)
public SendOptions SendOption { get; set; } // when to send: now || later || repeat
public RepeatDetails Repeat { get; set; }
public LaterDetails Later { get; set; }
// ==============================================
// enumerations & classes
// ==============================================
public enum SendOptions { Now = 0, Later = 1, Repeat = 2}
public enum RepeatTypes { Daily = 0, Weekly = 1, Monthly = 2, Yearly = 3 }
public enum WeekDay {
[EnumDescription("working day")]
WorkingDay,
[EnumDescription("weekend")]
WeekEnd,
[EnumDescription("sunday")]
Sunday,
[EnumDescription("monday")]
Monday,
[EnumDescription("tuesday")]
Tuesday,
[EnumDescription("wednesday")]
Wednesday,
[EnumDescription("thursday")]
Thursday,
[EnumDescription("friday")]
Friday,
[EnumDescription("saturday")]
Saturday
}
public enum WeekDayNumber
{
[EnumDescription("1st")]
First,
[EnumDescription("2nd")]
Second,
[EnumDescription("3rd")]
Third,
[EnumDescription("4th")]
Fourth,
[EnumDescription("Last")]
Last
}
public enum Month
{
[EnumDescription("January")]
January,
[EnumDescription("February")]
February,
[EnumDescription("March")]
March,
[EnumDescription("April")]
April,
[EnumDescription("May")]
May,
[EnumDescription("June")]
June,
[EnumDescription("July")]
July,
[EnumDescription("August")]
August,
[EnumDescription("September")]
September,
[EnumDescription("October")]
October,
[EnumDescription("November")]
November,
[EnumDescription("December")]
December
}
// ==============================================
// class for later screen details
// ==============================================
public class LaterDetails
{
public DateTimeOffset LaterUtc { get; set; }
}
// ==============================================
// class for repeat screen details
// ==============================================
public class RepeatDetails
{
public RepeatTypes RepeatType { get; set; }
public string StartAtTime { get; set; }
public RepeatDailyDetails Daily { get; set; }
public RepeatWeeklyDetails Weekly { get; set; }
public RepeatMonthlyDetails Monthly { get; set; }
public RepeatYearlyDetails Yearly { get; set; }
public EndByDetails EndBy { get; set; }
public class RepeatDailyDetails
{
public enum RepeatDailyTypes { EveryDay = 0, EveryWorkingDay = 1 }
public RepeatDailyTypes RepeatDailyType { get; set; }
public int EveryNthDay { get; set; }
}
public class RepeatWeeklyDetails
{
public int EveryNthWeek { get; set; }
public bool IsSunday { get; set; }
public bool IsMonday { get; set; }
public bool IsTuesday { get; set; }
public bool IsWednesday { get; set; }
public bool IsThursday { get; set; }
public bool IsFriday { get; set; }
public bool IsSaturday { get; set; }
}
public class RepeatMonthlyDetails
{
public enum RepeatMonthlyTypes { OnCertainDay = 0, At = 1 }
public RepeatMonthlyTypes RepeatMonthlyType { get; set; }
public int EveryNthMonth { get; set; }
public string OnNthDay { get; set; }
public WeekDayNumber WeekDayNumber { get; set; }
public WeekDay WeekDay { get; set; }
}
public class RepeatYearlyDetails
{
public int EveryNthYear { get; set; }
public Month Month { get; set; }
public enum RepeatYearlyTypes { OnCertainDay = 0, At = 1 }
public RepeatYearlyTypes RepeatYearlyType { get; set; }
public string OnNthDay { get; set; }
public WeekDayNumber WeekDayNumber { get; set; }
public WeekDay WeekDay { get; set; }
}
}
// ==============================================
// class for end by details
// ==============================================
public class EndByDetails
{
public enum EndByTypes { NoEndDate = 0, EndAfter = 1, EndByDate = 2 }
public EndByTypes EndByType { get; set; }
public int Occurrences { get; set; }
}
public TaskViewModel()
{
Later = new LaterDetails();
Repeat = new RepeatDetails()
{
Daily = new RepeatDetails.RepeatDailyDetails(),
Weekly = new RepeatDetails.RepeatWeeklyDetails(),
Monthly = new RepeatDetails.RepeatMonthlyDetails(),
Yearly = new RepeatDetails.RepeatYearlyDetails(),
EndBy = new EndByDetails()
};
}
}
</code></pre>
<p>EnumDescription attribute is used to create a dropdown list based on descriptions for enums:</p>
<pre><code>public class EnumDescription : Attribute
{
public string Text
{
get { return _text; }
} private string _text;
public EnumDescription(string text)
{
_text = text;
}
}
</code></pre>
<p>I'm not satisfied with a code, and need a fresh look. What would you suggest to improve? Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T13:07:41.680",
"Id": "61180",
"Score": "0",
"body": "Does this pertain to all of these versions, or do you just need a single [asp.net-mvc] tag?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:09:21.660",
"Id": "61222",
"Score": "1",
"body": "@Jamal I think that multiple tags on a single question that differ only by version almost never make sense. On the other hand, it makes sense to have a general non-version tag, so I've gone ahead and created it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:10:18.733",
"Id": "61223",
"Score": "0",
"body": "@svick: Good call. I was going to do it since SO has done the same, but I wasn't entirely sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:32:06.843",
"Id": "61228",
"Score": "0",
"body": "@Jamal, I just need a single tag"
}
] |
[
{
"body": "<p>Well one UI suggestion is where you can select to Repeat -> Daily -> Every working day. </p>\n\n<ul>\n<li><p>This is very culture specific e.g., a Swede will work on the 4th of July while an American won't.</p></li>\n<li><p>It also depends on the year as some holidays do not fall on the same date, and this takes us back to point 1</p></li>\n</ul>\n\n<p>As for your code I just feel like I need to say that I'm allergic to comments like</p>\n\n<pre><code>// ==============================================\n// class for repeat screen details\n// ==============================================\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:37:25.933",
"Id": "61229",
"Score": "3",
"body": "I have the same feeling about this kind of commenting style. It would nicer to simply rename RepeatDetails to RepeatScreenDetails, and remove the whole comment imho."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T09:55:45.083",
"Id": "37118",
"ParentId": "37115",
"Score": "3"
}
},
{
"body": "<p>For the end by option, I would add an option \"End after N occurences\".</p>\n\n<p>Also, by reading the code, I can't figure out what is the purpose of the variable \"LaterUtc\" in LaterDetails class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:41:15.173",
"Id": "37147",
"ParentId": "37115",
"Score": "1"
}
},
{
"body": "<h2>Some suggestions on reducing verbosity</h2>\n\n<p>Your <code>EnumDescription</code> is unnecessaryly verbose if you fallback to <code>Enum.ToString</code> as in <a href=\"https://stackoverflow.com/questions/479410/enum-tostring/479417#479417\">this SO answer</a> when description is not available, you could eliminate many description declarations e.g. months.</p>\n\n<p>If you had another attribute that describes optional string transformations, you could eliminate the rest of the attributes.</p>\n\n<pre><code>public enum WeekDay {\n [EnumDescription(\"working day\")]\n WorkingDay,\n [EnumDescription(\"weekend\")]\n WeekEnd,\n [EnumDescription(\"sunday\")]\n Sunday,\n [EnumDescription(\"monday\")]\n Monday,\n [EnumDescription(\"tuesday\")]\n Tuesday,\n [EnumDescription(\"wednesday\")]\n Wednesday,\n [EnumDescription(\"thursday\")]\n Thursday,\n [EnumDescription(\"friday\")]\n Friday,\n [EnumDescription(\"saturday\")]\n Saturday\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>[EnumDescriptionTransformations(\n new Transformations[]\n {\n Transformations.SplitCamelCase, \n Transformations.ToLower\n })]\npublic enum WeekDay {WorkingDay,\n // I really want to name this enum WeekEnd \n // even though it's grammatically incorrect\n [EnumDescription(\"weekend\")]\n WeekEnd,\n // without attributes these can be put on a single line\n Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday\n}\n</code></pre>\n\n<p>Where <code>Transformations</code> is fixed number of common transformations.</p>\n\n<pre><code>public enum Transformations{ SplitCamelCase, ToLower, Capitalize, .....}\n</code></pre>\n\n<p>I think <code>SplitCamelCase</code> would be a sensible default and could be replaced by <code>DoNotSplitCamelCase</code>.\nA reminder: when you are lower-casing for aesthetic reasons, and not grammatical reasons as was this time, that would be left to CSS etc to handle.</p>\n\n<p>You can also eliminate some common prefixes and improve readability. e.g. <code>RepeatDetails.RepeatDailyDetails</code> can be safely renamed to <code>RepeatDetails.DailyDetails</code>.</p>\n\n<p>Also </p>\n\n<pre><code> public class XXXDetails\n {\n public enum RepeatXXXTypes { ..... }\n public RepeatXXXTypes RepeatXXXType { get; set; }\n ......\n</code></pre>\n\n<p>can be safely converted to</p>\n\n<pre><code> public class XXXDetails\n {\n public enum Types { ...... }\n public Types Type { get; set; }\n ......\n</code></pre>\n\n<p><code>-Details</code> suffix is also unnecessary really, and serves only to prevent collision of property names and nested class names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:31:40.647",
"Id": "37212",
"ParentId": "37115",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T09:13:13.077",
"Id": "37115",
"Score": "0",
"Tags": [
"c#",
"asp.net-mvc"
],
"Title": "Task send options: Send Now, Send Later, Repeat (viewmodel)"
}
|
37115
|
<p>I am creating a string extension to validate some input.</p>
<p>My scenario is when we have a string it will format it according to following guideline.
If the sample string is “One Two Three Four Five” and the length is <=20 return same. If more than 20 then “One Two Three F Five”. If still length is more than 20 the “One Two T F Five” etc...</p>
<p>Is there any way I can improve this code? I thought it can use recursion?</p>
<pre><code>public static string ToShortName(this string name)
{
if (name.Length <= 20) return name;
var namelist = name.Split(' ');
var length = name.Length;
//add spaces
length = length + namelist.Count() - 1;
var output = "";
var indexList = new List<int>();
for (var i = namelist.Count() - 2; i >=1 ; i--)
{
indexList.Add(i);
if (length - namelist[i].Length <= 20)
{
break;
}
length = length - namelist[i].Length;
}
foreach (var i in indexList)
{
namelist[i] = namelist[i].Substring(0, 1);
}
output = string.Join(" ", namelist);
return output;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:31:28.043",
"Id": "61200",
"Score": "0",
"body": "As a side note, I would expect \"validation\" to return a true/false (or valid/invalid), rather than to return a possibly modified string. You may want to call this something else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:11:44.640",
"Id": "61224",
"Score": "0",
"body": "What should happen when you shorten is as much as you can and it still isn't less than 20 characters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:42:43.260",
"Id": "61339",
"Score": "0",
"body": "@svick: This is coming from a field which will be maximum 70 characters"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:03:01.607",
"Id": "61344",
"Score": "0",
"body": "@developcode It's still possible that can't be shortened, if the last and first words are too long, or if there's too many short words in the middle."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:23:54.870",
"Id": "61346",
"Score": "0",
"body": "@svick: That's the same thing I raised for Henriks' answer as well. It should have a check before it return the result. May be to return the initials only if the `result>20`. (I believe no one will have name initial which can occupy 20 characters though:))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:31:35.027",
"Id": "61347",
"Score": "0",
"body": "@MichaelUrman: Yes thanks, I have changed the name of the method"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:32:54.813",
"Id": "61348",
"Score": "0",
"body": "@developcode: That's a much better name than before!"
}
] |
[
{
"body": "<p>You should remove this</p>\n\n<pre><code>length = length + namelist.Count() - 1;\n</code></pre>\n\n<p>because length already includes the spaces.</p>\n\n<p>This </p>\n\n<pre><code>length = length - namelist[i].Length;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>length -= namelist[i].Length - 1;\n</code></pre>\n\n<p>because <code>namelist[i].Length-1</code> is the number of characters that are removed.</p>\n\n<p>Also: why <code>i >=1 - 1</code> instead of <code>i >= 0</code>?</p>\n\n<p>You can also do it in a single loop like this:</p>\n\n<pre><code> for (var i = namelist.Count() - 2; i >=1 && length > 20; i--)\n {\n length -= namelist[i].Length - 1;\n namelist[i] = namelist[i].Substring(0, 1);\n }\n\n return string.Join(\" \", namelist);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:14:32.213",
"Id": "61169",
"Score": "0",
"body": "Sorry,i >=1 - 1 was mistake. it is i >=1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:17:52.773",
"Id": "61170",
"Score": "0",
"body": "I am running two loops at the moment. Is it a good way of doing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:22:24.960",
"Id": "61172",
"Score": "0",
"body": "@developcode You can use single loop. See my edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:23:34.520",
"Id": "61173",
"Score": "0",
"body": "@Henrik: This loop will make everything shorter. like `O T T F Five`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:24:45.677",
"Id": "61174",
"Score": "0",
"body": "@huMptyduMpty No. Did you miss the `&& length > 20`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:27:39.273",
"Id": "61175",
"Score": "0",
"body": "@Henrik: Of course. I did miss that!! This is all fine :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:32:00.120",
"Id": "61176",
"Score": "0",
"body": "@Henrik: But at the end its better to check `if (output.Length > 39)\n output = output.NameCorrection();`?? but to check the first and last.since this always ignoring the first and last words. If combination of these to can be longer than 20 this will be invalid I guess?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:09:26.337",
"Id": "37122",
"ParentId": "37121",
"Score": "2"
}
},
{
"body": "<p>Here is more concise implementation. Also, when length of the string is more than max length, we need to run the loop at least once, so we should use <strong>do..while</strong> here. </p>\n\n<pre><code>public static string StringCorrection(this string name)\n{\n int maxLength = 20;\n if (name.Length <= maxLength) return name;\n\n string[] nameArray = name.Split(' ');\n int extraLength = name.Length - maxLength;\n int currentIndex = nameArray.Length - 2;\n\n if (currentIndex <= 0) return name;\n\n int wordLength = 0;\n do\n {\n wordLength = nameArray[currentIndex].Length;\n nameArray[currentIndex] = nameArray[currentIndex].Substring(0, 1);\n extraLength -= (--wordLength);\n currentIndex--;\n } while (extraLength > 0 && currentIndex > 0);\n\n return string.Join(\" \", nameArray);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T21:53:02.120",
"Id": "61273",
"Score": "1",
"body": "I find it hard to suggest using a do-while loop, and your implementation will walk right off the array if the described task isn't possible. But otherwise the advice is spot on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:48:13.890",
"Id": "61327",
"Score": "0",
"body": "Yes, we can add condition to make sure loop doesn't run off the array. I have updated the loop condition to care of that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T13:35:18.963",
"Id": "37128",
"ParentId": "37121",
"Score": "1"
}
},
{
"body": "<pre><code>public static string StringCorrection(this string name)\n</code></pre>\n\n<p><code>StringCorrection()</code> is not a great name. 1. I don't see any reason to call out the <code>String</code> type in the name. 2. This is not really a correction, it's more like shortening.</p>\n\n<p>Also, I'm not sure that this should be an extension method, because it's something quite specific, it's not generally useful for almost any string.</p>\n\n<pre><code>if (name.Length <= 20) return name;\n</code></pre>\n\n<p>I think the max length should be a parameter with a default value, so that the method is more general. Even if you don't do that, at least don't repeat the value, use a variable for it.</p>\n\n<pre><code>var output = \"\";\n</code></pre>\n\n<p>There doesn't seem to be any reason to declare the variable this early, or to actually have the variable at all. You could just write:</p>\n\n<pre><code>return string.Join(\" \", namelist);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:20:45.307",
"Id": "37143",
"ParentId": "37121",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:04:48.813",
"Id": "37121",
"Score": "3",
"Tags": [
"c#",
".net",
"strings",
"recursion"
],
"Title": "String Extension improvement"
}
|
37121
|
<p>Higher-order functions are functions which either</p>
<ol>
<li>take functions as arguments or</li>
<li>return them as output</li>
</ol>
<p>(or both). Functions which do neither of these are known, in contrast, as <em>first-order functions</em>.</p>
<p>Higher-order functions are a cornerstone of the functional programming paradigm, in which the manipulation and transformation of functions is at least as common as the manipulation and transformation of data. That said, several of the most widely-implemented higher-order functions are also found in modern imperative languages. Examples include</p>
<ol>
<li><code>map</code></li>
<li><code>filter</code></li>
<li>folding functions (<code>foldl</code>, <code>foldr</code> etc.)</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:56:13.123",
"Id": "37124",
"Score": "0",
"Tags": null,
"Title": null
}
|
37124
|
Higher-order functions are functions which either take functions as arguments or return them as output (or both). They are a cornerstone of functional programming.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T11:56:13.123",
"Id": "37125",
"Score": "0",
"Tags": null,
"Title": null
}
|
37125
|
<p>I have often encountered the following situation. I want to call a method in a Loop, but want to skip the call at the first run. It do not have to be a method, it also can be some lines of code that I want to skip. Here is one example:</p>
<p>I have a file which looks like that.</p>
<pre><code>headline:headline1
content:lorem ipsum dolor sit amet
content2:lorem ipsum dolor sit amet
content3:lorem ipsum dolor sit amet
headline:headline2
content1:lorem ipsum dolor sit amet
.
.
.
</code></pre>
<p>I iterate through the lines and generate following html:</p>
<pre><code><div> headline1 </div>
<ul>
<li> lorem ipsum dolor sit amet </li>
<li> lorem ipsum dolor sit amet </li>
<li> lorem ipsum dolor sit amet </li>
</ul>
<div> headline2 </div>
<ul>
<li> lorem ipsum dolor sit amet </li>
</ul>
.
.
.
</code></pre>
<p>My Code looks like that:</p>
<pre><code>private String createList(String file) {
StringBuilder output = new StringBuilder();
String[] lines = file.split("\n");
int headlineCounter = 0;
for (String line : lines) {
String[] fields = line.split(":");
if (fields[0].equals("headline")) {
if (headlineCounter > 0) {
output.append("</ul>");
}
output.append("<div>").append(fields[1]).append("</div>");
output.append("<ul>");
headlineCounter++;
} else {
output.append("<li>").append(fields[1]).append("</li>");
}
}
output.append("</ul>");
return output.toString();
}
</code></pre>
<p>The content always is wrapped with an <code><ul></code> tag. When a new headline appears the content of the last headline is at the end and has to be closed with <code></ul></code> <strong>except</strong> it's the first headline of course, because there is no content before, that has to be closed.</p>
<p>In my example I am using a counter. On this way it works, but there are other and better ways I think. How would you solve this problem? This is just an example there are of course other and better ways to generate html, I just wanted to show you an example to my question.</p>
|
[] |
[
{
"body": "<p>One elegant way to handle this is to parse the input into a more usable structure before transforming it to HTML. For example, each section could be represented as:</p>\n\n<pre><code>private class Section {\n final String headline;\n final List<String> contents = new ArrayList<String>();\n\n Section(String headline) {\n this.headline = headline;\n }\n\n String asHtml() {\n StringBuilder sb = new StringBuilde();\n\n sb.append(\"<div>\").append(headline).append(\"</div>\");\n sb.append(\"<ul>\");\n for (String item : contents) {\n sb.append(\"<li>\").append(item).append(\"</li>\");\n }\n sb.append(\"</ul>\");\n\n return sb.toString();\n }\n}\n</code></pre>\n\n<p>Note how the code clearly shows the structure of the resulting HTML.</p>\n\n<p>The parsing code now has a more focused responsibility: parsing and validating the input. It has nothing to do with the output format any more.</p>\n\n<pre><code>private Iterable<Section> parseList(String fileContents) {\n List<Section> sections = new LinkedList<Section>();\n\n for (String line : fileContents.split(\"\\n\")) {\n String[] fields = line.split(\":\");\n if (fields.length != 2) {\n // throw some exception\n }\n\n if (\"headline\".equals(fields[0])) {\n sections.add(new Section(fields[1]));\n continue;\n }\n\n if (sections.isEmpty()) {\n // throw some error because \"content\" came before \"headline\"\n }\n\n sections.getLast().contents.add(fields[1]);\n }\n\n return sections;\n}\n</code></pre>\n\n<p>I pointed out some lines with comments where you should do input validation. If you don't do this, you might get surprised by <code>ArrayIndexOutOfBoundsException</code>s if the input string is invalid.</p>\n\n<p>Building an object that represents each section has the advantage that invalid HTML <em>cannot</em> be produces – your current code could emit a <code><li></code> outside of an <code><ul></code>. </p>\n\n<p>Then in your main code, the sections are simply concatenated together:</p>\n\n<pre><code>StringBuilder output = new StringBuilder();\nfor (Sections section : parseList(...)) {\n output.append(section.asHtml());\n}\n</code></pre>\n\n<p>The advantage of separating the responsibilities of parsing and formatting is that it is now much easier to adapt a single part (e.g. to a new input or output format). My suggestion for the <code>Section</code> class has to be criticized here, because it does not follow the <em>Single Responsibility Principle</em>: it both represents a section, and formats the output. Those should ideally be separated into two different classes, so that the formatting can vary without <code>Section</code> having to change.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T14:51:53.897",
"Id": "61193",
"Score": "1",
"body": "Beware XSS!! Sanitize everything you put into a raw HTML string. Even if it's safe now, refactoring and changing requirements will put you at risk later, so better be safe than sorry!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:01:36.427",
"Id": "61536",
"Score": "0",
"body": "@Malachi I can't see where I forgot a `</div>`. Could you point it out to me so that I can fix it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:04:58.970",
"Id": "61537",
"Score": "0",
"body": "my bad I was looking in the wrong spot @amon"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T14:05:52.880",
"Id": "37131",
"ParentId": "37127",
"Score": "7"
}
},
{
"body": "<p>The problem with the input is that the <code>content</code> elements are not grouped. This is why the code uses the <code>headline</code> element, and it gives rise to the need to distinguish the first occurrence from all others.</p>\n\n<hr>\n\n<ul>\n<li><p><code>headlineCounter</code> is misleading. A boolean flag (e.g. <code>closingULneeded</code>) would have sufficed. By using an int, the code somewhat hides that fact.</p></li>\n<li><p>To know that the current <code>content</code> is the last one, the code would have to look ahead to the next line. Since it uses an iterator, this would have to be rewritten into a \"standard\" for loop (indexing into <code>lines</code>). Since the for loop would expose the position inside the array, the code then could just use a nested loop to process all following <code>content</code> elements; and btw write the opening and closing <code><ul></code> itself. No need to track any state information.</p></li>\n<li><p>The whole content of the file is passed to the method. Depending on the size of the file, this could get nasty. The code could easily avoid the string copy by not passing a string. In the same vein, don't return a string; this will display the same copy behaviour.</p></li>\n<li><p>Eventually, the creation of that <code>lines</code> array might be avoided, too.</p></li>\n<li><p>It looks like the code doesn't need to check for the whole <code>headline</code> string to decide whether the current line is a headline or content.</p></li>\n<li><p>The name of the method could reveal its intent a bit more explicitly. Something like <code>ConvertContentToHtmlFragment</code>; eventually containing the name of that particular file format, if existing.</p></li>\n<li><p>Should you know the format will complicate, perhaps a more <code>DSL</code>ish approach might prove useful.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T17:08:38.483",
"Id": "37149",
"ParentId": "37127",
"Score": "2"
}
},
{
"body": "<p>You probably want <code>line.split(\":\", 2)</code> if your text has any chance of containing colons.</p>\n\n<p>You can't concatenate just any text into HTML willy nilly. To prevent HTML injection flaws, you need to escape characters that may have special significance in HTML. You could use <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html\" rel=\"nofollow\"><code>StringEscapeUtils</code></a> in Apache Commons Lang or roll your own. The important thing is that you do it, for the sake of correctness and security.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:06:13.253",
"Id": "37181",
"ParentId": "37127",
"Score": "3"
}
},
{
"body": "<p>Besides the nice OO-solution, another (procedural) solution to your looping problem is possible:</p>\n\n<p>If you have cases, where you iterate over a collection of <code>x</code> and only the first element needs special treatment, you could <code>shift</code> it off your collection, treat it like you intended to and iterate over the rest, so in your case: parse the text until \"headline\" is reached and iterate as intended over the rest. You could make use of <code>ArrayList.remove(0)</code> to shift the first element.</p>\n\n<p>Pseudocode:</p>\n\n<pre><code>var current = Collection.shift();\nwhile(current!=\"headline\") Collection.shift();\n//do whatever with your first occurence of \"headline\"\nforeach(lines in Collection)\n// do the other nasty stuff\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:25:15.140",
"Id": "37218",
"ParentId": "37127",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "37131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T13:14:04.467",
"Id": "37127",
"Score": "7",
"Tags": [
"java",
"parsing",
"iteration"
],
"Title": "Looping Strategy: Change behaviour after first iteration"
}
|
37127
|
<p>How can I write this shorter (while keeping the same functionality and outputs to console)?</p>
<pre><code>def review():
v1 = value_of_current_cards(hand_one)
v2 = value_of_current_cards(hand_two)
v3 = value_of_current_cards(hand_three)
vd = value_of_current_cards(hand_dealer)
if number_of_hands > 0:
print ""
print "Recap of that round"
if v1 < 18:
print ""
print "First hand: You stayed on %s" % (v1)
if vd > 18:
print "*You won on First Hand*" " (Dealer busted with %s)" % (vd)
elif vd < 18:
print " Dealer stayed on %s" % (vd)
if vd > v1:
print "-You lost on First Hand-" " (Dealer was closer to 18)"
elif vd < v1:
print "*You won on First Hand*" " (You were closer to 18 than dealer)"
elif vd == v1:
print "*You tied on First Hand*" " (You and dealer both had %s)" % (vd)
elif v1 == 18:
print ""
print "First hand: You HIT HOT 18!"
if v1 > vd:
print "*You won on First Hand*" " (Dealer only had %s)" % (vd)
elif v1 == vd:
print "*You tied on First Hand*" " (You and dealer both had %s)" % (vd)
elif v1 < vd:
print "*You won on First Hand*" " (Dealer busted with %s)" % (vd)
elif v1 > 18:
print ""
print "-You lost on First Hand- " "(You had %s, so you went over 18)" % (v1)
if number_of_hands > 1:
if v2 < 18:
print ""
print "Second hand: You stayed on %s" % (v2)
if vd > 18:
print "*You won on Second Hand*" " (Dealer busted with %s)" % (vd)
elif vd < 18:
print " Dealer stayed on %s" % (vd)
if vd > v2:
print "-You lost on Second Hand-" " (Dealer was closer to 18)"
elif vd < v2:
print "*You won on Second Hand*" " (You were closer to 18 than dealer)"
elif vd == v2:
print "*You tied on Second Hand*" " (You and dealer both had %s)" % (vd)
elif v2 == 18:
print ""
print "Second hand: You HIT HOT 18!"
if v2 > vd:
print "*You won on Second Hand*" " (Dealer only had %s)" % (vd)
elif v2 == vd:
print "*You tied on Second Hand*" " (You and dealer both had %s)" % (vd)
elif v2 < vd:
print "*You won on Second Hand*" " (Dealer busted with %s)" % (vd)
elif v2 > 18:
print ""
print "-You lost on Second Hand-" " (You had %s, so you went over 18)" % (v2)
if number_of_hands > 2:
if v3 < 18:
print ""
print "Third hand: You stayed on %s" % (v3)
if vd > 18:
print "*You won on First Hand*" " (Dealer busted with %s)" % (vd)
elif vd < 18:
print " Dealer stayed on %s" % (vd)
if vd > v3:
print "-You lost on Third Hand-" " (Dealer was closer to 18)"
elif vd < v3:
print "*You won on Third Hand*" " (You were closer to 18 than dealer)"
elif vd == v3:
print "*You tied on Third Hand*" " (You and dealer both had %s)" % (vd)
elif v3 == 18:
print ""
print "Third hand: You HIT HOT 18!"
if v3 > vd:
print "*You won on Third Hand*" " (Dealer only had %s)" % (vd)
elif v3 == vd:
print "*You tied on Third Hand*" " (You and dealer both had %s)" % (vd)
elif v3 < vd:
print "*You won on Third Hand*" " (Dealer busted with %s)" % (vd)
elif v3 > 18:
print ""
print "-You lost on Third Hand-" " (You had %s, so you went over 18)" % (v3)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T14:31:24.757",
"Id": "61190",
"Score": "1",
"body": "You forgot to handle the case `v1 < 18 and vd == 18`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T16:25:45.000",
"Id": "416162",
"Score": "0",
"body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)."
}
] |
[
{
"body": "<p>You can/shuold extract repeating code, e.g. into into functions (see my example)</p>\n\n<p>example:</p>\n\n<pre><code>def evaluate_hand(value_of_hand, hand_no, hand_of_dealer):\n \"\"\"\n Evalutates ....\n\n @param value_of_hand the value for the current hand.\n @param hand_no the number of the hand. Have to be a value of the interval [1,4]\n @param hand_of_dealer contains the value of the dealers hand\n \"\"\"\n hand_to_str_dispatcher = {1: \"First hand\", 2: \"Second hand\", 3: \"Thrid hand\", 4: \"Fourth hand\"}\n print \"Recap of that round\"\n if value_of_hand < 18:\n print \"\"\n print \"{0}: You stayed on {1}\".format(hand_to_str_dispatcher[hand_no],value_of_hand)\n if hand_of_dealer > 18:\n print \"*You won on First Hand*\" \" (Dealer busted with {0})\".format(hand_of_dealer)\n elif hand_of_dealer < 18:\n print \" Dealer stayed on {0}\".format(hand_of_dealer)\n if hand_of_dealer > value_of_hand:\n print \"-You lost on {0}- (Dealer was closer to 18)\".format(hand_to_str_dispatcher[hand_no])\n elif hand_of_dealer < value_of_hand:\n print \"*You won on {0}* (You were closer to 18 than dealer)\".format(hand_to_str_dispatcher[hand_no])\n\n elif hand_of_dealer == value_of_hand:\n print \"*You tied on {0}* (You and dealer both had {1})\".format(hand_to_str_dispatcher[hand_no], hand_of_dealer)\n # .....\n # adjust the subsequent code accordingly\n\ndef recap_round():\n hand_of_dealer = 10\n v1 = 19\n v2 = 2\n v3 = 20\n v4 = 22\n hands = [v1, v2, v3, v4]\n print \"Recap of that round\"\n for i in range(0, len(hands)):\n evaluate_hand(hands[i], i + 1, hand_of_dealer)\n</code></pre>\n\n<p>Run the <code>recap_round</code> function in order to see how the example works.\nIf you try to understand the used concepts and methods you probably get a better\nidea how to structure you're code in the future.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T14:09:26.030",
"Id": "37133",
"ParentId": "37130",
"Score": "2"
}
},
{
"body": "<p>This rearrangement of the <code>if</code> statements avoids repetition of <code>print</code> statements:</p>\n\n<pre><code>print \nprint \"Recap of that round\"\nprint\nif v1 < 18:\n print \"First hand: You stayed on %s\" % (v1)\n if vd < 18:\n print \" Dealer stayed on %s\" % (vd)\nelif v1 == 18:\n print \"First hand: You HIT HOT 18!\"\n\nif v1 > 18:\n print \"-You lost on First Hand- \" \"(You had %s, so you went over 18)\" % (v1)\nelif v1 < vd <= 18:\n print \"-You lost on First Hand-\" \" (Dealer was closer to 18)\"\nelif v1 == vd:\n print \"*You tied on First Hand*\" \" (You and dealer both had %s)\" % (vd)\nelse:\n print \"*You won on First Hand*\",\n if vd > 18:\n print \" (Dealer busted with %s)\" % (vd)\n elif v1 == 18:\n print \" (Dealer only had %s)\" % (vd)\n else:\n print \" (You were closer to 18 than dealer)\"\n</code></pre>\n\n<p>Then, use string formatting to insert \"First hand\" from a variable. </p>\n\n<p>You could use a loop like this to call a function that prints the review of a single round:</p>\n\n<pre><code>rounds = ((\"First hand\", hand_one),\n (\"Second hand\", hand_two),\n (\"Third hand\", hand_three))\nfor name, hand in rounds[:number_of_hands]:\n review_round(name, hand, hand_dealer) \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T17:05:59.377",
"Id": "37148",
"ParentId": "37130",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37148",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T13:50:15.563",
"Id": "37130",
"Score": "1",
"Tags": [
"python",
"game",
"playing-cards"
],
"Title": "Conditional statements in Hot 18 card game"
}
|
37130
|
<p>What are the better solutions possible?</p>
<p>I have a character array with different strings. There is a max size for the strings. In case a string is smaller than max size remaining places are filled with '-'.
Sorting has to be done on this.</p>
<blockquote>
<p>Example:</p>
<p>maxStringSize = 5</p>
<p>totalStrings = 4</p>
<p>InputArray: w,a,t,e,r, c,a,t,-,-, f,i,v,e,-, b,a,l,l,-,-</p>
<p>outputArray: b,a,l,l,-,-, c,a,t,-,-, f,i,v,e,-, w,a,t,e,r</p>
</blockquote>
<p>-</p>
<pre><code>public class QuestionOne {
char[] mInput = {'w','a','t','e','r','c','a','t','-','-','f','i','v','e','-','b','a','l','l','-','-'};
int mBlockSize = 5;
int mTotalBlocks = 4;
public void init(char[] input, int blockSize, int totalBlocks)
{
mInput = input;
mBlockSize = blockSize;
mTotalBlocks = totalBlocks;
}
public char[] sort()
{
for(int i=0; i < mTotalBlocks; i++)
{
for(int j=i+1; j<mTotalBlocks; j++)
{
for(int count = 0; count < mBlockSize; count++ )
{
if(mInput[i*mBlockSize+count]>mInput[j*mBlockSize+count])
{
swapBlocks(i,j);
break;
}
else if(mInput[i*mBlockSize+count]<mInput[j*mBlockSize+count])
break;
}
}
}
return mInput;
}
private void swapBlocks(int blockOne, int blockTwo)
{
for(int i=0; i<mBlockSize; i++)
{
swap(blockOne*mBlockSize+i,blockTwo*mBlockSize+i);
}
}
private void swap(int one, int two)
{
char temp = mInput[one];
mInput[one] = mInput[two];
mInput[two] = temp;
}
}
</code></pre>
<p>What are the better solutions possible?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:44:16.983",
"Id": "61204",
"Score": "1",
"body": "Can you please provide more context to your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:48:40.390",
"Id": "61206",
"Score": "0",
"body": "So transforming it into strings, sorting these, joining them back together is not an option I guess?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:49:54.220",
"Id": "61207",
"Score": "0",
"body": "It's what I would do...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:51:20.403",
"Id": "61208",
"Score": "0",
"body": "No, array is very large. And there are more than one arrays. converting to string will hamper performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:56:53.720",
"Id": "61211",
"Score": "1",
"body": "\"Converting to string will hamper performance.\" So you did measure performance and came to the conclusion it's not fast enough?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:00:13.763",
"Id": "61214",
"Score": "0",
"body": "involving strings will obviously need a lot more memory and new object creation. This problem is for 10000+ such arrays with each array holding 50 - 100 strings. Based on this I am guessing it will be heavy on memory and processing time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:00:15.863",
"Id": "61215",
"Score": "0",
"body": "Also, do you want to sort 'in place', or is it feasible to have a separate array for the sort?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:01:40.833",
"Id": "61216",
"Score": "0",
"body": "In place is preferred."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:04:15.683",
"Id": "61218",
"Score": "0",
"body": "In that case, you need to work from 'first principles'... your code is doing a bubble-sort, you need to change it to a quicksort...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:05:16.907",
"Id": "61219",
"Score": "0",
"body": "Oh I guess its more similar to Insertion sort. Isnt it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:07:56.610",
"Id": "61220",
"Score": "0",
"body": "Guess, or believe? Insertion-sort needs something to insert into... you are bubbling big values to the top. It;s a bubblesort. Why is the class called `QuestionOne`. Is this homework you have not yet submitted?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:09:09.620",
"Id": "61221",
"Score": "0",
"body": "I have created different subsets of my product's problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:42:52.350",
"Id": "61230",
"Score": "1",
"body": "\"10000+ such arrays with each array holding 50 - 100 strings.\"\n\n10000*100*8*5 = 40 Mo of ram if you convert to strings, no biggie."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:45:18.953",
"Id": "61251",
"Score": "0",
"body": "The performance hit from creating strings is likely to be much less than the performance hit from using your own inefficient O(n^2) sorting algorithm."
}
] |
[
{
"body": "<p>How about the simple process of converting the chars to separate strings, sorting the Strings, then copying the results back to an array?</p>\n\n<p>It would look something like:</p>\n\n<pre><code>String source = new String(input);\nString[] values = new String[input.length / blocksize];\nfor (int i = 0; i < values.length; i++) {\n values[i] = source.substring(i * blocksize, (i + 1) * blocksize);\n}\nArrays.sort(values);\nchar[] result = new char[values.length * blocksize];\nfor (int i = 0; i < values.length; i++) {\n System.arraycopy(values[i].toCharArray(), 0, result, i* blocksize, blocksize);\n}\nreturn result;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:56:22.420",
"Id": "61210",
"Score": "0",
"body": "I thought about using `String.copyValueOf()`, otherwise would do it exactly like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:57:43.987",
"Id": "61212",
"Score": "0",
"body": "In pre-Java8 JVM's the string.substring is memory efficient ... which is an aspect to consider."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:59:32.010",
"Id": "61213",
"Score": "0",
"body": "To be honest, I did not try (was in the middle of writing it when seeing your answer). I just thought that it might be more elegant in this situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:03:24.083",
"Id": "61217",
"Score": "0",
"body": "This looks good other than that, I would prefer solution to be in place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:42:17.020",
"Id": "61250",
"Score": "0",
"body": "I'd use the `String(char[] value, int offset, int count)` constructor to create the strings and `String.getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)` to reconstitute the result."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:54:07.340",
"Id": "37142",
"ParentId": "37140",
"Score": "4"
}
},
{
"body": "<p>So let's start with the easy things, Java normally uses a modified K&R style with the opening braces on the same line:</p>\n\n<pre><code>function void test() {\n if (someVar) {\n // code\n } else {\n // code\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I don't need to tell you that <code>QuestionOne</code> is a bad class name?</p>\n\n<hr>\n\n<pre><code>char[] mInput = ...\n</code></pre>\n\n<p>Normally variables don't get prefixes with an identifier that tells you their visibility (and if I'm not mistaken <code>m</code> is normally used for <code>private</code> variables). It hinders only readability, and if you need to use such prefixes for clarity, there's something wrong with your code.</p>\n\n<hr>\n\n<pre><code>public void init(char[] input, int blockSize, int totalBlocks)\n{\n mInput = input;\n // ...\n}\n\npublic char[] sort()\n{\n // ...\n return mInput;\n}\n</code></pre>\n\n<p>First, I don't see a reason why this could not be a static helper function instead of a class.</p>\n\n<p>Second, imagine the following code:</p>\n\n<pre><code>char[] input = getInput();\nQuestionOne sorter = new QuestionOne();\nsorter.init(input, 5, 5);\nchar[] output = sorter.sort();\n</code></pre>\n\n<p>Quick, what values do <code>input</code> and <code>output</code> hold?</p>\n\n<p>If your answer was</p>\n\n<blockquote>\n <p>input holds the unsorted, output the sorted array.</p>\n</blockquote>\n\n<p>then your answer was wrong. Arrays are passed by reference, so <code>input</code> and <code>output</code> are in fact the same array. That's a problem when it comes to design of the API of this class. Either don't return something.</p>\n\n<pre><code>/**\n * Sorts the given array.\n */\nfunction void sort(char[] input) { // ...\n</code></pre>\n\n<p>Or return a <em>copy</em> of the array.</p>\n\n<pre><code>/**\n * Returns a sorted copy of the given array.\n */\nfunction char[] sort(char[] input) {\n char[] clone = input.clone(); // Also has caveats!\n return clone;\n}\n</code></pre>\n\n<hr>\n\n<p>Also you could derive the block size from the length of the array and the length of each block.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:30:02.627",
"Id": "61226",
"Score": "0",
"body": "`Java normally uses a modified K&R style with the opening braces on the same line` I've been fighting against this style for years now. newline braces make so much more sense to me. Of course, any project I work on that adheres to these style standards, I follow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:57:11.980",
"Id": "61234",
"Score": "0",
"body": "Thanks for your inputs Bobby, I was more sort of looking for a performance improvement here. Trust me I am not as novice as your answer makes this question look. :) And ya I hate K&R style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:21:29.960",
"Id": "61240",
"Score": "0",
"body": "@Cruncher: I like it, the indentation is (for me) enough to see that a new block of logic starts...though, of course that's preference, but Java code normally is that style, and so I mention it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:25:21.177",
"Id": "61241",
"Score": "1",
"body": "@varsh: If you actively choose a different style then the language default, then please mention it next time. Also, this is CR, so I did a code review, highlighting the problems I see with the code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:27:59.700",
"Id": "37145",
"ParentId": "37140",
"Score": "3"
}
},
{
"body": "<p>OK, taking in to consideration that memory footprint is a concern, then there is some scope for improvement. First, lets get through some of the basics....</p>\n\n<p>Firstly, your code has a bug, It fails to sort data with duplicates:</p>\n\n<pre><code>'w','a','t','e','r','c','a','t','-','-','b','a','l','l','-','f','i','v','e','-','b','a','l','l','-','-'\n</code></pre>\n\n<p>Your code sorts the above as:</p>\n\n<pre><code>[b, a, l, l, -, c, a, t, -, -, f, i, v, e, -, w, a, t, e, r, b, a, l, l, -, -]\n</code></pre>\n\n<p>Secondly, your example data has an extra '-' at the end. Is this intentional?</p>\n\n<p>Then, let's discuss the trade-offs between a few different concepts....</p>\n\n<ul>\n<li>Using Strings allows us to use pre-built algorithms for sorting. <code>Arrays.sort</code> uses heavily optimized code (TimSort) to get the data sorted fast, but, we will have an expensive <code>O(n)</code> cost to convert the data first.</li>\n<li>Additionally this will have a significant memory impact (significantly more than double the memory will be required).</li>\n<li>an in-between solution may be possible. We can create a custom object, say <code>CharRange</code> which represents a range in the base array. We can make this CharRange class <code>Comparable</code>. Then, we can create a CharRange instance for each word in the class, and sort the results. With the sorted results we can 'swap' the actual data to match the sorted results. This is more memory efficient than String, and has the advantage of using the native Collections.sort() algorithms. The drawback is that it <strong>does</strong> use memory, and the 'post-swap' algorithm will be 'fiddly'.</li>\n</ul>\n\n<p>Taking things to the other extreme, we can sort the data in-place, and not use any additional memory overhead.... but we will have to implement our own sort.</p>\n\n<p>Our sort will be slower than the native sort, but, we will not have the overhead of creating Objects....</p>\n\n<p>So, I have played with your code, and wrapped it in a quick-sort algorithm.... (your mileage may vary, buyer beware, use at your own risk, etc.)....</p>\n\n<p>Some notes:</p>\n\n<ul>\n<li>There is no apparent need for both <code>mBlockSize</code> and <code>mTotalBlocks</code>. The one can be calculated without the other (assuming that there is not more than mBlockSize bytes of 'padding' at the end of the data).</li>\n<li>The qsort algorithm shuffles through the data in steps of mBlockSize.</li>\n<li>I have used my own swap-in-place method, I don't like the two-levels of method-call you added to your code.</li>\n</ul>\n\n\n\n<pre><code> char[] mInput = {'w','a','t','e','r','c','a','t','-','-','b','a','l','l','-','f','i','v','e','-','b','a','l','l','-','-'};\n int mBlockSize = 5;\n int mTotalBlocks = 4;\n\n public void init(char[] input, int blockSize, int totalBlocks)\n {\n mInput = input;\n mBlockSize = blockSize;\n mTotalBlocks = totalBlocks;\n }\n\n public char[] qsort() {\n // find the start of the right-most character block...\n // this could be: qsortRecurse(0, mBlockSize * (totalBlocks - 1));\n qsortRecurse(0, mBlockSize * (mInput.length / mBlockSize - 1));\n return mInput;\n }\n\n public void qsortRecurse(final int lbound, final int rbound) {\n\n final int pivot = lbound;\n int left = lbound + mBlockSize;\n int right = rbound;\n\n if (right <= left) {\n return;\n }\n\n while (left <= right) {\n while (left <= right && compareBytes(left, pivot) <= 0) {\n left += mBlockSize;\n }\n while (left <= right && compareBytes(pivot, right) < 0) {\n right -= mBlockSize;\n }\n if (left < right) {\n swapInPlace(left, right);\n }\n }\n\n swapInPlace(pivot, right);\n\n qsortRecurse(lbound, right - mBlockSize);\n qsortRecurse(left + mBlockSize, rbound);\n\n }\n\n private void swapInPlace(int a, int b) {\n char temp;\n for (int i = 0; i < mBlockSize; i++) {\n temp = mInput[a + i];\n mInput[a + i] = mInput[b + i];\n mInput[b + i] = temp;\n }\n\n }\n\n private int compareBytes(final int a, final int b) {\n int i = 0;\n while (i < mBlockSize && mInput[a + i] == mInput[b + i]) {\n i++;\n }\n return i == mBlockSize ? 0 : (mInput[a + i] - mInput[b + i]);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:52:54.360",
"Id": "37158",
"ParentId": "37140",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T15:43:02.293",
"Id": "37140",
"Score": "4",
"Tags": [
"java",
"strings",
"array",
"homework",
"sorting"
],
"Title": "Sorting strings in a one dimensional array"
}
|
37140
|
<p>I'm trying to improve my javascript coding style and want to start writing my code more object-oriented. The code below is getting a JSON-stringified list of locations from a cookie and appending a <code>li</code> to a list for each location. I would appreciate some helpful critique and any general pointers. I have some questions too:</p>
<ol>
<li><p>Am I using <code>self</code> correctly? It feels like I'm over using it i.e. on function calls but when its not there I cannot access those functions. Some plugins I've used are written in this way and some are not, why is that?</p></li>
<li><p>If I wanted to use this as a static class, how can I code it differently instead of instantiating it?</p></li>
</ol>
<p>I have experience with vb/c# if that helps when explaining things. </p>
<pre><code>var favourites = function(list, settings) {
var self = this;
self.options = {
maxitems: 5,
cookiename: "fav-locations"
};
self._$list = $(list) || $();
self._locations = [];
//extend defaults with any settings
$.extend(self.options, settings);
//load the locations
var init = function (aryLocations) {
var index = 0;
if (aryLocations) {
for (index; index < aryLocations.length; index++) {
self.add(aryLocations[index]);
}
self.loadLocations();
self.bindRemoveButtons();
}
};
self.add = function (loc) {
if ((self._locations.length < self.options.maxitems) && self.find(loc)) {
self._locations.push(loc);
$.cookie(self.options.cookiename, JSON.stringify(self._locations), { path: '/' });
}
else {
console.log('exceeded limit');
}
};
self.remove = function (loc) {
var location_index = self.find(loc);
console.log(location_index);
if (location_index > -1) {
self._locations.splice(location_index, 1);
$.cookie(self.options.cookiename, JSON.stringify(self._locations), { path: '/' });
self.setCount();
}
else {
console.log('location not found.');
}
};
self.populateLocations = function () {
self.clearList();
$.each(self._locations, function (index, item) {
//get this locations name and id - format here is: name|id
var location = {
name: item.split('|')[0] || '',
id: item.split('|')[1] || 0
};
//create a new li element
var $thisItem = $('<li/>').appendTo(self._$list[0]).addClass('wrap');
$thisItem.data("loc", item);
$thisItem.html('<button class="remove-icon">&times;</button> <a href="/home/search-handler.asp">' + location.name + '</a>');
});
};
self.setCount = function () {
//set count value
var countelem = self._$list.prev().find('.count');
if (countelem.length > 0) { countelem.text(self._locations.length); };
};
self.loadLocations = function () {
self.populateLocations();
self.setCount();
};
self.clearList = function () {
$(self._$list).find('li').remove();
};
self.find = function (loc) {
var location_index = -1;
for (var index = 0; index < self._locations.length; index++) {
if (self._locations[index] === loc) {
location_index = index;
break;
}
}
return location_index;
};
//remove button click handler
self.bindRemoveButtons = function () {
$(document).on('click', '.remove-icon', function (e) {
var elem = $(this).parent();
e.preventDefault();
elem.slideUp('fast', function () {
self.remove(elem.data("loc"));
elem.remove();
});
});
};
//init the list
init(JSON.parse($.cookie(self.options.cookiename)));
};
var favLocs = new favourites("ul.favourites-list", { tester: 1 });
</code></pre>
<hr>
<p><strong>UPDATE</strong>: Using the feedback below I've refactored the code implementing as much as I can. The events are still there as I'm not sure how to resolve that one but I think the code has improved.</p>
<pre><code>var Favourites = (function ($) {
'use strict';
//constructor
function Favourites(list, settings) {
this.options = {
maxitems: 5,
cookiename: "fav-locations",
searchurl: null
};
this._$list = $(list) || $();
this._locations = [];
//extend defaults with any settings
$.extend(this.options, settings);
//add locations to the array
var index = 0,
locations = JSON.parse($.cookie(this.options.cookiename));
for (index; index < locations.length; index++) {
this.add(locations[index]);
}
this.loadLocations();
this.bindRemoveButtons();
this.bindLocationLinkHandler();
}
//methods
Favourites.prototype = {
add: function (loc) {
if ((this._locations.length < this.options.maxitems) && this.find(loc)) {
this._locations.push(loc);
$.cookie(this.options.cookiename, JSON.stringify(this._locations), { path: '/' });
} else {
console.log("exceeded limit");
}
},
remove: function (loc) {
var location_index = this.find(loc);
console.log(location_index);
if (location_index > -1) {
this._locations.splice(location_index, 1);
$.cookie(this.options.cookiename, JSON.stringify(this._locations), { path: '/' });
this.setCount();
} else {
console.log("location not found.");
}
},
populateLocations: function () {
var self = this;
this.clearList();
$.each(this._locations, function (item) {
//get this locations name and id - format here is: name|id
var location = {
name: item.split('|')[0] || '',
id: item.split('|')[1] || 0
},
//create a new li element
$thisItem = $('<li/>').appendTo(self._$list[0]).addClass("wrap");
$thisItem.data("location", location.name);
$thisItem.data("location-id", location.id);
$thisItem.html('<button class="remove-icon">&times;</button> <a href="' + self.options.searchurl + '" class="fav-link">' + location.name + '</a>');
});
},
setCount: function () {
//set count value
var countelem = this._$list.prev().find('.count');
if (countelem.length > 0) { countelem.text(this._locations.length); }
},
loadLocations: function () {
if ($(".search-nav:visible .current").length > 0) {
$(".favourites, .search-box").fadeIn(300);
}
this.populateLocations();
this.setCount();
},
clearList: function () {
$(this._$list).find('li').remove();
},
find: function (loc) {
var location_index = -1,
index = 0;
for (index; index < this._locations.length; index++) {
if (this._locations[index] === loc) {
location_index = index;
break;
}
}
return location_index;
},
bindRemoveButtons: function () {
var self = this;
$(document).on('click', '.remove-icon', function (e) {
var elem = $(this).parent();
e.preventDefault();
elem.slideUp('fast', function () {
self.remove(elem.data("location") + '|' + elem.data("location-id"));
elem.remove();
});
});
},
bindLocationLinkHandler: function () {
var self = this;
$(document).on("click", ".fav-link", function (e) {
var elem = $(this).parent();
self.forwardToSection(elem.data("location"), elem.data("location-id"), e);
});
},
forwardToSection: function (loc, locid, event) {
var section = $(".search-nav:visible .current a").text(),
qs = '?loc_Location=' + encodeURI(loc) + '&loc_exactlocation=' + locid;
if (section) {
if (event) {
event.currentTarget.href = event.currentTarget.href + qs + '&searchSite=' + section.toLowerCase();
} else {
window.location = this.options.searchurl + qs + '&searchSite=' + section.toLowerCase();
}
} else {
e.preventDefault();
alert("Please select a section above");
}
}
};
return Favourites;
}(jQuery));
var favLocs = new Favourites("ul.favourites-list", { searchurl: "/home/search-handler.asp" });
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:11:18.367",
"Id": "61247",
"Score": "0",
"body": "Would jQuery's $.proxy help here? You can wrap everything the a function and use this as the target in the second argument."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:36:02.540",
"Id": "61265",
"Score": "0",
"body": "What do you mean \"use this as the target in the second argument\"? What would this achieve?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:46:17.583",
"Id": "61296",
"Score": "1",
"body": "Would avoid the need to use a middleman \"self\" variable. Check the docs."
}
] |
[
{
"body": "<p>Some things to consider (after a first, superficial look at your code):</p>\n\n<ul>\n<li>Stick to the conventions: A constructor starts with an UpperCase, and is camelCased from their on. <code>Favourites</code> would be a better var name, because it signals a constructor, and requires the <code>new</code> keyword.</li>\n<li><code>self</code>, though not a reserved keyword is used by some JS engines for particular purposes. using <code>self</code> <em>can</em> lead to unexpected behaviour. Perhaps consider using <code>var that = this;</code> instead.</li>\n<li>Use the <code>prototype</code> for methods, to avoid creating too many function objects.</li>\n<li><code>self</code> isn't required all the time, but it's safer. You're not using it badly, you're using it, but don't seem to know what it's for.</li>\n<li>Binding event handlers (<code>self.bindRemoveButtons</code>) is <em>not</em> the job of an object, or any of its methods. It's not because you're using the <code>new</code> keyword, and methods, that you're writing good, OO code. Besides, JS is prototype-based, using traditional OO techniques in JS is like a barber, using a scythe to cut your hair...</li>\n<li>The <code>init</code> function needn't be declared for each instance, use a closure.</li>\n<li>You have no guarantee that <code>$</code> will be the jQuery object, use a closure.</li>\n</ul>\n\n<p>Now, some examples to help you on your way:</p>\n\n<pre><code>var Favourites = (function($)//pass jQ object to closure\n{\n 'use strict';\n var init = function()\n {\n //the init function here.\n };\n function Favourites(list, settings)\n {//properties here...\n this._$list = $(list) || $();\n init();//call closure function init declared above ^^\n }\n Favourites.prototype.setCount = function()\n {\n //methods belong to the prototype\n };\n return Favourites;//return reference to constructor\n}(jQuery));\n</code></pre>\n\n<p>This is what a more complex constructor definition in JS looks like.</p>\n\n<p><em>Update:</em><br/>\nYour updated code looks good. Honestly. It's not perfect, but then, in programming, perfection is more of a subjective thing. Personally, I rarely, if not never write constructors. I just use object literals and the module pattern.</p>\n\n<p>You've looked into closures. Great, I get the impression you get what they're for, but you don't yet see all the use-cases for them. For example the <code>bindLocationLinkHandler</code> method, and for that matter, all the DOM-related methods, contain <code>$(document)</code>. What this code does, essentially is call the jQuery init funtion, and constructs a jQuery wrapper object around the <code>document</code> object. Why would you do this over and over? why not wrap all those prototype methods in a simple closure like this:</p>\n\n<pre><code>(function($doc)\n{\n Favourites.prototype.bindLocationLinkHandler = function()\n {\n $doc.on('click', ...);\n };\n}($(document));//pass jQ wrapped document here\n</code></pre>\n\n<p>This'll save you a few jQ init calls. Your methods are also binding <em>the same handler</em>. Functions are first-class object in JS, construct them once, and use them everywhere. Replace, for example:</p>\n\n<pre><code>$(document).on(\"click\", \".fav-link\", function (e)\n{\n var elem = $(this).parent();\n self.forwardToSection(elem.data(\"location\"), elem.data(\"location-id\"), e);\n});\n</code></pre>\n\n<p>with something like:</p>\n\n<pre><code>(function($doc)\n{\n var self, handler = function(e)\n {\n var elem = $(this).parent();\n self.forwardToSection(elem.data(\"location\"), elem.data(\"location-id\"), e)\n };\n Favourites.prototype.bindLocationLinkHandler = function()\n {\n self = this;//DANGEROUS... won't always work\n $doc.on('click', '.fav-link', handler);\n };\n}($(document)));\n</code></pre>\n\n<p>Of course, you may have spotted that, owing to there only being a single <code>self</code> closure var for all of the instances, the <code>self</code> reference won't be as reliable. It depends on whatever method you're calling and weather or not it matters if you're calling the method on the same object or not. Either way, this was just to show that you can use closures for anything, simple, primitive variables, as well as functions. In fact, you're doing just that in jQ <em>all the time!</em>:</p>\n\n<pre><code>$('li').each(function()\n{//<-- jQ's each method accepts an function as argument\n});\n</code></pre>\n\n<p>To close this rant (few, I'm all over the place), I do have 1 more thing I'd like to point out. I left it out of my initial answer because I don't want to spark a pointless, yet lively debate, but still... In for a penny, in for a pound:<br/>\nIf I'm honest, I'm not too keen on jQuery. There's nothing <em>wrong</em> with jQ, but it's just something that is used too much. If all you're doing is delegate a single event, and perform one or two ajax calls, you don't need jQ, in such a scenario, where you're only using 5% of a monolithic toolkit, you're better off writing a few more lines of code. The performance benefits are, often, noticeable.</p>\n\n<p>In this case, one line in particular got up my nose. You're dabbling with OO JS. The point of OO is to contain certain sets of data and logic in manageable, clearly defined entities (objects). Your object <code>Favourites</code> depends on a toolkit that is anything <em>but</em> modular. An object that relies on an entire lib, just so the constructor can do what it needs to do is, IMHO, just plain silly.<br/>\nWhy not replace this line:</p>\n\n<pre><code>$.extend(this.options, settings);\n</code></pre>\n\n<p>With a simple loop:</p>\n\n<pre><code>for (var p in settings)\n{\n this.options[p] = settings[p];\n}\n</code></pre>\n\n<p>You can add checks for <code>settings[p]</code>, to ensure you're not assigning a function object to <code>this.options[p]</code>, include a line like <code>if (this.options.hasOwnProperty(p))</code> to deal with overriding of certain default properties, making sure the new values are <em>valid</em> and so on.<br/>\nYou could work on this code a bit more, and avoid your <code>Favourites</code> objects to depend on jQ being loaded all together, simply by doing something like:</p>\n\n<pre><code>this._list = document.querySelectorAll(list);\n</code></pre>\n\n<p>Most jQ selectors work with <code>querySelectorAll</code> anyway, and <code>querySelectorAll</code> is supported by IE8, even, so on the X-browser front, you're not going to have too many issues either.<br/>\nA way to delegate the click event X-browser isn't that hard, either:</p>\n\n<pre><code>var clickHandler = function(e)\n{\n e = e || window.event;\n var target = e.target || e.srcElement;\n if (target.className.test(/\\bremove-icon\\b/))\n {//handle remove-icon class elements only\n e.returnValue = false;\n if (e.preventDefault) e.preventDefault();\n target.parentNode.parentNode.removeChild(target.parentNode);\n }\n};\nif (window.addEventListener)\n{\n window.addEventListener('click', clickHandler, false);\n}\nelse\n{\n window.attachEvent('onclick', clickHandler);\n}\n</code></pre>\n\n<p>Granted, this is a bit more verbose, but it's not that difficult, IMO. The slide effect will require a bit more work, granted, but not nearly as much as you might think. All in all, you're free to use jQ if you want, just know that whatever jQ does, vanillaJS can do, too. If you take the time, and put in the effort to learn how you can do those things in vanillaJS, you'll find that you'll learn a great deal more about how JS actually works, which will improve the quality of your code, even when you <em>do</em> decide to use jQ</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T11:27:19.323",
"Id": "61350",
"Score": "0",
"body": "Thanks, exactly what I was hoping for. I've looked into closures and think I've fixed the `self` issues. I'll update my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:17:09.850",
"Id": "61381",
"Score": "0",
"body": "@DAC84: I've added quite a bit to my initial answer, focussing more on the use of jQ, because your updated code is OK, at first glance... just some more pointers on how you can use closures to make your code even more performant, really"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:59:50.740",
"Id": "61385",
"Score": "0",
"body": "So basically you are telling the OP to write his own `$.extend()` ? Sounds far-fetched, and you know it by writing 'and so on.'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:10:37.527",
"Id": "61390",
"Score": "0",
"body": "@tomdemuyt: No, what I'm saying is using a monolithic toolkit like jQ, to help you write more OO code doesn't add up. OO is about writing clean, small, reusable entities. If those entities rely on a gargantuan lib, they're not really OO... when I wrote _\"and so on\"_ I was talking about the things the OP could do to tailor the loop to fit his needs, I hinted at what that loop _could_ do, not on what it _has_ to do"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T16:01:25.837",
"Id": "61401",
"Score": "0",
"body": "Final snarky comment; read the code of .extend() here : http://code.jquery.com/jquery-2.0.3.js, it is clean, small and reusable and deals with traps when dealing with extending deep objects ( I mistakenly figured this is what you meant with so on ). OO is more about re-use than re-write, and I think that using $.extend() is the right call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:54:47.987",
"Id": "61600",
"Score": "0",
"body": "@tomdemuyt: Granted. I was hung up on jQ-bashing, perhaps too much to actually admit the merits of something like `$.extend` in this particular case. Still... Why not use `Object.create`, it's not entirely the same thing, but that's what I'd use here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T11:31:22.990",
"Id": "61633",
"Score": "0",
"body": "Appreciate the update and your time @EliasVanOotegem . Re closures I get what they're for (store a reference to current context so it can be accessed in 'sub-functions') but with more reading I'll figure out their full potential. I actually started using JS before jQ so I have an understanding of it, and I've been using jQ since v1.2 for ajax etc. as back then there were many cross-browser issues. Maybe now there aren't as many issues and vanillaJS could be used, its just not viable on this project, however I get your point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T12:15:53.980",
"Id": "61635",
"Score": "0",
"body": "@DAC84: Fair point on the X-browser stuff. Back in the days the `new XMLHttpRequest` - `ActiveX` try-catch blocks alone were reason enough to use jQ. It's just that nowadays, many beginners seem to think jQ is another language, and they don't _understand_ JS anymore. That sends me off in a rant, like it did here, too. By no means did I mean to _\"force\"_ you not to use jQ, I just think it's something people use all too often, without bothering to ask themselves weather or not they really _need_ jQ at all. ah well, as always: Always happy to help, as I hope I did"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:49:25.553",
"Id": "37204",
"ParentId": "37146",
"Score": "4"
}
},
{
"body": "<p>Using <code>self = this</code> is actually a bad practice. You'll end up with zillions of <code>self</code> that will mean different things at different times, and the mess will eat you up. Sadly it is used in many tutorials just because people are lazy to come up with better names.</p>\n\n<p>Give it meaningful names like <code>user = this</code> or <code>car = this</code> or whatever. So much more readable and helpful to whoever struggles to understand the code. Even the abstract <code>myObject = this</code> is already better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:59:27.620",
"Id": "61602",
"Score": "0",
"body": "Disagree. `self` is a necessary evil at times. Owing to JS's ad-hoc binding, you may want to keep a reference to `this` at hand, because `this` won't always be `this`. The only argument against `self` is that it's used internally by some JS engines, even though it's not a reserved keyword. I'd use `var that = this;`, which is what Douglas Crockford does, too"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:02:36.057",
"Id": "61603",
"Score": "0",
"body": "@EliasVanOotegem My point was about using the meaningless word `self` for the variable, not the practice of storing the current value of `this`, which is certainly useful. Sorry if it wasn't clear."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:54:33.257",
"Id": "37293",
"ParentId": "37146",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "37204",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T16:35:28.063",
"Id": "37146",
"Score": "3",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Learning OOP javascript - critique my class that creates a 'favourites' list"
}
|
37146
|
<p>Please only post contest questions that abide by the <a href="https://codereview.stackexchange.com/help/on-topic">site policy</a>. Namely, questions <em>must not</em> correspond to code-golf, obfuscation, "spaghetti code," or other requests that do not seek any kind of improvement.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:07:45.960",
"Id": "37151",
"Score": "0",
"Tags": null,
"Title": null
}
|
37151
|
This tag is for questions with code that you have written for a competition. CODE MUST STILL COMPILE AND RUN. Code that fails because of the time constraint may, however, still be on-topic.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:07:45.960",
"Id": "37152",
"Score": "0",
"Tags": null,
"Title": null
}
|
37152
|
<p>I'm making a little Python script that reads a text file and puts it on a HTML page. I haven't finished that part yet, but I've been working on the GUI with tkinter. Is my code sloppy?</p>
<pre><code>from Tkinter import *
import time
from datetime import datetime
#init variables
global r
r = 0
global delay
delay = 1000
#for testing
global lat
lat = "41.5345"
global lon
lon = "-85.343"
global zoom
zoom = 0
global mapDir
mapDir = ""
global mapDirEnabl
mapDirEnabl = 0
#clear log file
log = open("xpyMapLog.txt", "w")
log.write("")
log.close()
global log
log = open("xpyMapLog.txt", "a")
logStartMessage = "RUN TIME EXECUTED AT: %s \n" % str(datetime.now())
log.write(logStartMessage)
#error check
class safe:
def __init__(self, function):
self.function = function
def __call__(self, *args):
try:
return self.function(*args)
except Exception, e:
errorMsg = "Error: %r" % str(e)
log.write(errorMsg)
print "Error: %s" % e
#
#
#
#open data file
@safe
def openData():
global Data
Data = open("Data.txt", "r")
#
openData()
#init root window
root = Tk()
root.geometry("550x300+200+200")
root.title("XPYmap for x-plane 10")
#init functions
@safe
def mainLoop():
if r == 1:
#**************************************
#DATA READING AND WRITING TO MAP FILE!*
#**************************************
print "Hello"
#im not done with the data reading yet so just pretend its here
#######################################
#
#
@safe
def start():
global r
r = 1
mainLoop()
#
@safe
def stop():
global r
r = 0
posLabl["text"] = "Position: NOT RUNNING"
#
@safe
def setZoom(z):
global zoomlabel
zoom = int(z)
curntZoomLabl["text"] = "Current zoom level: %s" % zoom
#
@safe
def setDelay(d):
print "delay"
global delay
delay = int(d)
delayInSec = delay / 1000 # get seconds from milisec
curntDelayLabl["text"] = "Current update delay: %s seconds." % delayInSec
#
@safe
def chooseMapDir():
global mapDirEnabl
global mapDir
if mapDirEnabl == 0:
mapDirEnabl = 1
mapDirStat["text"] = "Custom map directory is currently: ENABLED!"
mapDir = str(mapDirEntry.get())
print mapDir
elif mapDirEnabl == 1:
mapDirEnabl = 0
mapDirStat["text"] ="Custom map directory is currently: DISABLED!"
mapDir = ""
print mapDir
#
#
#widgets
posLabl = Label(root, text = "Position: NOT RUNNING")
butStart = Button(root, text = "Start", command = start)
butStop = Button(root, text = "Stop", command = stop)
zoomLabl = Label(root, text = "Click the zoom level")
curntZoomLabl = Label(root, text = "Current zoom level:")
delayLabl = Label(root, text = "Select update delay")
curntDelayLabl = Label(root, text = "Current update delay: NONE")
mapDirLabl = Label(root, text = "ADVANCED ONLY! If you want to save the map file to another directory, enter it in below.")
mapDirBut = Button(root, text = "enable/disable directory", command = chooseMapDir)
mapDirStat = Label(root, text = "Custom map directory is currently: DISABLED!")
mapDirEntry = Entry(root, width = 60)
#column span for buttons
colspan = 1
#zoom with grid
bz1 = Button(root, text = "1", width=2, command = lambda:setZoom("1"))
bz1.grid(row = 5, column = 0, columnspan = colspan)
bz2 = Button(root, text = "2", width=2, command = lambda:setZoom("2"))
bz2.grid(row = 5, column = 1, columnspan = colspan )
bz3 = Button(root, text = "3", width=2, command = lambda:setZoom("3"))
bz3.grid(row = 5, column = 2, columnspan = colspan )
bz4 = Button(root, text = "4", width=2, command = lambda:setZoom("4"))
bz4.grid(row = 5, column = 3, columnspan = colspan )
bz5 = Button(root, text = "5", width=2, command = lambda:setZoom("5"))
bz5.grid(row = 5, column = 4, columnspan = colspan )
bz6 = Button(root, text = "6", width=2, command = lambda:setZoom("6"))
bz6.grid(row = 5, column = 5, columnspan = colspan )
bz7 = Button(root, text = "7", width=2, command = lambda:setZoom("7"))
bz7.grid(row = 5, column = 6, columnspan = colspan )
#delay with grid
bd1 = Button(root, text = "1", width=2, command = lambda:setDelay("1000"))
bd1.grid(row = 10, column = 0, columnspan = 1)
bd2 = Button(root, text = "2", width=2, command = lambda:setDelay("2000"))
bd2.grid(row = 10, column = 1, columnspan = 1)
bd3 = Button(root, text = "3", width=2, command = lambda:setDelay("3000"))
bd3.grid(row = 10, column = 2, columnspan = 1)
bd4 = Button(root, text = "4", width=2, command = lambda:setDelay("4000"))
bd4.grid(row = 10, column = 3, columnspan = 1)
bd5 = Button(root, text = "5", width=2, command = lambda:setDelay("5000"))
bd5.grid(row = 10, column = 4, columnspan = 1)
bd6 = Button(root, text = "6", width=2, command = lambda:setDelay("6000"))
bd6.grid(row = 10, column = 5, columnspan = 1)
bd7 = Button(root, text = "7", width=2, command = lambda:setDelay("7000"))
bd7.grid(row = 10, column = 6, columnspan = 1)
bd8 = Button(root, text = "8", width=2, command = lambda:setDelay("8000"))
bd8.grid(row = 10, column = 7, columnspan = 1)
bd9 = Button(root, text = "9", width=2, command = lambda:setDelay("9000"))
bd9.grid(row = 10, column = 8, columnspan = 1)
bd10 = Button(root, text = "10", width=2, command = lambda:setDelay("10000"))
bd10.grid(row = 10, column = 9, columnspan = 1)
#packing/grid
posLabl.grid(row = 1, column = 0, columnspan = 80)
butStart.grid(row = 2, column = 4, columnspan = 2)
butStop.grid(row = 2, column = 6, columnspan = 2)
zoomLabl.grid(row = 3, column = 0, columnspan = 80)
curntZoomLabl.grid(row = 4, column = 0, columnspan = 80)
delayLabl.grid(row = 6, column = 0, columnspan = 80)
curntDelayLabl.grid(row = 7, column = 0, columnspan = 80)
mapDirLabl.grid(row = 11, column = 0, columnspan = 55)
mapDirBut.grid(row = 12, column = 4, columnspan = 4)
mapDirStat.grid(row= 13, column = 0, columnspan = 7)
mapDirEntry.grid(row = 14, column = 0, columnspan = 25)
#mainloop
root.mainloop()
#close files
log.close()
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Is my code sloppy?</p>\n</blockquote>\n\n<p>It is, but there are very specifics things you can do to address that. Good news! First, use <a href=\"http://pep8online.com/\" rel=\"nofollow\">http://pep8online.com/</a> to make sure that your code follows <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>, which is a standard that most Python coders follow to make sure that every Python code can be easily understood by every Python coder.</p>\n\n<pre><code>from Tkinter import *\nimport time\nfrom datetime import datetime\n</code></pre>\n\n<p>You need two spaces after the module imports.</p>\n\n<pre><code>#init variables\nglobal r\nr = 0\nglobal delay\ndelay = 1000\n#for testing\nglobal lat\nlat = \"41.5345\"\nglobal lon\nlon = \"-85.343\"\nglobal zoom\nzoom = 0\nglobal mapDir\nmapDir = \"\"\nglobal mapDirEnabl\nmapDirEnabl = 0\n</code></pre>\n\n<p>Please don't use global variables, you don't need them and they only clutter your code. The good thing about a function is that I can understand it by only looking at it. With global variables, it's not true anymore and I need to be aware of all those variables.</p>\n\n<pre><code>#clear log file\nlog = open(\"xpyMapLog.txt\", \"w\")\nlog.write(\"\")\nlog.close()\nglobal log\nlog = open(\"xpyMapLog.txt\", \"a\")\nlogStartMessage = \"RUN TIME EXECUTED AT: %s \\n\" % str(datetime.now())\nlog.write(logStartMessage)\n</code></pre>\n\n<p>Python has a powerful <code>logging</code> module that you could use. To clear the log file, simply open it in <code>'w'</code> mode.</p>\n\n<pre><code>#error check\nclass safe:\n def __init__(self, function):\n self.function = function\n\n def __call__(self, *args):\n try:\n return self.function(*args)\n except Exception, e:\n errorMsg = \"Error: %r\" % str(e)\n log.write(errorMsg) \n print \"Error: %s\" % e\n</code></pre>\n\n<p>Make sure that you know why and when you're using the safe decorator. It's a bad idea most of the time: most exceptions are not recoverable and you should instead 1/ make sure they do not happen 2/ or recover when you know how to recover.</p>\n\n<pre><code> #\n #\n#\n</code></pre>\n\n<p>Remove those, and either get used to Python's indentation or find an editor that helps you to visualize the scope of your blocks.</p>\n\n<pre><code>#open data file\n@safe\ndef openData():\n global Data\n Data = open(\"Data.txt\", \"r\")\n#\nopenData()\n</code></pre>\n\n<p>Why is this a function? You only need <code>Data = open(\"Data.txt\", \"r\")</code> and nothing else if it's not a function. And you won't need the nasty <code>global</code>. <code>@safe</code> also makes no sense here. What do you want to do when opening the data file fails?</p>\n\n<pre><code>#init root window\nroot = Tk()\nroot.geometry(\"550x300+200+200\")\nroot.title(\"XPYmap for x-plane 10\")\n</code></pre>\n\n<p>Note that Tkinter is not considered a very nice Python library anymore, but I don't know what is the recommended one nowadays. Please rewrite your code considering what I have said already, and maybe resubmit the result on Code Review when it's done.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:32:51.750",
"Id": "37300",
"ParentId": "37154",
"Score": "4"
}
},
{
"body": "<p>On top of @Quentin's comments, please try to avoid repeting yourself too much and declaring useless variables as it tends to make things harder to read.</p>\n\n<pre><code>bz1 = Button(root, text = \"1\", width=2, command = lambda:setZoom(\"1\"))\nbz1.grid(row = 5, column = 0, columnspan = colspan)\nbz2 = Button(root, text = \"2\", width=2, command = lambda:setZoom(\"2\"))\nbz2.grid(row = 5, column = 1, columnspan = colspan )\nbz3 = Button(root, text = \"3\", width=2, command = lambda:setZoom(\"3\"))\nbz3.grid(row = 5, column = 2, columnspan = colspan )\nbz4 = Button(root, text = \"4\", width=2, command = lambda:setZoom(\"4\"))\nbz4.grid(row = 5, column = 3, columnspan = colspan )\nbz5 = Button(root, text = \"5\", width=2, command = lambda:setZoom(\"5\"))\nbz5.grid(row = 5, column = 4, columnspan = colspan )\nbz6 = Button(root, text = \"6\", width=2, command = lambda:setZoom(\"6\"))\nbz6.grid(row = 5, column = 5, columnspan = colspan )\nbz7 = Button(root, text = \"7\", width=2, command = lambda:setZoom(\"7\"))\nbz7.grid(row = 5, column = 6, columnspan = colspan )\n\nbd1 = Button(root, text = \"1\", width=2, command = lambda:setDelay(\"1000\"))\nbd1.grid(row = 10, column = 0, columnspan = 1)\nbd2 = Button(root, text = \"2\", width=2, command = lambda:setDelay(\"2000\"))\nbd2.grid(row = 10, column = 1, columnspan = 1)\nbd3 = Button(root, text = \"3\", width=2, command = lambda:setDelay(\"3000\"))\nbd3.grid(row = 10, column = 2, columnspan = 1)\nbd4 = Button(root, text = \"4\", width=2, command = lambda:setDelay(\"4000\"))\nbd4.grid(row = 10, column = 3, columnspan = 1)\nbd5 = Button(root, text = \"5\", width=2, command = lambda:setDelay(\"5000\"))\nbd5.grid(row = 10, column = 4, columnspan = 1)\nbd6 = Button(root, text = \"6\", width=2, command = lambda:setDelay(\"6000\"))\nbd6.grid(row = 10, column = 5, columnspan = 1)\nbd7 = Button(root, text = \"7\", width=2, command = lambda:setDelay(\"7000\"))\nbd7.grid(row = 10, column = 6, columnspan = 1)\nbd8 = Button(root, text = \"8\", width=2, command = lambda:setDelay(\"8000\"))\nbd8.grid(row = 10, column = 7, columnspan = 1)\nbd9 = Button(root, text = \"9\", width=2, command = lambda:setDelay(\"9000\"))\nbd9.grid(row = 10, column = 8, columnspan = 1)\nbd10 = Button(root, text = \"10\", width=2, command = lambda:setDelay(\"10000\"))\nbd10.grid(row = 10, column = 9, columnspan = 1)\n</code></pre>\n\n<p>can be rewritten :</p>\n\n<pre><code>for i in range(7):\n txt = str(i+1)\n but = Button(root, text = txt, width=2, command = lambda:setZoom(txt))\n but.grid(row = 5, column = i, columnspan = colspan)\n\nfor i in range(10):\n txt = str(i+1)\n delay = str((i+1)*1000)\n but = Button(root, text = txt, width=2, command = lambda:setDelay(delay))\n but.grid(row = 10, column = i, columnspan = 1)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T11:50:47.527",
"Id": "37301",
"ParentId": "37154",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T18:43:51.960",
"Id": "37154",
"Score": "6",
"Tags": [
"python",
"tkinter"
],
"Title": "Python tkinter GUI"
}
|
37154
|
<p>This was the most humerus coding I've ever done. It's for my string library in C. It detects if the user is angry to various degrees, namely <code>str_isHeated()</code>. </p>
<p><strong>Why?</strong></p>
<p>Ever play a text-based game and you're swearing at the computer by typing, typing multiple <code>!!!</code>, and the computer responds very dumb? I think it may be useful for AI where NPC's (non-playable characters) can judge your mood and respond appropriately. Maybe even used for customer service online.</p>
<p>It works, but I'm interested to see if anyone has any thoughts on how to improve it. I've been having some fun with it.</p>
<pre><code>/*
Function: str_getHeat()
Software usually gets user information, but it hardly
detects the user's emotion when entering in the information.
This may be useful for checking a customer's or player's
typing behavior, which may generate better responses with AI.
Calculated as follows:
All Caps
One or more words in caps
Exclamation Point Count
If 'please' or 'sorry' is found, take off heat points.
Swearing words
Returns: EHeat_Cold, EHeat_Warm, EHeat_Heated, EHeat_VeryHeated
*/
EHeat str_isHeated(STRING *objString)
{
int i;
int intHeatScore = 0; /* 0% cold; 100% very heated */
STRINGCOLLECTION tokens;
STRING temp_a;
/* Count how many exclamations there are */
for (i = 0; i < objString->length; i++)
{
if (objString->str[i] == '!')
intHeatScore += 10;
}
/* tokenize user's input */
sc_init(&tokens);
str_tokenize(objString, &tokens);
/* Check if all caps. That can be taken as impatient. */
if (str_isUpper(objString))
{
intHeatScore += 10;
}
else
{
/* check if one or more words are all in caps. That is
demanding behavior, and that is not nice. */
for (i = 0; i < tokens.count; i++)
{
if (str_isUpperCString(tokens.items[i]))
{
intHeatScore += 10;
/* 'I' is excused. */
if (!strcmp(tokens.items[i], "I"))
intHeatScore -= 10;
}
}
}
/* Check if the user said please. That's always nice.
Take off a few heat points. */
if (str_findStringIgnoreCaps(objString, "please"))
intHeatScore -= 6;
/* Check if the user said he's sorry. That's also nice. */
if (str_findStringIgnoreCaps(objString, "sorry"))
intHeatScore -= 6;
/* Almost forgot... swearing. That is never nice. */
for (i = 0; i < tokens.count; i++)
{
str_setText(&temp_a, tokens.items[i]);
str_toLower(&temp_a);
/* don't say these words out loud (censored for your innocence*/
if (str_findString(&temp_a, "$#@#") ||
str_findString(&temp_a, "@#$@") ||
str_findString(&temp_a, "@$$") ||
str_findString(&temp_a, "@$$#@") ||
str_findString(&temp_a, "%#@") ||
str_findString(&temp_a, "@#$")
)
{
/* big no-no */
intHeatScore += 20;
}
}
/* Check the final heat score */
if (intHeatScore >= 50)
return EHeat_VeryHeated;
else if (intHeatScore >= 30)
return EHeat_Heated;
else if (intHeatScore > 10)
return EHeat_Warm;
else if (intHeatScore >= 0)
return EHeat_Cold;
return EHeat_Cold;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:18:27.257",
"Id": "61248",
"Score": "8",
"body": "My initial thought was \"lol\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:49:27.937",
"Id": "61252",
"Score": "2",
"body": "If you're interested into the more academic side of this, look into sentiment analysis. What you've done is make a simple sentiment analyzer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T21:57:48.447",
"Id": "61275",
"Score": "0",
"body": "How about a dictionary of sorts for the words: `char *words[] = {\"!#@&\", \"^#$%\", …};`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:01:16.447",
"Id": "61281",
"Score": "0",
"body": "Good idea! I actually made a string table DS earlier, so I'll try it out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:14:11.527",
"Id": "61285",
"Score": "0",
"body": "Or that works too.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:15:30.380",
"Id": "61363",
"Score": "0",
"body": "Your score is strictly increasing, which means that given a randomly generated block of very long text will have a much higher score than a randomly generated block of very short text. To solve this you might want to take into account the length of input when computing the heatscore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T09:42:21.507",
"Id": "61618",
"Score": "0",
"body": "In addition with what Matt said you might want to accumulate over a time period that is calculated on the anger level. A very angry man will not cool down in a minute or two, but maybe over 20 mins, so during this time period you might want to calculate his additional response (does he say please, does he swear, etc...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T18:35:49.433",
"Id": "61672",
"Score": "0",
"body": "Thanks for the advice. That's a good idea. I left the function stand-alone, though for AI characters might have a random time limit of forgiveness individually. So, the characters remember, but the function doesn't - if that makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-08T19:44:17.493",
"Id": "227802",
"Score": "0",
"body": "This problem is a _really_ good fit for applying a supervised learning algorithm if you are into machine learning."
}
] |
[
{
"body": "<p>Use a hash table! Something like this would work: </p>\n\n<pre><code>#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <stdbool.h>\n#include <sys/resource.h>\n#include <sys/time.h>\n\n\n// default dictionary (LIST OF BAD WORDS)\n#define DICTIONARY \"/PATH_TO_BAD_WORDS\"\n\n// prototype\ndouble calculate(const struct rusage* b, const struct rusage* a);\n\nint main(int argc, char* argv[])\n{\n // check for correct number of args\n if (argc != 2 && argc != 3)\n {\n printf(\"Usage: speller [dictionary] text\\n\");\n return 1;\n }\n\n // structs for timing data\n struct rusage before, after;\n\n // benchmarks\n double ti_load = 0.0, ti_check = 0.0, ti_size = 0.0, ti_unload = 0.0;\n\n // determine dictionary to use\n char* dictionary = (argc == 3) ? argv[1] : DICTIONARY;\n\n // load dictionary\n getrusage(RUSAGE_SELF, &before);\n bool loaded = load(dictionary);\n getrusage(RUSAGE_SELF, &after);\n\n // abort if dictionary not loaded\n if (!loaded)\n {\n printf(\"Could not load %s.\\n\", dictionary);\n return 1;\n }\n\n // calculate time to load dictionary\n ti_load = calculate(&before, &after);\n\n // try to open text\n char* text = (argc == 3) ? argv[2] : argv[1];\n FILE* fp = fopen(text, \"r\");\n if (fp == NULL)\n {\n printf(\"Could not open %s.\\n\", text);\n unload();\n return 1;\n }\n\n // prepare to report misspellings\n printf(\"\\nMISSPELLED WORDS\\n\\n\");\n\n // prepare to spell-check\n int index = 0, misspellings = 0, words = 0;\n char word[LENGTH+1];\n\n // spell-check each word in text\n for (int c = fgetc(fp); c != EOF; c = fgetc(fp))\n {\n // allow only alphabetical characters and apostrophes\n if (isalpha(c) || (c == '\\'' && index > 0))\n {\n // append character to word\n word[index] = c;\n index++;\n\n // ignore alphabetical strings too long to be words\n if (index > LENGTH)\n {\n // consume remainder of alphabetical string\n while ((c = fgetc(fp)) != EOF && isalpha(c));\n\n // prepare for new word\n index = 0;\n }\n }\n\n // ignore words with numbers (like MS Word can)\n else if (isdigit(c))\n {\n // consume remainder of alphanumeric string\n while ((c = fgetc(fp)) != EOF && isalnum(c));\n\n // prepare for new word\n index = 0;\n }\n\n // we must have found a whole word\n else if (index > 0)\n {\n // terminate current word\n word[index] = '\\0';\n\n // update counter\n words++;\n\n // check word's spelling\n getrusage(RUSAGE_SELF, &before);\n bool misspelled = !check(word);\n getrusage(RUSAGE_SELF, &after);\n\n // update benchmark\n ti_check += calculate(&before, &after);\n\n // print word if misspelled\n if (misspelled)\n {\n printf(\"%s\\n\", word);\n misspellings++;\n }\n\n // prepare for next word\n index = 0;\n }\n }\n\n // check whether there was an error\n if (ferror(fp))\n {\n fclose(fp);\n printf(\"Error reading %s.\\n\", text);\n unload();\n return 1;\n }\n\n // close text\n fclose(fp);\n\n // determine dictionary's size\n getrusage(RUSAGE_SELF, &before);\n unsigned int n = size();\n getrusage(RUSAGE_SELF, &after);\n\n // calculate time to determine dictionary's size\n ti_size = calculate(&before, &after);\n\n // unload dictionary\n getrusage(RUSAGE_SELF, &before);\n bool unloaded = unload();\n getrusage(RUSAGE_SELF, &after);\n\n // abort if dictionary not unloaded\n if (!unloaded)\n {\n printf(\"Could not unload %s.\\n\", dictionary);\n return 1;\n }\n\n // calculate time to unload dictionary\n ti_unload = calculate(&before, &after);\n\n // report benchmarks\n printf(\"\\nWORDS MISSPELLED: %d\\n\", misspellings);\n printf(\"WORDS IN DICTIONARY: %d\\n\", n);\n printf(\"WORDS IN TEXT: %d\\n\", words);\n printf(\"TIME IN load: %.2f\\n\", ti_load);\n printf(\"TIME IN check: %.2f\\n\", ti_check);\n printf(\"TIME IN size: %.2f\\n\", ti_size);\n printf(\"TIME IN unload: %.2f\\n\", ti_unload);\n printf(\"TIME IN TOTAL: %.2f\\n\\n\", \n ti_load + ti_check + ti_size + ti_unload);\n\n // that's all folks\n return 0;\n}\n\n/**\n * Returns number of seconds between b and a.\n */\ndouble calculate(const struct rusage* b, const struct rusage* a)\n{\n if (b == NULL || a == NULL)\n {\n return 0.0;\n }\n else\n {\n return ((((a->ru_utime.tv_sec * 1000000 + a->ru_utime.tv_usec) -\n (b->ru_utime.tv_sec * 1000000 + b->ru_utime.tv_usec)) +\n ((a->ru_stime.tv_sec * 1000000 + a->ru_stime.tv_usec) -\n (b->ru_stime.tv_sec * 1000000 + b->ru_stime.tv_usec)))\n / 1000000.0);\n }\n}\n// maximum length for a word\n// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)\n#define LENGTH 45\n\n/**\n * Returns true if word is in dictionary else false.\n */\nbool check(const char* word);\n\n/**\n * Loads dictionary into memory. Returns true if successful else false.\n */\nbool load(const char* dictionary);\n\n/**\n * Returns number of words in dictionary if loaded else 0 if not yet loaded.\n */\nunsigned int size(void);\n\n/**\n * Unloads dictionary from memory. Returns true if successful else false.\n */\nbool unload(void);\n\n\n// size of hashtable\n#define SIZE 1000000\n\n// create nodes for linked list\ntypedef struct node\n{\n char word[LENGTH+1];\n struct node* next;\n}\nnode;\n\n// create hashtable\nnode* hashtable[SIZE] = {NULL};\n\n// create hash function\nint hash (const char* word)\n{\n int hash = 0;\n int n;\n for (int i = 0; word[i] != '\\0'; i++)\n {\n // alphabet case\n if(isalpha(word[i]))\n n = word [i] - 'a' + 1;\n\n // comma case\n else\n n = 27;\n\n hash = ((hash << 3) + n) % SIZE;\n }\n return hash; \n}\n\n// create global variable to count size\nint dictionarySize = 0;\n\n/**\n * Loads dictionary into memory. Returns true if successful else false.\n */\nbool load(const char* dictionary)\n{\n // TODO\n // opens dictionary\n FILE* file = fopen(dictionary, \"r\");\n if (file == NULL)\n return false;\n\n // create an array for word to be stored in\n char word[LENGTH+1];\n\n // scan through the file, loading each word into the hash table\n while (fscanf(file, \"%s\\n\", word)!= EOF)\n {\n // increment dictionary size\n dictionarySize++;\n\n // allocate memory for new word \n node* newWord = malloc(sizeof(node));\n\n // put word in the new node\n strcpy(newWord->word, word);\n\n // find what index of the array the word should go in\n int index = hash(word);\n\n // if hashtable is empty at index, insert\n if (hashtable[index] == NULL)\n {\n hashtable[index] = newWord;\n newWord->next = NULL;\n }\n\n // if hashtable is not empty at index, append\n else\n {\n newWord->next = hashtable[index];\n hashtable[index] = newWord;\n } \n }\n\n // close file\n fclose(file);\n\n // return true if successful \n return true;\n}\n\n/**\n * Returns true if word is in dictionary else false.\n */\nbool check(const char* word)\n{\n // TODO\n // creates a temp variable that stores a lower-cased version of the word\n char temp[LENGTH + 1];\n int len = strlen(word);\n for(int i = 0; i < len; i++)\n temp[i] = tolower(word[i]);\n temp[len] = '\\0';\n\n // find what index of the array the word should be in\n int index = hash(temp);\n\n // if hashtable is empty at index, return false\n if (hashtable[index] == NULL)\n {\n return false;\n }\n\n // create cursor to compare to word\n node* cursor = hashtable[index];\n\n // if hashtable is not empty at index, iterate through words and compare\n while (cursor != NULL)\n {\n if (strcmp(temp, cursor->word) == 0)\n {\n return true;\n }\n cursor = cursor->next;\n }\n\n // if you don't find the word, return false\n return false;\n}\n\n/**\n * Returns number of words in dictionary if loaded else 0 if not yet loaded.\n */\nunsigned int size(void)\n{\n // TODO\n // if dictionary is loaded, return number of words\n if (dictionarySize > 0)\n {\n return dictionarySize;\n }\n\n // if dictionary hasn't been loaded, return 0\n else\n return 0;\n}\n\n/**\n * Unloads dictionary from memory. Returns true if successful else false.\n */\nbool unload(void)\n{\n // TODO\n // create a variable to go through index\n int index = 0;\n\n // iterate through entire hashtable array\n while (index < SIZE)\n {\n // if hashtable is empty at index, go to next index\n if (hashtable[index] == NULL)\n {\n index++;\n }\n\n // if hashtable is not empty, iterate through nodes and start freeing\n else\n {\n while(hashtable[index] != NULL)\n {\n node* cursor = hashtable[index];\n hashtable[index] = cursor->next;\n free(cursor);\n }\n\n // once hashtable is empty at index, go to next index\n index++;\n }\n }\n\n // return true if successful\n return true;\n}\n\n#ifndef DICTIONARY_H\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:23:21.923",
"Id": "37277",
"ParentId": "37155",
"Score": "4"
}
},
{
"body": "<p>I would try and approach this more generically.</p>\n\n<p>Define a rules interface, run each section of the string through the Rule and add the result.</p>\n\n<p>The rules can then check individually for all caps, exclamation marks, etc rather than hard coding it into your central method.</p>\n\n<p>(i.e. a rule that returns 1 point for every exclamation mark it finds or something).</p>\n\n<p>Might be worth having two types of rule - \"full string rule\" and \"word rule\". the full string rule can process things like total number of exclamation marks and stuff, then you split the string on whitespace and run all the found words through the word rules.</p>\n\n<p>For things like nice/nasty words I would have a configuration file somewhere listing words and a positive or negative score next to them - for example please -10, swearing +10, etc.</p>\n\n<p>Your word rule can then scan your words against that dictionary and apply the result to your score.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:31:04.670",
"Id": "37546",
"ParentId": "37155",
"Score": "5"
}
},
{
"body": "<h2>Algorithm:</h2>\n\n<p>There are a few fallacies that you assume in your approach. Nothing <em>wrong</em>, but things that could be improved:</p>\n\n<ul>\n<li><p>You assume bounds on your \"heat score\" with this comment</p>\n\n<blockquote>\n<pre><code>/* 0% cold; 100% very heated */\n</code></pre>\n</blockquote>\n\n<p>But there is no code implementing these bounds. You can go negative, as well as go above 100. I'd recommend observing these bounds, and sentiment should be seen as a probability which can only be between 0 and 1. </p>\n\n<p>To match this probability, it might be better for you to store your sentiment score as a <code>double</code> rather than an <code>int</code> but that choice is up to you.</p></li>\n<li><p>Right now you are using a <a href=\"https://en.wikipedia.org/wiki/Bag-of-words_model\" rel=\"nofollow\">bag-of-words model</a>. This is a typical approach when first starting out with sentiment analysis since it is easier, but it usually gives a lower accuracy representing what the actual sentiment of the text is.</p>\n\n<p>As I was saying, it's a fairly straightforward and practical way to go, but there are a lot of situations where it will get make mistakes.</p>\n\n<ol>\n<li><p><strong>Ambiguous sentiment words</strong> - \"This product works terribly\" vs. \"This product is terribly good\"</p></li>\n<li><p><strong>Missed negations</strong> - \"I would never in a millions years say that this product is worth buying\"</p></li>\n<li><p><strong>Quoted/Indirect text</strong> - \"My dad says this product is terrible, but I disagree\"</p></li>\n<li><p><strong>Comparisons</strong> - \"This product is about as useful as a hole in the head\"</p></li>\n<li><p><strong>Anything subtle</strong> - \"This product is ugly, slow and uninspiring, but it's the only thing on the market that does the job\"</p></li>\n</ol>\n\n<p>As far as NLP helping you with any of this, <a href=\"http://en.wikipedia.org/wiki/Word_sense_disambiguation\" rel=\"nofollow\">word sense disambiguation</a> (or even just <a href=\"http://en.wikipedia.org/wiki/Part-of-speech_tagging\" rel=\"nofollow\">part-of-speech tagging</a>) may help with (1), <a href=\"http://en.wikipedia.org/wiki/Statistical_parsing\" rel=\"nofollow\">syntactic parsing</a> might help with the long range dependencies in (2), some kind of <a href=\"http://en.wikipedia.org/wiki/Shallow_parsing\" rel=\"nofollow\">chunking</a> might help with (3). It's all research level work though, there's nothing that I know of that you can directly use. Issues (4) and (5) are a lot harder, I throw up my hands and give up at this point.</p></li>\n<li><p>You are going to not score a decent amount of sentences that occur in actual life. Take a look at a lot of sentences in this post, for example. They don't contain swear words, \"please\" or \"sorry\", exclamation points or words in caps. You need a more general lexicon of positive, negative, and neutral words and then a system to weigh in the effects of these words into your score.</p></li>\n<li><p>There are some odd score modifications you do. Why is it when I refer to myself with \"I\", that the score is considered more positive? I don't think it should, and I would say to reconsider the reason you think so.</p>\n\n<p>Sentences that end with an exclamation point aren't necessary negative (higher heat) either. An exclamation point is often used to indicate strong feelings (such as excitement) <strong>or</strong> high volume. Most sentiment analysis systems that I've looked at don't consider punctuation in the final score at all.</p>\n\n<p>\"A\" should be considered the same as \"I\". It is very possible that a sentence could start with \"A\", and be either positive or neutral but your program considers it to have a negative connotation.</p></li>\n</ul>\n\n<p>For a basic sentiment analysis this is fine, but do note that it does have it's flaws. If you're looking to improve the accuracy of your algorithm, I'd recommend reading <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.73.524&rep=rep1&type=pdf\" rel=\"nofollow\">this research paper</a>, which achieves a classification accuracy of 90% (higher than any other published results). </p>\n\n<h2>Code:</h2>\n\n<ul>\n<li><p>Right now you have the method <code>str_findString()</code>. I'm guessing this is an variation of <a href=\"http://www.cplusplus.com/reference/cstring/strstr/\" rel=\"nofollow\"><code>strstr()</code></a>. I'm also guessing that <code><string.h></code>'s implementation of this method will be more efficient and faster, based on it being a standard library.</p>\n\n<pre><code>if (strstr(temp_a, \"$#@#\"))\n{\n ...\n}\n</code></pre></li>\n<li><p>Declare <code>i</code> inside of your <code>for</code> loops.<sup>(C99)</sup></p>\n\n<pre><code>for (int i = 0; i < objString->length; i++)\n</code></pre></li>\n<li><p>I would add another tab to the function body.</p>\n\n<pre><code>EHeat str_isHeated(STRING *objString)\n{\n int intHeatScore = 0; /* 0% cold; 100% very heated */\n STRINGCOLLECTION tokens; \n</code></pre></li>\n<li><p>I would combine your last two return conditions into one.</p>\n\n<blockquote>\n<pre><code>else if (intHeatScore >= 0)\n return EHeat_Cold; \n\nreturn EHeat_Cold;\n</code></pre>\n</blockquote>\n\n<p>I find the last <code>else-if</code> comparison useless overall, and would just return <code>EHeat_Cold</code> anyways if it wasn't included.</p>\n\n<pre><code>return EHeat_Cold;\n</code></pre></li>\n<li><p>I'm not too sure about what I'm assuming are <code>#define</code>s: <code>STRING</code> and <code>STRINGCOLLECTION</code>. I guess it is okay to keep them, but is there a specific reason you don't just put in what they actually are: <code>char*</code> and <code>char*</code> array respectively?</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:28:16.043",
"Id": "41910",
"ParentId": "37155",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:15:54.963",
"Id": "37155",
"Score": "15",
"Tags": [
"c",
"strings",
"game"
],
"Title": "C String - new function to detect user's anger"
}
|
37155
|
<p>I wrote my first AJAX script that brings content from other pages without refreshing the entire page. I just want to see if improvements can be added to it, or if I'm doing something not recommended.</p>
<pre><code>$(function(){
// content container content loader
$("#nav-tabs-list a").click(function() {
var page = this.hash.substr(1);
//$("#sidebar-content-container").html(""); // displays content only after fully loaded
$.get("content/" + page + ".php", function(gotHtml) {
$("#content-container").html(gotHtml);
});
});
if ( location.hash ) {
$("a[href="+location.hash+"]").click();
} else {
$("#nav-tabs-list a").click();
}
// sidebar content loader
$("#sidebar-container #sidebar-tabs-container a").click(function() {
var page = this.hash.substr(1);
//$("#sidebar-content-container").html(""); // displays content only after fully loaded
$.get("content/sidebar-content/" + page + ".php", function(gotHtml) {
$("#sidebar-content-container").html(gotHtml);
});
});
if ( location.hash ) {
$("a[href="+location.hash+"]").click();
} else {
$("#sidebar-container #sidebar-tabs-container a").click();
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:03:09.057",
"Id": "61254",
"Score": "0",
"body": "I assume this is jQuery? What javascript library are you using?"
}
] |
[
{
"body": "<p>You seem to have some copy pasted code there.</p>\n\n<p>How about</p>\n\n<pre><code>function enableLinks( selector , path , container )\n{\n /* Allow ajax to work */\n $( selector ).click( function()\n {\n var page = this.hash.substr(1);\n $.get( path + page + \".php\", function( html ) \n {\n $( container ).html( html );\n }); \n });\n /* Allow bookmarks to work */\n if ( location.hash )\n $(\"a[href=\"+location.hash+\"]\").click();\n else\n $(selector).click();\n}\n\n$(function()\n{\n enableLinks( \"#nav-tabs-list a\" , \"content/\" , \"#content-container\" );\n enableLinks( \"#sidebar-container #sidebar-tabs-container a\" , \n \"content/sidebar-content/\" ,\n \"#sidebar-content-container\" );\n});\n</code></pre>\n\n<p>The things you do with <code>location.hash</code> are a bit of a mystery to me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T21:38:27.783",
"Id": "61270",
"Score": "0",
"body": "@tomdenmuyt Your code seems the simplest and works. But when i try to navigate to a specific page it does not work for example http://localhost/TEMPLATE/#features in my code i go to the features page yet i cant in yours. How do i fix that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:16:48.923",
"Id": "61287",
"Score": "0",
"body": "@JarolinVargas Try now"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T21:03:26.907",
"Id": "37172",
"ParentId": "37157",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T19:32:28.347",
"Id": "37157",
"Score": "4",
"Tags": [
"javascript",
"ajax"
],
"Title": "Bringing content from other pages without refreshing the entire page"
}
|
37157
|
<p>I'm considering releasing a library as a bower module. Are there issues with code quality, missing test cases, that need to be addressed first? Perhaps it's not a good candidate for public release. If so, why not? </p>
<p>What level of documentation would you want for something like this? I've seen some open source modules publish annotated source, in addition to API documentation. Is annotated source documentation overkill for something like this?</p>
<p>Library Details:</p>
<ul>
<li>The library provides a simple object persistence layer for Angularjs apps using a local Pouchdb database. It is <code>$digest</code> aware and promise based. The public API consists of
<ul>
<li>setType(type, fn) <em>//register prototype</em></li>
<li>newObj() <em>//new object from registered prototype</em></li>
<li>saveObj(obj) <em>// insert and update</em></li>
<li>getAll(type)</li>
<li>getById(type,id)</li>
<li>getByName(type,name)</li>
<li>getByGQL(query) <em>//TODO: support arbitrary find conditions via Google Query Language</em></li>
<li>deleteObj(obj)</li>
<li>deleteById(id)</li>
</ul></li>
<li>Because the library supports objects that may include functions, the library requires a prototype for each <code>type</code> be registered with the library. The prototype is used to re-hydrate de-serialized objects retrieved from the database.</li>
<li>Evil <code>new Function()</code> calls are slated to be eliminated by replacing view based queries with their equivalent <a href="https://github.com/daleharvey/pouchdb/wiki/Google-Query-Language-Documentation">GQL</a> queries.</li>
<li>Models are required by <em>Pouchdb</em> to have <code>_id</code> and <code>_rev</code> properties. <code>_id</code> is unique within a database.</li>
<li>Models are required by the <em>library</em> to have <code>type</code> and <code>name</code> properties. Currently <code>name</code> is enforced to be unique within type. However, the <code>name</code> constraint is slated to be removed in favor of an available <code>unique</code> model validation, allowing any property to act as a unique key.</li>
<li>Model validation support will include all of <a href="http://validatejs.org/">validatejs</a>'s ActiveRecord style constraints, plus library specific <code>unique</code>, <code>exists</code> and <code>notExists</code> constraints.</li>
</ul>
<p>Sample Code (implements the save/update operations):</p>
<pre><code>// save or update an object, returns a promise -- exposed by the API
ret.saveObj = function (obj) {
var err;
var deferred = $q.defer();
if (typeof obj === 'undefined') {
err = {};
err.message = "saveObj - Error: object undefined";
safeApply($rootScope, function () {
deferred.reject(err);
});
} else {
save(obj, function (err, obj) {
if (err) {
safeApply($rootScope, function () {
deferred.reject(err);
});
} else {
safeApply($rootScope, function () {
deferred.resolve(obj);
});
}
});
}
return deferred.promise;
};
// ensure that Angularjs can 'see' any changes
var safeApply = function (scope, fn) {
if (scope.$$phase || scope.$root.$$phase) {
fn();
} else {
scope.$apply(fn);
}
};
// private save / update code (async)
var save = function (obj, callback) {
var err;
var constraints = {
type: {
presence: true,
simple: true,
inclusion: {
within: getNew
}
},
name: {
presence: true,
simple: true
}
};
err = validate(obj, constraints);
if (typeof err !== 'undefined') {
callback(err, obj);
} else {
// ensure name property is unique
var body = '';
if (obj._id && obj._id.length > 0) {
body = "if(doc.type === '" + obj.type + "' && doc.name === '" + obj.name + "' && doc._id !== '" + obj._id + "') {emit(doc.name, doc);}";
} else {
body = "if(doc.type === '" + obj.type + "' && doc.name === '" + obj.name + "' ) {emit(doc.name, doc);}";
}
var view = {
map: new Function("doc", body)
};
$db.query(view, {
reduce: false
}, function (error, response) {
err = {};
if (!error && response.rows.length > 0) {
err.message = "Another object with the name '" + obj.name + "' already exists";
callback(err, null);
} else {
// copy data to savable object
var serializableObj = {};
for (var field in obj) {
if (obj.hasOwnProperty(field)) {
if (typeof obj[field] !== 'function') {
serializableObj[field] = angular.copy(obj[field]);
}
}
}
if (obj._rev !== '') {
$db.get(obj._id, function (err, doc) {
if (error) {
callback(error, null);
} else {
if (doc.type == obj.type) {
update(serializableObj, function (error, obj) {
if (error) {
callback(error, null);
} else {
obj._rev = serializableObj._rev;
callback(null, obj);
}
});
} else {
err = {};
err.message = "Cannot update object of type '" + doc.type + "' to type '" + obj.type + "'";
callback(err, null);
}
}
});
} else {
insert(serializableObj, function (error, obj) {
if (error) {
callback(error, null);
} else {
obj._id = serializableObj._id;
obj._rev = serializableObj._rev;
callback(null, obj);
}
});
}
}
});
}
};
</code></pre>
<p>Tests (currently passing unless marked "PEND:"):</p>
<pre><code>pouch-model
delete expectations
should delete an object by id
should delete an object by object
should return an error on delete by id if object does not exist
should return an error on delete if object does not exist
should return an error on delete by id if id is undefined
should return an error on delete if object is undefined
should return an error on delete if object is missing an id
find expectations
should get all of a single type
should find an object by id and type
should find an object by name and type
should return null if object is not found
should return an error if find by id not passed type or id
should return an error if find by name not passed type or name
prototype expectations
should take object prototypes and return correct objects
should return an error when attempting to create an object if type is not configured
should return an error when attempting to find an object if type is not configured
should return an error when attempting to get all if type is not configured
should return an error when attempting to save objects if type is not configured
should return an error when calling setNew() with a value that is not a function
save expectations
should save an object and then get it back
should not save a new object with a duplicate name
should save an object with a duplicate name if their type properties differ
should return an error if name and type are not typeof string
should return an error if name and type are empty strings
should retain behavior after object is saved and restored from the pouchdb
should restore model data recursively including array and object properties
should return an error on missing name or type properties
should return an error on missing undefined object
update expectations
should update an object and then get it back
should not update an object to a duplicate name
should update an object name to a duplicate name if types differ
should return an error if type property is changed
validation expectations
PEND: should validate against pouch_model_validations if present
PEND: should not return error when pouch_model_validations are not present
PEND: should validate model for criteria unique on property
PEND: should validate model for criteria unique on property within collection
PEND: should validate model for criteria exists on type and property
PEND: should validate model for criteria not exists on type and property
</code></pre>
|
[] |
[
{
"body": "<p>The code looks good (make sure to replace <code>new Function</code> quickly :), and it's a great candidate for a public release.</p>\n\n<p>It is short enough to deserve annotated documentation that would explain how it works which is useful for debugging. But that should not replace the actual API documentation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T12:38:56.680",
"Id": "37303",
"ParentId": "37161",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:06:01.163",
"Id": "37161",
"Score": "7",
"Tags": [
"javascript",
"angular.js",
"couchdb"
],
"Title": "Open source angularjs pouchdb model persistence layer - release ready?"
}
|
37161
|
<p>I have created a program which rolls a die according to the number of sides that the user enters:</p>
<pre><code>def var():
import random
dicesides = int(input("Please enter the amount of sides you want the dice that is being thrown to have. The dice sides available are: 4, 6 and 12: "))
script(dicesides, random)
def script(dicesides, random):
if dicesides == 4:
dice4 = int(random.randrange(1, dicesides))
print(dicesides, " sided dice, score", dice4)
elif dicesides == 6:
dice6 = int(random.randrange(1, dicesides))
print(dicesides, " sided dice, score", dice6)
elif dicesides == 12:
dice12 = int(random.randrange(1, dicesides))
print(dicesides, " sided dice, score", dice12)
elif dicesides != 4 or dicesides != 6 or dicesides != 12:
print("That number is invalid. Please try again.")
var()
repeat = str(input("Repeat? Simply put yes or no : "))
if repeat == "yes":
var()
else:
quit()
var()
</code></pre>
<p>Is there a way to shorten this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:51:19.070",
"Id": "61297",
"Score": "0",
"body": "Given that you are using a computer random number generator, why not accept any number of sides? Anything wrong with a d23? At least 8 and 20 seem like they should be acceptable."
}
] |
[
{
"body": "<p>Your variables <code>dice4</code>. <code>dice6</code> and <code>dice12</code> are essentially the same variables, so let's give them the same name. It now happens that three of the cases are identical, and can be shortened to:</p>\n\n<pre><code>if dicesides != 4 or dicesides != 6 or dicesides != 12:\n print(\"That number is invalid. Please try again.\")\n var()\nelse:\n score = int(random.randrange(1, dicesides))\n print(dicesides, \" sided dice, score\", score)\n</code></pre>\n\n<p>The test for allowed numbers of sides can be shortened to <code>dicesides not in [4, 6, 12]</code>, which more clearly shows what you are trying to express. This would allow you to include the number of sides as an optional parameter to the function – some people use 20-sided dices a lot. And actually, there is no reason why you would constrain the user to a certain number of sides anyway.</p>\n\n<p>It is not clear to me what advantage recursion via the <code>var</code> method has over an ordinary loop. One <em>disadvantage</em> is that an avid player could theoretically overflow the stack….</p>\n\n<p>It is also not clear why <code>random</code> is a parameter to the <code>script</code>.</p>\n\n<p>You are using <code>random.randrange</code> wrong. The <code>help()</code> output on my system gives me:</p>\n\n<blockquote>\n <p>Choose a random item from <code>range(start, stop[, step])</code>.</p>\n \n <p>This fixes the problem with <code>randint()</code> which includes the endpoint; in Python this is usually not what you want.</p>\n</blockquote>\n\n<p>This means that rolling a 6-sided die, you will invoke <code>random.randrange(1, 6)</code>, which returns a random int in the range <code>[1, 6)</code> – this excludes the number <code>6</code>, and you actually pick from <code>1, 2, 3, 4, 5</code>. Fix this either by <code>1 + random.randrange(0, dicesides)</code> or preferably <code>random.randint(1, dicesides)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T00:04:46.373",
"Id": "61299",
"Score": "3",
"body": "`dicesides != 4 or dicesides != 6 or dicesides != 12` is always true, since `4 != 6`. On the other hand, `dicesides not in [4, 6, 12]` can be false."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:41:04.927",
"Id": "37170",
"ParentId": "37163",
"Score": "4"
}
},
{
"body": "<p>Absolutely! If you replace <code>dice4</code>, <code>dice6</code> and <code>dice12</code> with <code>rolled</code>, you'll see they all have the same code. At that point, just gate the shared code with something like <code>if dicesides in [4, 6, 12]:</code>, and change your final <code>elif</code> to an <code>else</code>.</p>\n\n<p>Other comments:</p>\n\n<ul>\n<li>I would suggest not passing <code>random</code> to <code>script()</code> (which itself should have a better name, such as <code>roll</code>).</li>\n<li>The way you loop uses a technique that looks a lot like recursion. However your approach is not using this in any meaningful fashion. I would probably move the part of your code from <code>repeat = str(input(...</code> into <code>var()</code> (which itself should either have a more meaningful name, or at least a common name like <code>main</code>), and put this in a while loop.</li>\n</ul>\n\n<p>Putting these together:</p>\n\n<pre><code>import random\n\ndef main():\n repeat = \"yes\"\n while repeat == \"yes\":\n dicesides = ...\n roll(dicesides)\n repeat = ...\n\ndef roll(dicesides):\n if dicesides in [4, 6, 12]:\n rolled = int(random.randrange(1, dicesides)) # but see amon's notes\n print(dicesides, \" sided dice, score\", rolled)\n else:\n print(\"That number is invalid. Please try again.\")\n\nmain()\n</code></pre>\n\n<p>Note that this does result in a slight change on invalid input - it now asks you if you want to repeat.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:45:45.190",
"Id": "37171",
"ParentId": "37163",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37170",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:13:18.833",
"Id": "37163",
"Score": "5",
"Tags": [
"python",
"random",
"dice"
],
"Title": "Roll a die according to the number of sides that the user enters"
}
|
37163
|
<p>I'm late to this weekend challenge (sorry), but since it's all in good fun, I hope that's ok. I'm no poker player, though, so I may have completely overlooked something.</p>
<p>The <code>Hand</code> class does the evaluation, and calculates (among other things) a <code>score</code> array which is ordered for possible comparison with another poker hand. First item is the hand's score (0-8), and the following 1-5 items are the tie-breaking values/kickers. E.g. a three-of-a-kind hand might be scored as</p>
<pre><code>[3, 5, 9, 6] # base score, value of tripled card, kicker, kicker
</code></pre>
<p>Or, for comparison purposes, consider two two-pair hands</p>
<pre><code>player1.score #=> [2, 7, 5, 3]
player2.score #=> [2, 7, 5, 8]
</code></pre>
<p>Both players have two pairs of 7s and 5s, but player 2 wins by having the higher kicker.</p>
<p>The (known and intentional) limitations are:</p>
<ul>
<li>5 cards per hand only (i.e. no communal cards, etc.)</li>
<li>No support for jokers/wildcards</li>
<li>No validation of the cards</li>
</ul>
<p>It does take into account high and low aces when determining straights, but otherwise it's not terribly flexible. (Of course, you can sidestep the "5 cards only" limitation by just brute-force checking 5-card combinations one at a time using, say, <code>Array#combination</code>, but that's another story.)</p>
<p>I haven't looked at how this challenge has been solved in other languages, so perhaps there are some tricks I'm missing. But really, the point was mostly to see how far I could get with a fairly functional approach and array/enumerable methods. The code's mostly one-line methods, so it went OK, I think.</p>
<p>Haven't bothered with optimization yet, but (if nothing else) a bunch of values can be memoized with a smattering of <code>||=</code>. However, I'm more interested in critiques of the overall approach (I just like <code>?</code> methods, ok?!) and possible alternatives (either overall or for specific parts)</p>
<p>The full code (including tests and more verbose comments) is <a href="https://gist.github.com/Flambino/2c67651035f59c9820fd">in this gist</a>; below are the principal classes (see further notes below)</p>
<pre><code>ACE_LOW = 1
ACE_HIGH = 14
# Use Struct to model a simple Card class
Card = Struct.new :suit, :value
# This class models and evaluates a hand of cards
class Hand
attr_reader :cards
RANKS = {
straight_flush: 8,
four_of_a_kind: 7,
full_house: 6,
flush: 5,
straight: 4,
three_of_a_kind: 3,
two_pair: 2,
pair: 1
}.freeze
def initialize(cards)
raise ArgumentError unless cards.count == 5
@cards = cards.freeze
end
# The hand's rank as an array containing the hand's
# type and that type's base score
def rank
RANKS.detect { |method, rank| send :"#{method}?" } || [:high_card, 0]
end
# The hand's type (e.g. :flush or :pair)
def type
rank.first
end
# The hand's base score (based on rank)
def base_score
rank.last
end
# The hand's score is an array starting with the
# base score, followed by the kickers.
def score
[base_score] + kickers
end
# Tie-breaking kickers, ordered high to low.
def kickers
repeat_values + (aces_low? ? aces_low_values.reverse : single_values)
end
# If the hand's straight and flush, it's a straight flush
def straight_flush?
straight? && flush?
end
# Is a value repeated 4 times?
def four_of_a_kind?
repeat_counts.include? 4
end
# Three of a kind and a pair make a full house
def full_house?
three_of_a_kind? && pair?
end
# If the hand only contains one suit, it's flush
def flush?
suits.uniq.count == 1
end
# This is the only hand where high vs low aces comes into play.
def straight?
aces_high_straight? || aces_low_straight?
end
# Is a card value repeated 3 times?
def three_of_a_kind?
repeat_counts.include? 3
end
# Are there 2 instances of repeated card values?
def two_pair?
repeat_counts.count(2) == 2
end
# Any repeating card value?
def pair?
repeat_counts.include? 2
end
# Actually just an alias for aces_low_straight?
def aces_low?
aces_low_straight?
end
# Does the hand include one or more aces?
def aces?
values.include? ACE_HIGH
end
# The repeats in the hand
def repeats
cards.group_by &:value
end
# The number of repeats in the hand, unordered
def repeat_counts
repeats.values.map &:count
end
# The values that are repeated more than once, sorted by
# number of occurrences
def repeat_values
repeated = repeats.map { |value, repeats| [value.to_i, repeats.count] }
repeated = repeated.reject { |value, count| count == 1 }
repeated = repeated.sort_by { |value, count| [count, value] }.reverse
repeated.map(&:first)
end
# Values that are not repeated, sorted high to low
def single_values
repeats.select { |value, repeats| repeats.count == 1 }.map(&:first).sort.reverse
end
# Ordered (low to high) array of card values (assumes aces high)
def values
cards.map(&:value).sort
end
# Unordered array of card suits
def suits
cards.map(&:suit)
end
# A "standard" straight, treating aces as high
def aces_high_straight?
straight_values_from(values.first) == values
end
# Special case straight, treating aces as low
def aces_low_straight?
aces? && straight_values_from(aces_low_values.first) == aces_low_values
end
# The card values as an array, treating aces as low
def aces_low_values
cards.map(&:value).map { |v| v == ACE_HIGH ? ACE_LOW : v }.sort
end
private
# Generate an array of 5 consecutive values
# starting with the `from` value
def straight_values_from(from)
(from...from + 5).to_a
end
end
</code></pre>
<h3>Notes and edits</h3>
<p>As a rule, I consider aces high (value of 14), and only count them as low (value of 1) when checking for an aces-low straight. That is, an ace <code>Card</code> instance will have a value of 14, but in the context of an aces-low straight, a <code>Hand</code> instance will report it as 1.</p>
<p><code>Hand</code> and <code>Card</code> instances are considered immutable (though, technically, cards aren't immutable, since I'm using <code>Struct</code>, but that's only for the purposes of this challenge; otherwise I'd define a "proper" class)</p>
<p>Looking at the code again, here are my own concerns (beyond the limitations noted above):</p>
<ul>
<li>Some methods return unordered arrays, some sort from high to low, and yet others from low to high. Might be nice to make this more consistent.</li>
<li>The straight-checking is pretty naïve: Generate 5 consecutive numbers and see if they match the card values. I considered enumerating the values in various ways instead, but a simple <code>==</code> comparison with a generated array seemed more straightforward than what I could come up with.</li>
<li>There's some repetition required in the <code>RANKS</code> hash keys and the method names, but I found it cleaner than the alternatives I played with.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T01:17:22.997",
"Id": "62175",
"Score": "0",
"body": "Looks like we need more ruby coders..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:12:59.150",
"Id": "62186",
"Score": "1",
"body": "@retailcoder Yeah :( Kinda strange actually, given how much emphasis the Ruby world puts on code quality, conventions, idioms and all that. I've been answering a lot of questions, which is why I'd like someone to critique _me_ for once - maybe I'm doing it wrong! But hey, you may get to keep your 50 rep if no one steps up, so it ain't all bad :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:14:41.897",
"Id": "62187",
"Score": "0",
"body": "Nope, the 50 rep is [gone already](http://codereview.stackexchange.com/users/23788/retailcoder?tab=reputation), but that's fine - but **I want to award that bounty manually** (I want that hat!) so you might want to self-review it, just in case :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:33:34.833",
"Id": "62193",
"Score": "1",
"body": "@retailcoder Ah, right, rep is withdrawn immediately. Well, I'll happily take your money-- I mean rep, but not only as a last resort: If no one appears in time for the bounty, I'll self-review, because you deserve a new hat! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:36:34.827",
"Id": "62195",
"Score": "0",
"body": "There should be a hat for *kill-your-own-zombie* - oh, there is one: *Sock Puppet* :)"
}
] |
[
{
"body": "<p>I think your example is well structured, I hope my review does it some justice. There are your concerns and some additional points I want to discuss:</p>\n\n<p><a href=\"https://gist.github.com/beatrichartz/06c3142d8a0dae8dae84\"><em>You'll find a working implementation of the following code here</em></a></p>\n\n<ol>\n<li><p>General coding style</p>\n\n<p>Is nice and consistent. I particularly like your use of question marks to denote methods returning a boolean value.</p>\n\n<ul>\n<li>Maybe you could omit braces also from method definitions, since you omit them in method calls where possible.</li>\n<li>You left <code>RANKS</code>, your attributes and the initializer without documentation. I think particularly <code>RANKS</code> and the initializer would benefit from it.</li>\n</ul></li>\n<li><p>Repetition in <code>RANKS</code> and instance methods</p>\n\n<p>I think this is ok, and I couln't come up with a better or more readable way.</p></li>\n<li><p>The <code>flush</code> method</p>\n\n<p>They could be written more elegantly using <a href=\"http://www.ruby-doc.org/core-2.0.0/Enumerable.html#method-i-one-3F\"><code>Enumerable#one?</code></a></p>\n\n<pre><code> # If the hand only contains one suit, it's flush\n def flush?\n suits.uniq.one?\n end\n</code></pre></li>\n<li><p>Decision to make cards a <code>Struct</code></p>\n\n<p>I like the use of constants in your code to improve readability and maintainability. One thing that caught my eye was that <code>ACE_LOW</code> and <code>ACE_HIGH</code> are global constants, while <code>RANKS</code> is not (which is good). I think this design flaw comes from your decision to make <code>Card</code> a <code>Struct</code> object, and the often deriving lack of logic in these kind of objects. Lets change that and make <code>Card</code> a first class citizen: Your code will benefit.</p>\n\n<pre><code>class Card\n include Comparable\n\n attr_reader :suit, :value\n\n # Value to use as ace low\n ACE_LOW = 1\n\n # Value to use as ace high\n ACE_HIGH = 14\n\n # initialize the card with a suit and a value\n def initialize suit, value\n super()\n @suit = suit\n @value = value\n end\n\n # Return the low card\n def low_card\n ace? ? Card.new(suit, ACE_LOW) : self\n end\n\n # Return if the card is an ace high\n def ace?\n value == ACE_HIGH\n end\n\n def ace_low?\n value == ACE_LOW\n end\n\n # Return if the card has suit spades\n def spades?\n suit == :spades\n end\n\n # Return if the card has suit diamonds\n def diamonds?\n suit == :diamonds\n end\n\n # Return if the card is suit hearts\n def hearts?\n suit == :hearts\n end\n\n # Return if the card has suit clubs\n def clubs?\n suit == :clubs\n end\n\n # Compare cards based on values and suits\n # Ordered by suits and values - the suits_index will be introduced below\n def <=> other\n if other.is_a? Card\n (suit_index(suit) <=> suit_index(other.suit)).nonzero? || value <=> other.value\n else\n value <=> other\n end\n end\n\n # Allow for construction of card ranges across suits\n # the suits_index will be introduced below\n def succ\n if ace?\n i = suit_index suit\n Card.new(Deck::SUITS[i + 1] || Deck::SUITS.first, ACE_LOW)\n else\n Card.new(suit, value + 1)\n end\n end\n\n def successor? other\n succ == other\n end\n\n def straight_successor? other\n succ === other\n end\n\n # Compare cards for equality in value\n def == other\n if other.is_a? Card\n value == other.value\n else\n value == other\n end\n end\n alias :eql? :==\n\n # overwrite hash with value since cards with same values are considered equal\n alias :hash :value\n\n # Compare cards for strict equality (value and suit)\n def === other\n if other.is_a? Card\n value == other.value && suit == other.suit\n else\n false\n end\n end\n\n private\n\n # If no deck, this has to be done with an array of suits\n # gets the suit index\n def suit_index suit\n Deck::SUITS.index suit\n end\nend\n</code></pre>\n\n<p>This would make the following improvements to the code in <code>Hand</code> possible:</p>\n\n<pre><code>class Hand\n\n # ... \n\n # Tie-breaking kickers, ordered high to low.\n def kickers\n same_of_kind + (aces_low? ? aces_low.reverse : single_cards)\n end\n\n # If the hand's straight and flush, it's a straight flush\n def straight_flush?\n straight? && flush?\n end\n\n # Is a value repeated 4 times?\n def four_of_a_kind?\n same_of_kind? 4\n end\n\n # Three of a kind and a pair make a full house\n def full_house?\n same_of_kind?(3) && same_of_kind?(2)\n end\n\n # If the hand only contains one suit, it's flush\n def flush?\n suits.uniq.one?\n end\n\n # This is the only hand where high vs low aces comes into play.\n def straight?\n aces_high_straight? || aces_low_straight?\n end\n\n # Is a card value repeated 3 times?\n def three_of_a_kind?\n collapsed_size == 2 && same_of_kind?(3)\n end\n\n # Are there 2 instances of repeated card values?\n def two_pair?\n collapsed_size == 2 && same_of_kind?(2)\n end\n\n # Any pair?\n def pair?\n same_of_kind? 2\n end\n\n def single_cards\n cards.select{|c| cards.count(c) == 1 }\n end\n\n # Does the hand include one or more aces?\n def aces?\n cards.any? &:ace?\n end\n\n # Ordered (low to high) array of card values (assumes aces high)\n def values\n cards.map(&:value).sort\n end\n\n # Unordered array of card suits\n def suits\n cards.map &:suit\n end\n\n # A \"standard\" straight, treating aces as high\n def aces_high_straight?\n all_successors? cards.sort_by(&:value)\n end\n\n # Special case straight, treating aces as low\n def aces_low_straight?\n aces? && all_successors?(aces_low)\n end\n alias :aces_low? :aces_low_straight?\n\n # The card values as an array, treating aces as low\n def aces_low\n cards.map(&:low_card).sort\n end\n\n private\n\n # Are there n cards same of kind?\n def same_of_kind?(n)\n !!cards.detect{|c| cards.count(c) == n }\n end\n\n # How many cards vanish if we collapse the cards to single values\n def collapsed_size\n cards.size - cards.uniq.size\n end\n\n # map the cards that are same of kind\n def same_of_kind\n 2.upto(4).map{|n| cards.select{|c| cards.count(c) == n }.reverse }.sort_by(&:size).reverse.flatten.uniq\n end\n\n # Are all cards succeeding each other in value?\n def all_successors?(cards)\n cards.all?{|a| a === cards.last || a.successor?(cards[cards.index(a) + 1]) }\n end\n\nend \n</code></pre>\n\n<p>Also</p>\n\n<ul>\n<li>it would contain the constants <code>ACE_HIGH</code> and <code>ACE_LOW</code> in <code>Card</code></li>\n<li>changing a card would be impossible. Values of cards as <code>Struct</code> in frozen <code>cards</code> array can still be modified since the structs respond to <code>value=</code> and <code>suit=</code></li>\n</ul></li>\n<li><p>The <code>Hand</code> initializer</p>\n\n<p>I think it would be nicer to have <code>cards</code> as a splat argument. To initialize with an array unnecessarily decreases readability. Also, the <code>ArgumentError</code> you raise is not very descriptive, which might lead to some confusion. All in all, this is how my improvements would look like:</p>\n\n<pre><code>def initialize(*cards)\n raise ArgumentError.new \"wrong number of cards (#{cards.count} for 5)\" unless cards.count == 5\n @cards = cards.freeze\nend\n</code></pre>\n\n<p>Depending on context of use, an additional sanity check may also be necessary: Check if you really receive 5 instances of <code>Card</code>.</p></li>\n</ol>\n\n<p><em>The following points are suggestions where you could go from here</em></p>\n\n<ol>\n<li><p>Make <code>Hand</code> a subclass of <code>Array</code></p>\n\n<p>A hand of cards is also an array of cards - The resemblance allows you to subclass <code>Array</code> with <code>Hand</code>. This will allow you to use the <code>Enumerable</code> and <code>Array</code> DSL directly on <code>Hand</code>,\nwhich could benefit you if you were to take this code any further (Think about a <code>Deck</code> and a <code>Game</code> class)</p>\n\n<p>Also, the way I'll do it will give you default sorting which should eliminate your problem with unsorted returns, plus you can call sort for suit-and-value based sorting.</p>\n\n<p>Additional sanity checks might be in order as soon as you decide to not <code>freeze</code> <code>Hand</code> on initialization:</p>\n\n<ul>\n<li>Check if <code>push</code>, <code>unshift</code>, <code>insert</code> and <code><<</code> get an instance of <code>Card as argument</code></li>\n<li>Check if <code>push</code>, <code>unshift</code>, <code>insert</code> and <code><<</code> don't add too many cards to a hand</li>\n</ul>\n\n<p>So, what does that make possible? Let's refactor:</p>\n\n<pre><code>class Hand < Array\n\n # .. RANKS\n\n def initialize(*cards)\n raise ArgumentError.new \"There must be 5 cards\" unless cards.count == 5\n super(cards)\n sort_by! &:value # This will give you a nicely sorted hand by default\n freeze\n end\n\n # The hand's rank as an array containing the hand's\n # type and that type's base score\n def rank\n RANKS.detect { |method, rank| send :\"#{method}?\" } || [:high_card, 0]\n end\n\n # The hand's type (e.g. :flush or :pair)\n def type\n rank.first\n end\n\n # The hand's base score (based on rank)\n def base_score\n rank.last\n end\n\n # The hand's score is an array starting with the\n # base score, followed by the kickers.\n def score\n ([base_score] + kickers.map(&:value))\n end\n\n # Tie-breaking kickers, ordered high to low.\n def kickers\n same_of_kind + (aces_low? ? aces_low.reverse : single_cards.reverse)\n end\n\n # If the hand's straight and flush, it's a straight flush\n def straight_flush?\n straight? && flush?\n end\n\n # Is a value repeated 4 times?\n def four_of_a_kind?\n same_of_kind? 4\n end\n\n # Three of a kind and a pair make a full house\n def full_house?\n same_of_kind?(3) && same_of_kind?(2)\n end\n\n # If the hand only contains one suit, it's flush\n def flush?\n suits.uniq.one?\n end\n\n # single cards in the hand\n def single_cards\n select{ |c| count(c) == 1 }.sort_by(&:value)\n end\n\n # This is the only hand where high vs low aces comes into play.\n def straight?\n aces_high_straight? || aces_low_straight?\n end\n\n # Is a card value repeated 3 times?\n def three_of_a_kind?\n collapsed_size == 2 && same_of_kind?(3)\n end\n\n # Are there 2 instances of repeated card values?\n def two_pair?\n collapsed_size == 2 && same_of_kind?(2)\n end\n\n # Any repeating card value?\n def pair?\n same_of_kind?(2)\n end\n\n # Does the hand include one or more aces?\n def aces?\n any? &:ace?\n end\n\n # Ordered (low to high) array of card values (assumes aces high)\n def values\n map(&:value).sort\n end\n\n # Ordered Array of card suits\n def suits\n sort.map &:suit\n end\n\n # A \"standard\" straight, treating aces as high\n def aces_high_straight?\n all?{|card| card === last || card.successor?(self[index(card) + 1]) }\n end\n alias :all_successors? :aces_high_straight?\n\n # Special case straight, treating aces as low\n def aces_low_straight?\n aces? && aces_low.all_successors?\n end\n alias :aces_low? :aces_low_straight?\n\n # The card values as an array, treating aces as low\n def aces_low\n Hand.new *map(&:low_card)\n end\n\n private\n\n # Are there n cards of the same kind?\n def same_of_kind?(n)\n !!detect{|card| count(card) == n }\n end\n\n def same_of_kind\n 2.upto(4).map{|n| select{|card| count(card) == n }.reverse }.sort_by(&:size).reverse.flatten.uniq\n end\n\n # How many cards vanish if we collapse the cards to single values\n def collapsed_size\n size - uniq.size\n end\n\nend\n</code></pre>\n\n<p>Together with the <code>Card</code> class, this gives you a nice DSL you can build on:</p>\n\n<pre><code>hand = Hand.new Card.new(:spades, 14), Card.new(:diamonds, 14), Card.new(:hearts, 14), Card.new(:clubs, 14), Card.new(:clubs, 14)\nhand.all? &:ace? #=> true, this guy is obviously cheating\n\nhand.any? &:spades? #=> true, he has spades\n\nhand.count &:ace? #=> 5\n</code></pre>\n\n<p>Just for fun, if you would have a <code>Deck</code> class which would also subclass <code>Array</code></p>\n\n<pre><code>class Deck < Array\n # the hands this deck creates\n attr_reader :hands\n\n # You can install any order here, Bridge, Preferans, Five Hundred\n SUITS = %i(clubs diamonds hearts spades).freeze\n\n # Initialize a deck of cards\n def initialize\n super (Card.new(SUITS.first, 1)..Card.new(SUITS.last, 14)).to_a\n shuffle!\n end\n\n # Deal n hands\n def deal! hands=5\n @hands = hands.times.map {|i| Hand.new *pop(5) }\n end\n\n # ... and so on\nend\n\ndeck = Deck.new\ndeck.deal!\n\ndeck.hands.sort_by &:rank #see who's winning\n\nhand = deck.hands.first\n\n# Select cards left in the deck that could be helpful to this hand\ndeck.select do |card|\n hand.any?{|card_in_hand| (card_in_hand..card_in_hand.succ).include? card }\nend\n</code></pre></li>\n<li><p>Where to go further</p>\n\n<ul>\n<li>Implement <code>Comparable</code> on <code>Hand</code></li>\n<li>Get rid of <code>freeze</code> on Hand so we can exchange cards for some type of games</li>\n<li>yada yada yada</li>\n</ul></li>\n</ol>\n\n<p>As I said, your example is already great and I hope you appreciate me sharing my ideas with you!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:29:38.567",
"Id": "62346",
"Score": "1",
"body": "Now THAT's a review!! (will certainly upvote when I reload at 12AM UTC)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:32:35.157",
"Id": "62347",
"Score": "0",
"body": "@retailcoder Your code was quite inspiring :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:16:47.400",
"Id": "62361",
"Score": "0",
"body": "Are you [hat-hunting](http://winterbash2013.stackexchange.com/leaderboard/codereview.stackexchange.com)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:22:28.930",
"Id": "62364",
"Score": "0",
"body": "Yes, but rather passively - I just take what's coming to me"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:23:38.153",
"Id": "62365",
"Score": "0",
"body": "Well here's CR's first awarded **Bounty-Hunter** hat!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:25:41.003",
"Id": "62367",
"Score": "1",
"body": "@retailcoder Thank you very much - I'll wear that one with pride!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:00:57.990",
"Id": "62452",
"Score": "3",
"body": "@BeatRichartz Excellent review, thank you! I agree with all your points, basically. This was of course just a Weekend Challenge, so I won't take it further myself, but you've done some nice work there. I don't quite know if I'd subclass Array. I thought about it, and while it makes sense on many levels I also found it a bit \"blunt\". I'd probably prefer a wholly custom class with a very focussed API to a specialization of a generic class. But either way will work fine, so it's practically just a matte of taste. Again, thanks for the review; great stuff!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:28:11.967",
"Id": "37618",
"ParentId": "37165",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "37618",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:26:22.900",
"Id": "37165",
"Score": "22",
"Tags": [
"ruby",
"weekend-challenge",
"playing-cards"
],
"Title": "Weekend Challenge: Ruby Poker Hand Evaluation"
}
|
37165
|
<h1>Normalization pertaining to Databases</h1>
<p>In SQL, normal forms are defining characteristics of relational databases. SQL forms get classified according to the types of modification anomalies they're subject to. First, second, and third normal forms (1NF, 2NF, 3NF) serve as remedies to the three main sources of modification anomalies.</p>
<p>The normal forms are nested in the sense that a table that's in 2NF is automatically also in 1NF. Similarly, a table in 3NF is automatically in 2NF, and so on. For most practical applications, putting a database in 3NF is sufficient to ensure a high degree of integrity. To be absolutely sure of its integrity, you must put the database into DK/NF.</p>
<p>The following lists lay out the criteria for each form:</p>
<h1>First Normal Form (1NF):</h1>
<ul>
<li>Table must be two-dimensional, with rows and columns.</li>
<li>Each row contains data that pertains to one thing or one portion of a thing.</li>
<li>Each column contains data for a single attribute of the thing being described.</li>
<li>Each cell (intersection of row and column) of the table must be single-valued.</li>
<li>All entries in a column must be of the same kind.</li>
<li>Each column must have a unique name.</li>
<li>No two rows may be identical.</li>
<li>The order of the columns and of the rows does not matter.</li>
</ul>
<h1>Second Normal Form (2NF):</h1>
<ul>
<li>Table must be in first normal form (1NF).</li>
<li>All nonkey attributes (columns) must be dependent on the entire key.</li>
</ul>
<h1>Third Normal Form (3NF):</h1>
<ul>
<li>Table must be in second normal form (2NF).</li>
<li>Table has no transitive dependencies.</li>
</ul>
<h1>Domain-Key Normal Form (DK/NF):</h1>
<ul>
<li>Every constraint on the table is a logical consequence of the definition of keys and domains.</li>
</ul>
<p>Taken from <a href="http://www.dummies.com/how-to/content/sql-criteria-for-normal-forms.html" rel="nofollow">www.dummies.com</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:37:25.243",
"Id": "37168",
"Score": "0",
"Tags": null,
"Title": null
}
|
37168
|
normalizing a Database to remove redundant information and produce an efficient database.
normal forms are defining characteristics of relational databases
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T20:37:25.243",
"Id": "37169",
"Score": "0",
"Tags": null,
"Title": null
}
|
37169
|
<p>I had to work in the Transport Problem and we're asked to try to make the fastest code for big matrices, so we're advised to try to avoid loops. And the only one I've got and I cannot imagine how to simplify it is this one for making an incidence matrix (with 1s, 0s and -1s) like that:</p>
<pre><code>b<-diag(-1,n2)
a<-b
for (i in 1:(n1-1)) {
a<-cbind(a,b)
}
</code></pre>
<p>Can this be simplified?</p>
|
[] |
[
{
"body": "<p>I can't think of anything faster than:</p>\n\n<pre><code>a <- matrix(diag(-1, n2), nrow = n2, ncol = n1 * n2)\n</code></pre>\n\n<p>The <code>n2 * n2</code> values inside <code>diag(-1L, n2)</code> will be recycled <code>n1</code> times to fill the final matrix of dimensions <code>n2-by-n1*n2</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:38:09.637",
"Id": "37183",
"ParentId": "37175",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37183",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T21:55:30.787",
"Id": "37175",
"Score": "3",
"Tags": [
"r",
"matrix"
],
"Title": "Simplifying loop for Incidence Matrix"
}
|
37175
|
<p>I write a metric ton of queries for an Oracle environment every day. These are reports that often require multiple separate queries that no end of joins and sub-queries will satisfy, hence lots of separate queries.</p>
<p>I find myself rewriting this bit of code all too often:</p>
<pre><code>try
{
using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings[current_database].ConnectionString))
{
conn.Open();
using (OracleCommand executeQuery = new OracleCommand(sql, conn) { CommandType = CommandType.Text, BindByName = true })
{
executeQuery.Parameters.Add( parameter, OracleDbType.SomeType ).Value = paramter_value
using (OracleDataReader dr = executeQuery.ExecuteReader())
{
while (dr.Read())
{
//iterate results
}
}//end-using-rdr
}//end-using-cmd
}//end-using-con
}
catch (Exception ex)
{
//do stuff
}
</code></pre>
<p>I have dumped this code into a class such that I call the class.method and send the SQL string, the parameters + parameter values, and list of columns I'd like returned with their SQL datatype.</p>
<h3>The method within the class</h3>
<pre><code>public Dictionary<string, Dictionary<string, string>> OracleSelect(string sql, Dictionary<string, string> parameters, List<string> columns)
{
string current_database;
int rowCount = 0;
Dictionary<string, Dictionary<string, string>> result_set = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> result = new Dictionary<string, string>();
current_database = getCurrentDB();
try
{
using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings[current_database].ConnectionString))
{
conn.Open();
using (OracleCommand executeQuery = new OracleCommand(sql, conn) { CommandType = CommandType.Text, BindByName = true })
{
//Iterate through Dictionary to bind parameter name (the dictionary key) and the parameter value (the dictionary value which is typically user input)
foreach (KeyValuePair<string, string> param in parameters)
{
executeQuery.Parameters.Add(":" + param.Key, OracleDbType.Varchar2).Value = param.Value;
}
using (OracleDataReader dr = executeQuery.ExecuteReader())
{
while (dr.Read())
{
foreach (string col in columns)
{
//Accepts values "ColumnName" or "ColumnName:DataType"
//Data type defaults to string if no datatype specified
//Checks for null values instead of having to write queries using nvl(ColumnName,"NullValueReplacement")
//Gets column values and assigns them to column name based off column name which causes extra overhead
string[] split = col.Split(':');
if (split.Length > 1)
{
if (!dr.IsDBNull(dr.GetOrdinal(split[0])))
{
switch (split[1])
{
case "string":
result.Add(split[0], dr.GetString(dr.GetOrdinal(split[0])));
break;
case "date":
result.Add(split[0], dr.GetDateTime(dr.GetOrdinal(split[0])).ToString());
break;
case "int":
result.Add(split[0], dr.GetInt32(dr.GetOrdinal(split[0])).ToString());
break;
default:
result.Add(split[0], dr.GetString(dr.GetOrdinal(split[0])));
break;
}//end-split
}
else
{
result.Add(split[0], "");
}
}
else
{
if (!dr.IsDBNull(dr.GetOrdinal(col)))
{
result.Add(col, dr.GetString(dr.GetOrdinal(col)));
}
else
{
result.Add(col, "");
}
}
}
rowCount = rowCount + 1;
var screwit = new Dictionary<string, string>(result);
result_set.Add(rowCount.ToString(), screwit);
result.Clear();
}
result.Add("count", rowCount.ToString());
result_set.Add("rows", result);
}//end-using-rdr
}//end-using-cmd
}//end-using-con
}
catch (Exception ex)
{
result.Add("result", ex.ToString());
result_set.Add("status", result);
return result_set;
}
return result_set;
}
</code></pre>
<p>With this query setup:</p>
<ul>
<li>I have row numbers appended to the result set</li>
<li>I have the total number of rows</li>
<li>If an error occurs I have a sanity check of "status" to let me know that it error'd out</li>
<li>I can iterate through the results to mold the data as a I see fit rather than dumping them into a preformed output format (this may be a bad idea on my part)</li>
<li>Parameters are bound regardless of how many parameters may have been passed</li>
<li>Null values are always handled</li>
<li>Varying data types are handled on result iteration (at the moment we only deal with the 3 types listed)</li>
</ul>
<h3>Things I'd love to know</h3>
<ol>
<li>What flaws do you see in the approach?</li>
<li>Is there a more flexible data return method than the strict <code>Dictionary<string,Dictionary<string,string></code> that also yields the return results I currently list? I am a PHP developer that recently moved to C#.NET so I still work in the mindset of associative arrays, and manipulating them into HTML. I imagine Microsoft has a mechanism for nullifying the usefulness of my chosen return type.</li>
</ol>
<p>If enough positive comments come in and proper direction I will be adding functionality for MSSQL as I re-use that same basic set of code at the top but specific to that database. I will also be implementing methods for basic CRUD operation. I just don't want to go down that rabbit hole without some constructive criticism and functional insight from the community.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:38:37.493",
"Id": "61294",
"Score": "3",
"body": "Have you considered using an ORM, like Entity Framework?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:13:34.550",
"Id": "61421",
"Score": "0",
"body": "I have, but I am limited in time and knowledge unfortunately :). From what I've experienced ORM's aren't terribly efficient with the large data-sets and some of the obscenely deep queries we do against the database. I would love to know all the facets of Entity Framework, but for now it is faster for me to write the raw sql and feed it into a method for grabbing the data. The current oracle database is sitting at somewhere near 3000 tables that I regularly pull from, not including stored procedures. My limited knowledge of EF and ORM make me think it may not be a good fit yet."
}
] |
[
{
"body": "<p>It's very easy to get started with EF, especially for CRUD operations, Plus, you always have the flexibility of executing native SQL queries to accomplish complicated tasks.</p>\n\n<p>Entity Framework has gobs of hours of optimization effort put into it, it's really quite remarkable in that respect, so I would hesitate to discard the notion based on speculative performance issues.</p>\n\n<p>Despite your time crunch, I would invest a few hours in following a tutorial before trying to write your own. I predict you'll save far more time than you'd lose. For example, EF would abstract for you the concern of handling both Oracle and MSSQL. </p>\n\n<p>It's really the first implementation to try for this class of problem in .NET. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:35:07.763",
"Id": "61456",
"Score": "0",
"body": "I am not discounting EF by any means. Would it be of any consequence that the Oracle will be Read only, while MSSQL will involve full CRUD when setting up EF? I guess I can simply ask the overlords if I can set aside a few hours a week to learn something that may save time in the long run."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:51:10.190",
"Id": "61463",
"Score": "0",
"body": "No, having a read-only database wouldn't change my answer. In my opinion, it's no more work than setting up ADO.NET."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T19:50:11.997",
"Id": "63187",
"Score": "1",
"body": "After much teeth gnashing I have entity framework enabled with the oracle database, using the oracle.net provider. I have managed to mangle together a few simple queries and some of the moderately difficult queries using the Foreign Key setup as well as some explicit joins declared outside of the DB Schema. This is definitely going to cut down on the coding once I learn the LINQ syntax for the insanely complicated queries. I've been meaning to try Entity Framework, but wasn't ready to make the jump. It was certainly a complicated setup, but it should work out great."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:28:09.017",
"Id": "37251",
"ParentId": "37176",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37251",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T22:29:30.760",
"Id": "37176",
"Score": "4",
"Tags": [
"c#",
".net",
"oracle",
"wrapper"
],
"Title": "Creating a reusable C#.NET Oracle Query Builder"
}
|
37176
|
<p>To detect <code>int</code> overflow/underflow in C, I use this code. What might be a simpler and more portable way of coding this (that is, fewer conditions)?</p>
<p>Assume 2's complement and don't use wider integers.</p>
<pre><code>int a,b,sum;
sum = a + b;
// out-of-range only possible when the signs are the same.
if ((a < 0) == (b < 0)) {
if (a < 0) {
// Underflow here means the result is excessively negative.
if (sum > b) UnderflowDetected();
}
else {
if (sum < b) OverflowDetected();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T00:44:09.053",
"Id": "61304",
"Score": "0",
"body": "I think you're misunderstanding underflow ... or am I? Let's say, as an example, the smallest number a `float` can represent is `0.001`. `1.0 / 10000` would result in a value of `0.0` because the actual value is too small."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T01:01:47.753",
"Id": "61305",
"Score": "2",
"body": "@BitFiddlingCodeMonkey this is on integers - there are various wrap-around cases where the result of an addition does not fit in the same size integer. Sometimes it's called underflow when it's the sum of two negative numbers that doesn't fit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:10:06.633",
"Id": "61359",
"Score": "3",
"body": "If you just change from using *int* to using *unsigned int*, or better still, *uint32_t* and *size_t*, you'll be able to do those checks after the operation. For signed *ints*, overflow and underflow can't be detected after-the-fact because of undefined behaviour. And be warned: undefined behaviour can exhibit itself as anything from the program appearing to work properly right through to malware being installed on your machine and being used to steal your credit card information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T15:46:09.257",
"Id": "61397",
"Score": "0",
"body": "@Matt Are you suggesting a method that would detect the out-of-range sum of 2 `int`s by employing `unsigned` conversion? OTOH if you are talking about overflow detection for 2 `unsigned`, that is a different question. `if (sum < a) OverflowDetected();` seems to work for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T15:52:54.873",
"Id": "61398",
"Score": "2",
"body": "@chux: No - I was merely pointing out that the method employed here (i.e. do an add and then see if an overflow occurred) is valid only on unsigned integers. For signed integers it is never valid because overflow of signed integers is inherently undefined in the language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-17T23:09:52.307",
"Id": "170953",
"Score": "2",
"body": "From GCC 5, there are [builtin functions to do this](https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-30T11:42:33.877",
"Id": "180675",
"Score": "0",
"body": "Also see [How to detect integer overflow in C/C++?](http://stackoverflow.com/q/199333) on Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T17:15:46.493",
"Id": "459233",
"Score": "0",
"body": "@o11c Are these builtin functions portable or available in other c compilers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T17:30:25.577",
"Id": "459234",
"Score": "0",
"body": "@abetancort They're in Clang, which is the only competitor that really matters."
}
] |
[
{
"body": "<p>It's not possible to avoid undefined behaviour by testing for it after the fact! If the addition overflows then there is already undefined behaviour here:</p>\n\n<pre><code>sum = a + b;\n</code></pre>\n\n<p>so attempting to test afterwards is too late. You have to test for possible overflow <em>before</em> you do a signed addition. (If you're puzzled by this, read Dietz et al. (2012), \"<a href=\"http://www.cs.utah.edu/~regehr/papers/overflow12.pdf\" rel=\"noreferrer\">Understanding Integer Overflow in C/C++</a>\". Or even you're not puzzled: it's an excellent paper!)</p>\n\n<p>If it were me, I'd do something like this:</p>\n\n<pre><code>#include <limits.h>\n\nint safe_add(int a, int b) {\n if (a > 0 && b > INT_MAX - a) {\n /* handle overflow */\n } else if (a < 0 && b < INT_MIN - a) {\n /* handle underflow */\n }\n return a + b;\n}\n</code></pre>\n\n<p>but I'm not entirely sure what the point of having separate cases for overflow and underflow is.</p>\n\n<p>I also use Clang's <a href=\"http://clang.llvm.org/docs/UsersManual.html#controlling-code-generation\" rel=\"noreferrer\"><code>-fsanitize=undefined</code></a> when building for test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:17:36.140",
"Id": "61288",
"Score": "0",
"body": "Quite a lengthy paper, yet you make it seem so simple here. :-) What are `INT_MAX` and `INT_MIN` equal to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:20:18.620",
"Id": "61289",
"Score": "1",
"body": "§5.2.4.2.1 in the [C99 standard](http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf) defines `INT_MIN` to be the \"minimum value for an object of type `int`\" and `INT_MAX` to be the \"maximum value for an object of type `int`\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:22:50.723",
"Id": "61290",
"Score": "0",
"body": "Ah, I see. And those macros come from `<limits.h>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:28:44.277",
"Id": "61292",
"Score": "0",
"body": "Okay. I assume the same thing is done in C++, but with `<climits>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T00:16:00.627",
"Id": "61300",
"Score": "0",
"body": "I had thought that `int` overflow was unspecified behavior or implementation-defined behavior. Thus with 2's complement, a code path was available. Although at assembly level, my approach may work, I do see the C11dr §3.4.2 explicit \"An example of undefined behavior is the behavior on integer overflow\" that you suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T00:16:51.103",
"Id": "61301",
"Score": "1",
"body": "@Jamal Actually, with `<limits>`. `std::numeric_limits<int>::min()` and `std::numeric_limits<int>::max()` to be precise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T00:24:53.237",
"Id": "61303",
"Score": "0",
"body": "A small simplification: `if (a >= 0) { if (b > INT_MAX - a) Over(); } else { if (b < INT_MIN - a) Under(); }`.\n`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:02:50.750",
"Id": "61358",
"Score": "2",
"body": "It's worth pointing out that integer overflow and underflow are undefined only for SIGNED types. For unsigned integers, overflow safely occurs as modulo arithmetic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T13:31:36.857",
"Id": "61643",
"Score": "0",
"body": "why not `if ((a + b) <= INT_MAX)` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T13:36:15.080",
"Id": "61644",
"Score": "2",
"body": "@Max: That would have undefined behaviour if `a + b` overflowed, and undefined behaviour is what we are trying to avoid! (But also, even if `a + b` were defined, your expression could not work, because `a + b` is an `int`, and all values of `int` are less than or equal to `INT_MAX`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-15T15:59:25.893",
"Id": "321655",
"Score": "1",
"body": "There is a use for separate cases in doing saturating arithmetic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:34:06.840",
"Id": "418326",
"Score": "0",
"body": "Reading the paper is worth it. It showcases open source libraries, explores shifts as an option to detect overflow, and calls out more sites than I could have imagined of Integer overflow in \"the wild\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T18:17:38.810",
"Id": "515744",
"Score": "0",
"body": "@GarethRees: `-(2**31)` and `(2**31)-1`, not `2**32`."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T22:56:57.900",
"Id": "37178",
"ParentId": "37177",
"Score": "45"
}
},
{
"body": "<p>Why not use a long to hold the result of the calculation? Then the long can be checked against the (int) MAX and MIN values to see if overflow or underflow occurred? If no violations have occurred, then the result can safely be re-cast back to an (int).</p>\n\n<p>Or, is this too simple and I'm missing something very fundamental? One thing that I HAVE omitted is the possibility that the long will also overflow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T17:18:58.917",
"Id": "99034",
"Score": "4",
"body": "As type `long` is only guaranteed to be _at least_ the range of `int`, converting to `long` may not provide any additional range. Thus the problem is fundamentally the same for `long` as for `int`. Same situation for `long long`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T05:29:44.833",
"Id": "418198",
"Score": "0",
"body": "While it's is technically true that `long long` is only guaranteed to be at least as long as `int`, I'm not aware of any platform that actually implements `long long` using the same number of bytes as `int`. So in practice, this solution just works, plus it's much simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T12:18:17.623",
"Id": "462194",
"Score": "0",
"body": "@SamuelLi Just because it works doesn't mean it's portable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T15:53:59.723",
"Id": "462381",
"Score": "0",
"body": "@S.S.Anne While your statement is true, but since there are only a handful of platforms there and none is emerging in the near future, I'd say this is a portable solution for available platforms today and many years to come."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:14:15.200",
"Id": "462384",
"Score": "1",
"body": "@SamuelLi The ILP64 ABI of x86_64 has a 64-bit `int`, `long`, and `long long`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T02:14:09.673",
"Id": "462564",
"Score": "0",
"body": "@S.S.Anne That's an interesting interface I'm not aware of. Thanks for pointing it out. It will cause portability issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-25T02:25:29.500",
"Id": "462565",
"Score": "0",
"body": "@Samuel Although that specific ABI is not widely-used... I can't remember where I saw the last system that used it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T15:51:50.543",
"Id": "56273",
"ParentId": "37177",
"Score": "-3"
}
},
{
"body": "<blockquote>\n <p>Simpler method to detect int overflow...</p>\n</blockquote>\n\n<p>The two simplest methods I know are:</p>\n\n<ul>\n<li>Use the <a href=\"https://safeint.codeplex.com/\" rel=\"nofollow noreferrer\">SafeInt</a> library in C++</li>\n<li>Use the <a href=\"https://android.googlesource.com/platform/external/safe-iop/\" rel=\"nofollow noreferrer\">safe_iop</a> library in C</li>\n</ul>\n\n<p><code>SafeInt</code> was written by David LeBlanc, and Microsoft uses it. <code>safe_iop</code> was written by ???, and Android uses it.</p>\n\n<hr>\n\n<p>The next simplest method is to use a compiler intrinsic. Unfortunately, I have not seen many of them. I believe I saw some for GCC recently.</p>\n\n<p>The neat thing about intrinsics are (1) they provide a familiar C function call and (2) they are not bound by the Undefined Behavior you are trying to avoid. That means an instrinsic <strong><em>can</em></strong> perform the addition and the program will still be well defined, even it it overflows.</p>\n\n<p>(In C/C++, if you perform the addition and it overflows, then the program is illegal. You are not allowed to perform the operation and then check the result).</p>\n\n<hr>\n\n<p>The next simplest method is assembly and inline assembly. Again, its not bound by the Undefined Behavior you are trying to avoid in C/C++.</p>\n\n<p>Assembly and inline assembly routines are the method I use. I work on mobile platforms and I have a library for i686, x86_64, ARM and MIPS.</p>\n\n<p>I learned a long time ago its a pain in the butt to try and do this cross-platform in a well defined, portable and efficient manner from C, especially for some operations.</p>\n\n<p>I was constantly checking results of compilations and starring at disassembled code to make sure the code generation was good. So I abandoned portable in the name of simplicity and efficiency.</p>\n\n<hr>\n\n<p>Also see <a href=\"https://stackoverflow.com/q/199333\">How to detect integer overflow in C/C++?</a> on Stack Overflow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T10:17:21.367",
"Id": "489794",
"Score": "0",
"body": "As of late 2018 there's a Boost library very similar to SafeInt: https://www.boost.org/doc/libs/1_74_0/libs/safe_numerics/doc/html/tutorial/8.html"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2015-07-30T11:57:33.887",
"Id": "98578",
"ParentId": "37177",
"Score": "7"
}
},
{
"body": "<p>Overflow and underflow can happen in two cases : either </p>\n\n<ol>\n<li>Both negative numbers and sum becomes positive or </li>\n<li>Both positive numbers and sum becomes negative.</li>\n</ol>\n\n<p>Then you can use this logical expression:</p>\n\n<pre><code> ((a<0)&&(b<0)&&(a+b>0)) || ((a>0)&&(b>0)&&(a+b<0))\n</code></pre>\n\n<p>or if you prefer integer arithmetics to logical expressions:</p>\n\n<pre><code> (a<0)*(b<0)*(a+b>0) + (a>0)*(b>0)*(a+b<0)\n</code></pre>\n\n<p>In two complements one can be pedantic and just pick out the sign bit to do operations on, or even in hardware.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-19T10:04:35.010",
"Id": "333882",
"Score": "2",
"body": "That's not exactly *portable*, given that you're invoking Undefined Behaviour and then attempting a test for it afterwards. This solution fails in systems with saturating arithmetic, for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-19T10:29:46.117",
"Id": "333887",
"Score": "0",
"body": "@TobySpeight : Yes you are right. I guess I haven't worked enough with those saturating arithmetics to think about it automatically. We can do some constant compile time tests from the start to determine that and use macros to decide if to compile our code or the saturated code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-23T11:42:53.737",
"Id": "147872",
"ParentId": "37177",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "37178",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-12-11T22:45:52.610",
"Id": "37177",
"Score": "26",
"Tags": [
"c",
"integer"
],
"Title": "Simple method to detect int overflow"
}
|
37177
|
<p>I've got a homework that is about methods. So first part is </p>
<blockquote>
<p>Write a method that prompts the customer for the car type. There are
three acceptable car types (E: Economy, M: Midsize, F: Fullsize). Your
method will return a valid car type.</p>
</blockquote>
<p>But the thing that I don't understand is, should I read input from the user first and then make the method give a valid car type, or should method also read from user? </p>
<pre><code>char type;
System.out.println("(E) Economy - 50 TL");
System.out.println("(M) Midsize - 70 TL");
System.out.println("(F) Fullsize - 100 TL");
do{
System.out.println("Enter the car type (E/M/F) : ");
type = input.next().charAt(0);
type = Character.toUpperCase(type);
} while (type != 'E' && type != 'M' && type != 'F' );
carType(type);
</code></pre>
<p>and;</p>
<pre><code>public static String carType(char y){
String x ="";
if(y == 'E')
x = "Economy";
if(y == 'M')
x = "Midsize";
if(y == 'F')
x = "Full size";
return x;
</code></pre>
<p>Do you think this is the right way to do it? Because it says "Write a method that prompts the user..." but what's the point of using method if I move all of the code above into method?</p>
|
[] |
[
{
"body": "<p>From the way you describe the problem, it is clear that there only needs to be one method. That method is supposed to: \"... prompts the customer for the car type. ... Your method will return a valid car type\".</p>\n\n<p>What you have presented here, is the guts of some code which prompts the user for a character value, and then another method which converts the <code>char</code> to a <code>String</code> type.</p>\n\n<p>From what I can tell (and filling in some blanks) your code looks functional, but I am not certain it satisfies the requirements (for just one method).</p>\n\n<p>I would start with the 'specification' for the method, and use that as a template for the code. I will make the assumption (as you have) that the method should return the 'full' name of the car type (i.e. return \"Economy\" instead of 'E').</p>\n\n<p>The good things in your code are the use of the <code>do {...} while(...)</code> block. You have a good loop there, with good conditional exit criteria.</p>\n\n<p>You have not shown us what <code>input</code> is so I will assume it is a <code>Scanner</code> on <code>System.in</code>.</p>\n\n<p>If we wrap the code you have there with a method that makes sense, it would be something like:</p>\n\n<pre><code>public String promptForCarType(Scanner input) {\n .....\n return carType;\n}\n</code></pre>\n\n<p>That would be a method that prompts the user for a car type, and returns the user's selection.</p>\n\n<p>The code inside that is what you have written above. There are a few things you should consider though:</p>\n\n<ul>\n<li>You should probably get the full input from the user (not just the first character), and make sure the user only entered a single character (data validation).</li>\n<li>Do you know what a 'switch' statement is? It would be really neat in here (and would remove the need to call the <code>carType(char)</code> method).</li>\n<li>When you have java methods that return a value, there is often no need to 'store' the return value to the end of the method... you can just return when you have it....</li>\n<li>when dealing with user input, you should try to leave them an 'exit strategy', like \"enter <code>Q</code> to quit\"</li>\n<li>if you do an early-return mechanism, there is no need to do any conditions in the loop, you can just do <code>while (true) {...}</code></li>\n</ul>\n\n<p>One possible method for you may be something like:</p>\n\n<pre><code>public String promptForCarType(Scanner input) {\n System.out.println(\"(E) Economy - 50 TL\");\n System.out.println(\"(M) Midsize - 70 TL\");\n System.out.println(\"(F) Fullsize - 100 TL\");\n // add in a Q option here ....\n // the Scanner may not have input....\n while (true) { // convert to while loop.\n System.out.println(\"Enter the car type (E/M/F) : \");\n if (!input.hasNext()) {\n throw SomeExceptionToSayTheresNoMoreInput(....);\n }\n String userinput = input.next();\n // check that input is just one character long.....\n char type = userinput.charAt(0);\n type = Character.toUpperCase(type);\n switch (type) {\n case 'E' : return \"Economy\";\n ..... // other cases\n case 'Q' : throw new UserWantsToQuitException(\".....\");\n default : // no need for a default, the loop will just go around again\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:34:18.310",
"Id": "61293",
"Score": "0",
"body": "I didn't know that I can use a user input as a parameter and I guess that's the way teacher wanted me to use. Thanks so much, your answer helped me a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:52:16.590",
"Id": "61298",
"Score": "0",
"body": "But I have no idea how to throw exceptions.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T04:59:52.193",
"Id": "61319",
"Score": "0",
"body": "All great advice, and I would go ahead with separating the steps into methods. If the teacher insists on using only one method, \"write a method\" is not strong enough. Writing three methods involves writing a method . . . and then writing two more. ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:23:43.790",
"Id": "37182",
"ParentId": "37179",
"Score": "3"
}
},
{
"body": "<p>An <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow\">enum</a> would be naturally suited to this situation. Since this is a homework problem, I have omitted parts of the solution.</p>\n\n<pre><code>enum CarType {\n Economy (50),\n Midsize (70),\n Fullsize (100);\n\n private final char init;\n private final int tl;\n private static final String MENU;\n\n static {\n StringBuilder sb = new StringBuilder();\n // …\n MENU = sb.toString();\n }\n\n CarType(int tl) {\n // …\n }\n\n public String toString() {\n return String.format(\"(%c) %-8s - %d TL\", init, name(), tl);\n }\n\n public static String menu() {\n return MENU;\n }\n\n public static CarType parse(String s) {\n char init = Character.toUpperCase(s.charAt(0));\n for (CarType ct : values()) {\n // …\n }\n return null;\n }\n}\n</code></pre>\n\n<p>If you ever need to add another car type in the future, it's trivial to define an additional enum member.</p>\n\n<p>Since the car types are all defined in the <code>enum</code>, prompting can be done elegantly:</p>\n\n<pre><code>CarType ct;\ndo {\n System.out.print(CarType.menu());\n ct = CarType.parse(input.next());\n} while (null == ct);\nSystem.out.println(\"You picked \" + ct);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T00:27:17.930",
"Id": "37186",
"ParentId": "37179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37182",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T22:57:29.323",
"Id": "37179",
"Score": "1",
"Tags": [
"java",
"homework"
],
"Title": "Which way should I use while writing this method?"
}
|
37179
|
<p>I have been working on this code for quite a while and just want to make sure it is up to good standards. I know many of you will have questions, so as they come up, I will edit my initial question to provide you answers. So any ways to make this code more concise would be great. Be gentle on me, I am only a beginner.</p>
<p>(If you are curious about this projects requirements or the source file I have inputted, if anyone knows how, I can perhaps maybe post a download link to the code or the assignment, let me know if you're interested!)</p>
<pre><code>#!/usr/bin/perl -w
# Final project
use strict;
use warnings;
use diagnostics;
#opens txt file: read mode
open MYFILE, '<', 'source_file.txt' or die $!;
#opens output txt file: write mode
open OUT, '>', 'Summary_Report.txt' or die $!;
#open output txt file: write mode
#used to store header 'split' info
open OUTFILE, '>', 'Header.txt' or die $!;
my $i = 0;
$| = 1; #disable output buffering
my $start_time = undef; #undefined to avoid recycling through other time stamps
my $end_time;
my $user = 0;
my $pass = 0;
my $packet_size = 0; #goes with length#
my @header;
my @source_ip;
my @source_port;
my $src_port;
my @src_port;
my @dest_ip;
my @dest_port;
my $destination_port;
my @destination_port;
while (<MYFILE>) { #loops through every line in file
chomp; #break new line
#separate pieces of information from TCPDUMP into list
@header = split (/\s+/, $_);
print OUTFILE "$.: @header\n\n";
if (/^\d+:\d+/) {
##############################T I M E###################################
#defining first 'line & time' as 'special'
if (/^22:28/ && !defined($start_time)) {
$start_time = $header[0];
#print "$start_time\n"; ###used as a check###
}
#Used recycling of time stamps to find last one available
if (/22:28/) {
$end_time = $header[0];
}
############################S O U R C E##################################
#categorizing each section of ip's from source
@source_ip = split ('\.', $header[2]);
#adding ip's together, joining in concatenation by '.'
$source_ip[$i] = $source_ip[0] . '.' . $source_ip[1] . '.' . $source_ip[2] . '.' . $source_ip[3];
#print $source_ip[$i]; (check)
@source_port = split (':', $source_ip[4]);
$src_port[$i] = $source_port[0];
#########################D E S T I N A T I O N###########################
#categorizing each section of ip's from destination
@dest_ip = split ('\.', $header[4]);
#adding ip's together, joining in concatenation by '.'
$dest_ip[$i] = $dest_ip[0] . '.' . $dest_ip[1] . '.' . $dest_ip[2] . '.' . $dest_ip[3];
#print $dest_ip[$i]; (check)
@dest_port = split (':', $dest_ip[4]);
$destination_port[$i] = $dest_port[0];
#############################L E N G T H#################################
#-1 represents length
#transferring $header[-1] into new variable for ease of use
$packet_size = $packet_size + $header[-1];
#print $packet_size; (check)
$i++;
}
}
############################INTERESTING TEXT#############################
my @total_timesplit;
my @s_timesplit = split (':', $start_time);
#print @start_split; check
my @e_timesplit = split (':', $end_time);
#print @end_split; check
$total_timesplit[0] = $e_timesplit[0] - $s_timesplit[0];
$total_timesplit[1] = $e_timesplit[1] - $s_timesplit[1];
$total_timesplit[2] = $e_timesplit[2] - $s_timesplit[2];
#print @total_split; check
#yields average packet size
my $avg_length = $packet_size/$i;
#print $mean; check
##############################SOURCEIP###################################
my %ip_source;
my @ip_source;
%ip_source = map {$_, 1} @ip_source;
my @distinct_src_ip;
@distinct_src_ip = keys %ip_source;
my $sourceip_amt;
$sourceip_amt = @distinct_src_ip;
#print $sourceipnum;
#############################SOURCEPORT##################################
my %port_source;
my @port_source;
%port_source = map {$_, 1} @port_source;
my @distinct_src_port;
@distinct_src_port = keys %port_source;
my $srcport_amt;
$srcport_amt = @distinct_src_port;
#print $srcportnum;
#############################DESTINATIONIP###############################
my %ip_dest;
my @ip_dest;
%ip_dest = map {$_, 1} @ip_dest;
my @distinct_dest_ip;
@distinct_dest_ip = keys %ip_dest;
my $destip_amt;
$destip_amt = @distinct_dest_ip;
#print $destipnum;
#############################DESTINATIONPORT#############################
my %port_dest;
my @port_dest;
%port_dest = map {$_, 1} @port_dest;
my @distinct_dest_port;
@distinct_dest_port = keys %port_dest;
my $destport_amt;
$destport_amt = @distinct_dest_port;
#print $destportnum;
close MYFILE;
#########################D A T A S E C T I O N###########################
open MYFILE, '<', 'source_file.txt' or die $!;
#I am separating loop to reset values#
while (<MYFILE>) {
#finds all instances of USER
$user++ if /USER/ig;
#print "user" (use as check)
#finds all instances of PASS
$pass++ if /PASS/ig;
#print "pass" (use as check)
}
#Output summary to new file: overwrite file
print OUT "SUMMARY REPORT:\n\n";
print OUT "# of total lines in the file = $.\n\n\n";
print OUT "Range of time the file encompasses:\n\n
Starting Time = $start_time\n\n
Ending Time = $end_time\n\n
Total Time = @total_timesplit\n\n\n";
print OUT "Total # of distinct SOURCE ip addresses = \n\n\n";
print OUT "Total # of distinct DESTINATION ip addresses = \n\n\n";
print OUT "Listing of distinct SOURCE ip addresses = \n\n\n";
print OUT "Listing of distinct DESTINATION ip addresses = \n\n\n";
print OUT "Total # of distinct SOURCE TCP ports = \n\n\n";
print OUT "Total # of distinct DESTINATION TCP ports = \n\n\n";
print OUT "Listing of distinct SOURCE TCP ports = \n\n\n";
print OUT "Listing of distinct DESTINATION TCP ports = \n\n\n";
print OUT "Total # of times phrases were used:\n\n
USER (variations thereof) = $user\n\n
PASS (variations thereof) = $pass\n\n\n";
print OUT "DETAIL SECTION:\n\n\n";
print OUT "SOURCE IP address activity by port over time:\n\n
Mean packet size for above = \n\n
Median packet size for above = \n\n\n";
print OUT "Detail IP address activity by port over time:\n\n
Mean packet size for above = \n\n
Median packet size for above = \n\n\n";
print OUT "Any and all interesting text w/in the DATA section of the file:\n\n
Packet total = $packet_size\n\n
Number of header lines = $i\n\n
Average packet size = $avg_length\n\n";
close OUT; #[ ]
close OUTFILE; #[close remaining files ]
close MYFILE; #[ ]
my $j = 0;
if ($j == 0) {
sleep (1); #dramatic pause!
print "\n\n File has successfully run. Please open your Local Disk C: folder to reveal\n
'Summary_Report' file\n\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:12:23.417",
"Id": "61284",
"Score": "0",
"body": "Not a question, but I'd appreciate it if you could put the code's intent as the title. That would help us and help you attract more reviewers."
}
] |
[
{
"body": "<p>This got a bit longer than expected.</p>\n\n<ul>\n<li><p>Don't use <code>-w</code> in the shebang line. it serves no purpose if you already <code>use warnings</code>.</p></li>\n<li><p>Instead of doing error handling for <code>open</code> etc. yourself, you should <code>use autodie</code>. This is a Core module since perl 5.10.1.</p></li>\n<li><p>Don't create “bareword filehandles”, because those are actually global variables. Instead: <code>open my $out, '>', 'some_file'</code>. Now <code>$out</code> would be the filehandle which you can print to as you're used to: <code>print $out \"stuff\"</code> or better: <code>print { $out } \"stuff\"</code>.</p></li>\n<li><p><code>$| = 1</code> disables buffering for the currently selected filehandle (by default, <code>STDOUT</code>). Only do this if you need to, as it degrades performance. Also, you should restrict this to the tightest scope neccessary, e.g. <code>if ($foo) { local $| = 1; print \"stuff\" }</code>. But as you have commented out all your debug statements, there is no need for unbuffered output anyway.</p></li>\n<li><p>Don't declare all your variables up front – declare them in the tightest scope possible. For example <code>@header</code> can be declared <em>inside</em> the loop.</p></li>\n<li><p><code>split /\\s+/, $_</code> is almost equivalent to the default behavior of <code>split</code> (which skips over leading whitespace). You probably want to use that instead: <code>my @header = split;</code>.</p></li>\n<li><p>Instead of <code>while (...) { ... if ($cond) { STUFF }}</code>, write:</p>\n\n<pre><code>while (...) {\n ...\n next if not $cond;\n STUFF;\n}\n</code></pre>\n\n<p>this avoids an unnecessary level of indentation.</p></li>\n<li><p><code>if (/^22:28/ && !defined($start_time)) { A } if (/22:28/) { B }</code> – are you sure the second regex shouldn't be anchored at the beginning as well? In that case, the code could be simplified to:</p>\n\n<pre><code>if (/^22:28/) {\n if (not defined $start_time) {\n A;\n }\n B;\n}\n</code></pre></li>\n<li><p>This line</p>\n\n<pre><code>$source_ip[$i] = $source_ip[0] . '.' . $source_ip[1] . '.' . $source_ip[2] . '.' . $source_ip[3]\n</code></pre>\n\n<p>would be better written as <code>$source_ip[$i] = join '.', @source_ip[0 .. 3]</code>. This uses an <em>array slice</em> and the <code>join</code> builtin.</p></li>\n<li><p>I am not sure about this piece of code:</p>\n\n<pre><code>$source_ip[$i] = $source_ip[0] . '.' . $source_ip[1] . '.' . $source_ip[2] . '.' . $source_ip[3];\n\n@source_port = split (':', $source_ip[4]);\n</code></pre>\n\n<p>You write into the <code>$i</code>-entry of <code>@source_ip</code>, and <code>$i</code> starts with zero. This means that <code>$source_ip[4]</code> is likely <code>undef</code>, and should emit some warning. Are you sure you didn't mean <code>$source_ip[4] = ...;</code>? But why don't you use another scalar variable for that? <code>my $ip_string = ...</code>. Actually, we don't need any extra variable here, and could just write:</p>\n\n<pre><code>@source_port = split /:/, join '.', @source_ip[0 .. 3];\n</code></pre></li>\n<li><p>I am not sure what that line intends to do, I guess you are trying to remove the port part of an IP address? A regex would do a better job than <code>split</code>ting and concatenating strings in order to parse the input.</p></li>\n<li><p><code>$packet_size = $packet_size + $header[-1]</code> would usually be written as:</p>\n\n<pre><code>$packet_size += $header[-1];\n</code></pre></li>\n<li><p>“Three or more, use a <code>for</code>”:</p>\n\n<pre><code>for my $i (0 .. 2) {\n $total_timesplit[$i] = $e_timesplit[$i] - $s_timesplit[$i];\n}\n</code></pre></li>\n<li><p>This is weird:</p>\n\n<pre><code>my %ip_source;\nmy @ip_source;\n%ip_source = map {$_, 1} @ip_source;\n</code></pre>\n\n<p>Because <code>@ip_source</code> was just declared, it is empty. Thus <code>%ip_source</code> does not contain <em>any</em> keys. You can basically remove that code, as it does nothing.</p></li>\n<li><p>To find unique elements in an array, you can use the trick with the hash. Instead of writing that code yourself every time, you can <code>use List::Util qw< uniq ></code>, and then find the unique elements like</p>\n\n<pre><code>my @unique_items = uniq @items_with duplicates;\n</code></pre></li>\n<li><p><code>… if /USER/ig</code> – please do not use the <code>/g</code> flag in scalar context, as that generally turns the match into an iterator over the current string – but not in this special case, for more complex reasons (which I can explain if you're really interested). But most of the time, this is a bug.</p></li>\n<li><p>Instead of multiple <code>print</code>s, of double-quoted strings,</p>\n\n<pre><code>print OUT \"SUMMARY REPORT:\\n\\n\";\n\nprint OUT \"# of total lines in the file = $.\\n\\n\\n\";\n</code></pre>\n\n<p>you could just use a here-doc:</p>\n\n<pre><code>print { $out } <<\"END\";\nSUMMARY REPORT:\n\n\n# of total lines in the file = $.\n\n\nRange of time the file encompasses:\n\n\n Starting Time = $start_time\n\n\n Ending Time = $end_time\n\n\n Total Time = @total_timesplit\n\n\n\n...\nEND\n</code></pre>\n\n<p>(but are you really sure that all those newlines in between actually make the output easier to read?)</p>\n\n<p>A heredoc is introduced with <code><<TERMINATOR</code> where <code>TERMINATOR</code> is either a double-quoted <code>\"string\"</code> (in which case the here-doc behaves like a double quoted string), or a single-quoted <code>'string'</code>. The terminator must occur on a line of its own. Heredocs cannot be indented. They are better than ordinary strings if you have a multi-line template (as is the case here).</p></li>\n<li><p>You might as well remove that condition, as it is always true:</p>\n\n<pre><code>my $j = 0;\nif ($j == 0) { ... }\n</code></pre></li>\n<li><p>I do not think that code like <code>sleep (1); #dramatic pause!</code> makes for a good user experience. </p></li>\n<li><p>If you find yourself writing the same code again and again (or worse: copy&pasting some code), then you will likely want to write a subroutine. See the introduction in the <a href=\"http://modernperlbooks.com/books/modern_perl/chapter_05.html\" rel=\"nofollow\">Modern Perl Book</a> or in the <a href=\"http://perldoc.perl.org/perlsub.html\" rel=\"nofollow\">official docs</a> to learn how to write your own subroutines.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:27:32.387",
"Id": "61515",
"Score": "0",
"body": "wow thats a lot thank you! But as you can see, I need some help with the hashes. Do you kind of see what I am trying to do with them at all?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T00:03:00.557",
"Id": "37184",
"ParentId": "37180",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37184",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T23:03:07.917",
"Id": "37180",
"Score": "1",
"Tags": [
"array",
"beginner",
"regex",
"perl"
],
"Title": "TCPDUMP file (part of a real capture)"
}
|
37180
|
<pre><code>//rename files
if(!empty($_FILES[$desktop_fieldname_1280x800]['name'])){
file_exists($desktop_filename_1280x800 = mb_strtolower($desktop_dir_1280x800 . 'wall_desktop_1280x800_' .
$_FILES[$desktop_fieldname_1280x800]['name']));
}
if(!empty($_FILES[$desktop_fieldname_1366x768]['name'])){
file_exists($desktop_filename_1366x768 = mb_strtolower($desktop_dir_1366x768 . 'wall_desktop_1366x768_' .
$_FILES[$desktop_fieldname_1366x768]['name']));
}
if(!empty($_FILES[$desktop_fieldname_1920x1080]['name'])){
file_exists($desktop_filename_1920x1080 = mb_strtolower($desktop_dir_1920x1080 . 'wall_desktop_1920x1080_' .
$_FILES[$desktop_fieldname_1920x1080]['name']));
}
</code></pre>
<p>With the above code, basically what I'm doing is renaming the files properly + consistently. What my code seems to be bit redundant to me, I think this can be done with some kind of loop or arrays, but I'm a newbie and not sure how it will be. So would like to ask your help to make this code more memory efficient, or shorten the code in some way.</p>
|
[] |
[
{
"body": "<p>The code does not rename any files, it modifies the values of certain variables.</p>\n\n<p>Using assignments as a parameter to your functions is confusing.</p>\n\n<p>You call <code>file_exists</code> but do nothing with it. It is supposed to be used to check for the existence of a file. Something like:</p>\n\n<pre><code>if (!file_exists($destination))\n{\n rename($source, $destination);\n}\n</code></pre>\n\n<p>To answer more you would need to show how the desktop_dir_xxx variables are calculated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T02:31:24.947",
"Id": "37194",
"ParentId": "37188",
"Score": "2"
}
},
{
"body": "<p>Firstly you're certainly <em>not</em> doing any file-renames in that code. As Paul mentions you call <code>file_exists</code> but that function only computes a value (which you ignore). It has no side-effects (other than the assignment in the parameter to <code>file_exists</code>, which as Paul also mentions, is bad design), and hence your code is just an elaborate variable assignment, like this:</p>\n\n<pre><code> if(!empty($_FILES[$desktop_fieldname_1280x800]['name'])){\n $desktop_filename_1280x800 = mb_strtolower($desktop_dir_1280x800 . 'wall_desktop_1280x800_' .\n $_FILES[$desktop_fieldname_1280x800]['name']);\n }\n</code></pre>\n\n<p>Secondly, your code <em>can</em> be made significantly more readable with a loop, or perhaps a function. Your code all seems to be of the form:</p>\n\n<pre><code> if(!empty($_FILES[SOMEVARIABLE]['name'])){\n SOMEVARIABLE = mb_strtolower($desktop_dir_1280x800 . 'wall_desktop_1280x800_' .\n $_FILES[SOMEVARIABLE]['name']);\n }\n</code></pre>\n\n<p>And you can of course factor that out into a function where SOMEVARIABLE is a <em>parameter</em> to the method.</p>\n\n<p>Finally, you're talking about making your code more memory/CPU efficient. It is <strong><em>always always always</em></strong> better to think about making your program more <strong><em>efficient to read</em></strong> than making it more <strong><em>efficient to run</em></strong>. </p>\n\n<p>The reason for this is slightly non-intuitive for new programmers, but basically it comes down to the fact that <em>programming</em> is an easy part of a programmer's job. It is <em>much</em> harder to <strong><em>debug</em></strong> and <strong><em>maintain</em></strong> sloppily written code - and any steps that you take now to make your code more readable - even at the expense of actual efficiency - will pay of many-fold later - and it's a good habit to get into early in your programming career.</p>\n\n<p>For this reason, unless there is a specific pressing concern about efficiency (i.e. your program is running unacceptably slow), spend your spare time making your code more readable, and leave CPU and memory efficient optimizations for later - and then only after you've specifically benchmarked to discover the performance problem in your design.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T11:57:32.830",
"Id": "37214",
"ParentId": "37188",
"Score": "2"
}
},
{
"body": "<p>I don't really understand how you got to that code... Doesn't make too much sense to me. </p>\n\n<p>As a principle, you can put that in a loop in the following way:</p>\n\n<pre><code>$sizes = array('1280x800','1366x768','1920x1080');\nforeach($sizes as $size) {\n $var = 'desktop_fieldname_'.$size;\n if(!empty($_FILES[$$var]['name'])){\n //[...]\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:34:38.653",
"Id": "37228",
"ParentId": "37188",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T01:13:32.993",
"Id": "37188",
"Score": "2",
"Tags": [
"php",
"array"
],
"Title": "Make code more memory efficient, or shorter"
}
|
37188
|
<p>According to Donald Knuth in <em>"The Art Of Computer Programming"</em>, the following is how to find the greatest common divisor of two positive numbers, <em>m</em> and <em>n</em>, using Euclid's Algorithm.</p>
<blockquote>
<ol>
<li>Divide <em>m</em> by <em>n</em> and let <em>r</em> be the remainder.</li>
<li>If <em>r</em> is 0, <em>n</em> is the answer; if <em>r</em> is not 0, continue to step 3.</li>
<li>Set <em>m</em> = <em>n</em> and <em>n</em> = <em>r</em>. Go back to step 1.</li>
</ol>
</blockquote>
<p>Below is my implementation of this algorithm.</p>
<pre><code>#include <stdio.h>
int greatestCommonDivisor(int m, int n)
{
int r;
/* Check For Proper Input */
if((m == 0) || (n == 0))
return 0;
else if((m < 0) || (n < 0))
return -1;
do
{
r = m % n;
if(r == 0)
break;
m = n;
n = r;
}
while(true);
return n;
}
int main(void)
{
int num1 = 600, num2 = 120;
int gcd = greatestCommonDivisor(num1, num2);
printf("The GCD of %d and %d is %d\n", num1, num2, gcd);
getchar();
return 0;
}
</code></pre>
<p>Though it appears to work just fine, it doesn't seem to be as elegant as I'd like, especially in the <code>do-while</code> loop. Also, the <code>while(true)</code> seems dangerous, though I'm pretty confident that <code>r</code> will be reduced to <code>0</code> eventually and we'll <code>break</code> out of the loop.</p>
<p>Do you have any suggestions on either making the code more elegant or robust?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T04:41:13.113",
"Id": "61318",
"Score": "8",
"body": "Well if `r` is never 0 and the loop never exits, blame Euclid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:25:53.513",
"Id": "61334",
"Score": "1",
"body": "all integers are divisible by 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T10:36:01.353",
"Id": "79335",
"Score": "0",
"body": "1. Implement Euclidean algorithm to find gcd of any N numbers.[ gcd(a,b), gcd(a,b,c), gcd(a,b,c,d) etc.]"
}
] |
[
{
"body": "<p>Firstly, your implementation is (arguably) not quite correct:</p>\n\n<pre><code> else if((m < 0) || (n < 0))\n return -1;\n</code></pre>\n\n<p>The GCD of two negative numbers is perfectly well defined. However, if you really don't want the user to pass in negative numbers, make it explicit in the function signature:</p>\n\n<pre><code>unsigned greatestCommonDivisor(unsigned m, unsigned n)\n</code></pre>\n\n<p>Euclid's algorithm is one of the most basic examples of where recursion shines:</p>\n\n<pre><code>unsigned greatestCommonDivisor(unsigned m, unsigned n)\n{\n if(n == 0) return m;\n return greatestCommonDivisor(n, m % n);\n}\n</code></pre>\n\n<p>We first check the base case, which is 2: <em>If r is 0, n is the answer; if r is not 0, continue to step 3.</em> The recursive call actually combines steps 1 and 3 here: <code>m % n</code> sets n to be the remainder <code>r</code>, and we call the function again with <code>n = m</code>.</p>\n\n<p>As a final note, a lot of people avoid recursive functions in C/C++ because most compilers don't optimise tail-calls to use constant stack space. However, Euclid's algorithm will perform only <code>O(log N)</code> steps, hence it's easy to see on any computer with (reasonable) stack size, this won't cause a stack overflow for numbers whose size is constrained by <code>int</code> or <code>unsigned</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T02:13:30.670",
"Id": "61309",
"Score": "0",
"body": "Donald Knuth says that the algorithm I mentioned in my question is for positive numbers. Is there another, or expanded, algorithm for both positive and negative numbers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T02:51:04.300",
"Id": "61311",
"Score": "0",
"body": "Disagreed on using `unsigned` parameters for the scenario described. For the given code, I would consider just taking the absolute values inside the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T03:29:33.773",
"Id": "61313",
"Score": "0",
"body": "@MichaelUrman Sure, that's probably the better idea in this case. Using unsigned was more a way of showing the idea of being explicit in what parameters are actually allowed for the function as-is. I agree though, using abs would be the better solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:36:16.630",
"Id": "61336",
"Score": "0",
"body": "If I passed `42, 0` your implementation would retrun `42`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:40:35.297",
"Id": "61338",
"Score": "2",
"body": "@Jodrell Yes? 0 is divisible by any number, hence gcd(a, 0) = a for all a. If you [really](http://math.stackexchange.com/questions/27719/what-is-gcd0-a-where-a-is-a-positive-integer) want to get into the math of it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:50:06.160",
"Id": "61342",
"Score": "0",
"body": "@Yuushi, could we also say that all numbers are infinitely divisible by `0` and simplify the function to `return 0;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:51:08.787",
"Id": "61343",
"Score": "4",
"body": "@Jodrell No. You have it mixed up. Nothing is divisible by `0`, but `0` is divisible by everything."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T01:39:27.550",
"Id": "37190",
"ParentId": "37189",
"Score": "21"
}
},
{
"body": "<p>You don't include <code><stdbool.h></code> at the beginning of your code, even though you use a <code>true</code> value in a statement.</p>\n\n<hr>\n\n<p>You never check if <code>m</code> and <code>n</code> are equal for an early exit.</p>\n\n<hr>\n\n<p>Your condition statements are good from a readability standpoint, but could be simplified if you desired</p>\n\n<pre><code>if((m == 0) || (n == 0))\n return 0;\n\nif(!m || !n) \n return 0;\n</code></pre>\n\n<hr>\n\n<p>Instead of hardcoding values, I would allow input by the users for values during run-time.</p>\n\n<pre><code>int num1 = 600, num2 = 120; // not dynamic\nint num1, num2;\nprintf(\"%s\\n\", \"Input two numbers: \");\nscanf(\"%d%d\", &num1, &num2);\nif(!isdigit(num1) || !isdigit(num2)) return -1; // check if input data are integers\n...\n</code></pre>\n\n<hr>\n\n<p>Some people may argue to not have a <code>break</code> statement in your code, and to just return.</p>\n\n<pre><code>if(r == 0)\n return n;\n</code></pre>\n\n<p>I'm actually a fan of the <code>break</code> statement, because otherwise you have to keep track of another place you return from, which I don't like.</p>\n\n<hr>\n\n<p>Use actual variable names instead of just letters.</p>\n\n<pre><code>int greatestCommonDivisor(int m, int n) // confusing in\nint r; // later algorithms\n\nint greatestCommonDivisor(int num1, int num2) // less\nint remainder; // confusing\n</code></pre>\n\n<hr>\n\n<p>I like to put simple <code>if</code> statements all on one line, it helps me know that the <code>if</code> condition has only one statement and no braces.</p>\n\n<pre><code>if((m == 0) || (n == 0)) return 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T03:30:29.480",
"Id": "61314",
"Score": "5",
"body": "I disagree with the variables names. Here, `m` and `n` are fine; using `num1` and `num2` is no more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T03:34:56.460",
"Id": "61315",
"Score": "0",
"body": "@Yuushi Here, maybe. In other places, probably not. It was just an example I gave. I'll edit in more useful names."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T02:27:57.727",
"Id": "37193",
"ParentId": "37189",
"Score": "5"
}
},
{
"body": "<p>Unlike Yuushi, I'm not too fond of recursions, at least when they are not really needed. This is one of those cases.</p>\n\n<p>First, the negative input... The greatest common divisor of numbers -8 and -12 is 4, wouldn't you agree? So, instead of</p>\n\n<pre><code>else if((m < 0) || (n < 0))\n return -1;\n</code></pre>\n\n<p>I'd put</p>\n\n<pre><code>if (m < 0) m = -m;\nif (n < 0) n = -n;\n</code></pre>\n\n<p>to ensure that both of the numbers are nonnegative. Btw, <code>else</code> rarely (if ever) makes sense after <code>return</code>.</p>\n\n<p>Second, I think that breaking the loop</p>\n\n<pre><code>if (r == 0)\n break;\n</code></pre>\n\n<p>is misguiding, because what you really want to do is stop the function and return the result. In other words,</p>\n\n<pre><code>if (r == 0) return n;\n</code></pre>\n\n<p>Third, since your loop is technically infinite, then <code>do { ... } while(true);</code> is equivalent to <code>while (1) { ... }</code>. Personally, I find the latter to be more readable.</p>\n\n<p>Lastly, <code>true</code> does not exist in standard C. If you really want to use it, then include <code>stdbool.h</code>. This belongs to the C99 standard (so, it doesn't work in C89/C90). Personally, I prefer 1 and 0, but this is probably a matter of habit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:21:59.670",
"Id": "61326",
"Score": "0",
"body": "[Here's](http://www.galactanet.com/comic/view.php?strip=307) the problem with do-while explained a little deeper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T18:38:47.907",
"Id": "61673",
"Score": "0",
"body": "This will converge to zero regardless of sign, so it's possible to just abs the result: `return n < 0 ? -n : n;` ...I'm also more inclined to say `while((r = m % n))`, but that's more personal preference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:37:29.580",
"Id": "61699",
"Score": "1",
"body": "@laindir I prefer working with the positive numbers, because there is a slight indeterminism with the negative ones: prior to C99, `%` was not uniquely defined for the negative numbers, and thus that depends on the compiler. I admit, it is highly unlikely to encounter such an old compiler, but doing one `?:` instead of two `if`-s is, IMO, not worth it. As for your `while`, I like it as well, but such constructs tend to be confusing to the reader (who can easily confuse `=` with `==`). Why the double parentheses?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T22:11:20.310",
"Id": "61727",
"Score": "1",
"body": "With Euclid's Algorithm (and probably other strictly mathematical uses of modulo--array indexing is not one), it doesn't matter whether your implementation of modulo is based on division rounding toward zero or toward negative infinity (which, as you correctly point out, is implementation defined in C89). Double parentheses is a habit I picked up by enabling all gcc warnings; it makes it explicit that the value of the assignment is used as an expression (and that the user didn't mean to write `while(r == m % n)`). You could more explicitly say `while((r = m % n) != 0)`, but I find that noisy."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T02:36:55.807",
"Id": "37196",
"ParentId": "37189",
"Score": "10"
}
},
{
"body": "<p>With this little code, it's more important to avoid inelegance than to try to display more elegance. (Unless you find recursion to be elegant, and as Yuushi shows, there's a decent argument for that.) So instead, I'm going to focus on non-code elegance.</p>\n\n<p>Consider future readers of your function: include some of the documentation you presented for your question in your code. While GCD is certainly common enough around here, and a word for word explanation would match your code, a link or reminder can go a long way. Not all algorithms are familiar to everyone.</p>\n\n<p>Consider also the users of your code: document what kinds of input the function accepts (apparently non-negative numbers) and what it does when provided inputs it does not accept (apparently it sometimes returns <code>-1</code> instead of a GCD). This may help you remember to consider and thus normalize the behavior when one parameter is <code>0</code> and the other is negative. If calling code only has access to a header file, the implementation can't be cross-checked, so such cases deserve mention to enable the caller to perform error checking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T03:00:29.463",
"Id": "37198",
"ParentId": "37189",
"Score": "5"
}
},
{
"body": "<p>Instead of the using the <code>while(true)</code> construct, it's clearer and readable to state a condition necessary for the loop to continue. Also, <code>gcd</code> is defined for negative integers as well and they can be handled easily. </p>\n\n<p>The base condition is:</p>\n\n<pre><code>gcd(m, n) = gcd(n, m % n) when n != 0\n = m when n = 0\n</code></pre>\n\n<p>When both <code>m</code> and <code>n</code> are zero, then <code>gcd</code> is not defined and we return -1.</p>\n\n<pre><code>#include <stdio.h>\n\nint gcd(int m, int n) {\n if (m == 0 && n == 0)\n return -1;\n\n if (m < 0) m = -m;\n if (n < 0) n = -n;\n\n int r;\n while (n) {\n r = m % n;\n m = n;\n n = r;\n }\n return m;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T05:38:34.533",
"Id": "37200",
"ParentId": "37189",
"Score": "8"
}
},
{
"body": "<p>The whole algorithm can be broken down into one simple line (not including input sanity check). For speed, that line can be put into a loop if needed and completely do away with the overhead of a function call.</p>\n\n<p>This also helps the compiler optimize by knowing where and how the loop will exit.</p>\n\n<p>Is this readable? Ehh, probably not by less experienced coders but it is elegant... </p>\n\n<pre><code>#include <stdio.h>\n\n\nunsigned int gcd(unsigned int m, unsigned int n)\n{\n if(!m || !n)\n return(0);\n\n for(unsigned int r = m%n; r; m = n, n = r, r = m%n);\n\n return(n);\n}\n\n\nint main()\n{\n printf(\"50, 5: %d\\n\", gcd(50,5));\n printf(\"5, 50: %d\\n\", gcd(5,50));\n printf(\"34534, 567568: %d\\n\", gcd(34534, 567568));\n\n return(0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:31:41.967",
"Id": "61550",
"Score": "0",
"body": "Very clever! I like it! That's basically what I've done, but used that nature of a `for` loop. Awesome!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:44:53.383",
"Id": "37267",
"ParentId": "37189",
"Score": "2"
}
},
{
"body": "<p>Here is a simple recursive solution in C, this is pretty elegant.</p>\n\n<p>Note* I used ternary operators for the boolean statements, Type it in on Google for more information and check out the wikipedia page for <a href=\"http://en.wikipedia.org/wiki/%3F%3a#C\" rel=\"nofollow\">ternary operators in C</a></p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\n// recursively computes gcd\nint gcd(int a, int b) \n{\n return (b != 0)? gcd(b, a % b): a;\n}\n\nint main(int argc, char* argv[]) \n{\n // Specify values a and b or\n int a = 28, b = 7, result;\n\n // Run program with command line arguments\n result = (argc != 3)? gcd(a, b): gcd( atoi(argv[1]), atoi(argv[2]) );\n\n // print result\n printf(\"\\n%d\", result);\n}\n</code></pre>\n\n<p>*<strong>And finally here it is in about every other language:\n<a href=\"http://rosettacode.org/wiki/Greatest_common_divisor\" rel=\"nofollow\">http://rosettacode.org/wiki/Greatest_common_divisor</a>*</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:53:39.193",
"Id": "61568",
"Score": "1",
"body": "Considering this is primarily an English website, most people wouldn't be able to understand that language. Your first code block and its explanation are okay, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:02:31.263",
"Id": "61569",
"Score": "0",
"body": "Yeah I just put it in there when I came across it on rosettacode.org"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:42:43.563",
"Id": "37272",
"ParentId": "37189",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37196",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T01:24:43.583",
"Id": "37189",
"Score": "17",
"Tags": [
"c",
"algorithm",
"mathematics",
"error-handling"
],
"Title": "Euclid's Algorithm (Greatest Common Divisor)"
}
|
37189
|
<p>I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order.</p>
<p>Alphabetical gives:</p>
<ul>
<li>file1</li>
<li>file10</li>
<li>file2</li>
</ul>
<p>What I'm calling "number aware" string sorting should give:</p>
<ul>
<li>file1</li>
<li>file2</li>
<li>file10</li>
</ul>
<p><a href="https://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters">Here</a> is what I have using a regex split from there.</p>
<p>The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient.</p>
<pre><code>import java.util.Comparator;
public class NumberAwareStringComparator implements Comparator<String>{
public int compare(String s1, String s2) {
String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
int i = 0;
while(i < s1Parts.length && i < s2Parts.length){
//if parts are the same
if(s1Parts[i].compareTo(s2Parts[i]) == 0){
++i;
}else{
try{
int intS1 = Integer.parseInt(s1Parts[i]);
int intS2 = Integer.parseInt(s2Parts[i]);
//if the parse works
int diff = intS1 - intS2;
if(diff == 0){
++i;
}else{
return diff;
}
}catch(Exception ex){
return s1.compareTo(s2);
}
}//end else
}//end while
//Handle if one string is a prefix of the other.
// nothing comes before something.
if(s1.length() < s2.length()){
return -1;
}else if(s1.length() > s2.length()){
return 1;
}else{
return 0;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T07:24:39.307",
"Id": "61324",
"Score": "0",
"body": "You want to compare digits no matter their place in the string, correct? For instance, given strings `file1img`, `file10img`, `file2img`, you want them sorted `file1img`, `file2img`, `file10img`? If so, the pattern matched in your linked answer should work. Otherwise you should compare from the ends of the strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:04:30.853",
"Id": "61379",
"Score": "3",
"body": "Rule of thumb: `}//end while` If you need such comments to structure your code or make it more readable, there's something wrong with your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:03:46.877",
"Id": "61387",
"Score": "1",
"body": "Bobby, Do you have any suggestions on improving the code? I think //end is entirely subjective and doesn't say anything about the code."
}
] |
[
{
"body": "<p>In general, I think this solutions is doing the right thing, and the algorithm, in a broad sense is doing it the right way.</p>\n\n<p>There are two specific areas where I think it can be improved:</p>\n\n<ol>\n<li><p>Regular Expressions can be compiled and reused. This compareTo method is splitting many, many strings, and it would make a big difference to reuse the patterns rather than to recompile them twice each time the method is called. So, compile the pattern and use a static reference to it:</p>\n\n<pre><code>private static final Pattern BOUNDARYSPLIT = Pattern.compile(\"(?<=\\\\D)(?=\\\\d)|(?<=\\\\d)(?=\\\\D)\");\n</code></pre>\n\n<p>Then, in your method you can reuse that pattern easily with:</p>\n\n<pre><code>String[] s1Parts = BOUNDARYSPLIT.split(s1);\nString[] s2Parts = BOUNDARYSPLIT.split(s2);\n</code></pre>\n\n<p>This will save a lot of performance.</p></li>\n<li><p>The second issue is the 'convenience' of using a try/catch block for the ParseInt. Creating, throwing, and catching an exception is a surprisingly slow and complicated process. Using a try/catch as part of a 'routine' code-path is a mistake. Especially in something as frequent as a compareTo method. You should first make an attempt to see whether the input has a small hope of converting before throwing an exception:</p>\n\n<pre><code>if (s1parts[i].charAt(0) >= '0' && s1parts[i].charAt(0) <= '9') {\n // put your try-catch block here....\n} else {\n return s1parts[i].compareTo(s2parts[i]);\n}\n</code></pre></li>\n<li><p>I noticed, while writing this up, that in your catch-block, you use:</p>\n\n<pre><code> return s1.compareTo(s2);\n</code></pre>\n\n<p>I don't think it makes a difference in the functionality, but, you should probably use:</p>\n\n<pre><code> return s1parts[i].compareTo(s2parts[i]);\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:21:51.720",
"Id": "61392",
"Score": "0",
"body": "Good points. Static pattern and a check before the exception are both great points. I think that adding a check on s2parts[i] in your if statement would ensure the try never thorws the exception. If s1part[i] is numeric but s2part[i] is not a normal string compare would be fine. Thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:25:33.840",
"Id": "61394",
"Score": "0",
"body": "@pbible - when I wrote my answer I worked on the assumption (which is broken, I think) that if s1parts[x] is a number then s2parts[x] is also a number (and visa-versa for string). As a result I thought I only needed to check one side to see if it was numeric. Now I see that, if the input is: \"file10x\" and \"10filex\" you will still get an exception.... so, you are right, you should have the second check."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:38:24.767",
"Id": "37217",
"ParentId": "37192",
"Score": "7"
}
},
{
"body": "<p>Your approach appears to be basically sound.</p>\n\n<p>My main concern is <code>catch(Exception ex)</code>. <strong>Catching all exceptions</strong> like that makes me very nervous and puzzled about your intent. I have to wonder, what could possibly go wrong inside the try-block? My thought process:</p>\n\n<ol>\n<li>The exception would have to be thrown from the <code>Integer.parseInt()</code> calls, since the diff portion is foolproof.</li>\n<li>Obviously, <code>Integer.parseInt()</code> could throw <code>NumberFormatException</code>.</li>\n<li>What about <code>ArrayIndexOutOfBoundsException</code>? No, we're safe, because you already checked in the while-loop condition. Furthermore, if <code>++i</code> got executed, it wouldn't enter the else-clause.</li>\n<li>What about <code>NullPointerException</code>? It seems impossible, since the parts arrays came from <code>String.split()</code>.</li>\n<li>Anything else? <code>OutOfMemoryError</code>, maybe? No, that's a <code>Throwable</code> but not an <code>Exception</code>.</li>\n<li>Any other possibilities? No. Am I sure? No.</li>\n</ol>\n\n<p>For my sanity, please change that to <code>catch (NumberFormatException ex)</code>!</p>\n\n<p>Changing the <strong>while-loop into a for-loop</strong> would make it easier to recognize the flow control. You can also save a level of indentation.</p>\n\n<pre><code>for (int i = 0; i < s1Parts.length && i < s2Parts.length; ++i) {\n //if parts are the same\n if (s1Parts[i].compareTo(s2Parts[i]) == 0) {\n continue;\n }\n try {\n int intS1 = Integer.parseInt(s1Parts[i]);\n int intS2 = Integer.parseInt(s2Parts[i]);\n\n //if the parse works\n int diff = intS1 - intS2; \n if (diff == 0) {\n // continue; // Actually, this is a no-op\n } else {\n return diff;\n }\n } catch (NumberFormatException ex) {\n // Buggy, as noted by @rolfl\n // return s1.compareTo(s2);\n return s1Parts[i].compareTo(s2Parts[i]);\n }\n}\n</code></pre>\n\n<p>The <strong>epilogue could be simplified</strong> to just <code>return s1.length() - s2.length()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:56:45.627",
"Id": "61444",
"Score": "0",
"body": "Definitely a good catch with NumberFormatException. What about the test for digits suggested by rolfl? Do you agree?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:17:35.540",
"Id": "61447",
"Score": "0",
"body": "See my other answer for an alternative to testing for digits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:10:58.717",
"Id": "61484",
"Score": "0",
"body": "@200_success - good catch on the NumberFormatException vs. Exception, but I think your other answer is much better, Excpetions should never be part of **expected** (routine) program flow."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:51:54.610",
"Id": "37244",
"ParentId": "37192",
"Score": "3"
}
},
{
"body": "<p>Exceptions should be reserved for exceptional situations, and should be avoided if possible. The fundamental reason you have to deal with <code>NumberFormatException</code> is that after splitting, you don't know whether each part contains a number or a non-number.</p>\n\n<p>Here's a strategy that always compares non-digits to non-digits, and numbers to numbers.</p>\n\n<pre><code>import java.math.BigInteger;\nimport java.util.Comparator;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class NumberAwareStringComparator implements Comparator<CharSequence> {\n public static final NumberAwareStringComparator INSTANCE =\n new NumberAwareStringComparator();\n\n private static final Pattern PATTERN = Pattern.compile(\"(\\\\D*)(\\\\d*)\");\n\n private NumberAwareStringComparator() {\n }\n\n public int compare(CharSequence s1, CharSequence s2) {\n Matcher m1 = PATTERN.matcher(s1);\n Matcher m2 = PATTERN.matcher(s2);\n\n // The only way find() could fail is at the end of a string\n while (m1.find() && m2.find()) {\n // matcher.group(1) fetches any non-digits captured by the\n // first parentheses in PATTERN.\n int nonDigitCompare = m1.group(1).compareTo(m2.group(1));\n if (0 != nonDigitCompare) {\n return nonDigitCompare;\n }\n\n // matcher.group(2) fetches any digits captured by the\n // second parentheses in PATTERN.\n if (m1.group(2).isEmpty()) {\n return m2.group(2).isEmpty() ? 0 : -1;\n } else if (m2.group(2).isEmpty()) {\n return +1;\n }\n\n BigInteger n1 = new BigInteger(m1.group(2));\n BigInteger n2 = new BigInteger(m2.group(2));\n int numberCompare = n1.compareTo(n2);\n if (0 != numberCompare) {\n return numberCompare;\n }\n }\n\n // Handle if one string is a prefix of the other.\n // Nothing comes before something.\n return m1.hitEnd() && m2.hitEnd() ? 0 :\n m1.hitEnd() ? -1 : +1;\n }\n}\n</code></pre>\n\n<p>Since strings of digits (such as those representing dates, like <code>20131212123456.log</code>) can overflow an <code>int</code>, I've used <code>java.math.BigInteger</code>.</p>\n\n<p>Also, since the code works just as well with <code>CharSequence</code> as with <code>String</code>, I've generalized the type to <code>Comparator<CharSequence></code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:40:28.473",
"Id": "61459",
"Score": "0",
"body": "I thought that Integer.parseInt always had to be surrounded with try catch (maybe this post explains it http://stackoverflow.com/questions/14255880/why-integer-parseint-is-compiling-without-try-catch). If it does not need to be caught then I could just remove the try catch portion after the check for digits. This solution seems good though. Good idea making it effectively static with the singleton like INSTANCE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:45:47.123",
"Id": "61461",
"Score": "1",
"body": "We have log files on our systems that have the following names: 201312121444.43234.log ... you still need the NumberFormatException"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:52:37.520",
"Id": "61466",
"Score": "1",
"body": "In this instance (because `\\\\d` does not match `-`) the expression `return n1 - n2;` is 'OK', but, in general, you should never use this 'pattern' in a comparator: If `n1 = 2147483640` and `n2 = -10` we would expect to return a 'positive' value, but, in reality, n1 - n2 will overflow, and will become very negative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:56:46.537",
"Id": "61475",
"Score": "0",
"body": "@rolfl Amended to use `java.math.BigInteger`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:07:37.137",
"Id": "61482",
"Score": "0",
"body": "For my purposes negative numbers are not an issue. The numbers in file names would be run numbers from a machine so no negative. I could envision cases for scientific notation 'run_10_4e-10.dat' but I'm not sure that could be easily handled."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:07:46.300",
"Id": "61483",
"Score": "1",
"body": "@200_success I think this is a good answer. If it really was **me** doing this compare, and if I thought of the regex pattern you used (which is a good one, BTW), then I also may add two checks before the BigInt work: make sure both values are same length (longer numbers are always bigger); do simple `Integer.parseInt(...)` for short values (9-digits or less)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:26:26.040",
"Id": "61489",
"Score": "0",
"body": "@rolfl Actually, in GNU Classpath at least, `BigInteger` has [optimizations](http://developer.classpath.org/doc/java/math/BigInteger-source.html#line.1601) for numbers that fit in an `int`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:30:41.800",
"Id": "61493",
"Score": "0",
"body": "Two questions, Can you explain the explicit calls to group(1) and group(2)? Also could you simplify the epilogue as you suggest with s1.length() - s2.length() in this solution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:44:49.287",
"Id": "61496",
"Score": "1",
"body": "Explained matcher.group() in comments. You _could_ use `return s1.length() - s2.length()` as an epilogue, but I chose to test `.hitEnd()` because it's obviously related to how the while-loop terminated, and therefore makes the code more coherent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:49:49.950",
"Id": "61499",
"Score": "0",
"body": "Thanks. I guess you can't use difference in lengths with your Match object in the loop. Good solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-28T19:01:58.193",
"Id": "142929",
"Score": "0",
"body": "@rolfl Longer numbers are not necessarily bigger, due to the possibility of leading zeros."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:14:16.797",
"Id": "37249",
"ParentId": "37192",
"Score": "8"
}
},
{
"body": "<p>Changes the pattern to this if you want to use decimals:</p>\n\n<pre><code>private static Pattern BOUNDARYSPLIT = Pattern.compile(\"(?<=\\\\D\\\\.)(?=\\\\d)|(?<=\\\\d)(?=\\\\D)\"); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-11T15:28:40.830",
"Id": "56769",
"ParentId": "37192",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37249",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T02:21:20.620",
"Id": "37192",
"Score": "12",
"Tags": [
"java",
"strings",
"sorting"
],
"Title": "Number aware string sorting with comparator"
}
|
37192
|
<p>Below is a script I wrote today to use CURL to monitor the length of various HTTP server outputs and output a response if this is different than 103 characters.
This is my first bash script, so I had some reading/experimenting to do and it is quite rough.
The idea is that if there are no errors, my php script will ouput exactly 103 characters. If there are errors, this will be increased.</p>
<p><strong>IDScript</strong></p>
<pre><code>#!/bin/bash
# Check for missing IDs - greater output than 103 characters
cd "/media/SMALL/scripts"
if [[ -z "$1" ]] # check if script arguement exists
then
a=$(./IDscript "server");
a=$(./IDscript "server2")$a; #concatenate with previous output
a=$(./IDscript "server3")$a;
lenA=$(expr length "$a");
if [ $lenA -eq 0 ] #check length of A is empty
then
echo "No errors";
else
mail -s "TID error" myEmail@company.org <<< "There are errors:"$a; # send the e-mail
fi
exit;
fi
#create random number from 50 to 99
r=$(( $RANDOM % 50 + 50 ));
#bypass HTTP proxy with random number
testURL=$1"/checkError?which=IDError&rand="$r;
curlOut=$(curl -s "$testURL");
curlLength=$(expr length "$curlOut");
if [ $curlLength -ne 103 ] #103 char is response length when no missing IDs exist
then
echo "length is not 103:"$testURL;
echo -e "\n";
fi
</code></pre>
<p>Comments and suggestions are welcome!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:07:31.783",
"Id": "61539",
"Score": "0",
"body": "Checking for a 103-byte response is rather weird. I would recommend that you check either the HTTP status code (the return value of `curl --fail --silent`) or verify if the output matches a particular string or pattern."
}
] |
[
{
"body": "<pre><code>#!/bin/bash\n</code></pre>\n\n<p>Minor, still good to know, <a href=\"http://en.wikipedia.org/wiki/Shebang_%28Unix%29#Portability\" rel=\"nofollow\">this is not portable</a>, f.e. BSDs will choke on it. This might not be an issue if you only intent to use it on Linux, but if you ever release script into the wild, you should consider using a portable shebang line.</p>\n\n<pre><code>#!/usr/bin/env bash\n</code></pre>\n\n<hr>\n\n<pre><code>if [[ -z \"$1\" ]] # check if script arguement exists\nthen\n</code></pre>\n\n<p>I'm a friend of the one-line-style, but that is for sure a pure personal preference.</p>\n\n<pre><code>if [[ -z \"$1\" ]]; then # check if script arguement exists\n</code></pre>\n\n<hr>\n\n<pre><code>a=$(./IDscript \"server\");\n</code></pre>\n\n<p>From the context of this I can say two things:</p>\n\n<ol>\n<li>that variable needs a better name</li>\n<li>that script needs a better name</li>\n</ol>\n\n<p>It is not obvious what the script does and neither what the variable will hold.</p>\n\n<hr>\n\n<pre><code>a=$(./IDscript \"server\");\n</code></pre>\n\n<p>In a shell script, there's no need to close every line with a semicolon. You can do it, but it's not necessary.</p>\n\n<hr>\n\n<pre><code>lenA=$(expr length \"$a\");\n</code></pre>\n\n<p>If you're going to use Bash, you can also use Bash syntax:</p>\n\n<pre><code>lenA=${#a}\n</code></pre>\n\n<p>Or shortened to:</p>\n\n<pre><code>if [ ${#a} -eq 0 ] #check length of A is empty\nthen\n</code></pre>\n\n<hr>\n\n<pre><code>if [[ -z \"$1\" ]]\n</code></pre>\n\n<p>What I made a habit out of in the last time is extracting arguments into named variables so that the script is easier to read.</p>\n\n<pre><code>webAddress=$1\n\nif [[ -z \"$webAddress\" ]]\n...\ntestURL=$webAddress\"/checkError?which=IDError&rand=\"$r;\n</code></pre>\n\n<p>This is of course not always useful, but pretty neat if you're going to use <code>$1</code> in multiple places, as the script becomes easier to read.</p>\n\n<hr>\n\n<pre><code>echo -e \"\\n\"; \n</code></pre>\n\n<p>This can be shortened.</p>\n\n<pre><code>echo\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:12:00.847",
"Id": "61361",
"Score": "0",
"body": "But otherwise I guess it seems ok..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:55:36.630",
"Id": "61377",
"Score": "0",
"body": "@meewoK: I don't see something wrong with it other then that (oh wait, there's something tiny). A few more comments (explaining what's going on) would be nice, but depending on your environment that might be absolutely unnecessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:56:55.660",
"Id": "37205",
"ParentId": "37199",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37205",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T03:23:07.973",
"Id": "37199",
"Score": "2",
"Tags": [
"bash",
"curl"
],
"Title": "Bash script to monitor Webserver php script"
}
|
37199
|
<p>I have the following code that gives me the indices of an array's largest value:</p>
<pre><code>public static void main(String[] args) {
float[] elementList = new float[7];
elementList[0] = 8F;
elementList[1] = 5F;
elementList[2] = 4F;
elementList[3] = 3F;
elementList[4] = 0F;
elementList[5] = 8F;
elementList[6] = 6F;
// findLargestNumberLocations(elementList);
largestNumbers(elementList);
}
private static void largestNumbers(float[] numbers) {
float largeNumber = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > largeNumber) {
largeNumber = numbers[i];
}
}
for (int j = 0; j < numbers.length; j++) {
if(largeNumber == numbers[j]){
System.out.println("largest number index "+j);
}
}
}
</code></pre>
<p>Is there any optimized way of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:55:55.820",
"Id": "61601",
"Score": "0",
"body": "What would you like the behaviour to be for an empty input? What if any of the numbers is `Float.NaN`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:19:40.123",
"Id": "61608",
"Score": "0",
"body": "Edited the OP, Please let me know if there is any mistake. @200_success"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:34:15.253",
"Id": "61610",
"Score": "0",
"body": "I've rolled back your edit. Please don't alter the question, as it invalidates all the reviews. I just wanted to seek clarification. Your wish appears to be: 1) `NullPointerException` if `numbers` is `null`, 2) No output if `numbers` is empty, 3) Ignore all `Float.NaN`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:57:25.350",
"Id": "61613",
"Score": "0",
"body": "Yes, That is how I did"
}
] |
[
{
"body": "<p>Your code doesn't just find the largest number's index. It finds the largest <em>number</em>, then searches again for any indices that match that value.</p>\n\n<p>Here's a method that uses less searching (pseudocode):</p>\n\n<pre><code>largestValue = numbers[0];\nvector largestIndices; // Will store all indices of largestValue as you search\nlargestIndices.add(0); // In case numbers[0] = the true largest value\n\nfor (i = 1; i < numbers.size(); i++) { // don't need to compare index 0\n if (numbers[i] > largestValue) {\n largestValue = numbers[i]; // Update largestValue\n largestIndices.clear(); // Get rid of indices of smaller values\n largestIndices.add(i); // Add this index\n }\n else if (numbers[i] == largestValue) {\n largestIndices.add(i); // Add this index\n }\n}\n\nfor (j = 0; j < largestIndices.size(); j++) {\n // no searching necessary!\n print(largestIndices[j]);\n}\n</code></pre>\n\n<p>This probably uses more data accesses, but saves searching time (important for huge arrays).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T07:08:04.060",
"Id": "37202",
"ParentId": "37201",
"Score": "7"
}
},
{
"body": "<p>Is the new line after a function starts intended?</p>\n\n<hr>\n\n<pre><code>private static void largestNumbers(float[] numbers) {\n</code></pre>\n\n<p>This function could have a better name, functions should have a verb as name, not an adjective.</p>\n\n<pre><code>private static void printLargestNumbersIndex(float[] numbers)\n</code></pre>\n\n<p>This is more verbose, but you immediately know what the function does.</p>\n\n<hr>\n\n<pre><code>float largeNumber = numbers[0];\n</code></pre>\n\n<p>Very minor, but I'd call it <code>largestNumber</code>.</p>\n\n<hr>\n\n<pre><code>for (int i = 0; i < numbers.length; i++) {\n if (numbers[i] > largeNumber) {\n largeNumber = numbers[i];\n }\n}\n</code></pre>\n\n<p>A <code>foreach</code> loop would be more appropriate for this use case.</p>\n\n<pre><code>for (float number : numbers) {\n if (number > largestNumber) {\n largestNumber = number;\n }\n}\n</code></pre>\n\n<p>Generally always try to use <code>foreach</code> loops instead of <code>for</code> loops unless you need to know the index of the element (which would be the case in the second loop).</p>\n\n<hr>\n\n<pre><code>for (int j = 0; j < numbers.length; j++) {\n</code></pre>\n\n<p>For myself I try to avoid one-letter variables as hard as possible (only exception being coordinates, <code>x</code> <code>y</code> <code>z</code>), and this opinion is for sure controversial and non-standard, but I think this loop would gain a lot of readability by simply using <code>index</code> as variable.</p>\n\n<pre><code>for (int index = 0; index < numbers.length; index++) {\n</code></pre>\n\n<hr>\n\n<pre><code>if(largeNumber == numbers[j]){\n</code></pre>\n\n<p>Always keep in mind that comparing floating point numbers with <code>==</code> <em>can</em> be problematic.</p>\n\n<hr>\n\n<pre><code>System.out.println(\"largest number index \"+j);\n</code></pre>\n\n<p>Ideally, from a code structure and reuse point of view, your function would return an <code>int[]</code> or <code>Collection<Integer></code> with all found indexes. That would make it easily reusable.</p>\n\n<hr>\n\n<pre><code>float[] elementList = new float[7];\nelementList[0] = 8F;\nelementList[1] = 5F;\nelementList[2] = 4F;\nelementList[3] = 3F;\nelementList[4] = 0F;\nelementList[5] = 8F;\nelementList[6] = 6F;\n</code></pre>\n\n<p>You can initialize arrays directly with values.</p>\n\n<pre><code>float[] elementList = new float[] {8f, 5f, 4f, 3f, 0f, 8f, 6f};\n</code></pre>\n\n<p>Also, <code>elementList</code> is not a great name for this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:56:56.220",
"Id": "61328",
"Score": "0",
"body": "Thank you for clear explanation, does it give performance? @Bobby"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:57:54.820",
"Id": "61329",
"Score": "0",
"body": "@MaheshVarma: You mean that initializer thing? Too minor to notice if at all, but it increases readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:59:30.963",
"Id": "61330",
"Score": "0",
"body": "I mean can we do it both finding the largest number and printing out it's indices in single for loop? @Bobby"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:02:28.913",
"Id": "61331",
"Score": "0",
"body": "@MaheshVarma: You'd need to sort the array first, otherwise I don't see how."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:45:10.980",
"Id": "61340",
"Score": "0",
"body": "Did you read the question? It is not asking about code semantics. Though your in-depth answer regarding naming and conventions could possibly be on-topic somewhere on CodeReview, OP clearly asked about optimization regarding execution. You don't address this at all. Regarding your mention of for-each loops: if you had understood the question, you would have realized that the index *is* necessary to improve runtime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:49:04.063",
"Id": "61341",
"Score": "0",
"body": "@trojansdestroy: You already addressed that, I did a general review. Yes, I'm doing reviews which the OP did not ask for but which I consider *good feedback* which might still help the OP. So for that matter, I consider your answer as *the* answer to this question, and my own as complementary only. If you feel like that's a problem with that, there's always Meta to discuss such issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T11:34:52.720",
"Id": "61351",
"Score": "1",
"body": "upvote but I oppose the idea of using `idx` as the variable name. `i` is industry standard and is perfectly fine. If you wish to move away from using industry standard I'd suggest using `index` as a more declarative alternative to `idx`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T11:40:51.403",
"Id": "61353",
"Score": "0",
"body": "@Max: You're right in both cases. I started preferring not using `i` because I've seen quite a lot unreadable (nested) loops which would have gained a lot of readability by not using `i`, `j`, `k`, `l`. I tried to make clear that this is only *my* preference and only food for thoughts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T11:42:28.937",
"Id": "61354",
"Score": "1",
"body": "@Bobby It's true that in a bigger scope (i.e., lots of nesting etc) a more descriptive variable name as `index` should be used, I agree with you on that. That is not the case here though."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T08:41:12.550",
"Id": "37203",
"ParentId": "37201",
"Score": "5"
}
},
{
"body": "<p>In this case, your performance will not be terrible, but, for really large arrays you may run in to problems.</p>\n\n<p>Also, there <strong>is</strong> a bug in your code... what if the input array is empty? Then you will get an <code>ArrayIndexOutOfBoundsException</code> on:</p>\n\n<pre><code>float largeNumber = numbers[0];\n</code></pre>\n\n<p>There is always more than one way to do things, but, I want to post an answer here because one possible solution (which may or may not be faster than your solution depending on data size) has a really close relationship to another CodeReview question posted recently. When I answered that question I could only think of artifical examples of when it was 'right' to use pre/post-increments. <strong>This is a good example of when....</strong></p>\n\n<p>See this answer here: <a href=\"https://codereview.stackexchange.com/a/36910/31503\">Is it bad practice to increment more than one variable in a for loop declaration?</a></p>\n\n<p>So, here is a good example of how and when a <code>count</code> and an <code>index</code> are related in a for loop and the way they can be incremented. I have some notes at the end:</p>\n\n<pre><code>private static int[] findLargeNumberIndices(float[] numbers) {\n\n // create an array of at least 8 members.\n // We may need to make this bigger during processing in case\n // there's more than 8 values with the same large value\n int[] indices = new int[Math.max(numbers.length / 16 , 8)];\n // how many large values do we have?\n int count = 0;\n // what is the largest value we have?\n float largeNumber = Float.NEGATIVE_INFINITY;\n for (int i = 0; i < numbers.length; i++) {\n if (numbers[i] > largeNumber) {\n // we have a new large number value... reset our history....\n largeNumber = numbers[i];\n // setting count to zero is enough to 'clear' our previous references.\n count = 0;\n // we know there's space for at least index 0. No need to check.\n // note how we post-increment - this is a 'pattern'.\n indices[count++] = i;\n } else if (numbers[i] == largeNumber) {\n // we have another large value.\n if (count == indices.length) {\n // need to make more space for indices... increase array by 25%\n // count >>> 2 is the same as count / 4 ....\n indices = Arrays.copyOf(indices, count + (count >>> 2));\n }\n // again, use the post-increment\n indices[count++] = i;\n }\n }\n // return the number of values that are valid only.\n return Arrays.copyOf(indices, count);\n}\n</code></pre>\n\n<p>Notes about this code:</p>\n\n<ol>\n<li>The presentation (<code>System.out.println(...)</code>) is now outside the method.</li>\n<li>It allocates a 'small' array to store the indexes. This array will grow if needed.</li>\n<li>I picked 'good enough` initial size for the array.... but some playing with the numbers may help performance.</li>\n<li>There is no real reason to believe that this code is faster than the two loops - creating the array may be more expensive than the second loops.</li>\n<li>note how the <code>i</code> index is incemented in the for-loop, but the `count` is post-incremented each time it is used in the array.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:30:46.250",
"Id": "61542",
"Score": "0",
"body": "Serindipitously upvoted :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T05:02:20.887",
"Id": "61582",
"Score": "0",
"body": "Nice explanation... can we directly tell count/4 is same as count >>> 2. Or does it come with experience? I never used this shift operator but I have an idea on this. From now on I will try to use this operator. But how to decide the result of x >>> 3 or x <<< 5 or x << 8. do we need to calculate binary digits and decide, oh! count >>> 4 is equal to count/4 ? Please give some idea on these shift operators in real time? @rolfl"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T12:27:17.957",
"Id": "61636",
"Score": "0",
"body": "@MaheshVarma - you can divide by any power-of-2 by using bit-shifts. 0, 1, 2, 3, ... bitshifts respectively mean divide by 1, 2, 4, 8, .... (or multiply by if it is a left-shift). The easiest explanation for it is to think in decimal: 12345 integer-divided by 100 is 123.... we 'shifted' 2 digits (2nd power of 10). Similarly, 12345 multiplied by 100 is 1234500 - we left-shifted twice. When you multiply/divide by powers-of-two, the shift operator is sometimes more convenient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T04:57:19.637",
"Id": "62029",
"Score": "0",
"body": "What could be the real time uses of these shift operators?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T05:26:06.533",
"Id": "62034",
"Score": "0",
"body": "@MaheshVarma - in this case they are essentially useless, but, in certain situations they are very, very useful... here's a good starting point: http://stackoverflow.com/questions/520625/have-you-ever-had-to-use-bit-shifting-in-real-projects"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T15:57:49.957",
"Id": "37231",
"ParentId": "37201",
"Score": "8"
}
},
{
"body": "<p>Your code is correct, except that you get an <code>ArrayOutOfBoundsException</code> for an empty input list. You'll have to decide what the desired behaviour should be for an empty input, but <code>ArrayOutOfBoundsException</code> isn't quite appropriate. <code>IllegalArgumentException</code> maybe, if you document the requirement that <code>numbers</code> be non-empty. Personally, I think that an empty input should produce empty output.</p>\n\n<p>Mixing logic and output is bad practice, as it ensures that your code will not be reusable. You should return an array instead of printing the results.</p>\n\n<p>I suggest renaming your function to include \"max\" in the name instead of \"largest\", as almost all APIs prefer \"max\", including <code>java.lang.Math.max()</code>.</p>\n\n<p>The primary performance concern would be that you iterate through the array twice. That may or may not be acceptable, depending on the size of the input you expect. Either way, the performance will be O(<em>n</em>), though you'll notice a significant difference for large <em>n</em>.</p>\n\n<p>@trojansdestroy suggests building the result set as as list in one pass.\n@rolfl suggests building the result set using arrays in one pass, which accomplishes the same thing the hard way to avoid the overhead of creating an <code>ArrayList</code> and its associated boxing-unboxing conversion.</p>\n\n<p>In contrast to those two approaches, I prefer to make two passes. The first pass finds the largest number and the size of the result set. The second pass fills in the result set.</p>\n\n<pre><code>/**\n * Finds the locations of the largest numbers. Any Float.NaN\n * elements in the input are ignored.\n *\n * @return An empty array if numbers is empty or consists solely\n * of Float.NaN; null if numbers is null; an array of\n * indexes otherwise.\n */\npublic static int[] maxIndexes(float[] numbers) {\n if (null == numbers) return null;\n\n int maxIndex = 0, maxCount = 0;\n\n // In case the array starts with Float.NaN\n while (maxIndex < numbers.length - 1 && Float.isNaN(numbers[maxIndex])) {\n maxIndex++;\n }\n\n // First pass: identify the max value and the number of times it occurs\n for (int i = maxIndex; i < numbers.length; i++) {\n if (numbers[i] > numbers[maxIndex]) {\n maxIndex = i;\n maxCount = 1;\n } else if (numbers[i] == numbers[maxIndex]) {\n maxCount++;\n }\n }\n\n // Second pass: Write the result\n int[] ret = new int[maxCount];\n for (int i = numbers.length - 1; i >= maxIndex; i--) {\n if (numbers[i] == numbers[maxIndex]) {\n ret[--maxCount] = i;\n }\n }\n return ret;\n}\n</code></pre>\n\n<p>There's a slight optimization on the second pass, so that it might not have to loop through the entire array.</p>\n\n<p>Which strategy will work best in practice? Most processes that generate floating-point numbers won't produce many numbers that are <em>exactly</em> equal to each other, so I would guess that @rolfl has the most practical code.</p>\n\n<p>Your test case would be…</p>\n\n<pre><code>public static void main(String[] args) {\n float[] numbers = { 8f, 5f, 4f, 3f, 0f, 8f, 6f };\n int[] max = maxIndexes(numbers);\n System.out.println(java.util.Arrays.toString(max));\n}\n</code></pre>\n\n<p>Note the simplified array initializer. You could even omit the <code>f</code> suffix on the float literals and let the compiler figure it out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:24:56.563",
"Id": "61609",
"Score": "0",
"body": "Please review the edited version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:46:04.223",
"Id": "61611",
"Score": "0",
"body": "The code in questions should not be edited in any significant way after the question has been posed, as that would invalidate the reviews."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:47:34.627",
"Id": "37291",
"ParentId": "37201",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37231",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T06:58:41.823",
"Id": "37201",
"Score": "8",
"Tags": [
"java",
"optimization",
"array",
"floating-point"
],
"Title": "Finding all indices of largest value in an array"
}
|
37201
|
<p>I wrote a simple <code>Polynomial</code> class:</p>
<pre><code>class Polynomial
def initialize(coefficients)
@coefficients = coefficients.reverse
end
def to_s
return '0' if @coefficients.all?(&:zero?)
@coefficients.map.with_index do |k, index|
" #{Polynomial.sign(k)} #{k.abs}x^#{index}"
end.reverse.join.strip # removes whitespace at the front
.gsub(/\A\+\s/, '') # removes + if first coefficient is positive
.gsub(/x\^0/, '') # removes x to the power of 0
.gsub(/\s(\+|-)\s0x\^\d/, '') # removes 0 coefficients
.gsub(/\s(\+|-)\s0/, '') # removes 0 at the end of the expression
.gsub(/\^1/, '') # removes power of 1
.gsub(/1x/, 'x')
end
def evaluate(x)
@coefficients.map.with_index { |k, index| k * (x**index) }.reduce(0, :+)
end
private
def self.sign(integer)
integer >= 0 ? '+' : '-'
end
end
</code></pre>
<p>There are a few things that bother me in the <code>to_s</code> method:</p>
<ol>
<li>Is it bad that I wrote the short comments explaining what each <code>gsub</code> does? <em>Bad</em> in terms of "Would you do this in production code?".</li>
<li><p>Since all but one of the <code>gsub</code>s do the same, I could replace them with a single <code>gsub</code>, containing a long regexp with lots of <code>or</code>s (<code>|</code>):</p>
<pre><code>.gsub(/\A\+\s|x\^0|\s(\+|-)\s0x\^\d|\s(\+|-)\s0|\^1/, '')
</code></pre>
<p>In that case though the regexp become quite unreadable. Which of the two is better?</p></li>
<li><p>Regarding the <code>map.with_index</code> part:</p>
<ul>
<li>I use <code>do/end</code>, but than the chaining of methods on the <code>end</code> doesn't look good.</li>
<li>If I use curly braces on multiple lines, I break the convention curly braces for single-line blocks, <code>do/end</code> for multi-line blocks.</li>
<li>If I use curly braces with a single-line block, the line will be more than 80 characters long. So which of the three variants would you use?</li>
</ul></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:34:59.743",
"Id": "61335",
"Score": "1",
"body": "some bugs: a power of `x^10` will be replaced with `x0`, just like `11x` will be replaced with `1x`. In other words you never account for multi digit coefficients or powers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:20:51.730",
"Id": "61345",
"Score": "0",
"body": "@ratchetfreak, thanks for noticing that, I corrected my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T17:38:05.190",
"Id": "65540",
"Score": "0",
"body": "The \"removes 0 coefficients\" substitution leaves junk for terms where the power is greater than 9."
}
] |
[
{
"body": "<blockquote>\n <p>Is it bad that I wrote the short comments explaining what each gsub does?</p>\n</blockquote>\n\n<p>In my opinion, no. Given the complexity Regular Expressions can reach, it is wise to comment them in one way or the other so that somebody who can not instantly parse/read Regular Expressions at least gets a faint idea what it is doing.</p>\n\n<blockquote>\n <p>Which of the two is better?</p>\n</blockquote>\n\n<p>Personal preference, I fear. If the Regular Expression is self-explaining/obvious there's no need to comment it, but that's seldom the case, so we <em>should</em> comment on them. There are two possibilities, do it like you did, or copy the Regular Expression into a comment and split and document it there.</p>\n\n<p>In your case, given that you only would join the Regular Expressions together with <code>or</code>, you do not gain anything by making it one big, so I consider your split-approach a very elegant and valid solution.</p>\n\n<p>As I never did Ruby I can't review your code any further, sorry. See this is as a long comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T17:44:43.383",
"Id": "65542",
"Score": "1",
"body": "I don't think it's personal preference. For example, the `\\A` anchor in the second `.gsub()` is not the same as the `\\A` anchor in the first `.gsub()`. Furthermore, separate substitutions would be much more readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:38:40.697",
"Id": "37209",
"ParentId": "37207",
"Score": "2"
}
},
{
"body": "<p>your <code>evaluate</code> can be made a bit more efficient by reversing and using a straight reduce:</p>\n\n<pre><code> def evaluate(x)\n @coefficients.reverse.inject(0){ | res, coef | res * x + coef }\n end\n</code></pre>\n\n<p>this works because <code>a4*x^4+a3*x^3+a2*x^2+a1*x^1+a0*x^0</code> is equivalent to <code>(((((a4)*x+a3)*x+a2)*x+a1)*x+a0)</code></p>\n\n<p>this avoids the <code>**</code> power operation</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:35:43.823",
"Id": "37213",
"ParentId": "37207",
"Score": "2"
}
},
{
"body": "<p>Rather than construct the polynomial string incorrectly, then fix it with regex's, it may be easier to contruct it directly. This is one way you could do that.</p>\n\n<pre><code>class Polynomial\n def initialize(coefficients)\n @coefficients = coefficients\n end\n\n def to_s\n coeffs = @coefficients.each_with_index.select { |c,k| c.nonzero? || k==0 }.reverse\n coeffs.each_with_object('') do |(c,k), s|\n cneg = (c.to_f < 0.0)\n if [c,k] == coeffs.first\n s << '-' if cneg\n else\n s << (cneg ? ' - ' : ' + ')\n end\n s << \"#{c.abs}\" unless (c.abs.to_f == 1.0 && k > 0)\n s << \"x\" if k > 0\n s << \"^#{k}\" if k > 1\n end\n end\nend \n\ncoefficients = [2.1, 3, 1.0, 0, -6.1, 1, -5.3, 0.2]\np Polynomial.new(coefficients).to_s\n # => 0.2x^7 - 5.3x^6 + x^5 - 6.1x^4 + x^2 + 3x + 2.1\n</code></pre>\n\n<p>For this example value of <code>coefficients</code>, this is what's happening:</p>\n\n<p>First save each coeffient's index with its value:</p>\n\n<pre><code>a = @coefficients.each_with_index\n # => [[2.1,0], [3,1], [1.0,2], [0,3], [-6.1,4], [1,5], [-5.3,6], [0.2,7]] \n</code></pre>\n\n<p>Next, select only pairs for which the value is non-zero or the exponent is zero:</p>\n\n<pre><code>b = a.select { |c,k| c.nonzero? || k==0 }\n # => [[2.1, 0], [3, 1], [1.0, 2], [-6.1, 4], [1, 5], [-5.3, 6], [0.2, 7]]\n</code></pre>\n\n<p>Notice that <code>[0,3]</code> has been removed. Now reverse the elements of the array: </p>\n\n<pre><code>coeffs = b.reverse\n # => [[0.2, 7], [-5.3, 6], [1, 5], [-6.1, 4], [1.0, 2], [3, 1], [2.1, 0]]\n</code></pre>\n\n<p><code>each_with_object('')</code> creates an empty string, designated <code>s</code> in the block. It is then a simple matter to consider each element of each term in the polynomial to build up the string.</p>\n\n<p>I'm not certain if I followed the formatting rules exactly, but if I did not, it should be easy to modify the code to conform.</p>\n\n<p>(Edited to fix boo-boos spotted by @200_success.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T09:17:28.927",
"Id": "65483",
"Score": "0",
"body": "`Polynomial.new([1]).to_s` evaluates to an empty string. Also, `Polynomial.new([0, 1, 0])` produces ` + x`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:30:42.840",
"Id": "65553",
"Score": "0",
"body": "`Polynomial.new([0]).to_s` also evaluates to an empty string."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T08:13:56.943",
"Id": "39128",
"ParentId": "37207",
"Score": "3"
}
},
{
"body": "<p>I agree with @CarySwoveland that you should build the string correctly instead of manipulating it with string substitutions afterwards. However, I would make one exception to strip a <code>+</code> from the leading coefficient using a string substitution because it's simple and robust in the case of degenerate situations where it takes some work to determine the leading coefficient, such as <code>@coefficients = [0, 1, 0]</code>.</p>\n\n<p>I'd write it this way:</p>\n\n<pre><code> def to_s(var='x')\n return '0' if @coefficients.all?(&:zero?)\n @coefficients.each_with_index\n .find_all { |coeff, power| coeff != 0 }\n .reverse \n .map do |coeff, power|\n (\n (coeff == -1 && power != 0) ? '- ' :\n (coeff == +1 && power != 0) ? '+ ' :\n (coeff < 0) ? \"- #{-coeff}\" : \"+ #{coeff}\"\n ) + (\n case power\n when 0; ''\n when 1; var\n else; \"#{var}^#{power}\"\n end\n )\n end\n .join(' ')\n .sub(/\\A\\+ /, '')\n end\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T09:37:45.213",
"Id": "39131",
"ParentId": "37207",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37209",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:22:37.330",
"Id": "37207",
"Score": "4",
"Tags": [
"ruby",
"regex"
],
"Title": "Representing a long regular expression in a Polynomial class"
}
|
37207
|
<p>For a WPF application, I have to sort the items in <code>ObservableCollection</code> after Added new item. </p>
<pre><code>public void UpdateSource(ObservableCollection<SomeType> source, SomeType newItem)
{
source.Add(newItem);
SortSource(source, newItem);
}
private void SortSource(ObservableCollection<SomeType> source, SomeType item)
{
var oldIndex = source.IndexOf(item);
var list = source.OrderBy(_=>_.SomeProperty).ToList();
var newIndex = list.IndexOf(item);
source.Move(oldIndex, newIndex);
}
</code></pre>
<p>In order to keep the observable functionality for binding element, the <code>ObservableCollection</code> reference cannot be changed, so I used an assistance list to help me sort the souce.</p>
<p>Any improvement about this?</p>
|
[] |
[
{
"body": "<p>Your code unnecessarily sorts the whole collection on each insert (which is likely going to be O(n log n)). It also produces two events for each insert (one for <code>Add</code> and one for <code>Move</code>), which also isn't necessary.</p>\n\n<p>What I would do:</p>\n\n<ol>\n<li>Find the index where the inserted item belongs.</li>\n<li>Insert the item at that index.</li>\n</ol>\n\n<p>A simple implementation for that could look like this:</p>\n\n<pre><code>public static void AddSorted<T>(this IList<T> list, T item, IComparer<T> comparer = null)\n{\n if (comparer == null)\n comparer = Comparer<T>.Default;\n\n int i = 0;\n while (i < list.Count && comparer.Compare(list[i], item) < 0)\n i++;\n\n list.Insert(i, item);\n}\n</code></pre>\n\n<p>This could be made faster by using binary search to find the index. Though the total complexity is still going to be O(n), even with binary search, because <code>Insert</code> is O(n) (it has to move all items after the inserted item).</p>\n\n<p>This means that using binary search would help the most if you're often inserting items at or near the end of the collection.</p>\n\n<hr>\n\n<p>Other notes about your code:</p>\n\n<pre><code>public void UpdateSource(ObservableCollection<SomeType> source, SomeType newItem)\n</code></pre>\n\n<p>I don't think <code>Update</code> is the right name here, this is not a general update, something like <code>AddToSource</code> would be better.</p>\n\n<pre><code>source.OrderBy(_=>_.SomeProperty)\n</code></pre>\n\n<p><code>_</code> as a parameter name of a lambda is commonly used when you don't care about the value of that parameter. If you do care about it (like here), use something like <code>x</code>, or, even better, a meaningful name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T10:25:15.130",
"Id": "37211",
"ParentId": "37208",
"Score": "29"
}
}
] |
{
"AcceptedAnswerId": "37211",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T09:32:51.680",
"Id": "37208",
"Score": "19",
"Tags": [
"c#",
"wpf"
],
"Title": "Sort ObservableCollection after added new item"
}
|
37208
|
<p>Please review my code and let me know of any additions or modifications that would make this even more useable.</p>
<p>The initial idea was to create a simple Time class that has only one function: To represent an instant in time. </p>
<p>I've created this mainly because I found NodaTime to be way more than I needed.</p>
<p>So here it is, the Time class:</p>
<pre><code>public class Time
{
private int _hour, _minute, _second;
public Time(int hour, int minute, int second)
{
Hour = hour;
Minute = minute;
Second = second;
}
#region ToString methods
public override string ToString() {
return string.Format("{0}:{1}:{2}", this.Hour.ToString().PadLeft(2, '0'), this.Minute.ToString().PadLeft(2, '0'), this.Second.ToString().PadLeft(2, '0'));
}
public string ToString(string format)
{
string preFormat = format.Replace("hh", "{0}")
.Replace("mm", "{1}")
.Replace("ss", "{2}")
.Replace("h", "{3}")
.Replace("m", "{4}")
.Replace("s", "{5}");
return string.Format(preFormat,
this.Hour.ToString().PadLeft(2, '0'),
this.Minute.ToString().PadLeft(2, '0'),
this.Second.ToString().PadLeft(2, '0'),
this.Hour.ToString(),
this.Minute.ToString(),
this.Second.ToString());
}
#endregion
#region Properties
public int Hour
{
get { return _hour; }
set
{
// fix out of range values
if (value < 0)
{
value = 24 - System.Math.Abs(value % 24);
}
if (value > 24)
{
value = System.Math.Abs(value % 24);
}
_hour = value;
}
}
public int Minute
{
get { return _minute; }
set
{
// fix out of range values
if (value < 0)
{
Hour -= (int)Math.Floor(System.Math.Abs((double)value / 60));
value = 60 - System.Math.Abs(value % 60);
}
if (value > 59)
{
Hour += System.Math.Abs((int)Math.Floor((double)value / 60));
value = System.Math.Abs(value % 60);
}
_minute = value;
}
}
public int Second
{
get { return _second; }
set
{
// fix out of range values
if (value < 0)
{
Minute -= (int)Math.Floor(System.Math.Abs((double)value / 60));
value = 60 - System.Math.Abs(value % 60);
}
if (value > 59)
{
Minute += System.Math.Abs((int)Math.Floor((double)value / 60));
value = System.Math.Abs(value % 60);
}
_second = value;
}
}
#endregion
#region Static Methods
/// <summary>
/// Parses a string in the form of 10:25:45 to a Time instance
/// </summary>
/// <param name="time">e.g. 10:25:45</param>
/// <param name="result">a boolean indicating the parsing succeeded</param>
/// <returns></returns>
public static bool TryParse(string time, out Time result)
{
Contract.Requires<ArgumentNullException>(time != null, "Can not parse null to Time");
var parts = time.Split(':');
int hour = 0;
int minute = 0;
int second = 0;
if (parts.Length > 0)
int.TryParse(parts[0], out hour);
if (parts.Length > 1)
int.TryParse(parts[1], out minute);
if (parts.Length > 2)
int.TryParse(parts[2], out second);
result = new Time(hour, minute, second);
return true;
}
/// <summary>
/// Parses a string in the form of 10:25:45 to a Time instance
/// </summary>
/// <param name="time">e.g. 10:25:45</param>
/// <returns>an instance of Time</returns>
public static Time Parse(string time)
{
Time output;
Time.TryParse(time, out output);
return output;
}
#endregion
#region Operators
public static implicit operator Time(string time)
{
return Time.Parse(time);
}
public static Time operator +(Time first, Time second)
{
return new Time(first._hour + second._hour, first.Minute + second.Minute, first.Second + second.Second);
}
public static Time operator -(Time first, Time second)
{
return new Time(first._hour - second._hour, first.Minute - second.Minute, first.Second - second.Second);
}
#endregion
}
</code></pre>
<p>My Unit tests to validate all it's functions:</p>
<pre><code>[TestClass]
public class TimeTests
{
[TestMethod]
public void CreateTimeFromString()
{
string timeString = "10:30:45";
Time time = Time.Parse(timeString);
Assert.IsTrue(time.Hour == 10 && time.Minute == 30 && time.Second == 45);
}
[TestMethod]
public void CreateEmptyTimeFromString()
{
string timeString = "";
Time time = Time.Parse(timeString);
Assert.IsTrue(time.Hour == 0 && time.Minute == 0 && time.Second == 0);
}
[TestMethod]
public void CreateTimeFromWeirdString()
{
string timeString = "8:7:9";
Time time = Time.Parse(timeString);
Assert.IsTrue(time.Hour == 8 && time.Minute == 7 && time.Second == 9);
}
[TestMethod]
public void CreateTimeFromWeirdButNotValidString()
{
string timeString = "not a time";
Time time = Time.Parse(timeString);
Assert.IsTrue(time.Hour == 0 && time.Minute == 0 && time.Second == 0);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CreateTimeFromNullString()
{
string timeString = null;
Time time = Time.Parse(timeString);
}
[TestMethod]
public void AddTimeInstancesTogether()
{
Time time = new Time(1, 2, 3);
time += new Time(1,2,3);
Assert.IsTrue(time.Hour == 2 && time.Minute == 4 && time.Second == 6);
}
[TestMethod]
public void SubtractTimeInstances()
{
Time time = new Time(1, 2, 3);
time -= new Time(1, 2, 3);
Assert.IsTrue(time.Hour == 0 && time.Minute == 0 && time.Second == 0);
}
[TestMethod]
public void TestInvalidTimeInstanceThroughSubtraction()
{
Time first = new Time(1, 0, 0);
first -= new Time(2, 1, 1);
Assert.IsTrue(first.Hour == 23 && first.Minute==59 && first.Second == 59);
}
[TestMethod]
public void TestStringDefaultFormat()
{
Time first = new Time(1, 0, 0);
Assert.IsTrue(first.ToString()=="01:00:00");
}
[TestMethod]
public void TestStringCustomFormat()
{
Time first = new Time(1, 0, 0);
Assert.IsTrue(first.ToString("hh:mm:ss h:m:s") == "01:00:00 1:0:0");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:11:52.783",
"Id": "61360",
"Score": "0",
"body": "Why are you doing this when there's already the System.DateTime type in C#?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:14:18.810",
"Id": "61362",
"Score": "0",
"body": "Because System.DateTime has way more functionality than a simple Time class. Way more then I need. This way there is no room for confusion in the code using the class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:18:54.163",
"Id": "61364",
"Score": "6",
"body": "No offense, but your code is a *LOT* more confusing than `DateTime.ParseExact(s, \"H:m:s\", null);`. It's also more likely to have bugs (like in your code 0h:30m:0s + 0h:30m:0s = 0h:0m:0s, but DateTime gets it right)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:22:20.920",
"Id": "61365",
"Score": "0",
"body": "I don't see how `Time.Parse(\"12:59\")` is more confusing then the DateTime alternative... `ParseExact(string,format)` would be an addition perhaps for the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:26:25.877",
"Id": "61367",
"Score": "0",
"body": "`Console.WriteLine(Time.Parse(\"0:30:0\") + Time.Parse(\"0:30:0\"));` prints `\"0:60:0\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:26:53.680",
"Id": "61368",
"Score": "0",
"body": "You're right, that's a bug. Thanks for pointing that out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:30:04.113",
"Id": "61369",
"Score": "1",
"body": "Also `Console.WriteLine(Time.Parse(\"1:0:0\") - Time.Parse(\"0:10:0\"));` prints `01:50:00`. But this is all missing the larger point. DateTime is well known and works. Why are you reinventing the wheel? DateTime does exactly what you want it to do, and unlike your code it does what you want it to do correctly. Please don't reinvent the wheel. It's not a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:34:52.113",
"Id": "61370",
"Score": "1",
"body": "Use TimeSpan structure to represent time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:41:28.753",
"Id": "61372",
"Score": "7",
"body": "@PeterKiss: Use a TimeSpan to represent a *duration* of time. Use DateTime to represent a *point in* time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:47:58.350",
"Id": "61373",
"Score": "2",
"body": "TimeSpan can be used to point a specific time (point in time is relative) like DateTime structure does with it's TimeOfDay property and also all .NET ORM mapper maps time SQL type to TimeSpan."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:51:26.707",
"Id": "61375",
"Score": "0",
"body": "The fact that there is so much discussion about this (not only here) leads me to think that none of the structures currently present in the .net framework is meant only to hold one instance of time. That is what lead me to making this class. Mike is right, I'm reinventing the wheel. I am tending to rewrite my class and make all calculations using the DateTime class instead of doing the calculations myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:59:34.200",
"Id": "61378",
"Score": "2",
"body": "Have a look at [Noda Time](http://nodatime.org/) - might have what you're after. (Not used it myself though so it might not...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:34:00.770",
"Id": "61455",
"Score": "2",
"body": "Regarding re-inventing the wheel... date and time is one of those topics which seems simple but is **incredibly** hard to get right. Therefore there is a lot of merit in attempting to roll your own, even if it's only to better appreciate the immense complexity of the subject - complexity which every software developer needs to be aware of."
}
] |
[
{
"body": "<pre><code>private int _hour, _minute, _second;\n</code></pre>\n\n<p>I'd suggest to not declare multiple variables in the same line for clarity.</p>\n\n<pre><code>private int _hour;\nprivate int _minute;\nprivate int _second;\n</code></pre>\n\n<p>In case you prefixed them so that they don't collide in the constructor, that's unnecessary, as you always get the parameter except if you use <code>this</code>.</p>\n\n<pre><code>private int value;\npublic Constructor(int value)\n{\n this.value = value;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public override string ToString() {\n return string.Format(\"{0}:{1}:{2}\", this.Hour.ToString().PadLeft(2, '0'), this.Minute.ToString().PadLeft(2, '0'), this.Second.ToString().PadLeft(2, '0'));\n}\n</code></pre>\n\n<p>You could use your own formatting method:</p>\n\n<pre><code>public override string ToString() {\n return ToString(\"hh:mm:ss\");\n}\n</code></pre>\n\n<hr>\n\n<p>Are you aware that your <code>TryParse</code> will never fail? That's a bad design, as other developers might implement it like this:</p>\n\n<pre><code>String userInput = ...;\nTime time;\nif (!Time.TryParse(userInput, out time))\n{\n // Will never happen!\n}\n</code></pre>\n\n<p>Either replace it with something different (like a <code>Parse</code> which states in it's documentation that it will never fail and instead return an 'empty' <code>Time</code>), or make it fail if it can't be parsed.</p>\n\n<p>At the moment there's no way to check for an error during parse (because input could have been \"00:00:00\", which is a valid time after all).</p>\n\n<hr>\n\n<p>Food for thoughts: Consider making the class immutable, as <code>DateTime</code> and <code>TimeSpan</code> are both immutable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:58:02.590",
"Id": "61384",
"Score": "5",
"body": "There is no official naming convention for private fields. I've seen no prefix, `_` and `m_`, and I think all are acceptable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:02:01.047",
"Id": "61386",
"Score": "0",
"body": "@svick: True, I just looked it up, private fields are exclusively excluded. Will rephrase that part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:31:16.017",
"Id": "61571",
"Score": "2",
"body": "@Bobby: It's somewhat shorter to write `_value = value` than `this.value = value`. Also the human brain tends to be better at pattern matching than scoping, so prefixed variables are easier to see as class members rather than having to \"parse\" the `this.` and make the connection from there. In the end I guess it comes down to personal preference."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:27:00.237",
"Id": "37219",
"ParentId": "37215",
"Score": "6"
}
},
{
"body": "<p>You are re-inventing a true and tested wheel. When doing so you need to remember that your wheel won't be as tested as the wheel everyone else is using, and thus more likely to hold hidden bugs. You also need to remember that your wheel looks exactly like every other wheel with no apparent benefit... Now, I can see how this would be useful if your usecase means you cannot implement the use of:</p>\n\n<ul>\n<li>An immutable or constant DateTime. You mentioned you needed something to represent an instance of any given time. By creating an immutable or a constant DateTime object you are now effectively representing a fixed instance of some time.</li>\n<li>A DateTime wrapper with a single read-only instance of a DateTime to make sure that once instantiated (and for as long as the wrapper reference does not change or is re-assigned) the internal DateTime will never change.</li>\n</ul>\n\n<p>Your code doesn't seem to meet these (admittedly, arbitrarily) bullet points. I'd love to discuss a specific user case for why you cannot use any of the aforementioned solutions - this is <em>CodeReview</em> afterall...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:38:49.830",
"Id": "37220",
"ParentId": "37215",
"Score": "3"
}
},
{
"body": "<p>I agree with others that to represent a point in time within a day, you should use <code>TimeSpan</code>, just like <code>DateTime.TimeOfDay</code> does. Or maybe a custom class that's a simple wrapper around <code>TimeSpan</code> (to forbid times outside of the [0, 24h) range).</p>\n\n<p>Anyway, here is my review of your code (I'm not going to repeat things mentioned by others):</p>\n\n<pre><code>public string ToString(string format)\n{\n string preFormat = format.Replace(\"hh\", \"{0}\")\n .Replace(\"mm\", \"{1}\")\n .Replace(\"ss\", \"{2}\")\n .Replace(\"h\", \"{3}\")\n .Replace(\"m\", \"{4}\")\n .Replace(\"s\", \"{5}\");\n return string.Format(preFormat, \n this.Hour.ToString().PadLeft(2, '0'), \n this.Minute.ToString().PadLeft(2, '0'), \n this.Second.ToString().PadLeft(2, '0'),\n this.Hour.ToString(),\n this.Minute.ToString(),\n this.Second.ToString());\n}\n</code></pre>\n\n<ul>\n<li><p>This code is pretty fragile (what if <code>format</code> already contains <code>{0}</code>? though that's probably quite unlikely) and also not general enough (how would you represent format like “19 h 36 min”?).</p></li>\n<li><p>I think you should use numeric format strings instead of <code>PadLeft()</code>, e.g. <code>{0:d2}</code>. When you do that, you can then omit all those <code>ToString()</code>s and also specify each property just once in the call to <code>Format()</code>.</p></li>\n<li><p>All those <code>Replace()</code>s produce some unnecessary garbage. If that becomes a problem, use a <code>StringBuilder</code> instead (it also has a <code>Replace()</code> method).</p></li>\n</ul>\n\n\n\n<pre><code>public int Hour\n{\n get { return _hour; }\n set\n {\n // fix out of range values\n if (value < 0)\n {\n value = 24 - System.Math.Abs(value % 24);\n }\n if (value > 24)\n {\n value = System.Math.Abs(value % 24);\n }\n\n _hour = value;\n }\n}\n</code></pre>\n\n<ul>\n<li><p>Are you sure you want to treat -12 and 36 exactly the same as 12? Consider making values outside of the allowed range into errors instead.</p>\n\n<p>If you want to support things like adding hours that overflows midnight, a method like <code>AddHours()</code> might be better than <code>time.Hours += x</code>.</p></li>\n<li><p>You can write just <code>Math</code>, no need to spell out the namespace.</p></li>\n<li><p>I don't see why are you using <code>Math.Abs()</code> so much. You already know the sign of the number, so you can just write <code>24 + value % 24</code> (when you know that <code>value</code> is negative) or <code>value % 24</code> (when you know that it's positive).</p></li>\n</ul>\n\n\n\n<pre><code>Minute -= (int)Math.Floor(System.Math.Abs((double)value / 60));\n</code></pre>\n\n<p>That's a mouthful. You could write just <code>Minute += value / 60</code> instead.</p>\n\n<pre><code>if (parts.Length > 0)\n int.TryParse(parts[0], out hour);\n</code></pre>\n\n<p>Does this mean that empty string is a valid time string? I'm not sure that's a good choice.</p>\n\n<pre><code>public static implicit operator Time(string time)\n</code></pre>\n\n<p>I'm not sure about this. Most types don't have such conversions, probably mostly because calling <code>Parse()</code> is more explicit. And you should use <code>TryParse()</code> most of the time anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:19:21.640",
"Id": "61598",
"Score": "0",
"body": "Thanks for the feedback. You've given me some new insights to think about and that's what I'm here for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:21:26.873",
"Id": "37250",
"ParentId": "37215",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T12:10:45.587",
"Id": "37215",
"Score": "6",
"Tags": [
"c#",
"unit-testing",
"datetime"
],
"Title": "Class that represents an instant in Time"
}
|
37215
|
<p>I received this question at a C++ programming interview:</p>
<pre><code>void memcpy(char* dst, const char* src, int numBytes)
{
int* wordDist = (int*)dst;
int* wordSrc = (int*)src;
int numWords = numBytes >> 2;
for (int i = 0; i < numWords; i++)
{
*wordDist++ = *wordSrc++;
}
int whatisleft = numBytes >> 2 - (numWords );
dst = (char*)wordDist;
src = (char*)wordSrc;
for (int i = 0 ; i <= whatisleft; i++);
{
*dst++ = *src++;
}
}
</code></pre>
<ol>
<li>What are portability issues? </li>
<li>At least 1 syntax error?</li>
<li>Algorithm considerations?</li>
</ol>
<p>Now I found that this line:</p>
<pre><code>int whatisleft = numBytes >> 2 - (numWords );
</code></pre>
<p>is wrong as it doesn't calculates the correct number of bytes left to copy.</p>
<p>The correct one should be:</p>
<pre><code>int numBytesInWord = (numWords << 2 );
int whatisleft = numBytes - numBytesInWord;
</code></pre>
<p>At the end, the copied <code>char</code> array is several characters shorter than the source.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T17:40:27.463",
"Id": "61415",
"Score": "0",
"body": "Use % instead of shift/subtract to get `whatisleft`. Shifts are best for logical operations not sums. The compiler may of course choose to use a shift at the machine level."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:07:17.483",
"Id": "61420",
"Score": "1",
"body": "CR isn't about \"find the errors in this piece of code\" - please see our [Help Center](http://www.codereview.stackexchange.com/help/on-topic)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:22:23.373",
"Id": "61799",
"Score": "1",
"body": "Teh biggest problem is `2`. Who said the size of integer is 2 bytes? You should be using `sizeof(int)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T19:49:15.453",
"Id": "99481",
"Score": "0",
"body": "@LokiAstari that's 4... right shift by 2 is dividing by 4 or the most common (but far from only possible) size of `int`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T20:02:48.800",
"Id": "99483",
"Score": "0",
"body": "@EmilyL.: Is it. I don't have a single machine with a sizeof(int) less than 8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T20:07:37.147",
"Id": "99484",
"Score": "1",
"body": "You're not using x86 or x86-64 at all? They all have `sizeof(int) == 4`..."
}
] |
[
{
"body": "<ul>\n<li>You are trying to re-assign a const.</li>\n<li>bit shift operator should be switched (and the whole <em>count bytes left</em>-algorithm is off)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:50:34.970",
"Id": "61382",
"Score": "0",
"body": "Why should it be switched?That calculation gives me number of bytes (chars) left after copy by word chunks is done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:55:55.497",
"Id": "61383",
"Score": "0",
"body": "i mean `>>` should be switched to `<<` as you said... didn't see that part of your post, sorry"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:48:19.950",
"Id": "37222",
"ParentId": "37221",
"Score": "1"
}
},
{
"body": "<p>There's a number of issues with this code:</p>\n\n<pre><code>int* wordDist = (int*)dst;\nint* wordSrc = (int*)src;\n</code></pre>\n\n<p>Even if this works on a given platform, it is definitely not portable. <code>int*</code> can often have more strict alignment requirements than <code>char*</code> - this is <em>technically</em> undefined behaviour.</p>\n\n<p>Further, <code>(int*)src;</code> is casting away <code>const</code>ness - always dangerous if you then modify the value somewhere in the rest of the function.</p>\n\n<pre><code>int numWords = numBytes >> 2; \n</code></pre>\n\n<p>This assumes that an <code>int</code> is 32 bit, which is again non-portable, and will of course be wrong on any platform where this isn't the case. This could be fixed by using:</p>\n\n<pre><code>int numWords = numBytes / sizeof(int);\n</code></pre>\n\n<p>However, the alignment issues mentioned previously still remain.</p>\n\n<p>This code:</p>\n\n<pre><code>int whatisleft = numBytes >> 2 - (numWords);\n</code></pre>\n\n<p>is completely wrong, as thanks to operator precedence, it is equivalent to <code>numBytes >> (2 - numWords)</code> which is likely to be negative, causing undefined behaviour. Also, one has to be careful regardless, and keep in mind the differences between an arithmetic right shift and a logical right shift. Again, technically, right shifts for signed values are implementation defined, and could potentially be either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T17:32:24.360",
"Id": "61410",
"Score": "1",
"body": "Your fix: `int numWords = numBytes >> (sizeof(int) / 2);` is wrong (try 8-bytes `int`s). It should be `numBytes / sizeof(int)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T22:06:26.557",
"Id": "61532",
"Score": "0",
"body": "@WilliamMorris You're 100% right, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:43:33.440",
"Id": "61553",
"Score": "0",
"body": "Should be `/` not `>>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T19:53:11.140",
"Id": "99482",
"Score": "0",
"body": "Fixed the bit count, but I'm a bit worried how many people get the right shift by two to be division by two when it in fact it's division by four. And by the fact that no one had noticed this in half a year."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:06:32.750",
"Id": "37223",
"ParentId": "37221",
"Score": "8"
}
},
{
"body": "<p>On the update :</p>\n\n<p>Notice the semi-colon at the end of the loop declaration : </p>\n\n<pre><code>for (i = 0 ; i < whatisleft; i++);\n</code></pre>\n\n<p>That's your syntax error : this loop does nothing since the semi-colon terminate it. </p>\n\n<pre><code>{\n *dst++ = *src++;\n\n\n}\n</code></pre>\n\n<p>The part of code that should be the loop's body is valid even if it's not in the loop, and therefore is executed once. (The brackets are valid, moreover they induce a local scope what can taken advantage of ).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:15:07.220",
"Id": "61391",
"Score": "0",
"body": "HaHa ,that's the typo ! +1 for the headsup :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T20:29:19.010",
"Id": "61824",
"Score": "2",
"body": "Where’s that a syntax error? Looks completely valid to me – algorithmically buggy, of course."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T14:10:51.130",
"Id": "37225",
"ParentId": "37221",
"Score": "4"
}
},
{
"body": "<p>Not mentioned elsewhere:</p>\n\n<h3>Source and destination can be pairwise unaligned</h3>\n\n<p>Which would force at least one unaligned write or unaligned read per word. Depending on platform this can cause a cpu exception, poor performance or be hardly noticeable. </p>\n\n<h3>Let the compiler do the job</h3>\n\n<p>A good optimising compiler will detect a memory copy and generate a fast sequence of instructions to do the copy. Just write a byte by byte copy and let the compiler worry about the details. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T17:48:36.530",
"Id": "56476",
"ParentId": "37221",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37223",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T13:39:29.710",
"Id": "37221",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"interview-questions"
],
"Title": "Are there any problems with this memcpy() implementation?"
}
|
37221
|
<p>Based on ASP.NET, ASP.NET MVC allows software developers to build a web application as a composition of three roles: </p>
<ol>
<li>Model
<ul>
<li>A model represents the state of a particular aspect of the application.</li>
</ul></li>
<li>Controller
<ul>
<li>A controller handles interactions and updates the model to reflect a change in state of the application, and then passes information to the view.</li>
</ul></li>
<li>View
<ul>
<li>A view accepts necessary information from the controller and renders a user interface to display that information.</li>
</ul></li>
</ol>
<p>In April 2009, the ASP.NET MVC source code was released under the Microsoft Public License (MS-PL).</p>
<p>ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with existing ASP.NET features. Some of these integrated features are master pages and membership-based authentication. </p>
<p>The MVC framework is defined in the System.Web.Mvc assembly.</p>
<p>The ASP.NET MVC Framework couples the models, views, and controllers using interface-based contracts, thereby allowing each component to be easily tested independently.</p>
<p><a href="http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework" rel="nofollow">ASP.NET MVC Framework as Told by Wikipedia</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T15:30:04.463",
"Id": "37229",
"Score": "0",
"Tags": null,
"Title": null
}
|
37229
|
Model-View-Controller for the ASP.NET framework
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T15:30:04.463",
"Id": "37230",
"Score": "0",
"Tags": null,
"Title": null
}
|
37230
|
<p>This is a console app I wrote for an end-of-chapter assignment in <em>Jumping into C++</em>. The parameters were for it to have a basic password system, and if you are eager, a multiple password / username system. I am going through this book completely on my own free will. It's not through a school assignment or whatnot.</p>
<p>It works quite well, but as I have a limited programming background, I wanted to post it here so any bad techniques or poor syntax could be brought to my attention.</p>
<pre><code>#include <iostream>
using namespace std;
string usrnam[] = { "admin", "user", "" };
string pasword[] = { "root", "default", ""};
string temp_pass;
string temp_usr;
bool loggedin;
int n = sizeof(usrnam) / sizeof(string);
int findPassword( string str[], int array_size, string query )
{
for ( int i = 0; i < array_size; i++ )
{
if ( str[i] == query )
{
return i;
}
}
}
int commandC()
{
int stage;
cout << "Enter '1' for calculator: ";
cin >> stage;
switch(stage)
{
case 1: {
cout << endl;
cout << "Not fully developed" << endl << endl;
}
}
cout << "_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-";
}
void login(string user, string pass){
if ( pass == pasword[findPassword(usrnam, n, user)] )
{
cout << "Logged in as " << user << endl << endl;
loggedin = true;
commandC();
}
}
void registerUser()
{
string answer;
cout << "No matches found in the database...would you like to make new account? (Y/N)";
cin >> answer;
if (answer == "y" || answer == "Y")
{
cout << "Please enter a username: ";
cin >> usrnam[n-1];
cout << "Please enter a password: ";
cin >> pasword[n-1];
login(usrnam[n-1],pasword[n-1]);
}
}
int main()
{
cout << "Enter username: ";
cin >> temp_usr;
cout << "Enter password; ";
cin >> temp_pass;
login(temp_usr,temp_pass);
if(!loggedin)
registerUser();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:39:06.987",
"Id": "61426",
"Score": "0",
"body": "is this `int n = sizeof(usrnam) / sizeof(string);` division, or are you initializing two variables on the same line?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:44:58.787",
"Id": "61432",
"Score": "0",
"body": "That is some code I found while looking around on the web to fix a problem I was having. It determines how many entries there are in the array \"usrnam\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:27:33.373",
"Id": "61451",
"Score": "3",
"body": "Learn from [Ken Thompson's regret](http://en.wikiquote.org/wiki/Kenneth_Thompson#Attributed): \"If I had to redesign UNIX, I'd spell creat with an e.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:33:57.897",
"Id": "61551",
"Score": "1",
"body": "@Malachi: It's a standard C idiom equivalent to int n = count(usrnam);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:28:45.180",
"Id": "61803",
"Score": "0",
"body": "You should **never** actually store the password. If your password DB falls into bad hands the bad people can then use the same passwords for other systems your users uses. So always hash your passwords before storing. That way even if your password DB is stolen nobody will know the actual password."
}
] |
[
{
"body": "<ul>\n<li><p>Try using <code>std::vector</code> instead of arrays. As a result, you'll not be required to keep track of the <code>array_size</code> in a separate variable like <code>n</code> in your case.</p>\n\n<p>Something like this:</p>\n\n<pre><code>std::vector<std::string> username;\nusername.push_back(\"admin\");\n//other entries go here\nstd::vector<std::string> password;\npassword.push_back(\"root\");\n//other entries go here\n</code></pre>\n\n<p>Then, the size of the <code>std::vector</code> is given by <code>size()</code>.</p></li>\n<li><p>Try to use proper names as variables. Avoid wrong spellings or short-names. Exact variable names make the code easy to understand, as the name represents the actual concept the variable is referring to.</p></li>\n<li><p>Also, in <code>registerUser()</code> the variable <code>answer</code> can just be a <code>char</code>. This will help in saving a little memory.\nLike:</p>\n\n<pre><code>char answer;\nstd::cin>>answer;\nif(answer=='y' || answer=='Y')\n{\n //code goes here\n}\n</code></pre></li>\n<li><p>In your code, the method <code>commandC()</code> is defined to return an <code>int</code>. But it doesn't do so. Make the return type <code>void</code> instead.</p>\n\n<pre><code>void CommandC()\n{\n //code goes here\n}\n</code></pre></li>\n<li><p>Also, the <code>main()</code> method is defined to return an <code>int</code> too. It is a good practice to declare it like that, but make sure to return an integer. 0 (zero) is preferred as it refers to successful completion of main().</p>\n\n<pre><code>int main()\n{\n //code goes here\n return 0; //indicates successful termination\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:43:45.327",
"Id": "61431",
"Score": "0",
"body": "I was aware of the misspellings, but I am glad you brought it up. Thanks for the suggestions as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:15:05.643",
"Id": "61446",
"Score": "0",
"body": "@Phaenomena I think you asked about `std` as I got a notification for the same. Nevertheless, `std` is a namespace which is like a scope resolver. Read more here: http://www.cplusplus.com/doc/tutorial/namespaces/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:25:15.767",
"Id": "61449",
"Score": "0",
"body": "I did, but I had a second thought that I could just Google it and not bother you xD Thanks anyhow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:28:16.410",
"Id": "61452",
"Score": "2",
"body": "@Phaenomena +1 :) Good to see your attitude to learn :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:55:33.180",
"Id": "61473",
"Score": "7",
"body": "This isn't Fortran. There's no reason to manage parallel arrays or vectors. Create a struct and then create a vector of that struct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T04:55:59.397",
"Id": "61581",
"Score": "1",
"body": "@jliv902 +1 Oh! I missed it. Thanks for reviewing the review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:31:49.163",
"Id": "61805",
"Score": "0",
"body": "If your program can not go wrong (ie there is no distinction between good and bad). Then it is best **not** to return anything from `main()`. As main is special the compiler will automatically add the `return 0;` for you and your non usage is an indication that the program has no failure state."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T20:39:31.687",
"Id": "61825",
"Score": "1",
"body": "@jiliv902: Or have a `map` that stores the passwords, indexed by user name."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:23:08.607",
"Id": "37239",
"ParentId": "37235",
"Score": "14"
}
},
{
"body": "<p>you should look at the way you are indenting your code, this piece of code almost confused me for a minute ( or two )</p>\n\n<pre><code>int findPassword( string str[], int array_size, string query )\n{\n for ( int i = 0; i < array_size; i++ )\n {\n if ( str[i] == query )\n {\n return i;\n }\n}\n}\n</code></pre>\n\n<p>it should look like this</p>\n\n<pre><code>int findPassword( string str[], int array_size, string query )\n{\n for ( int i = 0; i < array_size; i++ )\n {\n if ( str[i] == query )\n {\n return i;\n }\n }\n}\n</code></pre>\n\n<p>it is always good to keep your indentations straight (even thought you could write the code without them) it makes the code easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:40:47.500",
"Id": "61427",
"Score": "0",
"body": "It's indented flawlessly in my IDE, but something got messed up while formatting it into my post. xD Thanks for bringing it up though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:41:26.387",
"Id": "61428",
"Score": "0",
"body": "what about that integer declaration?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:43:06.823",
"Id": "61430",
"Score": "0",
"body": "Nevermind, I replied to your question"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:37:36.587",
"Id": "37242",
"ParentId": "37235",
"Score": "3"
}
},
{
"body": "<p>In the following:</p>\n\n<pre><code>int findPassword( string str[], int array_size, string query )\n{\n for ( int i = 0; i < array_size; i++ )\n {\n if ( str[i] == query )\n {\n return i;\n }\n}\n}\n</code></pre>\n\n<p>If you use std::vector as suggested by gargankit, or you use std::array, you would be able to take advantage of the range-based for loops in C++.\nInstead of:</p>\n\n<pre><code>for(int i = 0; i < array_size; ++i)\n{\n if(str[i] == query)\n {\n return i;\n }\n}\n</code></pre>\n\n<p>you would write</p>\n\n<pre><code>for(const auto & arrayElement : str)\n{\n if(arrayElement == query)\n {\n // note in this case arrayElement is a string, not\n // an integer index into the array, so this would\n // require changing the return type of findPassword\n return arrayElement;\n }\n}\n</code></pre>\n\n<p>The benefit of a range-based for loop is that you don't have to be concerned about the potential risk of stepping out of the bounds of the given container, in this case str.</p>\n\n<p>If you are feeling adventurous you might also look into using the standard algorithms included in the STL and calling either std::find_if, or std::any_of to find the array element you are looking for.</p>\n\n<p>For functions that you are writing which take parameters that you will not modify in the body of the function, prefer taking the parameters as const parameters to specify and enforce your intent not to modify those values.</p>\n\n<p>For example in:</p>\n\n<pre><code>void login(string user, string pass){\n if ( pass == pasword[findPassword(usrnam, n, user)] )\n {\n cout << \"Logged in as \" << user << endl << endl;\n loggedin = true;\n commandC();\n }\n}\n</code></pre>\n\n<p>You never modify the value of pass, and it would be particularly strange in this case if you did modify the password that the user was typing in. In such a case it is more clear and more correct to require pass be const in login:</p>\n\n<pre><code>void login(string user, const string pass){\n if ( pass == pasword[findPassword(usrnam, n, user)] )\n {\n cout << \"Logged in as \" << user << endl << endl;\n loggedin = true;\n commandC();\n }\n}\n</code></pre>\n\n<p>You can probably also do this to user, but that would require also making user const in the findPassword function.</p>\n\n<p>Also, for any variables that you pass along as const, consider passing them as \"const &\" so that you do not make any unnecessary copies of that data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:18:36.867",
"Id": "61448",
"Score": "2",
"body": "`pass` should actually be passed in as `const&`. If you're not modifying an object, doing this would avoid unnecessary copying."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:24:33.700",
"Id": "61512",
"Score": "0",
"body": "I attempted to change the findPassword loop, but it appears I am in \"C++98 mode\". I'm using Codeblocks. Should it be C++98 or should I change it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:31:28.413",
"Id": "61518",
"Score": "0",
"body": "If you can change it to C++11 you will be better off. C++11 is more modern and will help you develop better practices and habits that are up to date with the latest standard for C++. Also, the vast majority of C++11 still allows C++98 functionality so I doubt you'll run into too much trouble performing the exercises in your book even if the book is expecting C++98 as the compiler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:31:32.477",
"Id": "61519",
"Score": "0",
"body": "@Phaenomena: Range-based for-loops are only available in C++11. In C++98, you can still use iterators by doing `for (auto iter = container.begin(); iter != container.end(); ++iter) {}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:32:30.580",
"Id": "61520",
"Score": "0",
"body": "@Jamal auto however is in C++11 not C++98.\nSo the loop may look more like \n for(std::vector<int>::iterator iter = container.begin(); iter !- container.end(); ++iter) {}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:33:23.297",
"Id": "61521",
"Score": "0",
"body": "@YoungJohn: Oh yeah, you're right. :-) I'm still used to using `auto`, apparently."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:57:55.090",
"Id": "37245",
"ParentId": "37235",
"Score": "8"
}
},
{
"body": "<ul>\n<li><p>These are all being used as global variables:</p>\n\n<blockquote>\n<pre><code>string usrnam[] = { \"admin\", \"user\", \"\" };\nstring pasword[] = { \"root\", \"default\", \"\"};\n\nstring temp_pass;\nstring temp_usr;\n\nbool loggedin;\n\nint n = sizeof(usrnam) / sizeof(string);\n</code></pre>\n</blockquote>\n\n<p>This is bad practice because any of these variables can be modified anywhere at any time, which is a source of bugs and maintenance issues. Both of those initialized strings and <code>n</code> should be <code>const</code>, which will prevent them from being modified further.</p>\n\n<p>The rest of the variables should be declared in functions and possibly passed to other functions for use. This will allow you to keep track of how they're being used.</p></li>\n<li><p>Passing in a C-style array isn't preferred:</p>\n\n<blockquote>\n<pre><code>int findPassword( string str[], int array_size, string query ) {}\n</code></pre>\n</blockquote>\n\n<p>This will actually deprecate to a <em>pointer</em>, which is not what the user expects to happen. This is also common practice in C, but you're writing in C++.</p>\n\n<p>As @gargankit mentioned, prefer to use an STL container such as <code>std::vector</code> in place of all the C-style arrays to avoid this deprecation. It'll also no longer be necessary to pass in <code>array_size</code> since all STL containers know their sizes (accessible with the function <code>size()</code>).</p></li>\n<li><p><code>switch</code> seems needless here:</p>\n\n<blockquote>\n<pre><code>switch(stage)\n{\n case 1: {\n cout << endl;\n cout << \"Not fully developed\" << endl << endl;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>If you only have one <code>case</code>, just use an <code>if</code>:</p>\n\n<pre><code>if (stage == 1)\n{\n cout << endl;\n cout << \"Not fully developed\" << endl << endl;\n}\n</code></pre>\n\n<p>You could also make the body just one line, and with <code>\"\\n\"</code> instead of <code>std::endl</code>. <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">The latter also flushes the buffer, which takes longer</a>. No need to use it for every newline.</p>\n\n<pre><code>cout << \"\\nNot fully developed\\n\\n\";\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:21:38.763",
"Id": "61560",
"Score": "0",
"body": "I didn't notice that I copied you. Imitation is the best flattery, no? :-D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:24:52.627",
"Id": "61562",
"Score": "0",
"body": "@BitFiddlingCodeMonkey: No worries. :-) You didn't copy it *entirely*, plus you expanded on one of the variables quite effectively (minus the C-ness, haha). I merely pointed its wrongfulness and why it's wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:31:24.327",
"Id": "61564",
"Score": "0",
"body": "Thank you kindly. It is true what you say... every morning I wake up and say to myself, \"Why did you waste your life with C!\" ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:34:22.307",
"Id": "61566",
"Score": "1",
"body": "@BitFiddlingCodeMonkey: C still has its uses, and C++ is just another language. Fortunately for you, you could easily focus on algorithms rather than having to utilize the STL (although I personally like the STL and I don't do too well with my own algorithms at times)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:02:32.413",
"Id": "37246",
"ParentId": "37235",
"Score": "9"
}
},
{
"body": "<p>You have some compiler warnings:</p>\n\n<blockquote>\n<pre><code>$ clang++ -o console{,.cpp}\nconsole.cpp:24:1: warning: control may reach end of non-void function [-Wreturn-type]\n}\n^\nconsole.cpp:41:1: warning: control reaches end of non-void function [-Wreturn-type]\n}\n^\n2 warnings generated.\n</code></pre>\n</blockquote>\n\n<p>You have a segfault:</p>\n\n<blockquote>\n<pre><code>Enter username: a\nEnter password; b\nSegmentation fault: 11\n</code></pre>\n</blockquote>\n\n<p>For entering a wrong password, I wouldn't expect to be invited to create an account:</p>\n\n<blockquote>\n<pre><code>Enter username: user\nEnter password; WrongPassword\nNo matches found in the database...would you like to make new account? (Y/N)y\nPlease enter a username: admin\nPlease enter a password: LaxSecurity\n</code></pre>\n</blockquote>\n\n<p>If a password contains a space, weird things happen:</p>\n\n<blockquote>\n<pre><code>Enter username: user\nEnter password; correct y horse battery staple\nNo matches found in the database...would you like to make new account? (Y/N)Please enter a username: Please enter a password: Logged in as horse\n\nEnter '1' for calculator: _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:46:54.747",
"Id": "61498",
"Score": "0",
"body": "As for the first few problems, they may be fixed now as I've revised my code. The second \"problem\" isn't a problem at all, it's meant to be that way. And for the third problem, I'm currently working on a function that removes spaces from the input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:52:12.813",
"Id": "61501",
"Score": "3",
"body": "Stripping spaces is the wrong approach. Use `std::getline(std::cin, password)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:58:52.643",
"Id": "61503",
"Score": "0",
"body": "So do I need to change all my other \"cin >>\" statements now? I've read that mixing getline and cin is not the best thing to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:01:15.080",
"Id": "61504",
"Score": "0",
"body": "Well, you are expecting lines of input, not words, so they should all use `getline()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:07:47.780",
"Id": "61505",
"Score": "0",
"body": "I replaced the username and password inputs to getline, but I left the others with cin. Good enough I guess. It still seems to accept the whitespaces though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:38:06.237",
"Id": "61522",
"Score": "0",
"body": "@Phaenomena: You would just need `getline()` with your string inputs. `char`s and `int`s can still use `cin`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T19:50:09.450",
"Id": "37253",
"ParentId": "37235",
"Score": "12"
}
},
{
"body": "<p>You're using a lot of <code>global</code> variables, such as <code>bool loggedin;</code>. It's best to keep a variable's scope as small as possible. To make the scope smaller for <code>loggedin</code>, for example, remove this global declaration:</p>\n\n<pre><code>bool loggedin;\n</code></pre>\n\n<p>Do the following to the <code>login</code> function:</p>\n\n<pre><code>bool login(string user, string pass)\n{\n bool loggedin; // Make a local copy of this in login\n\n if(pass == pasword[findPassword(usrnam, n, user)])\n {\n cout << \"Logged in as \" << user << endl << endl;\n loggedin = true;\n commandC();\n }\n else\n {\n loggedin = false; // Always make sure variables are initialized to something\n }\n\n return loggedin; // Return this value to calling function\n}\n</code></pre>\n\n<p>Now you can call <code>login</code> like this:</p>\n\n<pre><code>int main()\n{ \n cout << \"Enter username: \";\n cin >> temp_usr;\n cout << \"Enter password; \";\n cin >> temp_pass;\n\n bool loggedin = login(temp_usr,temp_pass); // Make another local copy of loggedin in main\n\n if(!loggedin)\n registerUser();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:42:39.800",
"Id": "61524",
"Score": "0",
"body": "Regarding scope, you could just do `bool loggedin = login(temp_usr,temp_pass);` and remove the earlier declaration. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:51:32.167",
"Id": "61526",
"Score": "0",
"body": "@Jamal I'm paid by the line. ;-) Also, I have a heavy `C` background… so I'll blame that!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:53:54.773",
"Id": "61528",
"Score": "0",
"body": "Forgive me. Us humans are yet to truly understand the way of the code monkey. :-) And I have a C++ background (barely any C), so there's that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:56:17.280",
"Id": "61529",
"Score": "0",
"body": "@Jamal It's the convention, in C, to put all a function's variables at the top. I bet you'd cringe looking at the stuff I've written! :-))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:58:44.623",
"Id": "61530",
"Score": "0",
"body": "Eh, I'd just be bothered if there were a \"list\" of variables at the top of a function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T22:00:30.690",
"Id": "61531",
"Score": "0",
"body": "@Jamal Imagine declaring a variable at the top of a long function… and then not using it until the end. Insanity!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:40:16.540",
"Id": "61552",
"Score": "0",
"body": "@BitFiddlingCodeMonkey: If you're writing a long function in C, you're Doing It Wrong(TM)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:22:50.017",
"Id": "61561",
"Score": "0",
"body": "@Matt I'm talking about long by C standards, which I'm sure is quite short by other language's standards."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:34:35.057",
"Id": "37258",
"ParentId": "37235",
"Score": "7"
}
},
{
"body": "<p>In terms of best practice, you should keep in mind that passwords should never be stored raw, only as salted hashes. If you are going to ever write a program that will handle passwords in actual use (not just as a programming exercise), you really need to read <a href=\"https://crackstation.net/hashing-security.htm\">Salted Password Hashing - Doing it Right</a>. (Even if not, it's still a good read anyway.)</p>\n\n<p>The reason for this is not because your application necessarily needs to be secure, but to ensure someone doesn't hack your application and steal your users accounts for <em>other</em> services, because most people use the same username and password everywhere.</p>\n\n<p>Also, one other feature that would normally be needed is the ability to store the user data in a file and read it when it starts, so it can persist between sessions, although this too is probably beyond the scope of the excersise.</p>\n\n<p>With respect to other aspects of your code, it seems you are on the right track; everything else I can see has already been said by other users.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T14:04:06.837",
"Id": "61646",
"Score": "0",
"body": "+1 - In addition to the possibility of leaching username/passwords for other sites, this also falls into practice like your not practicing. Raw passwords (or passwords storage done wrong) should be avoided."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T22:51:47.477",
"Id": "37262",
"ParentId": "37235",
"Score": "6"
}
},
{
"body": "<p>Usually comment about this line (look it up in every other C++ review).</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Don't use C arrays. The C++ containers are much more useful. Every other answer has suggested you use <code>std::vector<std::string></code> as a replacement. That again is a terrible idea. Your main usage pattern is searching. Use a data structure that is designed to be searched. <code>std::map<std::string, std::string></code></p>\n\n<pre><code>string usrnam[] = { \"admin\", \"\", \"\" };\nstring pasword[] = { \"root\", \"default\", \"\"};\n\n// I would have used:\n\nstd::map<std::string, std::string> password = {{\"admin\",\"root\"},{\"user\",\"default\"}};\n</code></pre>\n\n<p>I can see putting the actual username/password in global scope (as it needs to be used from everywhere (not a great design but acceptable). But no other variables should be in the global scope they should be close to the point of usage.</p>\n\n<pre><code>string temp_pass;\nstring temp_usr;\n</code></pre>\n\n<p>This should have been const.\nYour current design did not allow for modification of the username/password so this should have been const. But if you use a standard C++ container this becomes superfluous.</p>\n\n<pre><code>int n = sizeof(usrnam) / sizeof(string);\n\n// Also note it is more traditional to write this as:\nint n = sizeof(usrnam) / sizeof(usrnam[0]);\n\n// This is because if you change the type of `usernam` this code is still\n// correct. In your version you would need to change the code in two places.\n</code></pre>\n\n<p>C++ requires you to return a value at the end of a function:</p>\n\n<pre><code>int findPassword( string str[], int array_size, string query )\n// This function does not return anything when the name is not\n// found. This will result in hard to find errors.\n</code></pre>\n\n<p>When dealing with user input read a line at a time then parse the line.</p>\n\n<pre><code>cin >> stage;\n\n// What happens if the user entered 1 12 <enter>\n// The next time you are looking for input then you will read 12\n// even though it is left over from this input.\n// \n// Users interact with the terminal in lines.\n// Because there input is not flushed until they hit `enter`\n// they will hit enter after their input. The program does not recognize\n// this and the operator>> does not remove the resulting '\\n' character\n// from the input. So if the next interaction with the user is getline()\n// you will mysteriously read an empty line even if the user enters text.\n</code></pre>\n\n<p>Always use a <code>break</code> at the end of <code>case</code>. The exception is so rare that it should be well documented with comments.</p>\n\n<p>Always put a <code>default</code> in a switch. Even if the default (throws an exception). An exception is better than the code blowing up because some other piece of code has changed.</p>\n\n<pre><code>switch(stage)\n{\n case 1: {\n cout << endl;\n cout << \"Not fully developed\" << endl << endl;\n }\n}\n</code></pre>\n\n<p>Password design.<br>\nAbsolutely <strong>NEVER</strong> store the plain text version of the password. Always use a one way hash <code>like md5</code> on the password and store the hash of the password.</p>\n\n<p>Many people use the same password on multiple systems. If you lose control of your passwords then your have compromised your customers security.</p>\n\n<p>So accept the password in plan text but always store it has a hash. You may also want to read up on slating the password first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:56:41.720",
"Id": "61814",
"Score": "0",
"body": "+1. Now it seems obvious that `std::map` is best for searching. My instinct still seems to be to almost always recommend `std::vector` in place of a C-style array (although my idea was a bit more general as I was mentioning why passing in a C-style array in C++ is not a good idea)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:50:59.557",
"Id": "37372",
"ParentId": "37235",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:03:25.813",
"Id": "37235",
"Score": "11",
"Tags": [
"c++",
"beginner",
"console",
"authentication"
],
"Title": "Basic password authentication system app"
}
|
37235
|
<p>Our instructor told us to create a basic Java program using everything we've learned in class thus far (basic prints, selection structures, looping, GUI, arrays, etc) and being a Pokemon fan, I decided to make a basic GUI Pokedex that lets the user search for the details of a particular starter Pokemon.</p>
<p>This program also asks the user if he wants to search by Pokemon type or by region of origin, just in case the user does not know the name of the Pokemon.</p>
<p>Here is the code I came up with and it runs:</p>
<pre><code>import javax.swing.*;
public class StarterPokedex {
public static void main(String[] args) {
String choice, desc=null, pokemon=null, searchBy=null, region=null, type=null, pokeNo=null, species=null, habitat=null;
choice = JOptionPane.showInputDialog(null, "Do you know the name of the Starter Pokemon you are looking for? (Yes/No)", "Welcome to the Starter Pokedex!", 3);
if (choice.equalsIgnoreCase("yes")) {
pokemon = JOptionPane.showInputDialog(null, "Enter the name of the Starter Pokemon: ", "Welcome to the Starter Pokedex!", JOptionPane.PLAIN_MESSAGE); }
else if (choice.equalsIgnoreCase("no")) {
searchBy = JOptionPane.showInputDialog(null, "Search by: 'type' or 'region'?", "Welcome to the Starter Pokedex!", 3);
if (searchBy.equalsIgnoreCase("type")) {
type = JOptionPane.showInputDialog(null, "Enter pokemon type: (Fire/Water/Grass)", "Welcome to the Starter Pokedex!", JOptionPane.PLAIN_MESSAGE);
if (type.equalsIgnoreCase("Fire")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are fire-type: \n\nCharmander \nCyndaquil \nTorchic \nChimchar \nTepig \nFennekin \n\nWhich Pokemon would you like to search?", "Fire-type Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else if (type.equalsIgnoreCase("Water")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are water-type: \n\nSquirtle \nTotodile \nMudkip \nPiplup \nOshawott \nFroakie \n\nWhich Pokemon would you like to search?", "Water-type Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else if (type.equalsIgnoreCase("Grass")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are grass-type: \n\nBulbasaur \nChikorita \nTreecko \nTurtwig \nSnivy \nChespin \n\nWhich Pokemon would you like to search?", "Grass-type Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else {
JOptionPane.showMessageDialog(null, "You entered an invalid keyword. Try again.", "Error!", 1); }
}
else if (searchBy.equalsIgnoreCase("region")) {
region = JOptionPane.showInputDialog(null, "Enter region: (Kanto/Johto/Hoenn/Sinnoh/Unova/Kalos)", "Welcome to the Starter Pokedex!", JOptionPane.PLAIN_MESSAGE);
if (region.equalsIgnoreCase("Kanto")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are from the Kanto region: \n\nBulbasaur \nCharmander \nSquirtle \n\nWhich Pokemon would you like to search?", "Kanto Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else if (region.equalsIgnoreCase("Johto")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are from the Johto region: \n\nChikorita \nCyndaquil \nTotodile \n\nWhich Pokemon would you like to search?", "Johto Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else if (region.equalsIgnoreCase("Hoenn")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are from the Hoenn region: \n\nTreecko \nTorchic \nMudkip \n\nWhich Pokemon would you like to search?", "Hoenn Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else if (region.equalsIgnoreCase("Sinnoh")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are from the Sinnoh region: \n\nTurtwig \nChimchar \nPiplup \n\nWhich Pokemon would you like to search?", "Sinnoh Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else if (region.equalsIgnoreCase("Unova")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are from the Unova region: \n\nSnivy \nTepig \nOshawott \n\nWhich Pokemon would you like to search?", "Unova Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else if (region.equalsIgnoreCase("Kalos")) {
pokemon = JOptionPane.showInputDialog(null, "Here are the list of Starter Pokemon that are from the Kalos region: \n\nChespin \nFennekin \nFroakie \n\nWhich Pokemon would you like to search?", "Kalos Starter Pokemon", JOptionPane.PLAIN_MESSAGE); }
else {
JOptionPane.showMessageDialog(null, "You entered an invalid keyword. Try again.", "Error!", 1); }
}
else {
JOptionPane.showMessageDialog(null,"You entered an invalid keyword. Try again.", "Error!", 1); }
}
else
JOptionPane.showMessageDialog(null,"You entered an invalid keyword. Try again.", "Error!", 1);
if (pokemon.equalsIgnoreCase("Bulbasaur")) {
region="Kanto";
pokeNo="001";
species="Seed";
type="Grass";
habitat="Grassland";
desc="A strange seed was planted on its back at birth. The plant sprouts and grows with this Pokémon.";
}
else if (pokemon.equalsIgnoreCase("Charmander")) {
region="Kanto";
pokeNo="004";
species="Lizard";
type="Fire";
habitat="Mountain";
desc="Obviously prefers hot places. When it rains, steam is said to spout from the tip of its tail.";
}
else if (pokemon.equalsIgnoreCase("Squirtle")) {
region="Kanto";
pokeNo="007";
species="Tiny turtle";
type="Water";
habitat="Water's-edge";
desc="After birth, its back swells and hardens into a shell. Powerfully sprays foam from its mouth.";
}
else if (pokemon.equalsIgnoreCase("Chikorita")) {
region="Johto";
pokeNo="152";
species="Leaf";
type="Grass";
habitat="Grassland";
desc="A sweet aroma gently wafts from the leaf on its head. It is docile and loves to soak up the sun's rays.";
}
else if (pokemon.equalsIgnoreCase("Cyndaquil")) {
region="Johto";
pokeNo="155";
species="Fire Mouse";
type="Fire";
habitat="Grassland";
desc="It is timid, and always curls itself up in a ball. If attacked, it flares up its back for protection.";
}
else if (pokemon.equalsIgnoreCase("Totodile")) {
region="Johto";
pokeNo="158";
species="Big Jaw";
type="Water";
habitat="Water's-edge";
desc="Its well-developed jaws are powerful and capable of crushing anything. Even its trainer must be careful.";
}
else if (pokemon.equalsIgnoreCase("Treecko")) {
region="Hoenn";
pokeNo="252";
species="Wood Gecko";
type="Grass";
habitat="Forest";
desc="Its well-developed jaws are powerful and capable of crushing anything. Even its trainer must be careful.";
}
else if (pokemon.equalsIgnoreCase("Torchic")) {
region="Hoenn";
pokeNo="255";
species="Chick";
type="Fire";
habitat="Grassland";
desc="A fire burns inside, so it feels very warm to hug. It launches fireballs of 1,800 degrees F.";
}
else if (pokemon.equalsIgnoreCase("Mudkip")) {
region="Hoenn";
pokeNo="258";
species="Mud Fish";
type="Water";
habitat="Water's-edge";
desc="The fin on MUDKIP's head acts as highly sensitive radar. Using this fin to sense movements of water and air, this POKÉMON can determine what is taking place around it without using its eyes.";
}
else if (pokemon.equalsIgnoreCase("Turtwig")) {
region="Sinnoh";
pokeNo="387";
species="Tiny Leaf";
type="Grass";
habitat="Lake-side";
desc="It undertakes photosynthesis with its body, making oxygen. The leaf on its head wilts if it is thirsty.";
}
else if (pokemon.equalsIgnoreCase("Chimchar")) {
region="Sinnoh";
pokeNo="390";
species="Chimp";
type="Fire";
habitat="Mountain";
desc="Its fiery rear end is fueled by gas made in its belly. Even rain can't extinguish the fire.";
}
else if (pokemon.equalsIgnoreCase("Piplup")) {
region="Sinnoh";
pokeNo="393";
species="Penguin";
type="Water";
habitat="Arctic";
desc="A poor walker, it often falls down. However, its strong pride makes it puff up its chest without a care.";
}
else if (pokemon.equalsIgnoreCase("Snivy")) {
region="Unova";
pokeNo="495";
species="Grass Snake";
type="Grass";
habitat="Forest";
desc="It is very intelligent and calm. Being exposed to lots of sunlight makes its movements swifter.";
}
else if (pokemon.equalsIgnoreCase("Tepig")) {
region="Unova";
pokeNo="498";
species="Fire Pig";
type="Fire";
habitat="Grassland";
desc="It can deftly dodge its foe's attacks while shooting fireballs from its nose. It roasts berries before it eats them.";
}
else if (pokemon.equalsIgnoreCase("Oshawott")) {
region="Unova";
pokeNo="501";
species="Sea Otter";
type="Water";
habitat="Unknown";
desc="The scalchop on its stomach isn't just used for battle - it can be used to break open hard berries as well.";
}
else if (pokemon.equalsIgnoreCase("Chespin")) {
region="Kalos";
pokeNo="650";
species="Spiny Nut";
type="Grass";
habitat="Unknown";
desc="The quills on its head are usually soft. When it flexes them, the points become so hard and sharp that they can pierce rock.";
}
else if (pokemon.equalsIgnoreCase("Fennekin")) {
region="Kalos";
pokeNo="653";
species="Fox";
type="Fire";
habitat="Unknown";
desc="Eating a twig fills it with energy, and its roomy ears give vent to air hotter than 390 degrees Fahrenheit.";
}
else if (pokemon.equalsIgnoreCase("Froakie")) {
region="Kalos";
pokeNo="656";
species="Foam Frog";
type="Water";
habitat="Unknown";
desc="It secretes flexible bubbles from its chest and back. The bubbles reduce the damage it would otherwise take when attacked.";
}
else {
JOptionPane.showMessageDialog(null, "No such Starter Pokemon exists. Try again."); }
JOptionPane.showMessageDialog(null, "Pokemon: " + pokemon + "\nRegion: " + region + "\nNational Pokemon #: " + pokeNo + "\nSpecies: " + species + "\nType: " + type + "\nHabitat: " + habitat + "\nDescription: " + desc, "Pokedex Results", 1);
}
}
</code></pre>
<p>I just wanted to ask for suggestions on how to improve this code. I know it looks sort of messy and I really wanted to make use of arrays, except for a program like this, it seems that I would be needing tables, but we haven't discussed that in class yet and we were advised not to get ahead of ourselves.</p>
<p>I wanted to use loops for this too, to make it a little more complex, but I have no idea where I can fit all that in.</p>
<p>Also, this is a really huge bulk of codes (the longest code I've written so far), and I am aware that in Java, the simpler the code, the more efficient it is to use. Is there any way I can simplify this code without having to stray from the basics and still getting my desired output?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:24:17.600",
"Id": "61422",
"Score": "2",
"body": "Have you learned about methods and classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:32:47.423",
"Id": "61423",
"Score": "5",
"body": "Where's Pikachu?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:35:18.553",
"Id": "61424",
"Score": "1",
"body": "@SimonAndréForsberg Yes. We've learned about creating methods and calling them in from a different class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:37:29.817",
"Id": "61425",
"Score": "0",
"body": "@retailcoder Haha! I was basing the results on the games. They are usually only the three basic types: fire, water and grass."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:54:31.100",
"Id": "61442",
"Score": "4",
"body": "\"we were advised not to get ahead of ourselves\" - please tell your teacher that the Code Review community respectfully disagrees with his methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:20:39.163",
"Id": "61559",
"Score": "0",
"body": "When I first read the title, my first thought was that it's probably actually 'Smartphone', and my XKCD substitution extension just replaced it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:07:00.260",
"Id": "62184",
"Score": "0",
"body": "@braindead feel free to mark an answer as \"accepted\", earns you a big +2 rep and a shiny new badge :)"
}
] |
[
{
"body": "<p>Your first problem that everything takes place in the <code>main</code> method. Much of the user interaction and initialization should be separated out into seperate methods to remove clutter.</p>\n\n<p>Then, you are confusing <em>data</em> with <em>code</em>. You have about a dozen snippets like:</p>\n\n<pre><code>else if (pokemon.equalsIgnoreCase(\"Totodile\")) {\n region=\"Johto\";\n pokeNo=\"158\";\n species=\"Big Jaw\";\n type=\"Water\";\n habitat=\"Water's-edge\";\n desc=\"Its well-developed jaws are powerful and capable of crushing anything. Even its trainer must be careful.\";\n}\n</code></pre>\n\n<p>First, we should create a <code>Pokemon</code> object that represents each Pokemon:</p>\n\n<pre><code>class Pokemon {\n final String name;\n final String region;\n final int pokeNo;\n final String species;\n final String type;\n final String habitat;\n final String description;\n\n Pokemon(String name,\n String region,\n int pokeNo,\n String species,\n String type,\n String habitat,\n String description) {\n this.name = name;\n this.region = region;\n this.pokeNo = pokeNo;\n this.species = species;\n this.type = type;\n this.habitat = habitat;\n this.description = description;\n }\n}\n</code></pre>\n\n<p>Such code is rather ugly in Java, but it will make our code cleaner in a moment.</p>\n\n<p>Next, we create a data structure that maps names to Pokemon objects. For now, we will require that proper capitalization of the name is used.</p>\n\n<pre><code>Map<String, Pokemon> pokemonsByName = new HashMap<String, Pokemon>();\n</code></pre>\n\n<p>then we can populate this data strucure, e.g.</p>\n\n<pre><code>pokemonsByName.put(\n \"Totodile\",\n new Pokemon(\n \"Totodile\",\n \"Johto\",\n 158,\n \"Big Jaw\",\n \"Water\",\n \"Water's-edge\",\n \"Its well-developed jaws are powerful and capable of crushing anything. \"\n + \"Even its trainer must be careful.\"\n )\n);\n</code></pre>\n\n<p>When we have done all of this for all Pokemon, we can query for Pokemons by name:</p>\n\n<pre><code>Pokemon requestedPokemon = pokemonsByName.get(pokemonName);\nif (requestedPokemon == null) {\n // no such Pokemon was found\n} else {\n // we have found a pokemon, so display it.\n}\n</code></pre>\n\n<p>But this makes our code longer! Why should we do this then? Well, as you add more and more Pokemon, you may not want to recompile your app each time. Instead, you might load all Pokemon stats from a CSV file at startup (there are open source libraries that will help you with this). Now you only have to edit the data file and restart the program in order to support new Pokemons.</p>\n\n<p>Then you can add further improvements. For example, there are only a limited number of Pokemon types. Instead of using a <code>String</code> (which could contain typos), we can use an <code>enum</code> (enumeration) that only supports certain values:</p>\n\n<pre><code>enum PokemonType {\n WATER, FIRE, GRASS;\n}\n</code></pre>\n\n<p>In the <code>Pokemon</code> class, you would then change the type of the <code>type</code> field from <code>String</code> to <code>PokemonType</code>. The constructor would then be invoked like</p>\n\n<pre><code>new Pokemon(\n ...,\n PokemonType.WATER, // instead of the string \"Water\"\n ...\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:42:33.923",
"Id": "61429",
"Score": "0",
"body": "I tried this method, actually! Except I don't really get Hashmaps yet and we haven't really discussed anything beyond Advance GUI in class. I particularly enjoy enum for being so handy but our instructor may not consider this code given that I strayed from what we were thought (the basics). This project is actually really just an application of what we've learned so far, but thank you for this comprehensive answer! Might make my own complete Pokedex in the near future using this one. Many thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:20:36.200",
"Id": "61486",
"Score": "0",
"body": "Would it be possible to use `enum` for all the PokemonType?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:22:54.383",
"Id": "61488",
"Score": "0",
"body": "@rolfl I don't quite understand that question. It is not possible to specify all properties of a Pokemon object via enums, as some are unique to the individual."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:27:01.343",
"Id": "61490",
"Score": "0",
"body": "@amon - I meant Pokemon Type, not PokemonType ... i.e. `public enum Pokemon { Totodile(\"Johto\",\"....\",....), Bulbasaur(\"...\",...), ....}` (with the correct Enum constructor, of course)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:29:31.623",
"Id": "61491",
"Score": "1",
"body": "@rolfl This would be possible, but I would advise against that. Not using an enum allows us to load the data from an external resource (e.g. a JSON document or CSV file), which is more flexible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:30:19.017",
"Id": "61492",
"Score": "0",
"body": "Fair point, well made."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:28:46.340",
"Id": "61563",
"Score": "0",
"body": "@rolfl however, it should probably be done as a singleton, with its construction limited exclusively to loading the pokemon types from the file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:32:02.917",
"Id": "61565",
"Score": "0",
"body": "Shouldn't this class actually be called `PokemonSpecies` or something like that? I would expect my `Pokemon` class to be the one that keeps track of hit points and moves known by the particular individual."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:35:48.807",
"Id": "37240",
"ParentId": "37238",
"Score": "13"
}
},
{
"body": "<p>Let's break down your inputs:</p>\n\n<ul>\n<li>Do you know the name of the Starter Pokemon you are looking for?\n<ul>\n<li><strong>Yes</strong>: Enter the name of the Starter Pokemon</li>\n<li><strong>No</strong>: Search by: 'type' or 'region'?\n<ul>\n<li><strong>Type</strong>: Enter pokemon type: (Fire/Water/Grass)</li>\n<li><strong>Region</strong>: Enter region: (Kanto/Johto/Hoenn/Sinnoh/Unova/Kalos)</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>Not very complex. What makes working with your code annoying, is all those if-else branches and the fact that you find an <code>else</code> branch several dozen lines under the <code>if</code> it belongs to.</p>\n\n<p><strong>Prompting for user input</strong> is one concern; put that in its own method - take a string for the title and another for the actual prompt, and an array of strings for validating the input; make that method return an empty string or a valid input.</p>\n\n<p>In your search prompts, you're listing types and regions - don't hard-code them into the prompt, fetch them from your data instead (whether that's an enum or a csv or some xml you grabbed from a web service).</p>\n\n<p>When you have a method that prompts for pokemons of a given type, take that type as a parameter, and fetch the pokemons that match that criteria instead of hard-coding them into your prompt string.</p>\n\n<p>Same for regions: take that as a parameter, and fetch the pokemons that match that criteria.</p>\n\n<p>This should leave you with much less redundant prompting code.</p>\n\n<p>Once you have the pokemon you want, take @amon's advice and just fetch the appropriate <code>Pokemon</code> object - don't mix code with data.</p>\n\n<p><sub>Sorry this isn't a code-oriented answer, I don't do much <a href=\"/questions/tagged/java\" class=\"post-tag\" title=\"show questions tagged 'java'\" rel=\"tag\">java</a> :)</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:36:41.790",
"Id": "61494",
"Score": "0",
"body": "I wonder if there's a web service that spits out XML-serialized pokemons..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:12:55.873",
"Id": "61546",
"Score": "0",
"body": "well, I found JSON: http://pokeapi.co/docs/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:20:38.553",
"Id": "61548",
"Score": "2",
"body": "and don't ask me why I even decided to look but you can query bulbapedia like this: http://bulbapedia.bulbagarden.net/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Bulbasaur (see http://www.mediawiki.org/wiki/API:Query#Sample_query)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:23:07.797",
"Id": "61549",
"Score": "0",
"body": "@IAmAlexAlright you're kidding me! Now I *have to* do something about that API!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:47:17.210",
"Id": "61554",
"Score": "0",
"body": "@retailcoder Am I seeing a weekly-challenge proposal in the near future?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T01:35:35.540",
"Id": "61567",
"Score": "0",
"body": "@SimonAndréForsberg This could be fun..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:41:00.727",
"Id": "61628",
"Score": "4",
"body": "Hey guys, I'm the creator of PokéAPI, if you need any help or support let me know. Also - if you find bugs or want to suggest any features then let me know!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:04:42.280",
"Id": "62183",
"Score": "0",
"body": "[weekend-challenge proposal here](http://meta.codereview.stackexchange.com/a/1284/23788)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:50:13.540",
"Id": "37243",
"ParentId": "37238",
"Score": "8"
}
},
{
"body": "<p>Look out for </p>\n\n<pre><code>if (pokemon.equalsIgnoreCase(\"Bulbasaur\")) {\n</code></pre>\n\n<p>This might produce a null pointer exception if it's not brought into the condition like this</p>\n\n<pre><code>if (pokemon != null && pokemon.equalsIgnoreCase(\"Bulbasaur\")) {\n</code></pre>\n\n<p>The actual answer for this potential problem is actually switching the comparison to </p>\n\n<pre><code>if (\"Bulbasaur\".equalsIgnoreCase(pokemon)) {\n</code></pre>\n\n<p>This way you can be sure that a String \"Bulbasaur\" will never be null and you can compare other stuff to it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T09:36:36.653",
"Id": "61616",
"Score": "1",
"body": "An `assert` is not triggered in production/release and as such are useless as a `null-check`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T09:37:08.050",
"Id": "61617",
"Score": "0",
"body": "Good point Max, I'll leave that out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T09:23:48.543",
"Id": "37295",
"ParentId": "37238",
"Score": "5"
}
},
{
"body": "<p>About nested <code>if</code> statements:</p>\n\n<pre><code>void f()\n{\n if(cond1) {\n ...\n }\n else if(cond2) {\n ...\n }\n else {\n\n }\n}\n</code></pre>\n\n<p>Can be rewritten as:</p>\n\n<pre><code>void f()\n{\n if(cond1) {\n ...\n return;\n }\n if(cond2) {\n ...\n return;\n }\n ...\n}\n</code></pre>\n\n<p>Which in my opinion is considerably more readable. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T00:34:20.070",
"Id": "44112",
"ParentId": "37238",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T18:06:07.557",
"Id": "37238",
"Score": "13",
"Tags": [
"java",
"beginner",
"pokemon"
],
"Title": "Basic Pokedex using if-else statements"
}
|
37238
|
<p>Another script that is used as a token to extract information from a 3rd party application, the application does other things in the background that I don't specifically know about. </p>
<p>This code does work inside the parent application and produces the expected output.</p>
<p>Is there a nicer way to write this code?</p>
<pre class="lang-vb prettyprint-override"><code>Public Function GetParameterXml()
GetParameterXml = _
"<Parameters>" &_
"<Parameter Value='Age' Code='A' Description='Age' Type='Combo' Tooltip='Would you like the newest or oldest Reason?'>" &_
" <Options>" &_
" <Option Code='O' Description='Oldest' Value='OLD' />" &_
" <Option Code='N' Description='Newest' Value='NEW' />" &_
" </Options>" &_
"</Parameter>" &_
"</Parameters>"
End Function
'Parameter Variables
Dim Age : Set Age = Parameters.Item( Bookmark , "Age" )
' PlaceHolder Variables
Dim oNodes
Dim oNode
Set oNodes = XmlDoc.SelectNodes("Record/CelloXml/Integration/Case/ServiceEvent")
'''stop here and look around
stop
If (Age.Value = "OLD") Then
For Each iNode in oNodes(0).childNodes
If iNode.nodeName = "Service" Then
For Each jNode in iNode.childNodes
If jNode.nodeName = "Comment" Then
ReturnData = ReturnData & jNode.text & MD & ""
End If
Next
End If
Next
If Len(ReturnData) > 0 Then
ReturnData = Left(ReturnData, Len(ReturnData) - Len(MD))
Else
ReturnData = ""
End if
ElseIf (Age.Value = "NEW") Then
For Each iNode in oNodes(oNodes.length - 1).childNodes
If iNode.nodeName = "Service" Then
For Each jNode in iNode.childNodes
If jNode.nodeName = "Comment" Then
ReturnData = ReturnData & jNode.text & MD & ""
End If
Next
End If
Next
If Len(ReturnData) > 0 Then
ReturnData = Left(ReturnData, Len(ReturnData) - Len(MD))
Else
ReturnData = ""
End If
Else
ReturnData = " Hit the Else Statement "
End If
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:08:46.217",
"Id": "61570",
"Score": "0",
"body": "What's `MD`? Is it declared anywhere?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T03:14:38.663",
"Id": "61574",
"Score": "0",
"body": "@retailcoder MD is a Delimiter used by the application for special formatting"
}
] |
[
{
"body": "<h3>Joined declaration & assignment</h3>\n<p>This isn't necessarily a <em>bad</em> use of the <code>:</code> instruction separator, but it did surprise me. Actually, I'd even give you a star on that one:</p>\n<blockquote>\n<pre><code>Dim Age : Set Age = Parameters.Item( Bookmark , "Age" )\n</code></pre>\n</blockquote>\n<p>Pretty much <em>any other use I can think of</em> of the <code>:</code> instruction separator is hindering readability. Here I find it's a clever way of joining declaration with assignment.</p>\n<p>However this:</p>\n<blockquote>\n<pre><code>Dim oNodes\nDim oNode\n\nSet oNodes = XmlDoc.SelectNodes("Record/CelloXml/Integration/Case/ServiceEvent")\n</code></pre>\n</blockquote>\n<p>Should then be written like this:</p>\n<pre><code>Dim xPath : xPath = "Record/CelloXml/Integration/Case/ServiceEvent"\nDim ServiceEventNodes : Set ServiceEventNodes = XmlDoc.SelectNodes(xPath)\n</code></pre>\n<p>I'm not going to mention I'm allergic to things like an "o" prefix to object variables' names (oops just did), but I think you'll agree with me that <code>ServiceEventNodes</code> is a much more descriptive name than <code>oNodes</code> can ever dream to be.</p>\n<p>I've skipped <code>oNode</code> here because.. I'll get there in a moment.</p>\n<hr />\n<blockquote>\n<pre><code>'''stop here and look around\n</code></pre>\n</blockquote>\n<p>I'll skip the <code>Stop</code> keyword and hope this isn't production code. This isn't a necessary comment, but it's well-placed - stop right here and look below, you've got <code>If...For...If...For...If</code> blocks nicely (!) nested here. I'd say <em>stop here and fill up your lungs with that horrible smell</em>, you've got two blocks of code that are rigorously identical, <em>except</em> for one tiny little thing; how about first deciding what the child nodes are, <em>and then</em> iterate them, regardless of <code>Age.Value</code>?</p>\n<pre><code>Dim ChildNodes\nSelect Case Age.Value\n Case "OLD":\n Set ChildNodes = ServiceEventNodes(0).childNodes\n Case "NEW":\n Set ChildNodes = ServiceEventNodes(ServiceEventNodes.length - 1).childNodes\n Case Else:\n Err.Raise 5 'invalid procedure call or argument\nEnd Select\n</code></pre>\n<p>Notice this is <strong>not</strong> allowing the code to run any further if there's an invalid input. Returning <code>" Hit the Else Statement "</code> <strong>is a dangerous thing to do</strong>, because it's a valid value that your function will return just as if everything went normal, and I don't know what that's used for, but I'm sure <code>" Hit the Else Statement "</code> doesn't quite belong in production data.</p>\n<p>That's why I'd rather throw an error and blow up than return a string that's actually an error message.</p>\n<hr />\n<p>That being settled, I believe both loops could be completely eliminated with a little XPath (untested; I <em>think</em> this would do it):</p>\n<pre><code>Dim CommentNodes : Set CommentNodes = ChildNodes.SelectNodes("Service/Comment")\n</code></pre>\n<p>Now that you've got the nodes you're after, you can iterate them:</p>\n<pre><code>Dim CommentNode\nFor Each CommentNode In CommentNodes\n ReturnData = ReturnData & CommentNode.Text & MD\nNext\n</code></pre>\n<p>I left out the <code>& ""</code> part, because that's concatenating an empty string, which does strictly nothing but add confusing clutter to your code.</p>\n<p>The last part:</p>\n<blockquote>\n<pre><code>If Len(ReturnData) > 0 Then\n ReturnData = Left(ReturnData, Len(ReturnData) - Len(MD))\nElse\n ReturnData = ""\nEnd If\n</code></pre>\n</blockquote>\n<p>Looks like it's working around the fact that you haven't properly declared and initialized <code>ReturnData</code> in the first place. If you put <code>Dim ReturnData : ReturnData = vbNullString</code> somewhere before the loop, then you don't need to assign it to an empty string if the loop resulted in a no-op.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T03:20:32.180",
"Id": "61575",
"Score": "0",
"body": "I like this. the reason for the weird if else stuff going on is... the structure of the XML that is being read in. there are multiple ServiceEvent Nodes with 1+ Service node where each one can have a comment, but sometimes they don't, if they do, return the text, even if there is more than one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T03:22:04.220",
"Id": "61576",
"Score": "0",
"body": "I was having a heck of a time trying to get the xPath to play nice with the VBScript on `Service/Comment` the way I wanted the Data. I am sure there hasn't been any testing by the Business Analysts yet, so I should be able to put this stuff into play, I will learn me to code VBScript sooner or later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T03:25:11.143",
"Id": "61577",
"Score": "0",
"body": "sorry for all the comments but I think it is relevant to the answer, this is not Production Code. and the only way to know about an exception is to have something returned via `ReturnData`. I work for the judicial system so this application creates forms (that are editable) and fills in the data. one line that I didn't include was the first line, `on error resume next`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:24:57.627",
"Id": "61653",
"Score": "1",
"body": "`ReturnData` is a Variable that is created and used by the application. I don't think that I should mess with that. Code for this is like coding with my nose because I have my hands tied behind my back."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:21:57.390",
"Id": "61663",
"Score": "0",
"body": "what if the `Comment` node Doesn't exist for that specific `Service` Node? I think that might be a dumb question. I am just trying to make sure I haven't changed the functionality of what I was doing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:25:58.783",
"Id": "61664",
"Score": "0",
"body": "@Malachi you make an XPath that selects all comment nodes, regardless of which \"service\" node they're under - that's the trick :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:26:57.087",
"Id": "61665",
"Score": "0",
"body": "but then it will grab comments from the other `ServiceEventNodes` right? and what if no Comment nodes exist?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:33:32.967",
"Id": "61666",
"Score": "0",
"body": "Hmm right. I'll edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:45:51.477",
"Id": "61667",
"Score": "0",
"body": "ok when I try running this, on `Set CommentNodes = ChildNodes.SelectNodes(\"Service/Comment\")` it gives me a runtime error: Object doesn't support this property or method: 'SelectNodes' that is the main reason why I went with the clunky For each loops and if statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:59:02.777",
"Id": "61668",
"Score": "1",
"body": "@Malachi Right. `ChildNodes` is a `IXMLDOMNodeList`, you need to iterate it once. Sorry :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T18:22:13.037",
"Id": "61671",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11958/discussion-between-malachi-and-retailcoder)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:33:15.677",
"Id": "37280",
"ParentId": "37254",
"Score": "3"
}
},
{
"body": "<p>Here is what I was able to come up with, thanks to @RetailCoder and some help on <a href=\"https://stackoverflow.com/questions/20617236/unknown-method-in-xpath-run-by-vbscript\">StackOverFlow</a> Dealing with the <code>last()</code> function/method not working I was able to add <code>xmlDoc.SetProperty \"SelectionLanguage\", \"XPath\"</code> to make it work for me. so here is how I simplified the whole process.</p>\n\n<ul>\n<li>I replaced my <code>If...For...If...For</code> loops with a single switch statement and some XPath statements to grab the correct nodes</li>\n<li>I don't have to worry about if the <code>Comment</code> node exists or not, if <code>ReturnData</code> is empty it is taken care of by the last If statement.</li>\n<li>Removed the <code>& \"\"</code> like @retailcoder said \n\n<blockquote>\n <p>I left out the <code>& \"\"</code> part, because that's concatenating an empty string, which does strictly nothing but add confusing clutter to your code.</p>\n</blockquote></li>\n<li>There isn't anywhere to use the Joined Declaration & Assignment, the <code>CommentNodes</code> variable is set differently based on the Switch statement and Declaring it in both would be redundant.</li>\n<li>I didn't add a <code>Case Else</code> the way this script functions it is not necessary to follow this path should they input a bad parameter, the application of this script is hard to describe. it is one of many tokens in a word document.</li>\n<li>one last thing, I only declared variables that I used in the rest of the script, the original had <code>oNode</code> and it was never used.</li>\n<li>I also didn't use any <code>Magic</code> iterator numbers like <code>iNode</code> or <code>jNode</code> even though I thought that was rather clever.</li>\n</ul>\n\n\n\n<hr>\n\n<pre><code>Public Function GetParameterXml()\n GetParameterXml = _\n \"<Parameters>\" &_\n \"<Parameter Value='Age' Code='A' Description='Age' Type='Combo' Tooltip='Would you like the newest or oldest Reason?'>\" &_\n \" <Options>\" &_\n \" <Option Code='O' Description='Oldest' Value='OLD' />\" &_\n \" <Option Code='N' Description='Newest' Value='NEW' />\" &_\n \" </Options>\" &_\n \"</Parameter>\" &_\n \"</Parameters>\"\nEnd Function\n\n'Parameter Variables\nDim Age : Set Age = Parameters.Item( Bookmark , \"Age\" )\n\n' PlaceHolder Variables\nDim CommentNodes\n\n''' stop here and look around\nstop\n\nxmlDoc.SetProperty \"SelectionLanguage\", \"XPath\"\n\nSelect Case Age.Value\n Case \"OLD\":\n Set CommentNodes = XmlDoc.SelectNodes(\"Record/CelloXml/Integration/Case/ServiceEvent[1]/Service/Comment\")\n Case \"NEW\":\n Set CommentNodes = XmlDoc.SelectNodes(\"/Record/CelloXml/Integration/Case/ServiceEvent[position() = last()]/Service/Comment\")\nEnd Select\n\nFor Each CommentNode In CommentNodes\n ReturnData = ReturnData & CommentNode.Text & MD\nNext\n\nIf Len(ReturnData) > 0 Then\n ReturnData = Left(ReturnData, Len(ReturnData) - Len(MD))\nElse\n ReturnData = vbNullString \nEnd If \n</code></pre>\n\n<p>Obviously I am going to remove the breakpoint when I put this into production. but I think this really cleaned up the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:35:54.557",
"Id": "37547",
"ParentId": "37254",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37547",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T20:20:17.647",
"Id": "37254",
"Score": "2",
"Tags": [
"vbscript"
],
"Title": "pulling specific data from XML from inside 3rd party application"
}
|
37254
|
<p>Minecraft is a game which also has multiplayer capabilities. You need to have an account (which needs to be verified) for playing on servers. The authentication procedure looks like this:</p>
<ol>
<li>Authenticate at the Mojang (creators of Minecraft) server with username and password</li>
<li>Retrieve a session id</li>
<li>Contact the server you want to play on and send your username and session id (for verification that you own that name)</li>
<li>Send every 5 minutes a keep-alive request to the Mojang server so that the id does not timeout</li>
</ol>
<p>This class is supposed to handle step 1, 2 and 4.</p>
<p>The class is used like this:</p>
<pre><code>Authentication authentication = new Authentication(username, password);
AuthenticationResponse response = AuthenticationResponse.UNKNOWN;
try {
response = authentication.authenticate();
} catch (UnsupportedEncodingException ex) {
LOGGER.log(Level.SEVERE, "Authentication failed!", ex);
} catch (MalformedURLException ex) {
LOGGER.log(Level.SEVERE, "Authentication failed!", ex);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Authentication failed!", ex);
}
if (response == AuthenticationResponse.SUCCESS) {
// Do something with the session id (authentication.getSessionId())
}
</code></pre>
<p>What you need to know along the way:</p>
<ul>
<li><code>Credentials</code> is a simple mutable container for a username and a password</li>
<li><code>AuthenticationResponse</code> is an enum</li>
<li>I designed it with the thought to give complete control to the client, that's why every single field is exposed to be changed</li>
</ul>
<p>Here's the code:</p>
<pre><code>package org.bonsaimind.minecraftmiddleknife.pre16;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.bonsaimind.minecraftmiddleknife.Credentials;
/**
* Deals with the authentication at the Mojang, or any other server.
*/
public class Authentication extends Credentials {
/**
* The default version which will be reported.
*/
public static final String LAUNCHER_VERSION = "884";
/**
* The addressof the Mojang server.
*/
public static final String MOJANG_SERVER = "https://login.minecraft.net";
private long currentVersion;
private String deprecated;
private boolean keepAliveUsesRealUsername = true;
private String realUsername;
private String server = MOJANG_SERVER;
private String sessionId;
private String userId;
private String version = LAUNCHER_VERSION;
public Authentication() {
}
public Authentication(Credentials credentials) {
super(credentials.getUsername(), credentials.getPassword());
}
public Authentication(String username, String password) {
super(username, password);
}
public Authentication(String server, String version, String username, String password) {
super(username, password);
this.server = server;
this.version = version;
}
/**
* Do the authentication.
* @return
* @throws UnsupportedEncodingException
* @throws MalformedURLException
* @throws IOException
*/
public AuthenticationResponse authenticate() throws UnsupportedEncodingException, MalformedURLException, IOException {
String request = String.format(
"user=%s&password=%s&version=%s",
URLEncoder.encode(getUsername(), "UTF-8"),
URLEncoder.encode(getPassword(), "UTF-8"),
URLEncoder.encode(getVersion(), "UTF-8"));
String response = httpRequest(getServer(), request);
String[] splitted = response.split(":");
if (splitted.length < 5) {
return AuthenticationResponse.getResponse(response);
}
currentVersion = Long.parseLong(splitted[0]);
deprecated = splitted[1];
realUsername = splitted[2];
sessionId = splitted[3];
userId = splitted[4];
return AuthenticationResponse.SUCCESS;
}
/**
* Returns the current version of Minecraft.
* @return The current version.
*/
public long getCurrentVersion() {
return currentVersion;
}
/**
* The DEPRECATED field of the login response, should always be "DEPRECATED".
* @return Nothing useful.
*/
public String getDeprecated() {
return deprecated;
}
/**
* Returns true of the keep-alive will be using the real username returned
* by the authentication server.
* @return If keep-alive uses the real username.
*/
public boolean isKeepAliveUsesRealUsername() {
return keepAliveUsesRealUsername;
}
/**
* Returns the real username (case corrected f.e.).
* @return The real username.
*/
public String getRealUsername() {
return realUsername;
}
/**
* Returns the server which will be used for authentication. Default value
* is the Mojang server.
* @return The server.
*/
public String getServer() {
return server;
}
/**
* Returns the session ID as acquired by the login process.
* @return The Session ID.
*/
public String getSessionId() {
return sessionId;
}
/**
* Returns the user ID as acquired by the login process.
* @return The user ID.
*/
public String getUserId() {
return userId;
}
/**
* Returns the version (of the launcher) which will be reported to
* the server. Default value is the default one.
* @return The launcher version.
*/
public String getVersion() {
return version;
}
/**
* Sends a keep-alive to the authentication server so that the session
* does not expire.
* @throws UnsupportedEncodingException
* @throws MalformedURLException
* @throws IOException
*/
public void keepAlive() throws UnsupportedEncodingException, MalformedURLException, IOException {
String request = String.format(
"?name={0}&session={1}",
URLEncoder.encode(isKeepAliveUsesRealUsername() ? getRealUsername() : getUsername(), "UTF-8"),
URLEncoder.encode(getSessionId(), "UTF-8"));
httpRequest(getServer(), request);
}
/**
* Determines if the keepa-live uses the real username returned by
* the authentication server or the username set by the user.
* @param keepAliveUsesRealUsername If keep-alive uses the real username.
*/
public void setKeepAliveUsesRealUsername(boolean keepAliveUsesRealUsername) {
this.keepAliveUsesRealUsername = keepAliveUsesRealUsername;
}
/**
* Set the real username, this is most likely returned by the auth server.
* @param realUsername The real username.
*/
public void setRealUsername(String realUsername) {
this.realUsername = realUsername;
}
/**
* Set the session id, used for keep-alive.
* @param sessionId The session id.
*/
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
/**
* Set the server which will be used for authentication.
* @param server The (full) address of the server.
*/
public void setServer(String server) {
this.server = server;
}
/**
* Set the version (of the launcher) which will be reported to
* the authentication server. This should be a valid int, even
* though it is a string.
* @param version The version of the launcher, a valid int would be nice.
*/
public void setVersion(String version) {
this.version = version;
}
private static String httpRequest(String url, String content) throws UnsupportedEncodingException, MalformedURLException, IOException {
byte[] contentBytes = content.getBytes("UTF-8");
URLConnection connection = new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(contentBytes.length));
OutputStream requestStream = connection.getOutputStream();
requestStream.write(contentBytes, 0, contentBytes.length);
requestStream.close();
String response = "";
BufferedReader responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
response = responseStream.readLine();
responseStream.close();
return response;
}
}
</code></pre>
<p>The problems I see with this are:</p>
<ul>
<li>I need to improve my JavaDoc skills as fast as possible</li>
<li>The inheriting <code>Credentials</code> might be a stupid idea</li>
<li>Handling all these values feels messy</li>
<li>I just realized that handling feels odd overall</li>
</ul>
<p>I'm a little bit stuck in my own head when it comes to the design of this class, any ideas?</p>
<p>Full source code is available <a href="https://github.com/RobertZenz/MinecraftMiddleKnife" rel="nofollow">at the GitHub repository</a>.</p>
|
[] |
[
{
"body": "<p>The logic and data encapsulation are a little disconnected here. I think it may because I have misunderstood where this class fits in to your class hierarchy.... but I don't think so. There are a few things I don't like:</p>\n\n<ul>\n<li>This Authenticate is really a 'AuthenticatedSession' and not a special type of Credential. i.e. this class <strong>uses</strong> a credential to create a <strong>session</strong>, and then it keeps that session alive.</li>\n<li>Why do you have so many constructors?</li>\n<li>you say that this class takes care of the 5-minute keep-alive, but all I see is a method and no timer</li>\n<li>I would expect this class to be immutable - no setters should be necessary .... will the login details and login server change at all?</li>\n<li>The httpRequest throws too many exceptions. I would catch all the exceptions in httpRequest and throw a single custom exception (initialized with the right cause) like <code>AuthenticationException</code></li>\n</ul>\n\n<p>So, from the context you provide, I would have called this something like an <code>AutheticatedSession</code>, and I would have a factory method on it that takes a server, and credential as parameters. There should be no need to 'remember' the credentials after the initial login.</p>\n\n<p>Given the challenge:</p>\n\n<blockquote>\n <p>Create a session logged in to an authentication server, that requires a regular heartbeat, and provides some additional data about the user.</p>\n</blockquote>\n\n<p>I would have a class something like:</p>\n\n<pre><code>public class AuthenticatedSession {\n\n /**\n * Factory method to create AuthenticatedSession instances.\n */\n public static AuthenticatedSession connect(String serverurl, Credential credential) throws AuthenticationException {\n\n // do the work of setting up the right URL and content.\n String response = httpRequest(serverurl, content);\n\n // use the string to build your AuthenticatedSession...\n return new AuthenticatedSession(....session details....);\n }\n\n // this timer will run the heart-beat.\n private static final ScheduledThreadPoolExecutor TIMEDEXECUTOR = new ScheduledThreadPoolExecutor (1);\n\n // This is the runnable instance that will sit in the timer schedule\n private final class KeepAlive implements Runnable {\n public void run() {\n // call the keepalive method on the main class.\n // if keepalive throws an exception it will stop this timer thread.\n keepAlive();\n }\n }\n\n\n // if a heartbeat fails, will be set false.\n private final AtomicBoolean linkAlive = new AtomicBoolean(true);\n private final String hbserver;\n private final String hbcontent;\n private final ...... // all the fields that are supplied by the server.\n\n // private constructor, called by the factory.\n private AuthenticatedSession(String .... all the fields that are supplied by the server) {\n this. ... fields = input fields;\n\n this.hbserver = ...; // details for the heartbeat URL\n this.hbcontent = ...; // details for the heartbeat Content. \n // start the keepalive.\n TIMEDEXECUTOR.scheduleAtFixedRate(new KeepAlive(), long 5, long 5, TimeUnit.MINUTE);\n }\n\n public boolean isAlive() {\n return linkAlive.get();\n }\n\n // the heartbeat can be private.\n private void heartBeat() {\n try {\n httpRequest(hbserver, hbcontent);\n } catch (AuthenticationException afe) {\n // need to throw an exception so that the timer on the heartbeat thread stops.\n // communicate the session is dead.\n linkActive.set(false);\n throw new IllegalStateException(\"Unable to renew session\", ioe);\n }\n }\n\n public String get....() {\n // have getters for the session's values (real name, etc.)\n }\n}\n</code></pre>\n\n<p>The advantages of this class are that:</p>\n\n<ul>\n<li>it is self-contained</li>\n<li>it is immutable, and thus fully thread-safe</li>\n<li>it is self-managing - no need for external intervention to keep-alive</li>\n<li>it does not hang on to unnecessary data (credentials).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:24:43.927",
"Id": "37270",
"ParentId": "37259",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37270",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T21:51:48.770",
"Id": "37259",
"Score": "7",
"Tags": [
"java",
"authentication"
],
"Title": "Authenticating with the official Mojang (Minecraft) server"
}
|
37259
|
<p>The following is used to create a masonry effect with varying height rectangles. How can I simplify and make this more elegant in Unity?</p>
<pre><code>private float startX = 0.0f;
private float startY = 0.0f;
private float posX = 0.0f;
private float posY = 0.0f;
private float prevWidth = 0;
private float prevHeight = 0;
private int index = 0;
private int currentCol = 0;
private void AddCard(int index, int col, float width, float height)
{
GameObject goCard = (GameObject)GameObject.Instantiate(pfCard00);
PackedSprite psCard = goCard.GetComponentInChildren<PackedSprite>();
goCard.name = "QuestItemCard" + index.ToString();
goCard.transform.parent = goCardContainer.transform;
psCard.height = height;
if (currentCol != col)
{
posX += width;
posY = 0;
prevHeight = 0;
}
// placement
posY += (prevHeight / 2) + (height / 2);
goCard.transform.localPosition = new Vector3(startX + posX, startY - posY, goCard.transform.position.z);
if (currentCol != col)
{
prevWidth = width;
currentCol = col;
}
prevHeight = height;
}
</code></pre>
<p>Usage:</p>
<pre><code>AddCard(0, 0, 100, 100);
AddCard(1, 0, 100, 100);
AddCard(2, 0, 100, 100);
AddCard(3, 0, 100, 200);
AddCard(4, 1, 100, 100);
AddCard(5, 1, 100, 100);
AddCard(6, 1, 100, 100);
AddCard(7, 1, 100, 200);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T05:52:09.030",
"Id": "62870",
"Score": "0",
"body": "A couple of questions before answering: Do you want gaps? It looks like the taller cards at the end (#3 and #7) will lift the next row by 100 units leaving a gap. Is it possible to have varying height cards in one row? And what do you want to do with the indices? you're not using them now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T11:38:17.323",
"Id": "84283",
"Score": "0",
"body": "A good start would be making index a static field and incrementing it each time you call AddCard. Then you don't have to pass that value in at all (or remember it somewhere)"
}
] |
[
{
"body": "<p>Consider splitting the code that increments the column into a separate method that can be called manually. Now you do not have to pass in column or row, and index can be incremented by the <code>AddCard</code> method. This greatly simplifies usage and allows you to make use of a for loop.</p>\n\n<pre><code>private float startX = 0.0f;\nprivate float startY = 0.0f;\nprivate float posX = 0.0f;\nprivate float posY = 0.0f;\nprivate float prevWidth = 0;\nprivate float prevHeight = 0;\nprivate int index = 0;\nprivate int currentCol = 0;\n\n\nprivate void IncreaseColumn()\n{\n currentCol++;\n posX += width;\n posY = 0;\n prevHeight = 0;\n}\n\nprivate void AddCard(float width, float height)\n{\n GameObject goCard = (GameObject)GameObject.Instantiate(pfCard00);\n PackedSprite psCard = goCard.GetComponentInChildren<PackedSprite>();\n\n goCard.name = \"QuestItemCard\" + index.ToString();\n goCard.transform.parent = goCardContainer.transform;\n psCard.height = height;\n\n // placement\n posY += (prevHeight / 2) + (height / 2);\n goCard.transform.localPosition = new Vector3(startX + posX, startY - posY, goCard.transform.position.z);\n\n prevWidth = width;\n prevHeight = height;\n\n index++;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var columns = 2;\nvar rows = 4;\n\nfor(int x= 0; x< columns; x++)\n{\n for(int y = 0; y<rows-1; y++)\n {\n AddCard(100, 100);\n }\n AddCard(100, 200);\n IncreaseColumn();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-08T11:53:33.837",
"Id": "62289",
"ParentId": "37260",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T22:07:52.920",
"Id": "37260",
"Score": "4",
"Tags": [
"c#",
"unity3d"
],
"Title": "Creating a masonry effect with varying height rectangles"
}
|
37260
|
<p>In various projects I need to enumerate all files and folders from a specific root folder, either on a local drive or across a network. I've broken the task down into two <code>IEnumerable</code> implementations as follows:</p>
<pre><code>static IEnumerable<string> EnumeratePaths(string root)
{
if (root == null)
throw new ArgumentNullException("root");
if (!Directory.Exists(root))
throw new ArgumentException("Invalid root path", "root");
if (root.Length > 3)
root = Path.GetDirectoryName(root + "\\");
Queue<string> queue = new Queue<string>();
queue.Enqueue(root);
while (queue.Count > 0)
{
string curr = queue.Dequeue();
bool failed = false;
try
{
foreach (var path in Directory.GetDirectories(curr))
queue.Enqeue(path);
}
catch
{
failed = true;
}
if (!failed)
yield return curr;
}
}
static IEnumerable<string> EnumerateFiles(string root)
{
var paths = EnumeratePaths(root);
foreach (var nxt in paths)
{
foreach (var filename in Directory.GetFiles(nxt))
yield return filename;
}
}
</code></pre>
<p>From these I can build LINQ expressions to do filtering, etc. When I'm scanning a folder structure containing a few million files in several thousand folders this saves me from filling up memory with data that I only need once.</p>
<p>However in certain cases I have to process folders that contain tens of thousands of files, and the entire process stalls at the call to <code>GetDirectories</code> or <code>GetFiles</code> while it processes the folder... and bulks up my process memory significantly with the resultant arrays. Worse, this happens twice in <code>EnumerateFiles</code> - once when <code>EnumeratePaths</code> calls <code>GetDirectories</code>, then again when I call <code>GetFiles</code>.</p>
<p>So my questions are:</p>
<ol>
<li><p>Is there anything overtly inefficient in the implementation as it stands (not related to the file system problems mentioned).</p></li>
<li><p>How can I best reduce the memory bloat and so on when processing folders containing huge numbers of files?</p></li>
</ol>
<hr>
<p>Update 1: <code>Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)</code></p>
<p>As MarcinJuraszek pointed out there is already a way to do full-depth file enumeration using <code>Directory.EnumerateFiles</code> that doesn't require me to fetch a full array of results in one hit. That's good because one of the folders I'm scanning has 150,000+ files in it (don't ask).</p>
<p>Here's some code I wrote to test it, using a drive mapped to a network share:</p>
<pre><code>Stopwatch sw = new Stopwatch();
for (int i = 0; i < 10; i++)
{
sw.Restart();
var enumfiles = Directory.EnumerateFiles("I:\\", "*", SearchOption.AllDirectories);
int maxlen = enumfiles.Max(fname => fname.Length);
sw.Stop();
Console.WriteLine("{0}: {1:0.00}s", i, sw.ElapsedMilliseconds / 1000.0);
}
</code></pre>
<p>The average time over 10 runs was 73.942 seconds. Substituting the <code>EnumerateFiles</code> method above gave an average of 72.264 seconds - close enough that network traffic variations could account for the difference. As for memory usage... <code>Directory.EnumerateFiles()</code> gives a peak working set (from <code>Process.GetCurrentProcess().PeakWorkingSet64</code>) of <code>35,896,786</code> bytes after 10 runs, compared to <code>80,711,680</code> bytes - a significant improvement.</p>
<p>Still feels like there is a lot of room for improvement though.</p>
<hr>
<p>Update 2: <code>FindFirstFile()</code> API</p>
<p>After much googling and testing I managed to get the kernel32 <code>FindFirstFile()</code> API working in C#, hoping that it would provide a bit more of a boost. For a few of my projects it might do, since it gives me all sorts of useful information in the <code>WIN32_FIND_DATA</code> structure during enumeration... but the overall performance when just enumerating file name is approximately equivalent to <code>Directory.EnumerateFiles</code>, both in time and memory usage.</p>
<p>Thanks Marcin - answer accepted.</p>
<hr>
<p>Update 3: <code>FindFirstFile</code> revisited</p>
<p>Final update. Using some of the code from <a href="http://www.pinvoke.net/default.aspx/kernel32.findfirstfile">P/Invoke</a> I've rewritten my FindFile enumeration code as follows:</p>
<pre><code>public static IEnumerable<string> EnumerateFiles(string path)
{
WIN32_FIND_DATA finddata;
Queue<string> paths = new Queue<string>();
paths.Enqueue(path);
while (paths.Count > 0)
{
var nxtpath = paths.Dequeue();
using (var fh = FindFirstFile(Path.Combine(nxtpath, "*"), out finddata))
{
if (fh.IsInvalid)
continue;
bool ok = true;
while (ok)
{
if ((finddata.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
{
if (finddata.cFileName != "." && finddata.cFileName != "..")
paths.Enqueue(Path.Combine(nxtpath, finddata.cFileName));
}
else
yield return Path.Combine(nxtpath, finddata.cFileName);
ok = FindNextFile(fh, out finddata);
}
}
}
}
</code></pre>
<p>This performs almost twice as fast as <code>Directory.EnumerateFiles</code> in my test case - network mapped drive containing numerous files and folders including one folder with over 150,000 files. I think this one is going to end up in my library :)</p>
|
[] |
[
{
"body": "<p>Why don't you use <a href=\"http://msdn.microsoft.com/en-us/library/dd383571%28v=vs.110%29.aspx\"><code>Directory.EnumerateFiles</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/dd383462%28v=vs.110%29.aspx\"><code>Directory.EnumerateDirectories</code></a> methods? There is an overload which takes <code>SearchOption</code> enum and lets you query subdirectiries too.</p>\n\n<pre><code>static IEnumerable<string> EnumerateFiles(string root)\n{\n return Directory.EnumerateFiles(root, \"*\", SearchOption.AllDirectories);\n}\n\nstatic IEnumerable<string> EnumeratePaths(string root)\n{\n return Directory.EnumerateDirectories(root, \"*\", SearchOption.AllDirectories);\n}\n</code></pre>\n\n<p>You can see, that <code>GetDirectories</code> and <code>GetFiles</code> uses the same logic as <code>Enumerate*</code> methods, just instantiate a list, instead of returning one element at the time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T00:01:30.727",
"Id": "37269",
"ParentId": "37264",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "37269",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:08:50.010",
"Id": "37264",
"Score": "9",
"Tags": [
"c#",
"file-system"
],
"Title": "Need advice on file/directory enumeration code"
}
|
37264
|
<p>I'm building pretty big application and I wonder how should I share the code between asp.net mvc website and standalone (self running) server application.
I've got some idea how I should do this but I'm not sure if I'm doing this right.
I've got Domain Entities, Services and Repositories that will be shared between asp.mvc app and server app. Services will perform transactions on multiple repositories using IDbTransaction (I can't use ORM, pure ado.net and mysql). </p>
<p><em>IDbContext.cs</em></p>
<pre><code>public interface IDbContext : IDisposable
{
IUnitOfWork CreateUnitOfWork();
}
</code></pre>
<p><em>IDbContextFactory.cs</em></p>
<pre><code>public interface IDbContextFactory
{
IDbContext Create();
}
</code></pre>
<p><em>IRepositoryFactory.cs</em></p>
<pre><code>public interface IRepositoryFactory
{
T GetRepository<T>(IDbContext context, IUnitOfWork unitOfWork = null)
where T : class;
}
</code></pre>
<p><em>IUnitOfWork.cs</em></p>
<pre><code> public interface IUnitOfWork : IDisposable
{
bool IsInTransaction { get; }
void BeginTransaction();
void BeginTransaction(IsolationLevel isolation);
void CommitTransaction();
void RollbackTransaction();
}
</code></pre>
<p>Now the MySql implementation</p>
<p><em>MysqlDbContext.cs</em></p>
<pre><code> public class MysqlDbContext : IDbContext
{
#region Fields
private MySqlConnection _connection;
private bool _disposed;
#endregion
#region Constructor
public MysqlDbContext(MysqlConnectionFactory connectionFactory)
{
//Todo: create and open the connection
_connection = connectionFactory.Create();
if (_connection.State != ConnectionState.Open)
_connection.Open();
}
#endregion
public MySqlConnection Connection
{
get { return _connection; }
}
public IUnitOfWork CreateUnitOfWork()
{
return new MysqlUnitOfWork(_connection);
}
public void Dispose()
{
Dispose(true);
}
public void Dispose(bool disposing)
{
if (!disposing)
return;
/*
* Dispose resources
*/
if(_connection != null)
{
Console.WriteLine("Dispose connection!");
_connection.Dispose();
_connection = null;
}
//Set disposed
_disposed = true;
}
}
</code></pre>
<p><em>MysqlDbContextFactory.cs</em></p>
<pre><code>public class MysqlDbContextFactory : IDbContextFactory
{
private MysqlConnectionFactory _connectionFactory;
public MysqlDbContextFactory(MysqlConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
public IDbContext Create()
{
return new MysqlDbContext(_connectionFactory);
}
}
</code></pre>
<p><em>MysqlRepositoryFactory.cs</em></p>
<pre><code>public class MysqlRepositoryFactory : IRepositoryFactory
{
#region Constructor
public MysqlRepositoryFactory()
{
}
#endregion
public TRepository GetRepository<TRepository>(IDbContext context, IUnitOfWork unitOfWork = null)
where TRepository : class
{
if (typeof(TRepository) == typeof(IUserRepository))
return (new UserRepository(context, unitOfWork)) as TRepository;
return default(TRepository);
}
}
</code></pre>
<p><em>MysqlUnitOfWork.cs</em></p>
<pre><code>public class MysqlUnitOfWork : IUnitOfWork
{
private readonly MySqlConnection _connection;
private MySqlTransaction _transaction;
private bool _disposed;
#region Constructor
public MysqlUnitOfWork(MySqlConnection connection)
{
if (connection.State != ConnectionState.Open)
throw new ApplicationException("Cannot begin transaction. Connection is not opened!");
_connection = connection;
}
#endregion
#region Properties
public bool IsInTransaction
{
get
{
if (_transaction != null)
return true;
return false;
}
}
public MySqlTransaction Transaction
{
get
{
return _transaction;
}
}
#endregion
public void BeginTransaction()
{
BeginTransaction(IsolationLevel.ReadCommitted);
}
public void BeginTransaction(IsolationLevel isolation)
{
if (_transaction != null)
throw new ApplicationException("Cannot begin a new transaction while an existing transaction is still running. Please commit or rollback the existing transaction before starting a new one");
_transaction = _connection.BeginTransaction(isolation);
}
public void CommitTransaction()
{
if (_transaction == null)
throw new ApplicationException("Cannot commit transaction while there is no transaction running");
_transaction.Commit();
}
public void RollbackTransaction()
{
if (_transaction == null)
throw new ApplicationException("Cannot rollback transaction while there is no transaction running");
_transaction.Rollback();
}
public void Dispose()
{
Dispose(true);
}
public void Dispose(bool disposing)
{
if (!disposing)
return;
if(_transaction != null)
{
_transaction.Dispose();
_transaction = null;
}
_disposed = true;
}
}
</code></pre>
<p><em>UserService.cs</em></p>
<pre><code>public class UserService : IUserService
{
#region Fields
private readonly IDbContextFactory _dbContextFactory;
private readonly IRepositoryFactory _repositoryFactory;
#endregion
#region Constructor
public UserService(IDbContextFactory dbContextFactory, IRepositoryFactory repositoryFactory)
{
_dbContextFactory = dbContextFactory;
_repositoryFactory = repositoryFactory;
}
#endregion
public void Test()
{
using(var context = _dbContextFactory.Create())
{
var userRepository = _repositoryFactory.GetRepository<IUserRepository>(context);
userRepository.Create(new User
{
Username = "admin",
Password = "admin",
Email = "admin@bidit.com",
});
}
}
public void TestTransaction()
{
using(var context = _dbContextFactory.Create())
{
using(var uow = context.CreateUnitOfWork())
{
var userRepository = _repositoryFactory.GetRepository<IUserRepository>(context, uow);
//Begin new transaction (defualt isolation level: ReadCommited)
uow.BeginTransaction();
try
{
userRepository.Create(new User
{
Username = "rlydontknow",
Password = "12345",
Email = "rlydontknow@bidit.com",
});
//Commit transaction
uow.CommitTransaction();
}
catch
{
//Rollback transaction on error
uow.RollbackTransaction();
throw;
}
}
}
}
}
</code></pre>
<p>IDbContextFactory and IRepositoryFactory will be injected into service.</p>
<p>What do you think about my solution?</p>
|
[] |
[
{
"body": "<p>Instead of an <code>ApplicationException</code>, your application would be better off throwing an <code>InvalidOperationException</code>, since that actually tells someone who uses your library a bit more about the problem.</p>\n\n<p>Why do you even have a variable <code>_disposed</code> if it is only ever assigned to once as soon as the objects do get disposed? It is never read from.</p>\n\n<p><code>MysqlRepositoryFactory</code> is not specific to your MySQL implementation at all - just call it your <code>RepositoryFactory</code>. Apart from that, <code>GetRepository<IUserRepository></code> should not work in the current version, because it is limited to classes?</p>\n\n<p>Those nitpicks aside, I would argue that the responsibility of creating, committing and disposing the unit of work should be somewhere else. The way your design works, you could not ever use the same unit of work (and transaction) for two or more service calls. Furthermore, you would end up creating a lot of duplicate code if you do that for every public method of every service.\nOne usual way of solving that with ASP.NET is to create the unit of work once for every ASP.NET request, inject it into the services/repositories directly, and commit it in <code>Application_EndRequest</code>. In a Windows service or WinForms app, you could still scope the unit of work for every logical action in - which might still span over more than one service call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T13:31:00.110",
"Id": "61642",
"Score": "0",
"body": "Well.. This is sample code and missing some stuff. About using the same unit of work accross multiple services - good point.\nMysqlRepositoryFactory returns Mysql implementation of UserRepository. I will re-design my code and post some changes tommorow. Got 12h shift at work today so no chance to make those changes today :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T12:10:37.420",
"Id": "37302",
"ParentId": "37266",
"Score": "6"
}
},
{
"body": "<p>I took hangy advice and rewritten my code totally. Now it looks like that.</p>\n\n<p><em>IDbContext.cs</em></p>\n\n<pre><code>public interface IDbContext : IDisposable\n{\n IUnitOfWork CreateUnitOfWork();\n}\n</code></pre>\n\n<p><em>IUnitOfWork.cs</em>/</p>\n\n<pre><code>public interface IUnitOfWork : IDisposable\n{\n void Commit();\n void Rollback();\n}\n</code></pre>\n\n<p><em>IConnectionFactory.cs</em></p>\n\n<pre><code>public interface IConnectionFactory\n{\n IDbConnection Create();\n}\n</code></pre>\n\n<p><em>MysqlConnectionFactory.cs</em></p>\n\n<pre><code>public class MysqlConnectionFactory : IConnectionFactory\n{\n private string _connectionString;\n\n public MysqlConnectionFactory(string connectionString)\n {\n _connectionString = connectionString;\n }\n\n public string ConnectionString\n {\n get\n {\n return _connectionString;\n }\n }\n\n\n public IDbConnection Create()\n {\n var connection = new MySqlConnection(_connectionString);\n connection.Open();\n\n return connection;\n }\n}\n</code></pre>\n\n<p><em>MysqlDbContext.cs</em></p>\n\n<pre><code>public class MysqlDbContext : IDbContext\n{\n private IDbConnection _connection;\n private MysqlUnitOfWork _currentUnitOfWork;\n\n public MysqlDbContext(IConnectionFactory connectionFactory)\n {\n //Create new connection\n _connection = connectionFactory.Create();\n if (_connection.State != ConnectionState.Open)\n _connection.Open();\n }\n\n public IDbConnection Connection\n {\n get\n {\n return _connection;\n }\n }\n\n public MysqlUnitOfWork CurrentUnitOfWork\n {\n get\n {\n return _currentUnitOfWork;\n }\n }\n\n\n public IUnitOfWork CreateUnitOfWork()\n {\n if (_currentUnitOfWork != null)\n throw new InvalidOperationException(\"Cannot create new unit of work. Commit or rollback current one.\");\n\n _currentUnitOfWork = new MysqlUnitOfWork(_connection);\n\n return _currentUnitOfWork;\n }\n\n public void Dispose()\n {\n Dispose(true);\n }\n\n public void Dispose(bool disposing)\n {\n if (!disposing)\n return;\n\n if(_connection != null)\n {\n _connection.Dispose();\n _connection = null;\n }\n }\n}\n</code></pre>\n\n<p><em>MysqlRepository.cs</em></p>\n\n<pre><code>public abstract class MysqlRepository\n{\n private readonly MysqlDbContext _context;\n\n public MysqlRepository(IDbContext context)\n {\n if (context.GetType() != typeof(MysqlDbContext))\n throw new InvalidOperationException(\"Incorrect context type. MysqlDbContext required!\");\n\n _context = (MysqlDbContext)context;\n }\n\n public MysqlDbContext Context\n {\n get\n {\n return _context;\n }\n }\n\n protected IDbConnection Connection\n {\n get\n {\n if (_context != null)\n return _context.Connection;\n\n return null;\n }\n }\n\n protected IDbTransaction Transaction\n {\n get\n {\n if (_context != null && _context.CurrentUnitOfWork != null)\n return _context.CurrentUnitOfWork.Transaction;\n\n return null;\n }\n }\n}\n</code></pre>\n\n<p><em>MysqlUnitOfWork.cs</em></p>\n\n<pre><code>public class MysqlUnitOfWork : IUnitOfWork\n{\n private IDbTransaction _transaction;\n private bool _commited;\n\n public MysqlUnitOfWork(IDbConnection connection, IsolationLevel isolation = IsolationLevel.ReadCommitted)\n {\n if (connection == null)\n throw new ArgumentNullException(\"connection\");\n\n if (connection.State != ConnectionState.Open)\n throw new InvalidOperationException(\"Cannot create unit of work. Connection to the database is not estabilished!\");\n\n //Begin new transaction\n _transaction = connection.BeginTransaction(isolation);\n\n }\n\n public IDbTransaction Transaction\n {\n get\n {\n return _transaction;\n }\n }\n\n public void Commit()\n {\n if (_transaction == null)\n throw new InvalidOperationException(\"Cannot commit transaction while there is no transaction running\");\n\n _transaction.Commit();\n\n _commited = true;\n }\n\n public void Rollback()\n {\n if (_transaction == null)\n throw new InvalidOperationException(\"Cannot rollback transaction while there is no transaction running\");\n\n if (_commited)\n throw new InvalidOperationException(\"Cannot rollback already commited transaction\");\n\n _transaction.Rollback();\n }\n\n public void Dispose()\n {\n Dispose(true); \n }\n\n public void Dispose(bool disposing)\n {\n if (!disposing)\n return;\n\n if(_transaction != null)\n {\n //Automatically rollback if not commited\n if (!_commited)\n _transaction.Rollback();\n\n _transaction.Dispose();\n _transaction = null;\n }\n\n }\n\n\n}\n</code></pre>\n\n<p><em>UserRepository.cs</em></p>\n\n<pre><code>public class UserRepository : MysqlRepository, IUserRepository\n{\n public UserRepository(IDbContext context)\n : base(context)\n {\n\n }\n\n public void Create(User user)\n {\n var parameters = new\n {\n username = user.Username,\n password = user.Password,\n email = user.Email,\n };\n\n user.Id = (uint)Connection.Query<ulong>(\"INSERT INTO users (username, password, email) VALUES (@username, @password, @email); select last_insert_id();\", parameters).First();\n }\n}\n</code></pre>\n\n<p><em>UserSerivce.cs</em></p>\n\n<pre><code>public class UserService : IUserService\n{\n private readonly IUserRepository _userRepository;\n\n public UserService(IUserRepository userRepository)\n {\n _userRepository = userRepository;\n }\n\n\n\n public void Create()\n {\n var user = new User\n {\n Username = \"rlydontknow\",\n Password = \"12345\",\n Email = \"rlydontknow@sharpbid.com\"\n };\n\n _userRepository.Create(user);\n\n Console.WriteLine(\"New user created! User id: \" + user.Id);\n\n }\n}\n</code></pre>\n\n<p><em>Program.cs</em></p>\n\n<pre><code>class Program\n{\n private static IConnectionFactory _connectionFactory;\n\n static void Main(string[] args)\n {\n _connectionFactory = new MysqlConnectionFactory(\"Server=localhost;Database=sharpbid;Uid=root;Pwd=maniek1;\");\n\n\n SomeLogicalOperation();\n\n Console.ReadLine();\n }\n\n static void SomeLogicalOperation()\n {\n using(var context = GetContext())\n {\n var userRepository = new UserRepository(context);\n\n /*\n * Do some stuff without transaction\n */\n\n //Begin transaction\n using (var uow = context.CreateUnitOfWork())\n {\n var userService = new UserService(userRepository);\n\n userService.Create();\n\n //Commit transaction\n uow.Commit();\n }\n }\n }\n\n static IDbContext GetContext()\n {\n return new MysqlDbContext(_connectionFactory);\n }\n}\n</code></pre>\n\n<p>It's just example code. Might missing few things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T07:06:14.830",
"Id": "61748",
"Score": "0",
"body": "Why pass in a IDbcontext to the MysqlRepository if the conditions are it requires a MysqlDbContext anyway. Why not just have it require a MysqlDbContext?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T13:47:58.847",
"Id": "61755",
"Score": "0",
"body": "Right... my bad. :P"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T06:47:41.783",
"Id": "37339",
"ParentId": "37266",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:32:19.103",
"Id": "37266",
"Score": "4",
"Tags": [
"c#",
"asp.net"
],
"Title": "Sharing domain between ASP.NET and self running application"
}
|
37266
|
<p>Building a 'card' database: I'm simply learning to take input data and store to database. Incorporating JSON, PDO, SQL, and enforcing my general coding skills through PHP, hopefully.</p>
<pre><code>$query = $dbh->prepare("SELECT * FROM " . $table);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_CLASS);
$temp = array();
$data = array();
foreach($result as $key => $val){
foreach($val as $key2 => $val2){
$temp[$key2] = $val2;
}
array_push($data, $temp);
}
echo json_encode($data);
</code></pre>
<p>Is there a better way to do what I am attempting?</p>
|
[] |
[
{
"body": "<p>Yes, there sure is. Effectively, what you seem to be doing can be reduced to this:</p>\n\n<pre><code>$stmt = $dbh->query(\"SELECT * FROM \" . $table);\n$data = $stmt->fetchAll(PDO::FETCH_ASSOC);\necho json_encode($data);\n</code></pre>\n\n<p>I'll explain how I got to those three lines above, simplifying your code step by step.<br/>\nThe inner loop just <em>does not make sense</em>:</p>\n\n<pre><code>foreach($val as $key2 => $val2){\n $temp[$key2] = $val2;\n}\narray_push($data, $temp); \n</code></pre>\n\n<p>What this does, is iterate over <code>$val</code>, which is either an iterable object, or an array. When doing so, you're creating a new array <code>$temp</code>, which is, essentially an array-version of <code>$val</code>. Of course, <code>$temp</code> is never <em>\"cleared\"</em>, so the second time the inner loop is performed, <code>$temp</code> will be assigned new keys and values.<br/>\nIn short, suppose <code>$temp</code> looks like this, after the first iteration:</p>\n\n<pre><code>array('foo' => 123);\n</code></pre>\n\n<p>Then <code>$data</code> will look like this:</p>\n\n<pre><code>array(array('foo' => 123));\n</code></pre>\n\n<p>The second time, <code>$temp</code> might look like this:</p>\n\n<pre><code>array('bar' => 1234, 'foo' => 123);\n</code></pre>\n\n<p>Or, if <code>$val</code> had a key/property called <code>foo</code>, then <code>$temp['foo']</code> will simply be reassigned to the new value, and <code>$temp</code> will look like</p>\n\n<pre><code>array('foo' => 'new value');\n</code></pre>\n\n<p>Either way, <code>$data</code> will look like:</p>\n\n<pre><code>array(array('foo' => 123), array('foo' => 'new value'));\n</code></pre>\n\n<p>But why the loop? Why don't you simply <em>cast</em> the <code>$val</code> to an array, and push it into the <code>$data</code> array?</p>\n\n<pre><code>foreach($result as $val)\n{//you're not using the $key anywhere, so you can omit it\n array_push($data, (array) $val);\n}\n</code></pre>\n\n<p>That's a hell of a lot shorter, isn't it? But you can simplify this even more. You're fetching the result as objects, only to convert it to an array. Why don't you just fetch the results as an array from the off? Simply change:</p>\n\n<pre><code>$result = $query->fetchAll(PDO::FETCH_CLASS);\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>$data = $query->fetchAll(PDO::FETCH_ASSOC);\n</code></pre>\n\n<p>You won't need the loops at all after this.<br/>\nJust as an asside, fetching the results of a query is often done using a <code>while</code> loop. I'll save you the inner-workings-details, but last time I checked, a <code>while</code> loop was actually marginally more performant than a <code>fetchAll</code> call... The only way to be sure is to benchmark both versions, but I tend to prefer the following:</p>\n\n<pre><code>$data = array();\nwhile($row = $query->fetch(PDO::FETCH_ASSOC))\n{\n $data[] = $row;\n}\n</code></pre>\n\n<p>Ah well, the result is the same, anyway.</p>\n\n<p><em>Other thoughts:</em><br/>\nThere are a couple of things you might want to consider, too:</p>\n\n<pre><code>$query = $dbh->prepare(\"SELECT * FROM \" . $table);\n</code></pre>\n\n<p>Is not the safest way to go about your business: What is the value of <code>$table</code>? If it's a value that comes from the client-side, who's to say it doesn't contain an invalid table name? something like <code>another_db.secret_table</code> would make for the following query:</p>\n\n<pre><code>SELECT * FROM another_db.secret_table\n</code></pre>\n\n<p>Fetching data that possibly wasn't intended for the client to see. That's a security issue. And a big one at that.<br/>\nNext, the variable <code>$query</code> is not the best name. <code>PDO::prepare</code> returns an instance of <code>PDOStatement</code>, which is a <em>prepared statement</em>, which isn't a query anymore. That's why you often see the return value of <code>PDO::prepare</code> being assigned to a variable called <code>$stmt</code>.</p>\n\n<p>Either way, with a query without a <code>WHERE</code> clause, prepared statements only cause more overhead. You're better of executing it from the off. Prepared statements are there when you want to insert variables into a query:</p>\n\n<pre><code>$stmt = $pdo->prepare('SELECT * FROM tbl WHERE field = :fieldVal');\n$result = $stmt->execute(array(':fieldVal' => $_POST['fieldVal']));\n</code></pre>\n\n<p>As an added bonus, you can re-use the same prepared statement over and over, to perform the same query a couple of times:</p>\n\n<pre><code>$stmt = $pdo->prepare('SELECT * FROM tbl WHERE field = :fieldVal');\n$vals = array('foo', 'bar');\nforeach($vals as $val)\n{\n echo 'Executing query with value: ', $val, PHP_EOL;\n $result = $stmt->execute(array(':fieldVal' => $val));\n //process $result...\n}\n</code></pre>\n\n<p>The code above will perform the same query twice, once for the value <em>\"foo\"</em> and once with the value <em>\"bar\"</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T22:56:32.643",
"Id": "61737",
"Score": "0",
"body": "Thanks for all of the detail and explaination. I've learned a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:44:28.493",
"Id": "37290",
"ParentId": "37275",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "37290",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:00:26.257",
"Id": "37275",
"Score": "4",
"Tags": [
"php",
"sql",
"beginner",
"json",
"pdo"
],
"Title": "Converting entire table to JSON data. Is there a better way?"
}
|
37275
|
<p>I've written this code in an attempt to create the Monty Hall problem and check the ratios. I would like someone to check the logic on it. I know it isn't organized well at all; I just need to see if I'm performing correctly.</p>
<p><a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">If you don't know what the Monty Hall problem is</a>.</p>
<pre><code>private static int losses = 0;
private static int wins = 0;
public static void main(String[] args) throws Exception {
for (int x = 0; x < 100; x++) {
boolean doors[] = getDoors();
run(getGuess(), doors);
}
System.out.println("Wins: " + wins);
System.out.println("Losses: " + losses);
double ratio = wins / wins + losses;
System.out.println("Ratio: " + ratio);
}
public static boolean[] getDoors() {
//door range
int min = 1;
int max = 3;
//generate random correct door
Random r = new Random();
int i = r.nextInt(max - min) + min;
//assign doors to boolean
boolean[] doors = new boolean[3];
for (int x = 0; x < 3; x++) {
if (x == i) {
doors[x] = true;
} else {
doors[x] = false;
}
}
return doors;
}
public static int getGuess() {
//guess range
int min = 1;
int max = 3;
//generate random guess
Random r = new Random();
int guess = r.nextInt(max - min) + min;
return guess;
}
public static void run(int guess, boolean[] doors) {
//if guess is valid before switch, declare loss
if (doors[guess]) {
losses++;
return;
}
//find other false door
int wrongDoor = 0;
for (int x = 0; x < 3; x++) {
if (doors[x] == false && guess != x) {
wrongDoor = x;
}
}
//switch doors
int newGuess = 0;
for (int x = 0; x < 3; x++) {
if (x != wrongDoor && x!= guess) {
newGuess = x;
}
}
//checkguess
if (doors[newGuess] == true) {
wins++;
} else {
losses++;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T03:58:09.643",
"Id": "61579",
"Score": "5",
"body": "`if (doors[newGuess] == true)` is equivalent to `if (doors[newGuess])`"
}
] |
[
{
"body": "<p>You know it is not running correctly, the ratio is supposed to be 66%, not 50%.... what you really want is some help debugging it.....</p>\n\n<p>Your issue is in your random number generation.... you are only ever setting, and choosing 2 of the three doors. Have a look at this common problem:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java\">https://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java</a></p>\n\n<p>You are not using the ranges properly:</p>\n\n<pre><code> //door range\n int min = 1;\n int max = 3;\n //generate random correct door\n Random r = new Random();\n int i = r.nextInt(max - min) + min;\n</code></pre>\n\n<p>in this code, <code>max-min</code> is 2, and <code>nextInt(2)</code> is going to be either <code>0</code>, or <code>1</code>., add that to <code>min</code> you get either <code>1</code> or <code>2</code>.</p>\n\n<p>You should not care about the min and max, you should just use:</p>\n\n<pre><code>int i = r.nextInt(doorcount); // assuming doorcount == 3\n</code></pre>\n\n<p>which will return <code>0</code>, <code>1</code>, or <code>2</code></p>\n\n<p>If you fix this in both the <code>getGuess</code> and <code>getDoors</code> method then you will get the correct ratio of 66%.</p>\n\n<p>Your code has a number of other problems too.</p>\n\n<ol>\n<li>there is no need to create a new <code>Random</code> instance each time you want a random number. Create a single instance and share it.</li>\n<li>do not call your method <code>run</code>. This will lead to confusion with the <code>java.lang.Runnable</code> interface</li>\n<li>the line: <code>double ratio = wins / wins + losses</code> does not do what you think it does.</li>\n</ol>\n\n<p>I think you should fix your program, then resubmit it for review....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:40:50.427",
"Id": "61701",
"Score": "0",
"body": "To know the probability that a contestant offered the chance to switch should do so, one must know the probability with which the host will show the empty door [rather than announcing a win] if the player's initial guess is correct, and the probability with which the host will show the empty door [rather than announcing a loss] if the player's initial guess is wrong. If both probabilities are 100%, a player would have a 2/3 chance of winning by switching, but I don't think the real Monty Hall behaved like that. Host behavior can shift the odds of win-by-switching anywhere from 0% to 100%."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:46:13.337",
"Id": "61720",
"Score": "0",
"body": "@supercat - the 'Monty-Hall' problem requires the host to reveal one door and then offer the chance to switch. Whether the actual Monty-Hall in his actual show always did this, is not significant when considering the problem named 'Monty-Hall' ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:35:27.817",
"Id": "37281",
"ParentId": "37276",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:19:16.667",
"Id": "37276",
"Score": "1",
"Tags": [
"java",
"simulation"
],
"Title": "Correct logic in Monty Hall Problem?"
}
|
37276
|
<p>I've made a working calendar program, BUT I believe it's extremely inefficient. I think I have way too many <code>else if</code> statements: </p>
<pre><code>import java.util.*;
public class MyOwnCalendar {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number of days in month: ");
int days = keyboard.nextInt();
System.out.print("Enter which day the first day is on: ");
int firstDay = keyboard.nextInt();
System.out.println("S M T W Th F Sa");
int ctr = 1;
if (days == 31 && firstDay == 1)
{
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 8 || ctr == 15 || ctr == 22 || ctr == 29)
{
System.out.println();
}
}
}
else if (days == 31 && firstDay == 2)
{
System.out.print("\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 7 || ctr == 14 || ctr == 21 || ctr == 28)
{
System.out.println();
}
}
}
else if (days == 31 && firstDay == 3)
{
System.out.print("\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 6 || ctr == 13 || ctr == 20 || ctr == 27)
{
System.out.println();
}
}
}
else if (days == 31 && firstDay == 4)
{
System.out.print("\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 5 || ctr == 12 || ctr == 19 || ctr == 26)
{
System.out.println();
}
}
}
else if (days == 31 && firstDay == 5)
{
System.out.print("\t\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 4 || ctr == 11 || ctr == 18 || ctr == 25)
{
System.out.println();
}
}
}
else if (days == 31 && firstDay == 6)
{
System.out.print("\t\t\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 3 || ctr == 10 || ctr == 17 || ctr == 24 || ctr == 31)
{
System.out.println();
}
}
}
else if (days == 31 && firstDay == 7)
{
System.out.print("\t\t\t\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 2 || ctr == 9 || ctr == 16 || ctr == 23 || ctr == 30)
{
System.out.println();
}
}
}
else if (days == 30 && firstDay == 1)
{
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 8 || ctr == 15 || ctr == 22 || ctr == 29)
{
System.out.println();
}
}
}
else if (days == 30 && firstDay == 2)
{
System.out.print("\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 7 || ctr == 14 || ctr == 21 || ctr == 28)
{
System.out.println();
}
}
}
else if (days == 30 && firstDay == 3)
{
System.out.print("\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 6 || ctr == 13 || ctr == 20 || ctr == 27)
{
System.out.println();
}
}
}
else if (days == 30 && firstDay == 4)
{
System.out.print("\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 5 || ctr == 12 || ctr == 19 || ctr == 26)
{
System.out.println();
}
}
}
else if (days == 30 && firstDay == 5)
{
System.out.print("\t\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 4 || ctr == 11 || ctr == 18 || ctr == 25)
{
System.out.println();
}
}
}
else if (days == 30 && firstDay == 6)
{
System.out.print("\t\t\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 3 || ctr == 10 || ctr == 17 || ctr == 24 || ctr == 31)
{
System.out.println();
}
}
}
else if (days == 30 && firstDay == 7)
{
System.out.print("\t\t\t\t\t\t");
while (ctr <= days)
{
System.out.print(ctr);
System.out.print(" ");
ctr++;
if (ctr == 2 || ctr == 9 || ctr == 16 || ctr == 23 || ctr == 30)
{
System.out.println();
}
}
}
}
}
</code></pre>
<p>What are some easier ways to do this? Would a <code>for</code> loop have made this easier?</p>
|
[] |
[
{
"body": "<p>This is a classic example of where the Modulo operator is useful.</p>\n\n<p>The modulo allows you to determine where in a sequence you hit a repeating part of the pattern. For example, you are processing thousands of lines of data, so you want to log some output, you print a message every 1000 lines with:</p>\n\n<pre><code>if (count % 1000 == 0) {\n System.out.println(\"Processing line \" + count);\n}\n</code></pre>\n\n<p>We can use the modulo to our advantage with weeks having 7 days....</p>\n\n<p>So, if we do something like:</p>\n\n<pre><code>for (int i = 1; i <= daysinmonth; i++) {\n System.out.print(\" \" + i);\n}\n</code></pre>\n\n<p>we will just get numbers printed accross the screen... but, if we do:</p>\n\n<pre><code>for (int i = 1; i <= daysinmonth; i++) {\n System.out.print(\" \" + i);\n if (i % 7 == 0) {\n System.out.println();\n }\n}\n</code></pre>\n\n<p>then the numbers will wrap neatly.</p>\n\n<p>Now, if you take that example, and extend it to start at a certain day of the week, you can do:</p>\n\n<pre><code>// note the start-at-1 offset.\nfor (int i = 1; i < firstDay; i++) {\n System.out.print(\" \"); // some spaces for the starting days.\n}\n</code></pre>\n\n<p>now we do the same loop as before, but we offset our line-break:</p>\n\n<pre><code>for (int i = 1; i <= days; i++) {\n System.out.print(\" \" + i);\n if ((i + firstDay) % 7 == 0) {\n System.out.println();\n }\n}\n</code></pre>\n\n<p>Using this logic you should be able to bring your code down to just two simple loops, a padding loop, and a number loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:53:59.803",
"Id": "37282",
"ParentId": "37278",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37282",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T02:25:26.000",
"Id": "37278",
"Score": "3",
"Tags": [
"java",
"optimization",
"datetime",
"formatting"
],
"Title": "How to make this calender program simpler/optimized?"
}
|
37278
|
<p>Using the <a href="http://www.1stwebdesigner.com/tutorials/flat-web-design-tutorial/">Flat Web Design Tutorial</a> offered at 1webdesigner I tried converting the resulting PSD file to HTML5 and CSS3. While attempting to use sectioning elements in the markup I quickly found myself lost in how to maintain semantic code while also adhering to the original design. As a result there are more div tags than I initially desired. How can I achieve the same result using the HTML5 sectioning elements?</p>
<p>If you notice <em>any</em> other areas that could use improvement, please don't hesitate to point them out.</p>
<p><a href="https://dl.dropboxusercontent.com/u/8800173/Web/index.html">Demo</a></p>
<p><strong>HTML</strong>
</p>
<pre><code><html>
<head>
<meta charset="utf-8">
<title>John Doe | Web &amp; Graphic Designer</title>
<link href="css/normalize.css" rel="stylesheet" type="text/css" media="screen">
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen">
</head>
<body>
<header role="banner">
<div class="container">
<a href="/" title="Return to Home">
<img src="img/logo.gif" id="logo" alt="Logo" height="35" width="37">
</a>
<nav>
<ul>
<li><a href="#" title="Home">Home</a></li>
<li><a href="#" title="Services">Services</a></li>
<li><a href="#" title="Portfolio">Portfolio</a></li>
<li><a href="#" title="Blog">Blog</a></li>
<li><a href="#" title="Hire me">Hire me</a></li>
</ul>
</nav>
<h1>Holla.</h1>
<h2>I'm <span class="keywords">John Doe</span> a Philippines-based <span class="keywords">web</span> & <span class="keywords">graphic</span> designer who creates
clean and modern design for the world of web.</h2>
<a href="#" title="View my work" id="view-work" class="btn">View my work</a>
</div> <!-- end container -->
</header>
<div id="services" class="container">
<section class="column four">
<img src="img/browser.png" alt="Web Browser" height="48" width="48" class="services-icons">
<div class="column-content">
<h3>Web Design</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<a href="#" title="Learn more">Learn more</a>
</div> <!-- end column-content -->
</section>
<section class="column four">
<img src="img/mobile.png" alt="Cell Phone" height="48" width="36" class="services-icons">
<div class="column-content">
<h3>Mobile Design</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<a href="#" title="Learn more">Learn more</a>
</div> <!-- end column-content -->
</section>
<section class="column four">
<img src="img/camera.png" alt="Camera" height="48" width="48" class="services-icons">
<div class="column-content">
<h3>Photography</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<a href="#" title="Learn more">Learn more</a>
</div> <!-- end column-content -->
</section>
</div> <!-- end services -->
<div id="projects">
<div class="container">
<div class="column six">
<h3>1stwebdesigner</h3>
<h4>01 july 2013</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<dl>
<dt>Client</dt>
<dd>Dainis Graveris</dd>
<dt>Role</dt>
<dd>Designer</dd>
<dt>Tools</dt>
<dd>Photoshop</dd>
</dl>
<a href="#" title="View Project" id="view-project" class="btn btn-secondary">View Project</a>
</div> <!-- end column -->
</div> <!-- end container -->
<img src="img/preview.png" id="preview" alt="Screenshot of 1stwebdesigner landing page">
</div> <!-- end projects -->
<footer role="contentinfo" class="container">
<h3>Say <span class="keywords">Hello.</span></h3>
<p>I'd love to hear from you.</p>
<nav>
<ul>
<li><a href="#" title="Email"><img src="img/email.png" alt="Email"></a></li>
<li><a href="#" title="Facebook"><img src="img/facebook.png" alt="Facebook"></a></li>
<li><a href="#" title="Twitter"><img src="img/twitter.png" alt="Twitter"></a></li>
<li><a href="#" title="Instagram"><img src="img/instagram.png" alt="Instagram"></a></li>
<li><a href="#" title="Dribbble"><img src="img/dribbble.png" alt="Dribbble"></a></li>
</ul>
</nav>
<p id="copyright">&copy; 2013 <span class="keywords">John Doe</span>. All rights reserved.</p>
</footer>
</body>
</html>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>/*
style.css
Colours
=======
Red: #f84242;
Darker Black: #111111;
Black: #25252a;
Dark Grey: #666666;
Grey: #9d9d9d;
Light Grey: #e5e5e5;
White: #ffffff;
*/
/* ------------------------
General Styles
------------------------ */
html {
-webkit-font-smoothing: antialiased;
text-rendering: optimizelegibility;
}
body {
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 15px;
line-height: 1.65;
color: #666666;
}
/* ------------------------
Typography
------------------------ */
h1, h2, h3, h4 {
margin: 0;
font-weight: 300;
line-height: 1.65;
}
h1, h2 {
color: #fff;
}
h4, dt {
font-weight: 400;
color: #9d9d9d;
}
h1, footer h3 {
font-size: 72px;
}
h2 {
font-size: 22px;
}
h3 {
font-size: 24px;
color: #111;
}
h4 {
font-size: 13px;
}
p {
margin: 0;
font-weight: 300;
color: #666666;
}
a {
color: #f84242;
text-decoration: none;
}
dt {
font-size: 11px;
text-transform: uppercase;
}
.keywords {
font-weight: bold;
}
#services h3 {
line-height: 2.0833;
}
#projects h3 {
margin-top: -6px;
font-size: 36px;
line-height: 1.3;
}
footer h3 .keywords {
font-weight: 300;
color: #f84242;
}
#copyright .keywords {
color: #111;
}
/* ------------------------
Layout
------------------------ */
.container {
margin: 0 auto;
padding: 120px 10px;
width: 940px;
overflow: auto;
}
header .container {
padding: 60px 10px 120px;
}
footer.container {
clear: right;
padding: 120px 10px 60px;
}
header {
background-image: url('../img/header-bg.jpg');
background-size: cover;
background-position: left bottom;
background-color: #f84242;
}
#logo {
float: left;
}
header h1 {
clear: both;
margin-top: 120px;
}
#view-work {
margin-top: 120px;
}
.column:last-child {
margin-right: 0;
}
.services-icons {
float: left;
margin: 0 6px;
}
#services img[width="36"] {
margin: 0 12px;
}
#services p {
margin: 10px 0 24px;
}
#projects {
background-color: #e5e5e5;
}
#projects p {
margin-top: 25px;
}
dd {
margin: 0 0 20px;
font-weight: 300;
}
#view-project {
margin-top: 28px;
}
#preview {
float: right;
margin-top: -580px;
}
/* ------------------------
Navigation
------------------------ */
header nav {
float: right;
margin: 0;
}
nav ul {
margin: 0;
padding: 0;
}
nav ul li {
display: inline-block;
}
header nav ul li a {
margin-right: 40px;
font-size: 16px;
font-weight: bold;
text-decoration: none;
color: #fff;
opacity: 0.6;
/* vertical align text */
height: 38px;
line-height: 38px;
vertical-align: middle;
}
header nav ul li:last-child a {
margin-right: 0;
}
header nav ul li a:hover {
border-bottom: 2px solid #fff;
opacity: 1;
}
footer nav {
float: none;
margin: 120px 0;
}
footer nav ul li {
vertical-align: top;
width: 128px;
height: 128px;
background-color: #e5e5e5;
text-align: center;
}
footer nav ul li a {
display: block;
margin: 40px auto;
width: 48px;
height: 48px;
}
/* ------------------------
Buttons
------------------------ */
.btn {
display: inline-block;
border-radius: 10px;
padding: 10px 20px;
background-color: #25252a;
font-size: 16px;
font-weight: bold;
color: #fff;
text-decoration: none;
cursor: pointer;
}
.btn-secondary {
border-radius: 2px;
background-color: #f84242;
}
/* ------------------------
Global Styles
------------------------ */
.column {
float: left;
margin-right: 20px;
}
.column-content {
margin-left: 80px;
}
.four {
width: 300px;
}
.six {
width: 460px;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:14:08.463",
"Id": "61607",
"Score": "0",
"body": "Well the reason why there is so much use of elements is because they use the a grid layout. This way much of the element positions are defined with padding and margin. To exclude those paddings and margins they place a new element in it that is defined by the padding and margin of the parent. How you can extend this? Base is probably the container class and the colum class. Could you give any specific place where you think there are too much elements used?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:16:54.150",
"Id": "61623",
"Score": "0",
"body": "I feel that I resorted to using the <div> element several times throughout my markup because I really wasn't sure how or where to use HTML5 elements like <main>, <article>, <section> or <aside> in a grid layout. There are several <div> elements in the markup which exist purely for visual reasons. Is this considered bad practice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T13:09:00.003",
"Id": "61641",
"Score": "0",
"body": "@Yaoki check out [WhatWG](http://www.whatwg.org/)'s summary of HTML5 in http://developers.whatwg.org/ - use the search in the top right to open the description for the element you want to check. Very useful! :)"
}
] |
[
{
"body": "<p>I find the CSS too low level for a good design.</p>\n\n<p>Do you really want to declare the same style for all 'h2' tags?\nThen you may not like it for some of them and will redeclare.\nThen redeclare again. Then the mess will grow over you. :)</p>\n\n<p>I rather prefer semantic approach. Give your declarations to meaningful classes. Don't use tag declarations unless they mean anything to you.</p>\n\n<p>Just my view.</p>\n\n<p>EDIT. Using tag declarations carry further problems. What if you decide to change 'h3' to 'h4'? Or to something else? Do you want to copy over all your declarations each time?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:03:16.523",
"Id": "61620",
"Score": "0",
"body": "Thanks, this is just what I needed! I think I understand what you mean by avoid assigning specific styles to generic selectors. So, when would you style an element selector? Also, would you say it's better to use class selectors over element or id selectors? My main worry about using class selectors is how to remain semantic when building a grid (i.e., \".col-12\" vs \".copyright\"). I'm not sure what the best practice is as it seems unavoidable to use unsemantic class names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:32:54.703",
"Id": "61624",
"Score": "0",
"body": "@Yaoki Every selector is element selector :) Any DOM node is called element. Id selectors have their use for unique elements that you don't want to repeat by mistake. \"col-12\" class is still semantic but serves different purpose - declaring exactly those. So specific declarations only for 'col-12' will go in that class but for anything else I would add other classes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:48:30.040",
"Id": "37292",
"ParentId": "37284",
"Score": "3"
}
},
{
"body": "<p>Quick note: to answer one of your comments, using div's exactly how you have is actually the purpose of div's. Since they have no semantic value you can use them solely for stylistic purposes as you have. In some cases you didn't have too, but you didn't do it incorrectly. </p>\n\n<p>HTML5 has really bolstered the semantic meaning behind elements. I would really look into articles that go into detail about why the tags should be used and where. Here are a few articles to look into:</p>\n\n<p>html5 doctor is a great resource for continually updated information on html5 (or any html) elements. <a href=\"http://html5doctor.com/lets-talk-about-semantics/\" rel=\"nofollow\">http://html5doctor.com/lets-talk-about-semantics/</a> just use their search on any html element and you'll get a great overview of its use.</p>\n\n<p>more reading on semantics: <a href=\"http://coding.smashingmagazine.com/2011/11/18/html5-semantics/\" rel=\"nofollow\">http://coding.smashingmagazine.com/2011/11/18/html5-semantics/</a> & <a href=\"http://alistapart.com/article/semanticsinhtml5\" rel=\"nofollow\">http://alistapart.com/article/semanticsinhtml5</a> & <a href=\"http://diveintohtml5.info/semantics.html\" rel=\"nofollow\">http://diveintohtml5.info/semantics.html</a> are <strong>always</strong> an amazing resource for information on all things web.</p>\n\n<p><a href=\"http://css-tricks.com/\" rel=\"nofollow\">http://css-tricks.com/</a> is one of my favorite places to bookmark information.</p>\n\n<hr>\n\n<p>As mentioned in the other answer, You can really minimize the amount of <code><div></code>'s you use if you avoid col- based setups, but if you want to go that route, instead of building your own I suggest looking into Zurb's Foundation (<a href=\"http://foundation.zurb.com/\" rel=\"nofollow\">http://foundation.zurb.com/</a>) and Twitter's Bootstrap (<a href=\"http://getbootstrap.com/\" rel=\"nofollow\">http://getbootstrap.com/</a>) frameworks. They're great starting points and have awesome documentation that will get you rolling very quickly. </p>\n\n<p>Keep in mind <code><div></code>'s have no semantic meaning to a browser, when you use <code><section></code>, <code><article></code>, <code><main></code>, <code><footer></code>, <code><header></code>, <code><nav></code> and <code><aside></code> they serve a purpose to the browser, and create an overall outline of the website, whereas it use to only be headings <code><h1></code> - <code><h6></code> that outlined a site. <a href=\"http://gsnedders.html5.org/outliner/\" rel=\"nofollow\">http://gsnedders.html5.org/outliner/</a> is a good resource to see if you're using headings and sectioning in a semantic meaningful way. These HTML5 tags all require a heading or they'll read as untitled, whereas <code><div></code> elements don't require headings.</p>\n\n<p>which bleeds into another semantic hiccup you have very poor use of headings throughout, this is a pet peeve of mine. <a href=\"http://html5doctor.com/the-time-element/\" rel=\"nofollow\">http://html5doctor.com/the-time-element/</a>, <a href=\"http://html5doctor.com/howto-subheadings/\" rel=\"nofollow\">http://html5doctor.com/howto-subheadings/</a>, <a href=\"http://html5doctor.com/outlines/\" rel=\"nofollow\">http://html5doctor.com/outlines/</a>, & <a href=\"http://coding.smashingmagazine.com/2013/01/18/the-importance-of-sections/\" rel=\"nofollow\">http://coding.smashingmagazine.com/2013/01/18/the-importance-of-sections/</a></p>\n\n<p>Where your heading belongs you have an image, and your <code><h1></code> is used on \"Hello\"? I'd go with something of this nature:</p>\n\n<p>HTML</p>\n\n<pre><code><h1 role=\"heading\" class=\"logo\">Site Title</h1>\n...\n<strong>Holla.</strong>\n</code></pre>\n\n<p>CSS (<a href=\"http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/\" rel=\"nofollow\">http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/</a>)</p>\n\n<pre><code>.logo{\n background: url(img/logo.png) no-repeat 50% 50%;\n background-size:35px 37px;\n text-indent: 100%;\n white-space: nowrap;\n overflow: hidden\n }\n</code></pre>\n\n<p>Also, this is bad practice, headings for time?</p>\n\n<p>e.g. <code><h4>01 july 2013</h4></code> should be <code><time datetime=\"2013-07-01\">01 July 2013</time></code></p>\n\n<p>and doing this...</p>\n\n<pre><code><h2>I'm <span class=\"keywords\">John Doe</span> a Philippines-based <span class=\"keywords\">web</span> & <span class=\"keywords\">graphic</span> designer who creates \nclean and modern design for the world of web.</h2>\n</code></pre>\n\n<p>...is something I'd avoid doing as well. As this isn't a title, it's a phrased description, I'd make it a <code><div></code> or <code><p></code> and put a link with <code><a href=\"#\" rel=\"author\"></code> for the name. </p>\n\n<hr>\n\n<p>Your use of the <code><nav></code> tag for social links in the <code><footer></code> is something that I'd debate, W3C's Spec</p>\n\n<blockquote>\n <p>The nav element represents a section of a page that links to other pages or to parts within the page: a section with navigation links.</p>\n \n <p>In cases where the content of a nav element represents a list of items, use list markup to aid understanding and navigation.</p>\n \n <p>Not all groups of links on a page need to be in a nav element — the element is primarily <strong>intended for sections that consist of major navigation blocks.</strong> In particular, it is common for footers to have a short list of links to various pages of a site, such as the terms of service, the home page, and a copyright page. The footer element alone is sufficient for such cases; while a nav element can be used in such cases, it is usually unnecessary.</p>\n</blockquote>\n\n<p>Where it could be the main source of navigation, in this case I don't believe it is. <a href=\"http://html5doctor.com/nav-element/\" rel=\"nofollow\">http://html5doctor.com/nav-element/</a></p>\n\n<hr>\n\n<p>Your images have <code>alt=\"\"</code> attributes which is great, but you can add even more semantic value to these if you use <code><figure></code> and <code><figcation></code> elements where necessary. <a href=\"http://html5doctor.com/the-figure-figcaption-elements/\" rel=\"nofollow\">http://html5doctor.com/the-figure-figcaption-elements/</a></p>\n\n<hr>\n\n<p>Your page could be much more simple and semantic, especially for something of this size. On a smaller site like this you could literally use all pseudo elements and have zero classes on any element. However, that is very difficult to maintain on a larger scale, so I'd suggest looking into SMACSS (www.smacss.com) which will really help you build a better knowledge of how to setup your css structure. I have too many grips on your css to mention here so just read into SMACSS and other style resources and it will help immensely. I will say that <em>normalize.css</em> is amazing; However, you should really work it into your code instead of just plugging it in separately (<a href=\"http://nicolasgallagher.com/about-normalize-css/\" rel=\"nofollow\">http://nicolasgallagher.com/about-normalize-css/</a>)</p>\n\n<blockquote>\n <p>Approach 1: use normalize.css as a starting point for your own project’s base CSS, customising the values to match the design’s requirements.</p>\n \n <p>Approach 2: include normalize.css untouched and build upon it, overriding the defaults later in your CSS if necessary.</p>\n</blockquote>\n\n<p><strong>Final Notes</strong>\nYou have great use of <code><p></code>'s and the use of <code><dl></code>, <code><dt></code>, and <code><dd></code> is good along with a decent overall structure, but I'd replace your <code>.container</code> with <code><main></code>, make better use of headings and the new HTML5 elements, understand what html5 elements actual purposes are, and you'll be well on your way.</p>\n\n<p>Also, look into WAI-ARIA <a href=\"http://www.webteacher.ws/2010/12/29/how-to-make-html5-semantic-elements-more-accessible/\" rel=\"nofollow\">http://www.webteacher.ws/2010/12/29/how-to-make-html5-semantic-elements-more-accessible/</a> and other means of accessibility. The use of <code>role=\"\"</code> and <code>aria-labelledby=\"\"</code> etc. can really boost semantic levels and has no effect on browsers that lack support. You have it a little, but you could add <code><nav role=\"navigation\"></code>, <code><h1 role=\"heading\"></code>, <code><ul role=\"list\"></code>, <code><li role=\"listitem\"></code>, <code><a role=\"link\"></code> <code><main role=\"main\"></code> among other things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:44:12.133",
"Id": "37361",
"ParentId": "37284",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37361",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T04:59:33.680",
"Id": "37284",
"Score": "7",
"Tags": [
"html",
"css",
"html5"
],
"Title": "How can I improve the following code using HTML5 and CSS3?"
}
|
37284
|
<p>I wanted to write a human readable datetime.timedelta that can be used in log files.</p>
<p>Eg, "Report issued 1 hour, 44 minutes, 20 seconds ago"</p>
<p>I noticed that casting a timedelta to str() generates something almost like what I want, but not quite.</p>
<p>To this end I wrote this:</p>
<pre><code>def verbose_timedelta(delta):
hours, remainder = divmod(delta.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
dstr = "%s day%s" % (delta.days, "s"[delta.days==1:])
hstr = "%s hour%s" % (hours, "s"[hours==1:])
mstr = "%s minute%s" % (minutes, "s"[minutes==1:])
sstr = "%s second%s" % (seconds, "s"[seconds==1:])
dhms = [dstr, hstr, mstr, sstr]
for x in range(len(dhms)):
if not dhms[x].startswith('0'):
dhms = dhms[x:]
break
dhms.reverse()
for x in range(len(dhms)):
if not dhms[x].startswith('0'):
dhms = dhms[x:]
break
dhms.reverse()
return ', '.join(dhms)
</code></pre>
<p>Essentially, it's shaving off both ends of a list to make the results more meaningful.</p>
<p>The code above feels clunky though. Is there a more "Pythonic" way to do it? I'm using Python 2.7.3.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:12:56.853",
"Id": "61584",
"Score": "0",
"body": "Use `xrange` instead of `range` and `str.format` instead of the `%` operator. But these are just side notes ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:16:53.373",
"Id": "61585",
"Score": "2",
"body": "You can also use `\"s\" if hours==1 else \"\"` instead of `\"s\"[hours==1:]`. This goes with the \"Explicit is better than implicit.\" Python idiom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:44:32.103",
"Id": "61586",
"Score": "0",
"body": "Thanks. The main part I wanted to clear up was the two for loops and the double reversing. This seems like something python could do in a single line. Maybe. Hmm."
}
] |
[
{
"body": "<ul>\n<li>Use a <a href=\"http://docs.python.org/2/reference/expressions.html#conditional-expressions\" rel=\"nofollow\">ternary operator</a> in <code>\"s\"[seconds==1:]</code>.</li>\n<li>Use a generator expression to replace the <code>xstr = \"%s...</code> lines.</li>\n<li>The two for loops should use <a href=\"http://docs.python.org/2/library/functions.html#enumerate\" rel=\"nofollow\"><code>enumerate()</code></a>, i.e. they could be <code>for s, i in range(...)</code>.</li>\n<li>The two for loops should be moved into a <code>for _ in range(2):</code>.</li>\n<li><code>i</code> is preferred over <code>x</code> when using an <em>i</em>ncrementing <em>i</em>ndex counter.</li>\n<li>The filtering of the redundant strings which the for-loop does could be done earlier so that the number to string code can be modified but the filtering code will not require adjustments.</li>\n</ul>\n\n<p><em>PS</em>: I have implemented a similar function <a href=\"https://github.com/RamchandraApte/unvanquished-installer/blob/master/installer.py#L232\" rel=\"nofollow\">here</a>:</p>\n\n<pre><code> days, rem = divmod(seconds, 86400)\n hours, rem = divmod(rem, 3600)\n minutes, seconds = divmod(rem, 60)\n if seconds < 1:seconds = 1\n locals_ = locals()\n magnitudes_str = (\"{n} {magnitude}\".format(n=int(locals_[magnitude]), magnitude=magnitude)\n for magnitude in (\"days\", \"hours\", \"minutes\", \"seconds\") if locals_[magnitude])\n eta_str = \", \".join(magnitudes_str)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:42:04.950",
"Id": "61587",
"Score": "0",
"body": "I really like this because it's teaching me how to get under the belly of Python. However, it doesn't __quite__ do what I would like. Or what my function above does. Your code could return something like this:\n\n\"7 days, 5 seconds\"\n\nIe because hours and minutes aren't set they're not shown. I don't like this, but purely on aesthetic grounds. For me, intervening zero time intervals should be shown, eg \"7 days, 0 hours, 6 minutes\" not \"7 days, 6 minutes\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T05:03:56.000",
"Id": "61588",
"Score": "0",
"body": "@Paul Yes, it doesn't do exactly the same thing as yours. I should update it to shave off both the ends like yours does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-06T19:15:59.687",
"Id": "504615",
"Score": "0",
"body": "I'm not sure if using `locals()` is considered best practice. I probably rather give it a dict instead. Makes it easier to adapt it for other languages, too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:17:24.727",
"Id": "37286",
"ParentId": "37285",
"Score": "3"
}
},
{
"body": "<p><em>Pythonic</em> is in the eye of the beholder, but here's my stab at it:</p>\n\n<pre><code>def verbose_timedelta(delta):\n d = delta.days\n h, s = divmod(delta.seconds, 3600)\n m, s = divmod(s, 60)\n labels = ['day', 'hour', 'minute', 'second'] \n dhms = ['%s %s%s' % (i, lbl, 's' if i != 1 else '') for i, lbl in zip([d, h, m, s], labels)]\n for start in range(len(dhms)):\n if not dhms[start].startswith('0'):\n break\n for end in range(len(dhms)-1, -1, -1):\n if not dhms[end].startswith('0'):\n break \n return ', '.join(dhms[start:end+1])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:39:23.323",
"Id": "61589",
"Score": "0",
"body": "Cool, looks like it might fall foul to \"0 hour ago\". Plural exists on zero quantities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T18:42:33.133",
"Id": "61590",
"Score": "0",
"body": "@Paul: Changed `i > 1` to `i != 1` to address zero quantities."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T20:11:53.910",
"Id": "37287",
"ParentId": "37285",
"Score": "3"
}
},
{
"body": "<p>here are my cents:</p>\n<ol>\n<li>From the 1st look, I see quite a lot of duplication. When you see repeated code try to somehow unify it. But not at whatever cost. Everything has a limit ;) But the <code>s</code> suffix handling can be definitely unified somehow.</li>\n<li>There is useful <code>timedelta.total_seconds()</code> method. It's better to use it than handling the attributes separately.</li>\n<li>I think also the handling of zeros should be done in reverse. You should filter them out by comparing <code>hours > 0</code> etc. and only then format the data into a string. Numbers are much better data for processing in your case and the converting to the UI (in this case "string") should be the last piece of the code.</li>\n</ol>\n<p>I would like to add my readable version of the readable <code>timedelta</code> in Python 3 :) Hope it helps you and other people how to make it a little more readable. It's not the exact version as yours but still, there are some useful hints about data structures and the program flow.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def readable_timedelta(duration: timedelta):\n data = {}\n data['days'], remaining = divmod(duration.total_seconds(), 86_400)\n data['hours'], remaining = divmod(remaining, 3_600)\n data['minutes'], data['seconds'] = divmod(remaining, 60)\n\n time_parts = [f'{round(value)} {name}' for name, value in data.items() if value > 0]\n if time_parts:\n return ' '.join(time_parts)\n else:\n return 'below 1 second'\n</code></pre>\n<p>It does not handle the <code>s</code> suffixes so it will produce <code>1 minutes</code> and similar, but that is no big deal for me. It should be easy to add also suffix handling. For example like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def readable_timedelta(duration: timedelta):\n data = {}\n data['days'], remaining = divmod(duration.total_seconds(), 86_400)\n data['hours'], remaining = divmod(remaining, 3_600)\n data['minutes'], data['seconds'] = divmod(remaining, 60)\n\n time_parts = ((name, round(value)) for name, value in data.items())\n time_parts = [f'{value} {name[:-1] if value == 1 else name}' for name, value in time_parts if value > 0]\n if time_parts:\n return ' '.join(time_parts)\n else:\n return 'below 1 second'\n</code></pre>\n<p>And here are the tests:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@pytest.mark.parametrize('duration, readable_duration', [\n (timedelta(), 'below 1 second'),\n (timedelta(seconds=29), '29 seconds'),\n (timedelta(seconds=61), '1 minutes 1 seconds'),\n (timedelta(minutes=5, seconds=66), '6 minutes 6 seconds'),\n (timedelta(hours=4, minutes=0, seconds=5), '4 hours 5 seconds'),\n (timedelta(hours=48, minutes=5), '2 days 5 minutes'),\n])\ndef test_readable_timedelta(duration, readable_duration):\n assert readable_timedelta(duration) == readable_duration\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T08:54:09.473",
"Id": "245215",
"ParentId": "37285",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37286",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T16:08:40.283",
"Id": "37285",
"Score": "5",
"Tags": [
"python",
"optimization",
"datetime",
"formatting"
],
"Title": "Efficient human readable timedelta"
}
|
37285
|
<p>I've some classes (<code>Derived1</code>, <code>Derived2</code>, etc.) derived from class <code>Base</code>. All of derived classes have a following methods (reduced sample):</p>
<pre><code>void Derived1::handleTimer(const StatusType &st) {
if (!st.isOk()) {
m_timer->WakeUpPeriod(10); // wait for 10 seconds;
m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
return;
}
try {
... // there is some specific for Derived's code
m_timer->WakeUpPeriod(10 * 60); // wait for 10 minutes;
m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
}
catch(...) {
m_timer->WakeUpPeriod(10); // wait for 10 second;
m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
}
}
void Derived1::start() {
m_timer->WakeUpPeriod(1); // wait for 1 second;
m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
}
</code></pre>
<p>I'd like to move these methods to <code>Base</code>. However, my trying looks pretty ugly. Is there more appropriate way?
There is my current solution.</p>
<pre><code>class Base {
public:
typedef boost::function <void (const StatusType&)> HandlerType;
Base(HandlerType handler) : m_hadler(handler) {}
void start() {
m_timer->WakeUpPeriod(1); // wait for 1 second;
m_timer->SetHandler(m_handler);
}
protected:
virtual void doSomeSpecific() = 0;
void handleTimer(const StatusType &st) {
if (!st.isOk()) {
m_timer->WakeUpPeriod(10); // wait for 10 seconds;
m_timer->SetHandler(m_handler);
return;
}
try {
doSomeSpecific();
m_timer->WakeUpPeriod(10 * 60); // wait for 10 minutes;
m_timer->SetHandler(m_handler);
}
catch(...) {
m_timer->WakeUpPeriod(10); // wait for 10 second;
m_timer->SetHandler(m_handler);
}
}
private:
HandlerType m_handler;
... // other data and function members
};
</code></pre>
<p>Now <code>Derived</code> classes</p>
<pre><code>void Derived1::doSomeSpecific() { ... }
Derived1::Derived1() : Base(boost::bind(Derived1::handleTimer, this, _1) {}
void Derived1::handleTimer(const StatusType &st) { Base::handleTimer(st); }
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:50:46.273",
"Id": "61612",
"Score": "3",
"body": "Why would the derived classes have to override `handleTimer()`? Couldn't they just inherit it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T09:50:04.027",
"Id": "61619",
"Score": "0",
"body": "Why do you call `AsynWait` on `Derived1::handleTimer` inside `Derived1::handleTimer` itself? This looks like an endless recursion to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:08:49.270",
"Id": "61622",
"Score": "0",
"body": "@Andris - Looks like I obfuscate code trying to make sample. Thank you. See update"
}
] |
[
{
"body": "<p>The use of <code>doSomeSpecific</code> inside of <code>handleTimer</code> is remarkably similar to the <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow\">Template Pattern</a>.</p>\n\n<p>If there is no base implementation of <code>doSomeSpecific</code> you might consider making it private (still virtual so it can be overridden). Unless of course you really want further derived classes to be able to call the <code>doSomeSpecific</code> implementations of their parent classes.</p>\n\n<p>Also, you can consider making <code>handleTimer</code> non-virtual if all derived classes must have the same behavior.</p>\n\n<p>By making <code>doSomeSpecific</code> private, and <code>handleTimer</code> non-virtual, the only point of customization becomes <code>doSomeSpecific</code>, and it becomes an all or nothing point of customization. This can simplify your implementations of your derived classes, because you can trust that they only customize one specific part of your base class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:21:57.247",
"Id": "37311",
"ParentId": "37294",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T08:46:07.447",
"Id": "37294",
"Score": "7",
"Tags": [
"c++",
"inheritance",
"boost"
],
"Title": "Moving method from derived class to base"
}
|
37294
|
<p>I am trying to import a .csv file, clean the contents, and make sure all the errors are eliminated.</p>
<ul>
<li>IO error</li>
<li>file format error</li>
<li>data error</li>
</ul>
<p>I am using the snippet below. Could someone help me clean it and make it more pythonic?</p>
<pre><code>try:
fl = request.FILES['csv']
except:
return HttpResponse("Some IO Error")
try:
reader = csv.reader(fl)
except:
return HttpResponse("File Not Supported")
reader.next() # this makes sure the heading is
cleaned_csv_content = list()
for row in reader:
err = 0
fname, lname, e_mail = row
try:
validate_email(email)
except:
pass
err = 1
if not err:
cleaned_csv_content.append(fname, lname, e_mail)
</code></pre>
|
[] |
[
{
"body": "<p>Firstly, you should <code>raise</code> not <code>return</code> your errors.</p>\n\n<p>Secondly, <code>try:</code> with a bare <code>except:</code> is bad practice (e.g. <a href=\"http://blog.codekills.net/2011/09/29/the-evils-of--except--/\" rel=\"nofollow\">http://blog.codekills.net/2011/09/29/the-evils-of--except--/</a>); what do you expect <em>could</em> go wrong with each step? Test for specific errors and deal with them appropriately. It is this which has hidden the <code>NameError</code> I mention at the end.</p>\n\n<p>Thirdly, your use of the flag <code>err</code> seems a bit odd; much more Pythonic to use an actual boolean <code>err = False</code> or, better, <code>else:</code>:</p>\n\n<pre><code>try:\n validate_email(e_mail) # see comment below\nexcept: # but only the errors you expect - see above \n pass\nelse:\n cleaned_csv_content.append((fname, lname, e_mail)) # note additional parentheses\n</code></pre>\n\n<p>or, even better, refactor <code>validate_email</code> to <code>return True</code> for a valid email and <code>False</code> otherwise, rather than raising errors:</p>\n\n<pre><code>if validate_email(e_mail):\n cleaned_csv_content.append((fname, lname, e_mail))\n</code></pre>\n\n<p>Finally, note that <code>\"email\" != \"e_mail\"</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:36:58.847",
"Id": "61626",
"Score": "0",
"body": "how about the for loops, can that be made more idiomatic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:38:33.193",
"Id": "61627",
"Score": "0",
"body": "No; `for row in reader:` is fine and the tuple unpacking of each `row` is very Pythonic"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:43:03.080",
"Id": "61629",
"Score": "0",
"body": "I am getting this error - `Error: 'line contains NULL byte'` `for row in reader` Any corrections?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:51:34.200",
"Id": "61630",
"Score": "0",
"body": "Not to the code, as such; you will need to look at your input data and what is ending up in `reader`, or use another `try` and handle that specific error appropriately (e.g. `pass` on that line)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T11:29:21.830",
"Id": "61631",
"Score": "0",
"body": "thanks done, another doubt. I am getting output of - `for row in readline: print row` as follows \n\n`['First Name\\tLast Name\\tEmail Address']\n['ASdf \\tasdf\\tasdf@asdf.asdf']`\n\nThe delimiter here is \\t, any idea how to fix it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T11:31:21.413",
"Id": "61632",
"Score": "0",
"body": "Read the [documentation](http://docs.python.org/2/library/csv.html#csv.reader)! Iterative StackExchange commenting is not an appropriate way to write a programe."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:29:51.297",
"Id": "37299",
"ParentId": "37298",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T10:18:28.193",
"Id": "37298",
"Score": "6",
"Tags": [
"python",
"django",
"csv"
],
"Title": "Creating a pythonic snippet to read and clean .csv files"
}
|
37298
|
<p>I'm working on a website on ASP.NET MVC4 and EF5. I want to ensure that only modified values are updated in the database. I'm using a unit of work pattern and repositories for data work. Here's the code for a generic repository. I've two questions, and need a code review for the following code.</p>
<ol>
<li><p><em>Is the code to update only modified fields good?</em> It works, but I don't know if this is the best way. I especially don't like that I have to do this loop through the properties myself (can't EF do this?). I also don't like the cast to object and the comparison.</p></li>
<li><p><em>How are my Add and Update methods?</em> I'm planning the clients (MVC/API controllers) to use a service (passing in a unit of work) to get the work done. They will not directly use the repository. The repository will not have a Save() method, only the UnitOfWork will have one. I can ensure within the service that I will use the same context to update/add entities. Given this, are there any scenarios where my Add/Update code is going to fail?</p></li>
</ol>
<pre><code>public class EFRepository<T> : IRepository<T> where T : class
{
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public EFRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
public virtual void Add(T entity)
{
DbContext.Entry(entity).State = EntityState.Added;
}
public virtual void Update(T entity)
{
//dbEntityEntry.State = EntityState.Modified; --- I cannot do this.
//Ensure only modified fields are updated.
var dbEntityEntry = DbContext.Entry(entity);
foreach (var property in dbEntityEntry.OriginalValues.PropertyNames)
{
var original = dbEntityEntry.OriginalValues.GetValue<object>(property);
var current = dbEntityEntry.CurrentValues.GetValue<object>(property);
if (original != null && !original.Equals(current))
dbEntityEntry.Property(property).IsModified = true;
}
}
//... Other methods ...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T19:14:45.243",
"Id": "61675",
"Score": "0",
"body": "So this is assuming the T entity is not already an object obtained directly from the dbcontext already?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T19:20:05.047",
"Id": "61677",
"Score": "0",
"body": "yes, T is not something like dbconext.Persons.First(). T is a domain class auto-generated by Ef. an instance of this type is created, typically from view model."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T19:22:31.103",
"Id": "61678",
"Score": "0",
"body": "Is there any reason why you wouldn't obtain the entity direct and manipulate that only? then you don't have to worry about calling any update method. Perhaps you could use something like AutoMapper to map from your viewmodel to model? Just thoughts"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T19:34:06.457",
"Id": "61679",
"Score": "0",
"body": "my bad, I do call a FindById() before the update, as I get only the Id from the view. then after I map the VM to the object, I call this Update(). so it does come from the same context after all. Oh, do you mean to say I don't even have to set entitystate??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T19:40:21.363",
"Id": "61681",
"Score": "4",
"body": "If you are obtaining the object from your context, then by modifynig those properties and then calling SaveChanges on your context it will perform an update on that model already. EF handles this for you. Is that your understanding?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T03:30:37.803",
"Id": "62202",
"Score": "0",
"body": "@dreza I misunderstood the reason for [this](http://msdn.microsoft.com/en-in/data/jj592676.aspx) post. I misunderstood the \"disconnected\" scenario. I did some more experiments, and realized that as long as I use everything within the same context scope, it works perfectly. Only modified properties are sent to DB, adds and updates are handled by EF itself. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-25T05:32:48.877",
"Id": "283887",
"Score": "1",
"body": "Just an update, I've totally moved away from EF and am completely on Dapper now."
}
] |
[
{
"body": "<p>Why bother checking if the value/property has been changed? You are just adding additional complexity for no reason. Sure, it might be <em>slightly!</em> faster to only update modified values, but in return you are adding an overhead to keep track of the modified values, which will diminish whatever performance boost you got. </p>\n\n<p>Just invoke <code>Update</code> on the entire object... All values that has not been changed will remain the same and the values that has been modified will, well, update.</p>\n\n<p>If it's speed you're looking for you are <em>most likely</em> looking at the wrong place to squeeze ms from. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T14:09:08.233",
"Id": "61647",
"Score": "16",
"body": "I'm thinking from a DB perspective. If I update all the fields in a row, *ALL* my indexes in that table are going to get updated. Okay, most likely I wont have this logic for all entities, but in certain heavy tables, I need to have this option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-04T18:29:54.373",
"Id": "232652",
"Score": "3",
"body": "@Narayana because a large part of the C# community (note: NOT C# itself) penalizes anyone who dares to think in terms of performance. That's a biiiig no no. Yeah, you're right, I'm a bit jaded about this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-16T17:39:09.710",
"Id": "305015",
"Score": "1",
"body": "And what if after all the checks it turns out that no updates are necessary at all and we can save the whole round-trip to the database. Not to mention potential caches invalidation and as @Narayana mentions rebuilding the indices."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-19T20:46:41.097",
"Id": "305774",
"Score": "1",
"body": "To extend on the idea that updating fields in the DB without changes, consider (albeit poorly written) triggers that check IF UPDATE(FieldName) and then execute logic. If EF includes the unchanged field in the update statement, it will check true in the IF UPDATE(FieldName) check and likely perform unnecessary logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T13:48:55.493",
"Id": "438197",
"Score": "1",
"body": "This is such a poor answer.. what if you are developing a mobile application and you have a wide table. Just send the entire DTO back, all 45 columns and update the indexes? As mentioned above, what if the table is heavily indexed? Now we should just cause fragmentation in 10 indexes as well? Can't believe this got 24 up votes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T15:40:23.800",
"Id": "449496",
"Score": "0",
"body": "Guys, why did you blindly assumed that the database will rebuild the indexes when data was changed to the same value? The same optimization could and most like is implemented on the database side."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T14:00:26.963",
"Id": "37306",
"ParentId": "37304",
"Score": "30"
}
},
{
"body": "<p>I am just learning EF but I would worry about concurrent users with your update. </p>\n\n<p>When you call SaveChanges it would be best if EF will only update the fields that are changed to minimize the chance for collisions or overwriting the changes of a concurrent user. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:36:46.117",
"Id": "72259",
"Score": "0",
"body": "Hi, I ended up doing everything within a context, so EF takes care of it. I do not have disconnected scenarios now, meaning, I don't explicitly set modified or added states. I let EF take care of those."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T20:32:10.000",
"Id": "72833",
"Score": "1",
"body": "So if you make use of the change tracking for the entities I think EF will generate an update for only those columns that are dirty. But I know that it can also be circumvented or overridden (such as attach after setting field values, etc) so just wanted to make sure everyone's code watches out for this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T18:05:31.420",
"Id": "74097",
"Score": "0",
"body": "@sdmcnitt then this should probably be a comment..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T11:30:21.187",
"Id": "41953",
"ParentId": "37304",
"Score": "3"
}
},
{
"body": "<p>If you are worried about the update statement that it might slow the query down, I would suggest a slightly different approach. You can modify your code to pass in the modified property list. So that in scenarios when you know which property is updated you have an option to make it even quicker and also when no property is supplied, then you can update all - </p>\n\n<pre><code>public virtual void Update(T entity, params Expression<Func<T, object>>[] updatedProperties)\n{\n //dbEntityEntry.State = EntityState.Modified; --- I cannot do this.\n\n //Ensure only modified fields are updated.\n var dbEntityEntry = DbContext.Entry(entity);\n if (updatedProperties.Any())\n {\n //update explicitly mentioned properties\n foreach (var property in updatedProperties)\n {\n dbEntityEntry.Property(property).IsModified = true;\n }\n }else{\n //no items mentioned, so find out the updated entries\n foreach (var property in dbEntityEntry.OriginalValues.PropertyNames)\n {\n var original = dbEntityEntry.OriginalValues.GetValue<object>(property);\n var current = dbEntityEntry.CurrentValues.GetValue<object>(property);\n if (original != null && !original.Equals(current))\n dbEntityEntry.Property(property).IsModified = true;\n }\n }\n}\n</code></pre>\n\n<p>This approach gives you the freedom of doing the both of the below - </p>\n\n<pre><code>_repository.Update(obj);\n</code></pre>\n\n<p>and also </p>\n\n<pre><code>_repository.Update(obj, o => o.Name, o => o.Description);\n</code></pre>\n\n<p>Also notice, I am taking <code>params</code>. So you can chain as much properties as you like.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-06T20:25:08.463",
"Id": "292436",
"Score": "0",
"body": "I appreciate this idea because it's very helpful, but I'm struggling to understand how to implement the \"else\" clause that finds the updated entries. Every time my OriginalValues match my CurrentValues for every property. How does it know the original values?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-31T06:43:37.883",
"Id": "109352",
"ParentId": "37304",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "37306",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T12:57:24.690",
"Id": "37304",
"Score": "35",
"Tags": [
"c#",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Update only modified fields in Entity Framework"
}
|
37304
|
<p>I have many small but similar classes like these:</p>
<pre><code>class DepartmentSerializer < Serializer
self.root = false
attributes :id, :name
has_many :employees, serializer: EmployeeSerializer
has_one :location, serializer: LocationNameSerializer
end
class DepartmentWithManagersSerializer < Serializer
self.root = false
attributes :id, :name
has_many :primary_managers, serializer: ManagerSerializer
has_many :secondary_managers, serializer: ManagerSerializer
end
class DepartmentNameSerializer < Serializer
self.root = false
attributes :id, :name
end
class DepartmentWithEmployeesSerializer < Serializer
self.root = false
attributes :id, :name
has_many :employees, serializer: EmployeeNameSerializer
end
</code></pre>
<p>As you can see they're all just variations on a theme. There is a potential here for a combinatorial explosion of classes if there are enough use cases. Should I do something like <code>ActiveRecord</code>'s find methods which allow you to create methods like <code>.find_by_name_and_manager_and_location</code>?</p>
|
[] |
[
{
"body": "<p>Using inheritance, first you can clean up your structure as following:</p>\n\n<pre><code>class DepartmentNameSerializer < Serializer\n self.root = false\n attributes :id, :name\nend\n\nclass DepartmentSerializer < DepartmentNameSerializer\n has_many :employees, serializer: EmployeeSerializer\n has_one :location, serializer: LocationNameSerializer\nend\n\nclass DepartmentWithManagersSerializer < DepartmentNameSerializer\n has_many :primary_managers, serializer: ManagerSerializer\n has_many :secondary_managers, serializer: ManagerSerializer\nend\n\nclass DepartmentWithEmployeesSerializer < DepartmentNameSerializer\n has_many :employees, serializer: EmployeeNameSerializer\nend\n</code></pre>\n\n<p>There is little you can do to really enhance your code any further in terms of readability and reusability if you want to separate all serializer contexts into separate classes like this.</p>\n\n<p>If you are using <code>ActiveModel::Serializers</code> which I think you do, since <code>0.8.0</code> you can use <code>ActiveRecord</code>-Serialization-like <code>:except</code> and <code>:only</code> to add some serialization context, so you could refactor your structure to work like the following:</p>\n\n<pre><code>class DepartmentSerializer < Serializer\n self.root = false\n attributes :id, :name, :employee_names, :location_names\n # it is afaik not possible to pass serialization context to the other serializers \n # via association\n # has_many :employee_names, serializer: EmployeeSerializer, only: :name\n # has_one :location_names, serializer: LocationSerializer, only: :name\n has_many :employees, serializer: EmployeeSerializer\n has_many :primary_managers, serializer: ManagerSerializer\n has_many :secondary_managers, serializer: ManagerSerializer\n\n def employee_names\n EmployeeSerializer.new(object.employees, only: :name) # + root: false if EmployeeSerializer uses a root\n end\n\n def location_names\n LocationSerializer.new(object.locations, only: :name) # + root: false if LocationSerializer uses a root\n end\nend\n</code></pre>\n\n<p>And your controllers can call the <code>DepartmentSerializer</code> like this:</p>\n\n<pre><code>class DepartmentController < ApplicationController # or other\n\n def some_context_with_managers\n render json: @department, except: %i(employees employee_names location_names)\n end\n\n # ... and so on\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T22:32:34.087",
"Id": "61951",
"Score": "0",
"body": "You're right that I'm using ActiveModel::Serializers. I didn't know about the :except and :only options. Thanks for the tip and the great answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:51:25.103",
"Id": "37444",
"ParentId": "37305",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37444",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T13:49:56.223",
"Id": "37305",
"Score": "5",
"Tags": [
"object-oriented",
"ruby",
"serialization",
"active-record"
],
"Title": "Classes to serialize departments and their employees"
}
|
37305
|
<p>The specific issue is this: I am writing to a file and want to output a new line after each line written. If I use a normal loop without any further checks, this will create a blank line at the very end of the file for no reason. So I need to do this every time <em>except</em> the last one.</p>
<p>Despite the fact that this is a specific problem, I'm actually looking for a better <em>general</em> coding practice to deal with scenarios like this, since it isn't the first and won't be the last time I have to deal with it.</p>
<p>Here's my unsatisfying solution:</p>
<pre><code>//Write contents to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for(int i = 0; i < lines.size(); i++) {
writer.write(lines.get(i));
if(i < lines.size() - 1) writer.newLine();
}
</code></pre>
<p>It seems wasteful to check the conditions twice through each iteration of the loop, and I feel like there ought to be a better way to accomplish what I want without the vague code smell. Anyone have any cool tips or tricks to make this more elegant?</p>
<p>It also prevents me from using an enhanced for loop, which makes me sad.</p>
<p><code>lines</code> is a <code>List<String></code>.</p>
<p>Also, for those saying I should just join all the <code>String</code>s with <code>\n</code>, that's not an adequate solution. Firstly, it doesn't actually address the general coding practice. Secondly, when writing to a file with a <code>BufferedWriter</code>, it's important to use <a href="http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#newLine%28%29"><code>newLine()</code></a> rather than writing a <code>\n</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T19:36:14.340",
"Id": "61680",
"Score": "7",
"body": "*Somebody has to say this... a text file is a series of lines. A line includes a newline terminator. A file that does not have a newline as its final character **is not a text file**. A file that ends in a blank line has 2 consecutive newlines as its last 2 characters: one to terminate the next-to-last line and one to terminate the empty line. \"Text files\" with an unterminated last line are a disease. Don't catch it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:15:05.207",
"Id": "61684",
"Score": "3",
"body": "@WumpusQ.Wumbley In what circumstances would that _ever_ be necessary? I'm not saying there are none, I just don't know of any. Arbitrarily declaring a format that all text files must follow seems overly ambitious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:17:26.643",
"Id": "61685",
"Score": "2",
"body": "@WumpusQ.Wumbley It may be a windows thing, from [wikipedia Text file](http://en.wikipedia.org/wiki/.txt#Standard_Windows_.txt_files) : \"MS-DOS and Windows use a common text file format, with each line of text separated by a two-character combination: CR and LF, which have ASCII codes 13 and 10. It is common for the last line of text not to be terminated with a CR-LF marker, and many text editors (including Notepad) do not automatically insert one on the last line.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:31:28.353",
"Id": "61686",
"Score": "0",
"body": "@DanielCook It's not just a Windows thing. Many Unix shell utilities, especially the older ones, behave unpredictably if the last line doesn't end in LF. On the other hand, sometimes the *absence* of a final LF is essential, as when using PHP to generate XML - if the PHP source file has a LF after the final `?>`, it will be copied to the output and probably wind up in a place where the XML parser doesn't like it. So it's not by any means a hard rule."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:45:42.180",
"Id": "61689",
"Score": "1",
"body": "@WumpusQ.Wumbley - One of the 16-bit Visual C++ compilers had a bug that would manifest when the source file did not end with CR/LF. But I haven't encountered anything else with such an issue in the past 15 years."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:27:58.897",
"Id": "61696",
"Score": "0",
"body": "@WumpusQ.Wumbley: What term would you use to describe a file which encapsulates a sequence of lines, potentially followed by a partial line? The fact that concatenating such files will cause the partial line at the end of one to be joined to the first line of the second is often a bad thing, but is in some cases exactly what is required (especially when the second file contains only one line or partial line)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T23:41:49.073",
"Id": "61738",
"Score": "0",
"body": "@WumpusQ.Wumbley Interesting. But there's actually a specific reason I don't want a blank line at the end of the document. What I'm writing is a CSV file which will be uploaded line by line to a database. I'd rather have every line in the file legitimately be a row in the table, rather than having extraneous empty lines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T09:07:35.343",
"Id": "61752",
"Score": "0",
"body": "@WumpusQ.Wumbley: I can't tell if you're being serious or sarcastic..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:38:08.227",
"Id": "61806",
"Score": "0",
"body": "@JeffGohlke Most if not all DB export / import utils use a newline at the end. Winblows / M$SQL might as always be an exception, but it's common practice to have it there. I remember numerous times when I was almost ready to buy a plane ticket just to go over & slap the bastard who wrote stuff that didn't put it there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:46:32.040",
"Id": "62197",
"Score": "0",
"body": "@WumpusQ.Wumbley That is why we should stop referring to codepoints 0x0D and 0x0A as if they denoted line _breaks_. CR is really the __line begin__ character, and LF is the __line end__ character. CR's original purpose was to _move the cursor to the beginning of the line_ and LF was to _move the cursor off the current line_."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:54:14.430",
"Id": "62199",
"Score": "0",
"body": "@WumpusQ.Wumbley Ideally, they really ought to work the same way STX and ETX ought to be used, to denote the start and end of textual data."
}
] |
[
{
"body": "<p>I presume <code>lines</code> is a Collection of some sort. One option that has slightly less of a smell (although it still is odoriferous), is to use an iterator, which will essentially do the same work, but will be more readable:</p>\n<pre><code>for (Iterator<String> it = lines.iterator(); it.hasNext();) {\n writer.write(it.next());\n if (it.hasNext()) {\n writer.newline();\n }\n}\n</code></pre>\n<p>As I say, all this does is make it more readable....</p>\n<p>Other options are to duplicate the <code>write</code> - once in the loop, and then the last one outside the loop:</p>\n<pre><code>if (!lines.isEmpty()) {\n int limit = lines.size() - 1;\n for (int i = 0; i < limit; i++) {\n ....\n }\n writer.write(lines.get(limit));\n}\n</code></pre>\n<p><strong>EDIT:</strong> <a href=\"https://codereview.stackexchange.com/users/14625\">@konijn</a> suggested reversing the newline to happen only after the first line as follows:</p>\n<pre><code>if (!lines.isEmpty()) {\n writer.write(lines.get(0));\n // start index at 1 instead of 0.\n for (int i = 1; i < lines.size(); i++) {\n writer.newline();\n writer.write(lines.get(limit));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:15:47.930",
"Id": "61650",
"Score": "0",
"body": "Yep, `lines` is a `List<String>`. Nice. I like the idea of performing the last `write` outside of the loop rather than constantly checking inside of the loop. Still seems vaguely funky to me, but better than what I've got now. Thanks. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:22:30.927",
"Id": "61651",
"Score": "9",
"body": "I tend to write the first one without newline, then write newline + nextline for the rest, starting loop from 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:23:57.867",
"Id": "61652",
"Score": "1",
"body": "@tomdemuyt - put that in an answer - it's a good solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:34:44.177",
"Id": "61655",
"Score": "0",
"body": "@tomdemuyt That's actually probably what I'll end up doing, now that you mention it. You definitely should post that as an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:03:16.653",
"Id": "61692",
"Score": "0",
"body": "Reason I did not is because in my case I always have minimum 2 lines, now the code can fail if there is only 1 line, and then it gets ugly again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:58:56.667",
"Id": "62236",
"Score": "0",
"body": "We have for-each-loops now - no need for for loops with indices as in your later code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-12-13T14:59:41.773",
"Id": "37310",
"ParentId": "37309",
"Score": "23"
}
},
{
"body": "<p>This case is usually concerning joining strings. There's a method for that in Apache Commons Lang:</p>\n\n<pre><code>StringUtils.join(lines, \"\\n\");\n</code></pre>\n\n<p>Also here's a pattern that can be used with a <code>foreach</code> loop</p>\n\n<pre><code>StringBuilder buf = new StringBuilder();\nfor (String line : lines) {\n if(buf.length() > 0) {\n buf.append(\"\\n\");\n }\n buf.append(line);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:39:12.190",
"Id": "61656",
"Score": "0",
"body": "I am not sure this code solves the problem ... `!lines.isEmpty()` will return true on every run through the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:46:02.167",
"Id": "61658",
"Score": "0",
"body": "My mistake: I meant `buf.isEmpty()`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:27:08.727",
"Id": "37312",
"ParentId": "37309",
"Score": "13"
}
},
{
"body": "<p>A small twist on @rolfls' answer:</p>\n\n<pre><code>BufferedWriter writer = new BufferedWriter(new FileWriter(file));\nif ( lines.size() > 0 ) {\n writer.write(lines.get(0));\n}\nfor (int i = 1; i < lines.size(); i++) {\n writer.newLine();\n writer.write(lines.get(i));\n}\n</code></pre>\n\n<p>Exact same idea though, move the extra check outside of the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:51:12.250",
"Id": "61660",
"Score": "0",
"body": "Hm... are you coming from JavaScript? I don't think `if(lines.size())` will compile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:05:25.530",
"Id": "61662",
"Score": "0",
"body": "Indeed -- It's the logic I'd like to express, not the syntax ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:12:25.633",
"Id": "61694",
"Score": "0",
"body": "FWIW, I personally feel this may be the best approach. I was about to post the same idea, when I finally noticed someone already had. The *reason* I like this better is that there is only one `if` check done at the beginning. Most of the other solutions require doing some kind of comparison each run through. In this case, we can eliminate unnecessary comparisons through the for loop. My two cents..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:44:36.530",
"Id": "61762",
"Score": "1",
"body": "`lines.size() > 0` is lame and potentially harmful (if `lines` is a singly linked list, knowing its size might be `O(n)`). Use `lines.nonEmpty()` or `!lines.isEmpty()` if the earlier is not available."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:42:58.287",
"Id": "37314",
"ParentId": "37309",
"Score": "5"
}
},
{
"body": "<p>You can do it by just removing the last seperator when you are done:</p>\n\n<pre><code>CharSequence concatSep(Iterable<?> items, CharSequence separator){\n if(!lines.iterator().hasNext()) return \"\";\n\n StringBuilder b = new StringBuilder();\n for(Object item: items)\n b.append(item.toString()).append(separator);\n return b.delete(b.length() - separator.length(), b.length());\n}\n</code></pre>\n\n<p>where <code>separator</code> is the desired item seperator, whether newline, comma, semicolon, tab, or more than one character.</p>\n\n<p>In your case: <code>concatSep(lines, System.getProperty(\"line.seperator\"))</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T05:59:26.490",
"Id": "61744",
"Score": "0",
"body": "This does not work if lines.Length == 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:23:36.520",
"Id": "61780",
"Score": "0",
"body": "@Matt Fixed, also put them in functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T17:02:49.383",
"Id": "37315",
"ParentId": "37309",
"Score": "8"
}
},
{
"body": "<p>For the general case you can either pull the first or last line out of the loop, or move the loop exit into the middle of the loop using a break statement - modifying rolfl's example:</p>\n\n<pre><code>Iterator<String> it = lines.iterator()\nif (it.hasNext()) {\n while (true) {\n writer.write(it.next());\n if (!it.hasNext()) \n break;\n writer.newline();\n }\n}\n</code></pre>\n\n<p>'Structured programming with goto statements' is a classic paper on handling non-standard looping cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:24:09.307",
"Id": "61897",
"Score": "1",
"body": "This pattern is my favorite because: a. It doesn't require you to duplicate code - \"writer.write\" appears only once. b. It doesn't require you to duplicate tests inside the loop - the loop exit test is performed only once, in the middle of the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:39:24.650",
"Id": "62196",
"Score": "0",
"body": "A better idiom for this needs to be added to java: just let the user have both a block before _and_ after the same `while`. Like this: `do { doSomething(); } while (condition()) { doSomethingElse(); }`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T18:34:43.403",
"Id": "37317",
"ParentId": "37309",
"Score": "6"
}
},
{
"body": "<p>Just a little simpler:</p>\n\n<pre><code>BufferedWriter writer = new BufferedWriter(new FileWriter(file));\nfor(int i = 0; i < lines.size(); i++) {\n if(i > 0) writer.newLine();\n writer.write(lines.get(i));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T18:36:47.580",
"Id": "37318",
"ParentId": "37309",
"Score": "5"
}
},
{
"body": "<p>why not reverse it: write a newline first except on the first line:</p>\n\n<pre><code>boolean newline = false;\nfor(int i = 0; i < lines.size(); i++) {\n if(newline) writer.newLine();\n else newline = true;\n writer.write(lines.get(i));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T18:44:37.837",
"Id": "37319",
"ParentId": "37309",
"Score": "5"
}
},
{
"body": "<p>Definitely, definitely take the <code>if</code> statement out of the loop. People always talk about \"the optimizer\" but optimizers are different, and whatever you can do to help it is probably a good idea.</p>\n\n<pre><code>//Write contents to the file\nBufferedWriter writer = new BufferedWriter(new FileWriter(file));\nfor(int i = 0; i < lines.size() - 1; i++) {\n writer.write(lines.get(i));\n writer.newLine();\n}\n\n// Write the last one without extra newline\nif( lines.size() )\n writer.write(lines.get(lines.size()-1));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T06:01:43.187",
"Id": "61746",
"Score": "0",
"body": "This does not work if lines.Length == 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T14:03:57.223",
"Id": "61756",
"Score": "0",
"body": "@Matt Good point. Fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T04:55:52.833",
"Id": "37337",
"ParentId": "37309",
"Score": "2"
}
},
{
"body": "<pre><code>BufferedWriter writer = new BufferedWriter(new FileWriter(file));\n int i =0;\n for(;i < lines.size()-1; i++)\n {\n writer.write(lines.get(i));\n writer.newLine();\n }\n if(lines.size()>0)\n {\n writer.write(lines.get(i));\n }\n</code></pre>\n\n<p>This way you can avoid the conditional statement every time, keeping your code the same.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T05:59:05.077",
"Id": "37338",
"ParentId": "37309",
"Score": "2"
}
},
{
"body": "<p>There are two issues in your code:</p>\n<ol>\n<li><p>As you noticed, the <code>if</code> is checked at each loop although you know that it will be invalidated only on the last loop. A good way to avoid the problem is to treat the first or last element of your list specifically before (or after) entering the loop. Treating the first element separately is much easier.</p>\n<p>Note that your <code>if</code> check may be quite cheap if you assume that calculating <code>size</code> is constant-time. (Note that size could be calculated once before the loop.) The optimization will probably be completely negligible (especially since you are performing costly I/O in the loop).</p>\n</li>\n<li><p>Maybe more subtle: if <code>lines</code> is a <code>List</code>, is may not be indexed (e.g., <code>lines</code> is a <code>LinkedList</code>). Calling <code>lines.get(i)</code> may then be <em>O(i)</em>, and your whole loop be <em>O(n²)</em> although <em>O(n)</em> is doable. Using an <code>Iterator</code> as @rolfl suggested is the best way to avoid this problem. It may or may not improve readibility depending on your experience, but it will surely improve performance drastically depending on the nature of your <code>List</code>.</p>\n</li>\n</ol>\n<p>BTW, this problem is solved generically in the very Java API: look for the implementation of <code>toString</code> in <code>AbstractCollection</code> (just replace separators with your own, and remove the test for <code>e == this</code> which is quite specific):</p>\n<pre><code>public String toString() {\n Iterator<E> it = iterator();\n if (! it.hasNext())\n return "[]";\n\n StringBuilder sb = new StringBuilder();\n sb.append('[');\n for (;;) {\n E e = it.next();\n sb.append(e == this ? "(this Collection)" : e);\n if (! it.hasNext())\n return sb.append(']').toString();\n sb.append(',').append(' ');\n }\n}\n</code></pre>\n<p>I would be surprised if a more general implementation with user-definable separators would not to be found in Apache Commons or Google Guava.</p>\n<p>Anyway, here is the final code, using <code>BufferedWriter</code> instead of <code>StringBuilder</code>:</p>\n<pre><code>private static void <E> write(BufferedWriter writer, List<E> lines) {\n Iterator<E> it = lines.iterator();\n if (!it.hasNext()) return;\n\n for (;;) {\n E e = it.next();\n writer.write(e);\n if (!it.hasNext()) return;\n writer.newLine();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:16:42.560",
"Id": "61777",
"Score": "0",
"body": "You're right, I knew I could simply join the various `String`s together with `\\n` as you suggest. But when writing to a file with `BufferedWriter`, you're supposed to use `newLine()` instead because it's system agnostic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T21:58:31.403",
"Id": "61829",
"Score": "0",
"body": "Well, you can still use the above structure, replacing references to `StringBuilder` by `BufferedWriter`. I edited my answer above to include the final code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:59:45.223",
"Id": "37353",
"ParentId": "37309",
"Score": "5"
}
},
{
"body": "<p>You do not need condition check if you change the loop limit from <code>lines.size()</code> to <code>lines.size() -1</code>. This ensures that the last entry in the <code>lines</code> is skipped. Next, after the loop, you write <code>line</code>'s last content.</p>\n\n<pre><code>//Write contents to the file\n BufferedWriter writer = new BufferedWriter(new FileWriter(file));\n int last = lines.size()-1;\n for(int i = 0; i < last; i++) {\n writer.write(lines.get(i));\n writer.newLine(); //no condition check anymore\n }\n\n //write last line content\n writer.write(lines.get(last)); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-01T05:14:25.550",
"Id": "64347",
"ParentId": "37309",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37310",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T14:38:49.163",
"Id": "37309",
"Score": "38",
"Tags": [
"java",
"iteration"
],
"Title": "Perform instruction in loop every time except the last time?"
}
|
37309
|
<p>I have this JavaFX code which is used for listing groups by ID and name:</p>
<pre><code>import java.util.List;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class Listobject extends Application
{
public class GroupConverter extends StringConverter<ListGroupsObj>
{
@Override
public String toString(ListGroupsObj obj)
{
return obj.getGroupId() + " - " + obj.getGroupName();
}
@Override
public ListGroupsObj fromString(String obj)
{
return ListGroupsObj.newInstance().groupName(obj);
}
}
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage stage)
{
// Insert Some data
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Group12");
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Group13");
ListGroupsObj oa = ListGroupsObj.newInstance().groupId(14).groupName("Group14");
ListGroupsObj oz = ListGroupsObj.newInstance().groupId(15).groupName("Group15");
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.setConverter(new GroupConverter());
listGroups.setButtonCell(new GroupListCell());
listGroups.setCellFactory(new Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>>()
{
@Override
public ListCell<ListGroupsObj> call(ListView<ListGroupsObj> p)
{
return new GroupListCell();
}
});
listGroups.setEditable(true);
listGroups.getItems().addAll(ob, osb, oa, oz);
listGroups.setValue(ob);
// Display the selected Group
listGroups.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ListGroupsObj>()
{
@Override
public void changed(ObservableValue<? extends ListGroupsObj> arg0, ListGroupsObj arg1, ListGroupsObj arg2)
{
if (arg2 != null)
{
System.out.println("Selected Group: " + arg2.getGroupId() + " - " + arg2.getGroupName());
}
}
});
final StackPane layout = new StackPane();
layout.getChildren().add(listGroups);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
}
class GroupListCell extends ListCell<ListGroupsObj>
{
@Override
protected void updateItem(ListGroupsObj item, boolean empty)
{
super.updateItem(item, empty);
if (item != null)
{
setText(item.getGroupId() + " - " + item.getGroupName());
}
}
}
private List<ListGroupsObj> lisGroups;
public static class ListGroupsObj
{
private int groupId;
private String groupName;
public static ListGroupsObj newInstance()
{
return new ListGroupsObj();
}
public ListGroupsObj()
{
}
public ListGroupsObj groupId(int groupId)
{
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName)
{
this.groupName = groupName;
return this;
}
public int getGroupId()
{
return groupId;
}
public String getGroupName()
{
return groupName;
}
// @Override
// public String toString()
// {
// return serverName;
// }
}
}
</code></pre>
<p>How I can make the code more compact and easy for use?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:32:14.450",
"Id": "61687",
"Score": "0",
"body": "What do you mean by \"easy for use\"? Are you planning on letting other people use this code as (part of) a library?"
}
] |
[
{
"body": "<p>I have to admit that I don't know much about JavaFX, but I do know Java so I can help you with the things I can come up with:</p>\n\n<p>If by \"more compact\" you mean \"less number of lines\" there are several things that you can do:</p>\n\n<ul>\n<li>Use Java coding conventions and don't put <code>{</code> on a new line. That alone will save several lines.</li>\n<li>You have unnecessary empty lines on some places, for example in the beginning of methods.</li>\n<li>Remove commented code, such as your <code>toString</code> method (Also, including commented code in your question here will only make us confused - Do you want your commented code to be reviewed as well? - Rhetorical question, no need to answer that)</li>\n<li>Remove public empty constructors, those are added automatically by Java</li>\n<li><p>Instead of using anonymous inner classes, you can let your <code>Listobject</code> class implement the <code>ChangeListener<ListGroupsObj></code> and <code>Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>></code> interfaces, this would let you use:</p>\n\n<pre><code>listGroups.setCellFactory(this);\n</code></pre>\n\n<p>and elsewhere in the <code>Listobject</code> class you put this method:</p>\n\n<pre><code>@Override\npublic ListCell<ListGroupsObj> call(ListView<ListGroupsObj> p) {\n return new GroupListCell();\n}\n</code></pre>\n\n<p>if you use this approach, you might want to extract an interface for your <code>Listobject</code> class, since those methods will be a part of it's public API (although there's not much harm in letting them be a part of the class' public API, it might confuse users of your class).</p></li>\n</ul>\n\n<p>A couple of other notes:</p>\n\n<ul>\n<li>Are you sure you want <code>GroupConverter</code> to be a <strong><code>public</code></strong> static class? You might want to set it to private.</li>\n<li><code>GroupListCell</code> could be, and probably should be, a <code>private static class</code></li>\n<li>Not really sure why you are using a factory method for the <code>ListGroupsObj</code> class. Instead you could pass <code>groupId</code> and <code>groupName</code> to the constructor and make the two fields <strong>final</strong> and you will have yourself a nice immutable class. Then you can remove your \"setters\" for this class.</li>\n</ul>\n\n<p>Edit: Adding a sample of code to show how to implement <code>ChangeListener<ListGroupsObj></code> and <code>Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>></code> on an existing class instead of using anonymous classes:</p>\n\n<pre><code>public class Listobject extends Application implements Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>>, ChangeListener<ListGroupsObj> {\n\n @Override\n public ListCell<ListGroupsObj> call(ListView<ListGroupsObj> p) {\n return new GroupListCell();\n }\n @Override\n public void changed(ObservableValue<? extends ListGroupsObj> arg0, ListGroupsObj arg1, ListGroupsObj arg2) {\n if (arg2 != null) {\n System.out.println(\"Selected Group: \" + arg2.getGroupId() + \" - \" + arg2.getGroupName());\n }\n }\n\n @Override\n public void start(Stage stage)\n {\n ...\n\n listGroups.setConverter(new GroupConverter());\n listGroups.setButtonCell(new GroupListCell());\n listGroups.setCellFactory(this); // \"this\" means \"the current Listobject\"\n // the current Listobject is also a Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>>, which is what the `setCellFactory` method wants\n\n listGroups.setEditable(true);\n\n listGroups.getItems().addAll(ob, osb, oa, oz);\n listGroups.setValue(ob);\n\n // Display the selected Group\n listGroups.getSelectionModel().selectedItemProperty().addListener(this); // \"this\" is a Listobject, which is also a ChangeListener<ListGroupsObj>\n\n ...\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:51:14.607",
"Id": "37322",
"ParentId": "37320",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:24:49.627",
"Id": "37320",
"Score": "4",
"Tags": [
"java",
"javafx"
],
"Title": "Listing groups by ID and name"
}
|
37320
|
<p>Basically, this function returns a list of flights for an airline. But if the airline doesn't exist, I want to throw some custom runtime exception. If that airline does exist, I want to return a list of flights (which could potentially be empty).</p>
<p>Is this is the standard way of doing things in Scala, or is there a better way to write this code? </p>
<p>Coming from a Java background, I'm still trying to get to grips with the Scala way of doing things. </p>
<pre><code>def getFlightsForAirline(id:Long):Try[Option[List[Flight]]] = {
val maybeAirline:Option[Airline] = Airline.getById(id)
maybeAirline match {
case Some(airline) => {
Success(Flight.getFlightsByAirline(airline))
}
case None => Failure(new RecordNotFoundException("Couldnt find airline"))
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>The <code>maybeAirline</code> variable isn't necessary. Note that the type annotation in the declaration is optional, and can easily be inferred by the compiler. So I would change that to:</p>\n\n<pre><code>def getFlightsForAirline(id: Long): Try[Option[List[Flight]]] =\n Airline.getById(id) match {\n case Some(airline) => Success(Flight.getFlightsByAirline(airline))\n case None => Failure(new RecordNotFoundException(\"Couldnt find airline\"))\n }\n</code></pre>\n\n<p>Notice that the Scala style guide <a href=\"http://docs.scala-lang.org/style/types.html#annotations\">suggests putting a space after the colon</a> in a type annotation – <code>name: Type</code> instead of <code>name:Type</code>.</p></li>\n<li><p>Every time you destructure an <code>Option</code> with <code>match/case</code>, they kill a puppy because you <em>should</em> have probably used <code>map</code>. Well, almost every time, because the <code>Failure</code> is an important part of this function's behaviour. But this still is somewhat of a code smell.</p></li>\n<li><p>The return type <code>Try[Option[List[Flight]]]</code> strikes me as rather weird: What is the difference between <code>Success(Some(List()))</code> and <code>Success(None())</code>? I guess the latter might occur if <code>getFlightsByAirline</code> isn't passed a valid airline.</p>\n\n<p><code>Try</code>, <code>Option</code> and <code>List</code> are essentially the same thing (either you get a result, or there isn't anything there: Failure, None or empty List). Therefore it does not make much sense to nest them, and it would be better to return a <code>Try[List[Flight]]</code>. This could be implemented along the lines of:</p>\n\n<pre><code>def getFlightsForAirline(id: Long): Try[List[Flight]] =\n Airline.getById(id) flatMap { Flight.getFlightsByAirline(_) } match {\n case Some(flights) => Success(flights)\n case None => Failure(new RecordNotFoundException(\"Couldnt find airline\"))\n }\n</code></pre>\n\n<p>This way, the <code>Failure</code> is returned if either of the <code>getXByY</code> methods returns <code>None</code>.</p>\n\n<p>Interestingly, there is no builtin way to transform an <code>Option</code> to a <code>Try</code> (along the lines of <code>maybe toTry { MyException(\"Reason\") }</code>) while there is a <code>try.toOption</code> method.</p></li>\n<li><p>Your <code>RecordNotFoundException</code> will have a much more Scala-ish vibe if you use a <a href=\"http://docs.scala-lang.org/tutorials/tour/case-classes.html\"><code>case class</code></a> here. This way, you can omit the <code>new</code> to create a new instance, and just write: <code>Failure(RecordNotFoundException(\"...\"))</code></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:21:52.430",
"Id": "61759",
"Score": "0",
"body": "+1 for the `Option[List[...]]` type, seen it too many times where it doesn't make sense :). Also how about considering `Seq` instead of `List`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:19:34.353",
"Id": "61798",
"Score": "1",
"body": "Good. You might want to comment on the clarity of ```getFlightsForAirline``` and ```getFlightsByAirline``` as well. It is not obvious which you would like to use and how either of those would behave."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:52:50.330",
"Id": "62041",
"Score": "0",
"body": "You can use a `map` here instead of a `flatMap`, cannot you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T08:58:04.587",
"Id": "62044",
"Score": "0",
"body": "@scand1sk No I cannot, that is the point of this exercise. Using Haskell's notation: `map :: (A → B) → M[A] → M[B]` and `fmap :: (A → M[B]) → M[A] → M[B]`. Translated into Scala, the former produces two nested `Option`s: `Option[Flight].map(Airline => Option[List[Flight]]): Option[Option[List[Flight]]]`, whereas `Option[Flight].flatMap(Airline => Option[List[Flight]]): Option[List[Flight]]`. In `map`, the thing inside the output container is returned. In `flatMap`, instances of the output container are returned, which are then concatenated to produce the final output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:43:22.970",
"Id": "62048",
"Score": "0",
"body": "You are right, I did not realized that `getFlightsForAirLine` returned an `Option`. I have seen cases where `Some(Nil)` have not the same semantics as `None`, but this one ought not to be such a case."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T11:22:25.627",
"Id": "37347",
"ParentId": "37321",
"Score": "7"
}
},
{
"body": "<p>The most idiomatic way of using <code>Option</code> is to use <code>map/flatMap</code> methods:</p>\n\n<pre><code>def getFlightsForAirline(id: Long): Try[List[Flight]] =\n Airline.getById(id) flatMap Flight.getFlightsByAirline map Success.apply getOrElse {\n Failure(new RecordNotFoundException(\"Couldnt find airline\"))\n }\n</code></pre>\n\n<p><em>Note</em>: this works, if you simplify returned type, e.g strip <code>Option</code>.</p>\n\n<p>Otherwise, you need just change <code>flatMap</code> to <code>map</code>:</p>\n\n<pre><code>def getFlightsForAirline(id: Long): Try[Option[List[Flight]]] =\n Airline.getById(id) map Flight.getFlightsByAirline map Success.apply getOrElse {\n Failure(new RecordNotFoundException(\"Couldnt find airline\"))\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-29T18:38:15.223",
"Id": "61497",
"ParentId": "37321",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "37347",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:30:31.440",
"Id": "37321",
"Score": "8",
"Tags": [
"beginner",
"scala",
"error-handling",
"null"
],
"Title": "Idiomatic Scala try option code block"
}
|
37321
|
<p>In my code I declared a dictionary to store various counters</p>
<pre><code>let counters = Dictionary<Type, int>()
</code></pre>
<p>Later, I need to generate several labels using these counters, like this:</p>
<ul>
<li>First type a label is generated for a given type, it should consist of the type name itself:<br>
<code>"MyType"</code></li>
<li>Subsequent label should be the type name, appended with the number of times a label was previously generated for that type, in parentheses:<br>
<code>"MyType (2)"</code></li>
</ul>
<p>Here's how I'm accomplishing this now:</p>
<pre><code>let t : Type = ...
let label =
if (counters.ContainsKey(t)) then
counters.[t] <- counter.[t] + 1
sprintf "%s (%i)" t.Name counters.[t]
else
counters.Add(t, 1)
t.Name
</code></pre>
<p>This is exactly how I would write it if I had to use C# (with the exception of the in-line if / else), but after I wrote it F#, it seems clumsy and a little messy. I suspect there is a much more elegant, idiomatic way of writing this in F#. Perhaps using a match expression?</p>
|
[] |
[
{
"body": "<p>You can indeed use <code>match</code>, together with the fact that F# converts methods with <code>out</code> parameters (like <code>Dictionary.TryGetValue()</code>) to methods returning tuples:</p>\n\n<pre><code>let label =\n match counters.TryGetValue(t) with\n | (true, counter) ->\n counters.[t] <- counter + 1\n sprintf \"%s (%i)\" t.Name counter\n | (false, _) ->\n counters.Add(t, 2)\n t.Name\n</code></pre>\n\n<p>Though I'm not sure whether this is actually any better.</p>\n\n<p>Few more notes:</p>\n\n<ul>\n<li>I think that <code>t</code> should be a parameter of <code>label</code>.</li>\n<li><p>Using a mutable collection like <code>Dictionary</code> in F# doesn't feel right. I guess the “right” way to do it in functional style would be something like:</p>\n\n<pre><code>label (map : Map<Type, int>) (type : Type) : (Map<Type, int>, string)\n</code></pre>\n\n<p>But this would lead to code that's even less clear.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T22:22:05.903",
"Id": "61729",
"Score": "0",
"body": "Thanks for your input. Please see my answer below. Hopefully the rewrite is clear an idiomatic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:47:52.700",
"Id": "37330",
"ParentId": "37323",
"Score": "1"
}
},
{
"body": "<p>Thanks to the input provided in the other answers, here's what I've come up with:</p>\n\n<pre><code>let label = \n let (found, value) = this.counters.TryGetValue(t)\n this.counters.[t] <- value + 1\n if found \n then (sprintf \"%s (%i)\" t.Name (value + 1)) \n else t.Name\n</code></pre>\n\n<p>Or using a match expression</p>\n\n<pre><code>let label = \n let (found, value) = this.counters.TryGetValue(t)\n this.counters.[t] <- value + 1\n match found with \n | true -> (sprintf \"%s (%i)\" t.Name (value + 1)) \n | false -> t.Name\n</code></pre>\n\n<p>I've also refactored this into a separate function, so the actual assignment is just</p>\n\n<pre><code>let label = getNextLabel(t)\n</code></pre>\n\n<p>Both of these look better than my original code, though I'm not sure that the match has added any expressiveness to the code, so for now I'm keeping the plain old <code>if</code> / <code>else</code> statement. This is mostly just taking advantage of the built-in behavior of dictionaries in .NET (<code>TryGetValue</code> returns the default value if the key is not found, and the <code>Item</code> property's setter will perform an insert if necessary), but I'm still open to any suggestions on improving this more.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-13T04:30:31.457",
"Id": "203856",
"Score": "0",
"body": "Wrapping parentheses for `sprintf` are not needed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T22:18:41.030",
"Id": "37333",
"ParentId": "37323",
"Score": "3"
}
},
{
"body": "<p>Another improvement would be to close over <code>counters</code>, assuming it's only used by this function.</p>\n\n<pre><code>let mkLabel =\n let counters = Dictionary()\n fun (ty: Type) ->\n match counters.TryGetValue(ty) with\n | true, curCount ->\n let newCount = curCount + 1\n counters.[ty] <- newCount\n sprintf \"%s (%i)\" ty.Name newCount\n | _ ->\n counters.Add(ty, 1)\n ty.Name\n\n//Usage\nmkLabel typeof<int>\nmkLabel typeof<string>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T22:40:06.453",
"Id": "61733",
"Score": "0",
"body": "Good suggestion. Yes, `counters` is only used for the purpose of generating labels in this function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T22:24:10.117",
"Id": "37334",
"ParentId": "37323",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37334",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:55:08.070",
"Id": "37323",
"Score": "4",
"Tags": [
"functional-programming",
"f#"
],
"Title": "Improving F# conditional assignment with match expression"
}
|
37323
|
<p>I'm starting with object oriented programming, but I know PHP procedural style "pretty well" I'd say. I'm working on a ticket support site for this website.</p>
<p>This <code>mysqliSingleton</code> class was in a question I previously visited. I only added the <code>set_charset()</code> method to feet my database. By the way, should that line be in the <code>__constructor</code> or in the <code>init</code> method?</p>
<pre><code>class mysqliSingleton {
private static $instance;
private $connection;
private function __construct() {
$this->connection = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$this->connection->set_charset('utf8');
}
public static function init() {
if(is_null(self::$instance)) {
self::$instance = new mysqliSingleton();
}
return self::$instance;
}
public function __call($name, $args) {
if(method_exists($this->connection, $name)) {
return call_user_func_array(array($this->connection, $name), $args);
} else {
trigger_error('Unknown Method ' . $name . '()', E_USER_WARNING);
return false;
}
}
}
</code></pre>
<p>This is a piece of my ticket class which also has other methods <code>delete</code>, <code>getFromUser</code>, <code>getAll</code>, and some others:</p>
<pre><code>class Ticket extends mysqliSingleton {
private $mysqli;
public function __construct() {
$this->mysqli = mysqliSingleton::init();//Singleton db
}
//Submit a ticket
public function submitTicket($idusuario, $problem,$moreinfo){
$query = "INSERT INTO tbl_name (tbl_field,tbl_problem,tbl_moreinfo) VALUES (?,?,?)";
$stmt = $this->mysqli->prepare($query) or die($this->mysqli->error);
if ($stmt) {
$stmt->bind_param('iss',$idusuario,$problem,htmlentities($moreinfo));
if ($stmt->execute()) {
return true;
} else return false;//Problem sql
}
}
}
</code></pre>
<p>Am I using the singleton pattern right? But (unfortunately) after I code that, I starting reading more about abstract classes and Interfaces, and I've started to doubt if this is right. By the way, the ticket class is one of many classes that will extend to <code>mysqliSingleton</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:07:43.180",
"Id": "61702",
"Score": "1",
"body": "Question: why are you applying `htmlentities` on a string before you store it in a database? That function (or rather: `htmlspecialchars`) is for *outputting* text in an HTML context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:10:44.880",
"Id": "61703",
"Score": "0",
"body": "Don't you get bored writing `mysqliSingleton` every time you need a database call?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:11:07.763",
"Id": "61704",
"Score": "0",
"body": "Becouse I expect the user will not to insert any HTML attributes.\n\nWell, i'm deffining a variable $mysqli so I do `$this->mysqli->whatEverMethod()`. How should I do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:12:25.997",
"Id": "61705",
"Score": "0",
"body": "Why `trigger_error('Unknown Method '`? Doesn't PHP already handle unknown methods?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:13:49.173",
"Id": "61706",
"Score": "1",
"body": "Implementing Singletons in PHP make no sense. If you need the same instance in multiple clases use Dependency Injection. In PHP Objects do not live in the application memory, a singleton created for one request lives exactly for that request only. That beats the purpose of a singleton."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:14:27.537",
"Id": "61707",
"Score": "0",
"body": "Yeah, I thought that too, but as I said, that mysqliSingleton class was taken from a question here in StackOverflow. And I thin the class aint even using that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:16:08.430",
"Id": "61708",
"Score": "0",
"body": "Alan, honestly I don't know what is Dependency Injection. Googling it right now. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:19:39.810",
"Id": "61709",
"Score": "0",
"body": "Dependecy Injection is very simple. You pass the class as an argument of your constructor. That way, the class cannot be instantiated if the database object is not present. Read this:\n\nhttp://fabien.potencier.org/article/11/what-is-dependency-injection"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T17:25:17.377",
"Id": "61711",
"Score": "3",
"body": "Please don't use **'singleton'** and **'OOP'** in same sentence."
}
] |
[
{
"body": "<p>Well, although this code belongs to Codereview@stackexchenge, but as nobody cares to follow any rules here - so I would.</p>\n\n<p>There are too much problems with your code, ut to outline most:</p>\n\n<ol>\n<li>It seems you don't quite understand what singleton is and why use it.</li>\n<li><a href=\"https://stackoverflow.com/a/18853389/285587\">There is no point in extending application class from database handler class.</a> </li>\n<li><code>trigger_error('Unknown Method ')</code> is apparently redundant. PHP can handle absent methods as well.</li>\n<li><strong>Never</strong> use die() in production code. </li>\n<li>This whole class makes very little sense as it don't help you to handle mysqli even a bit. </li>\n</ol>\n\n<p>Frankly, exactly the same result you can have without any \"singleton\" class but just by creating mysqli instance and making it</p>\n\n<pre><code>public function __construct() {\n global $mysqli;\n $this->mysqli = $mysqli;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:22:00.260",
"Id": "61713",
"Score": "0",
"body": "You have access to moderator tools, can't you just move it to codereview?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:24:28.553",
"Id": "61714",
"Score": "0",
"body": "1. You are right, as I've said im new to OOP stuff.\n\n2. You're completly right, I haven't realized that!!\n\n3. removed right now.\n\n4. im not in producition mode. but thanks.\n\n5. i didn't really understood this point!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:27:05.857",
"Id": "61715",
"Score": "1",
"body": "@AlanChavez I will start using moderator tools not sooner than at least 50% of local population will start follow site rules (namely: closing duplicated and offtopic questions). Means never."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:30:15.933",
"Id": "61716",
"Score": "0",
"body": "@LCH 1. Don't use it then. 2. Just added a perfect link. 4. Any code *is* production. Are you going to go through ALL the code and change dirty stuff like that then moving to production? Why not to make it ALREADY the right way? 5. See example of class then helps: https://github.com/colshrapnel/safemysql"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:30:31.607",
"Id": "61717",
"Score": "0",
"body": "Your Common Sens, i'm sorry but I didnt' really understoo your edit: if I do that, wouldn't i be creating a new mysqli instance everytime i create a new object?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:31:24.283",
"Id": "61718",
"Score": "0",
"body": "@LCH edit was intended to show the fact that your class is useless and you can toss it away and never notice it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:35:41.423",
"Id": "61719",
"Score": "0",
"body": "Ah! ok I understood with the link you eddited! Thank you very much for your time."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:19:33.310",
"Id": "37329",
"ParentId": "37327",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37329",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T16:03:00.373",
"Id": "37327",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"mysqli",
"singleton"
],
"Title": "OOP MySQLi singleton"
}
|
37327
|
<p>I have a concept of the user having many API keys, but the API key belongs to the user, so I did the following:</p>
<p><strong>config/routes.rb</strong></p>
<pre><code> resources :users do
resources :api_keys, path: '/developmentcenter'
end
</code></pre>
<p><strong>app/models/api_key.rb</strong></p>
<pre><code>class ApiKey < ActiveRecord::Base
belongs_to :user
end
</code></pre>
<p><strong>app/controllers/api_keys.rb</strong></p>
<p><strong>Note:</strong> I have separate some of the logic up because I don't like messy methods, so I split them into lib/aisis_planner/api_keys_controller_mixins.rb.</p>
<pre><code>class ApiKeysController < ApplicationController
before_action :authenticate_user!
def index
@user = User.find(params[:user_id])
@api_key = User.apikeys
end
def create
@user = User.find(params[:user_id])
@api_key = ApiKey.new(create_new_api_key)
create_api_key(@api_key, @user)
end
def destroy
@user = User.find(params[:user_id])
destroy_api_key(@user)
end
private
def create_new_api_key
params.permit(:api_key, user_attributes: [:id])
end
end
</code></pre>
<p><strong>lib/aisis_planner/api_keys_controller_mixins.rb</strong></p>
<pre><code>module AisisPlanner
module ApiKeysControllerMixins
def create_api_key(api_key, user)
if api_key.save
flash[:notice] = 'Created a new API Key'
redirect_to user_path(user.id)
else
flash[:alert] = 'Could not create API Key please try again'
redirect_to user_path(user.id)
end
end
def destroy_api_key(user)
ApiKey.find(params[:id]).destroy
flash[:notice] = 'Api Key has been deleted.'
redirect_to user_path(user.id)
end
end
end
</code></pre>
<p>Now for the tests. There are no integration tests at this time (I use capybara).</p>
<pre><code>require 'spec_helper'
describe ApiKeysController do
let(:user) { FactoryGirl.create(:user) }
describe "#create" do
it "should not create an api key for those not logged in" do
post :create, :user_id => '', :id => ''
expect(response).to redirect_to login_path
end
it "should create an api key" do
sign_in user
cookies[:auth_token] = user.auth_token
post :create, :user_id => user.id.to_param
expect(response).to redirect_to user_path(user.id)
end
end
describe "#destroy" do
it "should not delete an api for a user not logged in" do
post :destroy, :user_id => '', :id => ''
expect(response).to redirect_to login_path
end
it "should delete an api key for a logged in user" do
sign_in user
cookies[:auth_token] = user.auth_token
key = FactoryGirl.create(:api_key, user_id: user.id)
post :destroy, :user_id => user.id.to_param, :id => key.id.to_param
end
end
end
</code></pre>
<p>What are your thoughts?</p>
|
[] |
[
{
"body": "<p>Quite a few things sprang to mind immediately, but as I delved deeper I realized that, well, there are a lot of issues. So here goes.</p>\n\n<h2>Outright bugs, I think</h2>\n\n<p><code>User.apikeys</code> - what? Shouldn't that be <code>@user.api_keys</code>? But I notice you don't test the <code>index</code> action, which would have caught that.</p>\n\n<h2>Security Issues</h2>\n\n<p>You're not really using params filtering correctly. You're permitting (rather than <em>requiring</em>) some top-level params, but never actually filter the \"sub-params\". The point is usually to filter the nested params, e.g. <code>params.require(:api_key).permit(:foo, :bar)</code>.<br>\nBut judging by your tests, it seems that <em>creating an API key doesn't need any params at all</em>, which makes things simpler.</p>\n\n<p>Secondly, create new API key records through the <code>has_many</code> association on <code>User</code> (which I assume you have); don't set the <code>user_id</code> directly. I.e. <code>@user.api_keys.new(...)</code>. But read on first.</p>\n\n<p>If the idea is that a user can only create API keys for himself/herself (which the tests seem to indicate), then <strong>don't</strong> find the user by <code>params[:user_id]</code>. Right now, it's very easy to craft a request with a different <code>user_id</code> param, and destroy API keys that belong to other users in the system.</p>\n\n<p>So if you only want the current user to create keys for himself/herself, the route doesn't need to be nested at all, since you only ever need the currently logged in user. I'm assuming you're using Devise, so the current user is accessible via the aptly named <code>current_user</code> helper method. (You can also dispense with the nested routing, if you only want the current user).</p>\n\n<p>Even so, <em>any user would still be able to delete other people's keys</em>, because you don't check whether a given <code>id</code> param actually belongs to the current user (or the <code>@user</code> for that matter). Basically, if someone's logged in, they can just call the <code>destroy</code> action with completely arbitrary numbers and destroy everything.</p>\n\n<p>Heck, you can do that from the JS console in a browser. Try typing <code>$.ajax({url: \"/users/x/developmentcenter/y\", type: \"DELETE\"})</code> where <code>x</code> is your own user ID (which you can see in a URL somewhere) and <code>y</code> is any number between 1 and whatever the maximum for your database's ID column is. If <code>y</code> happens to a key id - any key - it'll get destroyed.</p>\n\n<p>The mixins could also be a source of security issues. See the section below about that.</p>\n\n<h2>Consistency and Naming</h2>\n\n<p>In your <code>index</code> action you have <code>@api_key = User.apikeys</code>.<br>\nWhy is one singular, and the other one plural? <code>@api_key</code> should be called <code>@api_keys</code> (since it's a collection), and the <code>has_many</code> relation on <code>User</code> should be <code>api_keys</code> with an underscore (since that's how you write it everywhere else). Again, I'm thinking that last part is a straight-up bug.</p>\n\n<p>Your <code>create_new_api_key</code> doesn't do what it says; it doesn't create anything. Call it <code>api_key_params</code> instead, since that's what it returns. Besides, it's pretty confusing to have two methods called <code>create_new_api_key</code> and <code>create_api_key</code>... which one do you think actually creates an API key? But again, judging by your tests, you don't need <code>create_new_api_key</code> at all, since no params filtering should be needed.</p>\n\n<h2>Pointless Mixins</h2>\n\n<p>I understand that you don't like long methods, but making a mixin module is excessive. Do you intend to create/destroy API keys (and redirect) in other controllers? I'm guessing that the answer is \"no\" (if it's \"yes\", you've got other problems). So your mixins can only be mixed into 1 specific class, which completely negates the point of having \"mixins\".<br>\nThe only thing you're \"gaining\" is that you've split your code into two files. Now you've got two places to look whenever you have to work with the code. Personally, I had to look back and forth quite a few times to figure stuff out. Since this is supposed to be a very straight-forward controller, that's not a good sign.</p>\n\n<p>Besides, responsibility is all over the map now. In <code>create_api_key</code> you pass in both the user and the new API key instance. So there, your controller code handles params, and object instantiation. But in <code>destroy_api_key</code> you only pass only the user, and let the mixin method mess around with params to find the API key to destroy.</p>\n\n<p>Optimally, a mixin has zero dependencies on its use context (your code depends on at least <code>params</code>, <code>redirect_to</code> which are only relevant for controllers), and is of general use (your code simply isn't). What you're doing is moving some lines of code and making things worse.</p>\n\n<p>I can't actually see where you include the module... if you're doing it in <code>ApplicationController</code> you're polluting <em>every</em> controller with completely irrelevant methods.</p>\n\n<p><em>And</em> all those methods become <em>public</em> methods on every controller they're included in, meaning they function as actions. So worst case scenario, if you've got a too-liberal routing scheme, all of those methods can be called as actions simply by putting their names in the URL. </p>\n\n<h2>Odds and Ends</h2>\n\n<p>Don't pass the <code>id</code> attribute to path/url helpers; pass the record itself. If you ever want to override <code>to_param</code> in your models to make nicer URLs, it won't have any effect if all your code explicitly passes only the <code>id</code> attribute. I.e. <code>redirect_to user_path(user.id)</code> → <code>redirect_to user_path(user)</code></p>\n\n<p>Furthermore, for <code>link_to</code> and <code>redirect_to</code> you don't even need to use a path/url helper if it's a resourceful route; you can just pass the record. Rails will figure the rest out. I.e.\nSo <code>redirect_to user_path(user)</code> → <code>redirect_to user</code></p>\n\n<p>If you've only got <code>index</code>, <code>create</code> and <code>destroy</code> actions, then make that explicit in the routes. And there's no need for a slash in the <code>path</code> argument.<br>\n<code>resources :api_keys, only: [:index, :create, :destroy], path: 'developmentcenter'</code></p>\n\n<p>Your last test is missing an expectation. It just calls some stuff, but doesn't actually <em>test</em> anything. I'd suggest <em>at least</em> an <code>expect {...}.to change(ApiKeys, :count).by(-1)</code>.</p>\n\n<p>More tests in general - for instance, tests of all the security stuff mentioned above.</p>\n\n<p>Proof-read your flash messages (and test 'em while you're at it).</p>\n\n<hr>\n\n<p>Here's how I'd write it. I'm assuming you only want users to create/delete their own keys and no params are required to do so</p>\n\n<pre><code>class ApiKeysController < ApplicationController\n before_action :authenticate_user!\n\n def index; end # just access current_user.api_keys directly in the view\n\n def create\n api_key = current_user.api_keys.new\n if api_key.save\n redirect_to current_user, notice: 'Created a new API key'\n else\n redirect_to current_user, alert: 'Could not create a new API key. Please try again'\n end\n end\n\n def destroy\n api_key = current_user.api_keys.find params[:id]\n api_key.destroy\n redirect_to current_user, notice: 'API key has been deleted.'\n end\nend\n</code></pre>\n\n<p>No mixins, yet shorter than the original, and a lot more secure</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T01:44:52.280",
"Id": "37389",
"ParentId": "37335",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T23:40:11.340",
"Id": "37335",
"Score": "2",
"Tags": [
"beginner",
"ruby",
"ruby-on-rails",
"api"
],
"Title": "Rails 4.0 api_key implementation"
}
|
37335
|
<p>This Caesar cipher can take any integer and it will wrap around the correct number of times and still perform the encryption/decryption.</p>
<p>Let's say we have a text file named <code>dog</code>.</p>
<blockquote>
<p>~$ cat dog<br>
The quick brown fox jumps over the lazy dog...</p>
</blockquote>
<p><br>
If the user enters a normal offset (1-26), it will perform like any other Caesar cipher.</p>
<blockquote>
<p>~$ ./caesar dog 1<br>
~$ cat dog<br>
Uif rvjdl cspxo gpy kvnqt pwfs uif mbaz eph... </p>
</blockquote>
<p><br>
Negative numbers can be used to shift backwards. </p>
<blockquote>
<p>~$ ./caesar dog -1<br>
~$ cat dog<br>
The quick brown fox jumps over the lazy dog...</p>
</blockquote>
<p><br>
Now, here's the beauty of it. Choosing an offset of 1 is no different then choosing an offset of, say, 53 or -51. This algorithm will correctly wrap around. </p>
<blockquote>
<p>~$ ./caesar dog -51<br>
~$ cat dog<br>
Uif rvjdl cspxo gpy kvnqt pwfs uif mbaz eph...<br>
~$ ./caesar dog 51<br>
~$ cat dog<br>
The quick brown fox jumps over the lazy dog...</p>
</blockquote>
<p>I wrote this a long time ago and I posted it on some other programming site back in the day. I haven't really written much pure <code>c</code> code since. I'm guessing there's plenty of room for improvement. </p>
<p>Compiles with:<br>
<code>gcc -ansi -pedantic -Wall -Werror -O3 -o caesar caesar.c</code></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* #define offset (-1) */ /* My chosen default offset */
#define lstart (0x61) /* Start of lowercase ASCII alphabet */
#define ustart (0x41) /* Start of uppercase ASCII alphabet */
#define nalpha 26 /* Number of letters in my alphabet */
int main(int argc, char **argv) {
int ec, wrap, offset;
FILE *fp;
if (argc != 3) {
fprintf(stderr, "Usage: %s <filename> <offset>\n", argv[0]);
return 1;
}
fp = fopen(argv [1], "r+b");
offset = atoi (argv[2]);
if(!fp) {
fprintf(stderr, "Error: could not open file!\n");
return 1;
}
while((ec = fgetc(fp)) != EOF) {
if(isalpha(ec)) {
if(islower(ec)) {
wrap = (ec + offset - lstart) % nalpha;
wrap = (wrap < 0) ? nalpha + wrap : wrap;
} else {
wrap = (ec + offset - ustart) % nalpha;
wrap = (wrap < 0) ? nalpha + wrap : wrap;
}
ec = islower(ec) ? wrap + lstart : wrap + ustart;
fseek(fp, -1L, SEEK_CUR);
fputc(ec, fp);
}
}
fclose(fp);
return 0;
}
</code></pre>
<hr>
<p><strong>Update:</strong> I will leave the code I originally posted above. Any modifications that I make will be posted below. </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define NALPHA (26)
int main (int argc, char **argv) {
int ec, offset ;
FILE *fp ;
if (argc != 3) {
fprintf(stderr, "Usage: %s <filename> <offset>\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "r+b");
offset = atoi(argv[2]);
if (!fp) {
fprintf(stderr, "Error: Could not open file: %s\n", argv[1]);
return 1;
}
while ((ec = fgetc(fp)) != EOF) {
if (isalpha(ec)) {
const int ascii_offset = islower (ec) ? 'a' : 'A';
int wrap = (ec + offset - ascii_offset) % NALPHA;
if (wrap < 0) {
wrap += NALPHA ;
}
ec = wrap + ascii_offset;
}
fputc(ec, stdout);
}
fclose(fp);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>Macros in C are typically named in <code>UPPERCASE</code>.</li>\n<li><p>You can reduce some code duplication in this block:</p>\n\n<pre><code> if(islower(ec)) {\n wrap = (ec + offset - lstart) % nalpha;\n wrap = (wrap < 0) ? nalpha + wrap : wrap; \n\n } else {\n wrap = (ec + offset - ustart) % nalpha;\n wrap = (wrap < 0) ? nalpha + wrap : wrap; \n }\n\n ec = islower(ec) ? wrap + lstart : wrap + ustart;\n</code></pre>\n\n<p>The only difference in the different branches are <code>lstart</code> vs <code>ustart</code>. You can store it in a variable first and use that generically:</p>\n\n<pre><code> int ascii_offset = islower(ec) ? lstart : ustart;\n\n wrap = (ec + offset - ascii_offset) % nalpha;\n wrap = (wrap < 0) ? nalpha + wrap : wrap; \n\n ec = wrap + ascii_offset;\n</code></pre></li>\n<li><p>Changing the input file seems dodgy to me. The Unix way would be to write the \"encrypted\" output to <code>stdout</code>. This way the user can choose what to do with it (redirect to another file or to another program for example).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:21:32.987",
"Id": "61834",
"Score": "1",
"body": "I have made the suggested changes. I'm thinking that the LSTART and USTART macros might be a little pointless. They don't really seem to help with readability. I originally had them for Unicode support, but I don't think functions such as `isalpha` and `islower` are Unicode friendly. Do you think it would be better to just substitue `'a'` for LSTART and `'A'` for USTART?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T09:07:46.423",
"Id": "37344",
"ParentId": "37336",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>Putting parens around macro constants like <code>USTART (0x41)</code> is a good idea. Suggest doing it with all as in <code>NALPHA (26)</code>.</p></li>\n<li><p>To be highly portable, the assumption A to Z are continuous need to be abandoned. But I see marginal value in accommodating things like EDCIDC.</p></li>\n<li><p>Minor: Robust would check return values of <code>fseek()</code>, <code>fputc()</code>, and <code>fclose()</code>.</p></li>\n<li><p>Better error message:</p>\n\n<pre><code>fprintf(stderr, \"Error: could not open file: \\\"%s\\\"\\n\", argv[1])\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:38:54.800",
"Id": "61964",
"Score": "0",
"body": "Abandoning that assumption would break my algorithm. I'll read up on EDCIDC, but most likely I won't be able to support it. Good call on the error message."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T02:00:26.017",
"Id": "37391",
"ParentId": "37336",
"Score": "2"
}
},
{
"body": "<p>Some comments on your updated code in <a href=\"https://codereview.stackexchange.com/revisions/37336/3\">Rev 3</a>:</p>\n\n<ul>\n<li><p>I would define your constants as follows:</p>\n\n<pre><code>#define LSTART ('a')\n#define USTART ('A')\n#define NALPHA ('z' - 'a' + 1)\n</code></pre>\n\n<p>You now need no comments - they are obvious.</p></li>\n<li><p>It would be normal to use <code>perror(argv[1]);</code> to print the error on opening\nthe file.</p></li>\n<li><p>My man-page says <code>atoi</code> has been depracated in favour of <code>strtol</code></p></li>\n<li><p>return values from main are traditionally <code>EXIT_FAILURE</code> and <code>EXIT_SUCCESS</code></p></li>\n<li><p>I would define <code>offset</code> and <code>wrap</code> at their point of first use. Also it is\ngenerally recommended not to define multiple variables on one line.</p></li>\n<li><p>In the <code>while</code> loop you should put the <code>fputc(ec, stdout);</code> outside the\n<code>if(isalpha(ec)) {...}</code> condition. That way the format of what you encrypt\nis maintained. Equally, I would omit printing \\n at the end so that the\noutput file (on stdout) has the same form as the input.</p></li>\n<li><p>I prefer to see a space after keywords, <code>if</code>, <code>while</code> etc. </p></li>\n<li><p>Don't overuse <code>?:</code> - it is not a universal replacement for if-else</p></li>\n<li><p>I find a character named <code>ec</code> to be less intuitive than one named <code>ch</code>, but\nmaybe that is just me.</p></li>\n<li><p>I think your encryption code: </p>\n\n<pre><code> int ascii_offset = islower (ec) ? LSTART : USTART;\n\n wrap = (ec + offset - ascii_offset) % NALPHA;\n wrap = (wrap < 0) ? NALPHA + wrap : wrap;\n ec = islower(ec) ? wrap + LSTART : wrap + USTART;\n</code></pre>\n\n<p>would be better written:</p>\n\n<pre><code> const int ascii_offset = islower(ec) ? LSTART : USTART;\n int wrap = (ec + offset - ascii_offset) % NALPHA;\n if (wrap < 0) {\n wrap += NALPHA;\n }\n ec = wrap + ascii_offset;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:37:02.760",
"Id": "61963",
"Score": "0",
"body": "1. Should I even bother with having the `LSTART` and `USTART` macros? 2. The C89/90 ISO forbids mixing variable declarations and code. I do not want to use a newer version of C. 3. Good catch on the `fputc`. I'll post my updated code in a little bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:57:51.200",
"Id": "61965",
"Score": "0",
"body": "I'd like to make `offset` a `const int` but I'm not sure if that's possible since I have to do the argument count check first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T01:59:18.987",
"Id": "61968",
"Score": "0",
"body": "1. Most reviewers advise against embedding magic values because such values are difficult to find and change, especially if used more than once. That doesn't mean you should never do it, just that it is best to have a good reason for doing so. In this case, as the two are used just once, it might even be more readable to use 'a' and 'A', as they are unlikely ever to change. And the names `LSTART` and `USTART` do not have obvious meanings (I should have commented on that). On the other hand, `NALPHA` is used twice and is probably best kept as a macro."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T02:01:12.387",
"Id": "61970",
"Score": "0",
"body": "2. Why would you want to stick with an outdated version of C? I think the changes introduced in C99 improve the language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T02:25:58.757",
"Id": "61972",
"Score": "0",
"body": "Even though I wrote this on Linux, I use Visual Studio on my Windows machine. As far as I know, they don't really like C99."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:53:55.203",
"Id": "37431",
"ParentId": "37336",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37431",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T02:49:10.323",
"Id": "37336",
"Score": "10",
"Tags": [
"c",
"caesar-cipher"
],
"Title": "Caesar Cipher that takes an arbitrary offset"
}
|
37336
|
<p>I have written a simple desk accessory in Proccessing called Trip, you can see it below. It is working, but it is very simple, and needs more features.</p>
<pre><code>import processing.pdf.*;
PImage tardis;
int flash = 0;
void setup() {
size(256, 256);
frame.setResizable(true);
tardis = loadImage("TARDIS1.jpg");
beginRecord(PDF, "trip.pdf");
background(random(100), random(100), random(100));
randomSeed(299792458);
}
void draw() {
stroke(random(100), random(100), random(100));
line(random(width), random(height), mouseX, mouseY);
if (flash == 1) {
background(random(100), random(100), random(100));
}
}
void keyPressed() {
if (key == 's') {
endRecord();
exit();
}
else if (key == 'q') {
exit();
}
else if (key == 'b') {
background(random(100), random(100), random(100));
}
else if (key == 't') {
image(tardis ,0 ,0, width, height);
}
else if (key == 'f') {
if (flash == 0) {
flash = 1;
}
else if (flash == 1) {
flash = 0;
}
}
}
</code></pre>
<p>I would appreciate any new ideas for features, particularly Easter egg-style secret features.</p>
|
[] |
[
{
"body": "<p>How about something where if you change the background to a particular color, something cool happens? </p>\n\n<p>Like if it turns full black,<code>(0,0,0)</code>, it causes an image to pop up on screen. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T09:56:34.543",
"Id": "134318",
"Score": "0",
"body": "Hi, thanks for joining CodeReview. Although it is good to answer questions, try to answer questions only that are within scope of the site. CodeReview is not intended for questions about feature requests."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T09:03:57.367",
"Id": "73900",
"ParentId": "37340",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T07:23:06.020",
"Id": "37340",
"Score": "0",
"Tags": [
"processing"
],
"Title": "New features for Processing game/desk accessory"
}
|
37340
|
<p>Is this a good C program for splitting a command line without doing any expansion on it? Don't worry too much about <code>main()</code> and the output -- those are for testing.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
void pullwhitespace(char **input);
int main (int argc, char **argv)
{
if (argc != 2) {
fputs("Must have exactly one command line argument\n", stderr);
return 64;
}
char *input = argv[1];
char *outstring = malloc(strlen(argv[1]) + 1);
char *outptr = outstring;
char a;
pullwhitespace(&input);
NORMAL:
/* We are in an unquoted part of the input */
switch ((a = *input++))
{
case ' ' :
case '\t':
*outptr++ = '\0';
pullwhitespace(&input);
goto NORMAL;
case '\n':
case '\0':
goto DONE;
case '\\':
if (((a = *input++)) == '\n') {
break;
} else if (a) {
*outptr++ = a;
goto NORMAL;
} else {
goto FAIL;
}
case '\'':
goto QUOTE;
case '"':
goto DQUOTE;
default:
*outptr++ = a;
goto NORMAL;
}
assert(0);
QUOTE:
/* We are in a single quoted string */
while (((a = *input++)) != '\'') {
if (a) {
*outptr++ = a;
} else {
goto FAIL;
}
}
goto NORMAL;
DQUOTE:
/* We are in a double quoted string */
switch ((a = *input++))
{
case '\0':
goto FAIL;
case '\\':
{
char b = *input++;
switch (b)
{
case '\0':
goto FAIL;
default:
*outptr++ = a;
case '"':
case '\\':
*outptr++ = b;
case '\n':
break;
}
}
goto DQUOTE;
default:
*outptr++ = a;
goto DQUOTE;
case '"':
goto NORMAL;
}
assert(0);
FAIL:
fprintf(stderr, "%s: Invalid string input\n", argv[0]);
return 1;
assert(0);
DONE:
*outptr++ = '\0';
*outptr++ = '\0';
errno = 0;
fwrite(outstring, 1, (size_t)(outptr - outstring), stdout);
int error = errno;
if(ferror(stdout)) {
fprintf(stderr, "%s: write error: %s\n", argv[0], strerror(error));
return 1;
}
fflush(stdout);
if ( errno != 0) {
fprintf(stderr, "%s: write error: %s\n", argv[0], strerror(error));
return 1;
}
return 0;
}
void pullwhitespace (char **inputptr)
{
char *input = *inputptr;
char a;
while (( a = *input)) {
if (a != ' ' && a != '\t') {
return;
}
input++;
}
}
</code></pre>
<p>I know that it is FULL of goto statements (more than every other program I have ever made put together) -- is that okay?</p>
<p>The reason for the <code>goto</code> statements is that this is meant as a lightweight state machine. Intended applications include parsing command line arguments or (possibly - this is far fetched) for the parser (not supporting code) to be the basis of a kernel module to parse shebang lines, allowing multiple arguments to be passed to a shebang interpreter.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T14:25:51.900",
"Id": "61757",
"Score": "0",
"body": "No, it's a [lexer](http://stackoverflow.com/q/2842809/89999) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:17:14.430",
"Id": "61765",
"Score": "0",
"body": "What test cases have you tried this with? If you haven't got a set of tests for complex functions like this that it consistently passes, my default opinion is that it's not production ready."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:27:03.510",
"Id": "61836",
"Score": "0",
"body": "Why so many `goto`s? Those are frowned upon in C... in fact, I'm frowning right now. :-("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T00:04:27.240",
"Id": "61847",
"Score": "0",
"body": "That is because this is a state machine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:52:31.163",
"Id": "62360",
"Score": "0",
"body": "You should be able to write a state machine without gotos."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T00:01:06.803",
"Id": "62393",
"Score": "1",
"body": "`goto`s need not be feared irrationally, and I've seen them in in lexers before, including in the CPython lexer ([tokenizer.c](http://hg.python.org/cpython/file/26d92a21f6cf/Parser/tokenizer.c)), that said, it's good to figure out the alternatives, which you may end up liking more."
}
] |
[
{
"body": "<p>I doubt that this code actually works. Especially <code>pullwhitespace</code> doesn't do what you probably intended (hint: it doesn't modify the argument, it makes a copy of the pointer and advances it). Have you tested it before submitting it for review here?</p>\n\n<p>Anyway: You might want to have a look <a href=\"https://stackoverflow.com/questions/133214/is-there-a-typical-state-machine-implementation-pattern\">here</a> for alternative ways to implement a state machine. You approach is similar to Remo.D's answer in the linked question but I think his macros make it more readable.</p>\n\n<p>A few things I noticed:</p>\n\n<ol>\n<li><p>When you are in <code>NORMAL</code> and read a white space you do this <code>*outptr++ = '\\0';</code> Given that strings in C are NULL terminated character sequences this seems dodgy as it will terminate the output right there unless you tell someone to read further by supplying a length. If you intend to split on white space then you should store the results in a <code>char **</code> like <code>argv</code>.</p></li>\n<li><p>Again in <code>NORMAL</code>:</p>\n\n<pre><code>case '\\\\':\n if (((a = *input++)) == '\\n') {\n break;\n } else if (a) {\n *outptr++ = a;\n goto NORMAL;\n } else {\n goto FAIL;\n }\n</code></pre>\n\n<p>So if you find a <code>\\</code> followed by a newline you <code>break</code> the <code>switch</code> which is followed by an <code>assert(0)</code>. Normally <code>assert</code> should be used to state invariants as \"this function expects this condition to be true and it is probably a bug in the program if it is not\". Specifically <code>assert(0)</code> should be used as \"should never execute this code path\". It seems weird that external user input can trigger an <code>assert</code> just because the program doesn't like he input. Especially since you have a <code>FAIL</code> state anyway.</p>\n\n<p>Also the <code>else</code> condition evaluation depends on the side effect of the <code>if</code> condition evaluation - not very nice. You should read the next character first in a separate line and then evaluate. This makes it much clearer. So this case could probably have been written as:</p>\n\n<pre><code>case '\\\\':\n a = *input++;\n if (a && a != '\\n') {\n *outptr++ = a;\n goto NORMAL;\n }\n goto FAIL;\n</code></pre></li>\n<li><p>If you are in <code>DQUOTE</code> and encounter a <code>\\</code> then you read another character from the input. However that character simply gets swallowed because in the default case you do this: <code>*outptr++ = a;</code> which will write the <code>\\</code> to the output and skip the current character (held in <code>b</code>). </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T08:50:21.150",
"Id": "37342",
"ParentId": "37341",
"Score": "2"
}
},
{
"body": "<p>This parser is not that complicated, you don't need jumps.\nMy example below ignores some corner cases, just showing the priciple.\nYou can expand it to your needs.</p>\n\n<pre><code>#include <stdio.h>\n#include <ctype.h>\n\nint main(int argc, char **argv)\n{\n const char *s, *e;\n\n for (e = argv[1]; *e; s = e) {\n while (isspace(*e)) e++;\n\n if (*e == '\\\"') {\n for (s = ++e; *e && *e != '\\\"'; e++);\n if (!*e) return 1; // missing closing quote\n } else if (*e == '\\'') {\n for (s = ++e; *e && *e != '\\''; e++);\n if (!*e) return 1; // missing closing quote\n } else {\n for (s = e; *e && !isspace(*e); e++);\n }\n printf(\"'%.*s'\\n\", (int)(e - s), s);\n\n if (*e == '\\\"' || *e == '\\'')\n e++; // advance after closing quote\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:42:18.117",
"Id": "61761",
"Score": "2",
"body": "I think this answer would be a lot more helpful with some discussion on how this approach differs from the original, and why you think it's better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:20:36.527",
"Id": "61766",
"Score": "0",
"body": "Your code doesn't cope with escape-sequences in double- or single-quoted strings like the original."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T10:04:31.073",
"Id": "37346",
"ParentId": "37341",
"Score": "0"
}
},
{
"body": "<p>Comments about <code>pullwhitespace()</code>:</p>\n\n<ol>\n<li><p>Code is broken. Needs work to <em>update</em> <code>*inputptr</code>.</p></li>\n<li><p>Needs better name than <code>inputptr</code>. Maybe <code>string_ptr</code>. Hmm, no <em>much</em> better.</p></li>\n<li><p>Rather than define \"whitespace\" as <code>' '</code> and <code>'\\t'</code>, use the C definition of whitesapce.</p></li>\n<li><p>[Edit] Deleted <code>const</code> susggestion.</p>\n\n<pre><code>void pullwhitespace (char **inputptr) {\n char *input = *inputptr;\n char a;\n while ((a = *input) != '\\0') {\n if (!isspace((unsigned char) a)) {\n break;\n }\n input++;\n }\n *inputptr = input;\n}\n</code></pre></li>\n</ol>\n\n<p>If one accept using the C standard <code>isspace()</code> further simplification results in</p>\n\n<pre><code> void pullwhitespace (char **inputptr) {\n char *input = *inputptr;\n while (isspace(*input)) input++;\n *inputptr = input;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:29:03.317",
"Id": "62354",
"Score": "0",
"body": "Adding `const` to the definition of parameter `inputptr` doesn't work the way you'd expect (see http://c-faq.com/ansi/constmismatch.html). You have also modified the function in ways that make it worse than the original (first commented line)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:51:48.223",
"Id": "62359",
"Score": "0",
"body": "@William Morris I have seen the error of my ways concerning `const` and corrected `while ((a = *(*inputptr)) != '\\0')`. Please detail about your 2nd point, what is worse?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:25:40.400",
"Id": "62366",
"Score": "0",
"body": "@William Morris I also see that `isspace()` needs an `unsigned char` or `EOF`. Is that your concern?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:56:13.043",
"Id": "62386",
"Score": "0",
"body": "The original code had `char *input = *inputptr;` and then de-referenced `input`, whereas your code omits that and uses eg `*(*inputptr)`, which is more difficult to read (and hence worse). I would have made the OP's `input` a `const`, ie: `const char *input = *inputptr;`. Also it is arguable that the OP might have wanted just space and tab to be treated instead of all white-space (although I haven't read the code to see)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:58:23.337",
"Id": "62387",
"Score": "0",
"body": "BTW, when you use @ to quote a name, there should be no spaces in the name. With @WilliamMorris I get a notification, with the space, I don't :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T23:28:32.407",
"Id": "62390",
"Score": "0",
"body": "@WilliamMorris The change from `*input` to `*(*inputptr)` is a functional change. OP's original function does _not_ work. It nicely iterates looking for spaces and does `input++`. Unfortunately, this has no effect on `*inputptr` and thus the function does _nothing_ except kill CPU time. The method, I've shown, though \"more difficult to read\", is the correct functionality. One could instead do the `char *input = *inputptr` and then just before the returning (in 2 places) do `*inputptr = input`. This is my point #1 \"Needs work to conditionally update *inputptr\". Sorry if not more clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T02:30:57.207",
"Id": "62409",
"Score": "0",
"body": "+1. I was aware that the original fn was broken, but it hadn't occurred to me that your `(*inputptr)++;` fixed that. Now I see why you did it that way. All the same I've been programming C for (too) many years, so maybe that proves my point that it was not optimally readable :-) I like your latest version better, but for me, I'd replace `pullwhitespace` with `s += strspn(s, \" \\t\");`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T02:57:53.650",
"Id": "62413",
"Score": "0",
"body": "@WilliamMorris nice solution with `s += strspn(s, \" \\t\")`. Its better than calling a function `pullwhitespace()` that does not pull \"whitepsace\" as defined by C, but \"whitespace\" defined locally."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T01:46:03.440",
"Id": "37390",
"ParentId": "37341",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T07:37:33.420",
"Id": "37341",
"Score": "3",
"Tags": [
"c",
"parsing"
],
"Title": "Splitting a command line in C"
}
|
37341
|
<p>Here's my attempt at <a href="https://codereview.meta.stackexchange.com/q/1245/9357">Weekend Challenge #3</a>.</p>
<p>Key characteristics of this Python entry are:</p>
<ul>
<li>The strategy is to alternate between "auto-complete" (making simple deductions such as naked singles and hidden singles) and recursive guessing.</li>
<li>The puzzle state is stored in a <code>Sudoku</code> object, which has a mutable 2D array. Unknowns are represented as <code>None</code>.</li>
<li>When <code>.solutions()</code> finds a solution, it <code>yield</code>s a copy of the <code>Sudoku</code> object. That is the only time the object and its 2D array is copied; most of the time it mutates the array entries directly, using a <code>Transaction</code> to help roll back to the previous state after each guess.</li>
</ul>
<p>Concerns include:</p>
<ol>
<li>Brute-force guessing is uninspiring. Furthermore, the data structures don't really pave the way to more clever analysis techniques.</li>
<li>I feel like I should be able to accomplish this task with less code. In particular, code to handle rows and code to handle columns are repetitive.</li>
<li>If there are multiple solutions, the code would enumerate each solution multiple times; the <code>.solutions()</code> method deliberately de-duplicates results. That's wasteful.</li>
<li>Both the main <code>.solutions()</code> method and its helper <code>.guess_from()</code> call <code>.autocomplete()</code>. The code there could probably be less redundant.</li>
</ol>
<p>The code works in Python 2.7. It breaks in Python 3, apparently due to <a href="http://www.python.org/dev/peps/pep-3113/" rel="nofollow noreferrer">PEP 3113 — Removal of Tuple Parameter Unpacking</a>. Suggestions for rectifying that would be appreciated.</p>
<p>Anyway, the more I try to prettify the code, the slower it gets, so it's time for me to stop working on it, and let Code Review have a shot at it.</p>
<hr>
<p>Some preliminaries: imports, an exception class, and the <code>Transaction</code> class…</p>
<pre><code>from collections import Set
from copy import deepcopy
from itertools import chain
from math import sqrt
class InconsistentBoardException(Exception):
def __init__(self, r=None, c=None):
self.r, self.c = r, c
######################################################################
class Transaction:
def __init__(self, sudoku):
self.sudoku = sudoku
def __enter__(self):
return self.commit()
def __exit__(self, type, value, traceback):
return self.rollback()
def commit(self):
self._count = len(self.sudoku.undo_list)
return self
def rollback(self):
self.sudoku.undo(self._count)
return self
def move_count(self):
return len(self.sudoku.undo_list) - self._count
def __nonzero__(self):
return self.move_count()
</code></pre>
<p>The main code:</p>
<pre><code>class Sudoku:
@classmethod
def parse(cls, string, box_h=None, box_w=None, symbols=None):
return Sudoku([[None if v == '.' else int(v) for v in line]
for line in filter(None, string.split('\n'))],
box_h, box_w, symbols)
def __init__(self, array, box_h=None, box_w=None, symbols=None):
self.array = array
self.symbols = symbols or set(range(1, 1 + int(sqrt(len(array) * len(array[0])))))
self.box_h = box_h or int(sqrt(len(self.symbols)))
self.box_w = box_w or int(sqrt(len(self.symbols)))
self.undo_list = []
def dup(self):
return Sudoku(deepcopy(self.array), self.box_h, self.box_w, self.symbols)
def __repr__(self):
return '\n'.join(
''.join(
str(n) if n is not None else '.' for n in row
) for row in self.array
)
def __eq__(self, other):
return self.array == other.array and \
self.symbols == other.symbols and \
self.box_h == other.box_h and \
self.box_w == other.box_w
def __hash__(self):
return sum(map(lambda row: sum([v or 0 for v in row]), self.array)) ^ \
sum(self.symbols) ^ self.box_h ^ self.box_w
def is_solved(self):
"""
Checks whether all cells are filled in (without checking for
consistency).
"""
return all(all(row) for row in self.array)
def row_cell_iter(self, r):
for c in range(len(self.array[r])):
yield (r, c)
def col_cell_iter(self, c):
for r in range(len(self.array)):
yield (r, c)
def box_cell_iter(self, r, c):
box_row_lb = r // self.box_h * self.box_h
box_row_ub = box_row_lb + self.box_h
box_col_lb = c // self.box_w * self.box_w
box_col_ub = box_col_lb + self.box_w
for r in range(box_row_lb, box_row_ub):
for c in range(box_col_lb, box_col_ub):
yield (r, c)
def _to_set(self, cells, r=None, c=None):
a = filter(None, [self.array[r][c] for r, c in cells])
s = set(a)
if len(a) != len(s):
raise InconsistentBoardException(r, c)
return s
def row_excl(self, r):
"""
Returns the set of impossible symbols for row r due to
repetition with other cells in row r.
"""
return self._to_set(self.row_cell_iter(r), r, None)
def col_excl(self, c):
"""
Returns the set of impossible symbols for column c due to
repetition with other cells in column c.
"""
return self._to_set(self.col_cell_iter(c), None, c)
def box_excl(self, r, c):
"""
Returns the set of impossible symbols for cell (r, c) due to
repetition with other cells in the box that contains (r, c).
"""
return self._to_set(self.box_cell_iter(r, c), r, c)
def candidates(self, r, c):
"""
Returns the set of symbols possible for cell (r, c) after eliminating
the values that appear in the same row, column, or box.
"""
return self.symbols - self.row_excl(r) \
- self.col_excl(c) \
- self.box_excl(r, c)
def set(self, r, c, value):
self.array[r][c] = value
self.undo_list.append((r, c))
def undo(self, n=-1):
"""
If n < 0, undo the last abs(n) moves. If n >= 0, undo all but the
first n moves.
"""
for r, c in self.undo_list[n:]:
self.array[r][c] = None
self.undo_list[n:] = []
def solutions(self):
with Transaction(self):
self.autocomplete()
if self.is_solved():
yield self.dup()
return
solutions = {} # Deduplicate solutions
for solution in self.guess_from(0, 0):
if not solution in solutions:
solutions[solution] = True
yield solution
def naked_singles(self):
"""
Enumerates all naked singles in the board. A naked single is an empty
cell whose candidate values have been reduced to just one possibility
by their row, column, or box neighbors.
"""
for r in range(len(self.array)):
for c in range(len(self.array[r])):
if self.array[r][c] is None:
candidates = self.candidates(r, c)
if not candidates:
raise InconsistentBoardException(r, c)
if 1 == len(candidates):
yield (r, c), list(candidates)[0]
def hidden_singles(self):
"""
Enumerates hidden singles in the board. A hidden single is an empty
cell that must be filled in with a symbol because that symbol has
nowhere else to go in that row or column. (It's also possible to
detect hidden singles for boxes, but the time to accomplish that is
worse than guessing.)
"""
for v in self.symbols:
# Hidden single in row
for r in range(len(self.array)):
row = self.array[r]
if not v in row:
placements = set(filter(lambda c: row[c] is None, range(len(row))))
for c in set(placements):
if not v in self.candidates(r, c):
placements.discard(c)
if not placements:
raise InconsistentBoardException(r, c)
elif 1 == len(placements):
yield (r, list(placements)[0]), v
# Hidden single in col
for c in range(len(self.array[0])):
col = [self.array[r][c] for r in range(len(self.array))]
if not v in col:
placements = set(filter(lambda r: col[r] is None, range(len(col))))
for r in set(placements):
if not v in self.candidates(r, c):
placements.discard(r)
if not placements:
raise InconsistentBoardException(r, c)
elif 1 == len(placements):
yield (list(placements)[0], c), v
def autocomplete(self):
"""
Fills in all naked singles and hidden singles.
"""
with Transaction(self) as transaction:
changed = True
while changed:
changed = False
for (r, c), value in chain(self.naked_singles(),
self.hidden_singles()):
self.set(r, c, value)
changed = True
self.trace_autocomplete(transaction)
transaction.commit()
def guess_from(self, init_r, init_c):
"""
At the next empty cell after (init_r, init_c), pick any of its
candidate values. Explore the resulting possibilities by running
autocomplete, then recursively guessing again starting from the next
empty cell. If it doesn't work out, roll back the transaction.
"""
for r in range(init_r, len(self.array)):
for c in range(init_c, len(self.array[r])):
if self.array[r][c] is None:
candidates = self.candidates(r, c)
if not candidates:
self.trace_inconsistent(r, c)
return # No solution possible
for v in candidates:
with Transaction(self):
try:
self.set(r, c, v)
self.trace_guess(r, c, candidates)
with Transaction(self):
self.autocomplete()
if self.is_solved():
yield self.dup()
for solution in self.guess_from(r, c + 1):
yield solution
except InconsistentBoardException:
pass
finally:
self.untrace_guess()
pass
init_c = 0
</code></pre>
<p>There's some debugging code within the <code>Sudoku</code> class. Consider this to be throw-away code, not worthy of review. I'm including it just in case you find it helpful to see the inner workings. Uncomment the <code>print</code> in <code>.trace()</code> to enable debugging output.</p>
<pre><code> def trace(self, message):
#print(message)
pass
level = 0
def trace_guess(self, r, c, candidates):
self.level += 1
indent = ' ' * (2 * self.level)
self.trace("%sGuessing (%d, %d) = %s (candidates %s)" % (indent, r, c, self.array[r][c], candidates))
self.trace('\n'.join(map(lambda line: indent + line, str(self).split('\n'))))
def trace_inconsistent(self, r, c):
self.trace("%sINCONSISTENT: No candidates for (%d, %d)!" % (' ' * (2 * self.level), r, c))
pass
def trace_autocomplete(self, transaction):
indent = ' ' * (2 * self.level)
if not transaction:
self.trace("%sAutocompleted 0 moves" % (indent))
return
moves = transaction.move_count()
autocompletes = self.undo_list[-moves:]
self.trace("%sAutocompleted %d moves: %s" % (indent, moves, ', '.join(map(str, autocompletes))))
after = str(self)
redo_values = map(lambda r, c: self.array[r][c], autocompletes)
for r, c in autocompletes:
self.array[r][c] = None
before = str(self)
for (r, c), value in zip(autocompletes, redo_values):
self.array[r][c] = value
if str(self) != after:
raise "Trace error"
self.trace('\n'.join(map(lambda before_line, after_line: indent + before_line + " " + after_line, zip(before.split('\n'), after.split('\n')))))
def untrace_guess(self):
self.level -= 1
</code></pre>
<p>Test cases:</p>
<pre><code>four = Sudoku.parse("""
2...
.13.
3..1
.24.
""")
four_inconsistent = Sudoku.parse("""
22..
....
....
....
""")
four_2 = Sudoku.parse("""
22..
....
....
....
""")
six_easy = Sudoku.parse("""
3....4
..43..
.3..6.
.4..1.
..21..
1....2
""", 2, 3)
six_hard = Sudoku.parse("""
....2.
2.3..1
.5....
.3.1.5
.2..3.
.4....
""", 2, 3)
nine_easy = Sudoku.parse("""
.931.564.
7.......5
5.12.9387
2.......3
.369.752.
9.......1
3.24.81.9
6.......4
.473.285.
""")
nine_hard = Sudoku.parse("""
.5...6...
2...7...1
.19....8.
.9.6..8..
..2...6..
..3..9.7.
.3....71.
9...2...3
...4...6.
""")
nine_inconsistent = Sudoku.parse("""
..624..3.
.3.....9.
2......7.
5..6...2.
..1...6..
.2...3..7
.5......3
.9.....8.
.1..625..
""")
for puzzle in [four, four_inconsistent, six_easy, six_hard, nine_easy, nine_hard, nine_inconsistent]:
print(puzzle)
try:
for solution in puzzle.solutions():
print("\nSolution:\n%s" % (solution))
except InconsistentBoardException:
print("\nNo solution possible!")
print('-' * 72)
</code></pre>
|
[] |
[
{
"body": "<p>Looping over the rows and columns in <code>naked_singles</code> and <code>hidden_singles</code> is costing a lot of time. You can achieve those effects more efficiently by tracking the possible values available to each cell, row, column, and box. The last three can be modeled using a <code>Group</code> collection class that knows the cells it contains while each cell knows which groups it belongs to.</p>\n\n<pre>\nCell:\n Group row, col, box // probably don't even need to name the three groups\n Set possibles\n int known\n\nGroup:\n Cell[9] cells\n Set possibles // may be able to achieve some shortcuts by tracking here too\n\nBoard:\n Cell[9][9] cells\n Group[9] rows, cols, boxes // same here\n</pre>\n\n<p>While this will require more code, it will be pretty straight-forward and allow you to make moves without iterating over the same possible numbers again and again.</p>\n\n<ul>\n<li>When you place a number <em>N</em> in a cell <em>C</em> (e.g. when initializing the board from input), <em>N</em> from the set of possibles of all other cells belonging to the row, column, and box containing <em>C</em>.</li>\n<li>When a set of possibles for a cell <em>C</em> is reduced to a single number <em>N</em>, set that cell to <em>N</em> as above.</li>\n</ul>\n\n<p>The next step which I didn't implement in my Scala version is to model the intersections between every pair of groups. For example, imagine the only known numbers are 1 through 6 on the first row starting from the left.</p>\n\n<pre>\n1 2 3 4 5 6 x x x\n. . . . . . y y y\n. . . . . . z z z\n</pre>\n\n<p>Obviously, the three <em>x</em> cells at the end of that row must contain 7, 8 and 9 in some order. This allows you to eliminate them from the <em>y</em> and <em>z</em> mini-groups. I haven't thought through yet how you'd make use of this, but it may enable more complex rules.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T11:10:43.247",
"Id": "61753",
"Score": "0",
"body": "I agree, maintaining a persistent set of candidates for each cell would help efficiency. However, when the algorithm relies heavily on guesswork, the bookkeeping might be rather intense. I'd either have to put more effort into supporting rollbacks when guesses fail, or copy all the data structures defensively before each guess. Or maybe just reconstruct the candidate sets when backtracking. What would you do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:59:50.140",
"Id": "61815",
"Score": "0",
"body": "For guessing I made a copy of the board state. Since you pick a cell and then iterate over all possibles, you only need to make one copy per cell. While it would be more work to implement full transaction support, it would also be an interesting challenge. A couple implementations of the [Command pattern](http://en.wikipedia.org/wiki/Command_pattern) should be sufficient: `RemovePossible(cells, value)` and `SetKnown(cell, value)`. The tricky part is probably dealing with the cascade effect of setting values and removing possibles."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T09:56:47.823",
"Id": "37345",
"ParentId": "37343",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>It doesn't work! First problem:</p>\n\n<pre><code>>>> list(Sudoku.parse(puzzle).solutions())\nTraceback (most recent call last):\n ...\n File \"cr37343.py\", line 278, in trace_autocomplete\n redo_values = map(lambda r, c: self.array[r][c], autocompletes)\nTypeError: <lambda>() takes exactly 2 arguments (1 given)\n</code></pre>\n\n<p>So I changed this line to:</p>\n\n<pre><code>redo_values = [self.array[r][c] for r, c in autocompletes]\n</code></pre>\n\n<p>Second problem:</p>\n\n<pre><code>Traceback (most recent call last):\n ...\n File \"cr37343.py\", line 286, in trace_autocomplete\n self.trace('\\n'.join(map(lambda before_line, after_line: indent + before_line + \" \" + after_line, zip(before.split('\\n'), after.split('\\n')))))\nTypeError: <lambda>() takes exactly 2 arguments (1 given)\n</code></pre>\n\n<p>So I changed this line to:</p>\n\n<pre><code>self.trace('\\n'.join(indent + b + \" \" + a for b, a in zip(before.split('\\n'), after.split('\\n'))))\n</code></pre>\n\n<p>And then it worked.</p></li>\n<li><p>The code is not portable to Python 3, but the reason is nothing to do with <a href=\"http://www.python.org/dev/peps/pep-3113/\">PEP 3113</a>. The problem is here, in <code>Sudoku._to_set</code>:</p>\n\n<pre><code>a = filter(None, [self.array[r][c] for r, c in cells])\ns = set(a)\nif len(a) != len(s):\n</code></pre>\n\n<p>In Python 3, <a href=\"http://docs.python.org/3/library/functions.html#filter\"><code>filter</code></a> returns an iterator rather than a list, and this causes <code>len(a)</code> to raise <code>TypeError</code>. The problem with <code>filter</code> is easily fixed:</p>\n\n<pre><code>a = list(filter(None, (self.array[r][c] for r, c in cells)))\n</code></pre>\n\n<p>but why didn't you see the <code>TypeError</code>? That's because it was suppressed by your <code>Transaction</code> class. <code>Transaction.__exit__</code> always returns <code>self</code>. In Python 2 this gets converted to a <code>bool</code> via the <code>__nonzero__</code> method. But Python 3 doesn't support the <a href=\"http://docs.python.org/2/reference/datamodel.html#object.__nonzero__\"><code>__nonzero__</code></a> method (the Python 3 equivalent is <a href=\"http://docs.python.org/3/reference/datamodel.html#object.__bool__\"><code>__bool__</code></a>), so <code>self</code> is always <code>True</code>, and so all exceptions are suppressed.</p>\n\n<p>The way to fix this portably would be to use <code>__len__</code> instead of <code>__nonzero__</code>. But can it really be right for you to suppress exceptions? Surely what you want is something like this:</p>\n\n<pre><code>def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n self.rollback()\n return False\n</code></pre></li>\n<li><p>There's no documentation for the <code>Transaction</code> and <code>Sudoku</code> classes. How am I supposed to use these classes?</p></li>\n<li><p>To expand on point #1, code of the form:</p>\n\n<pre><code>map(lambda args: expression, iterable)\n</code></pre>\n\n<p>is nearly always better written as a list comprehension:</p>\n\n<pre><code>[expression for args in iterable]\n</code></pre>\n\n<p>(if you really do want to allocate a list) or as a generator expression:</p>\n\n<pre><code>(expression for args in iterable)\n</code></pre>\n\n<p>(if you don't). By getting rid of the <code>lambda</code> you avoid a function call for each item, and function calls are moderately costly in Python.</p>\n\n<p>In particular:</p>\n\n<pre><code>sum(map(lambda row: sum([v or 0 for v in row]), self.array))\n</code></pre>\n\n<p>could be rewritten like this:</p>\n\n<pre><code>sum(sum(v or 0 for v in row) for row in self.array)\n</code></pre></li>\n<li><p>Similarly for <code>filter(lambda: ...)</code>. Code of the pattern:</p>\n\n<pre><code>filter(lambda args: expression, iterable)\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code>(args for args in iterable if expression)\n</code></pre>\n\n<p>This avoids a function call for each item. In particular, your code:</p>\n\n<pre><code>placements = set(filter(lambda c: row[c] is None, range(len(row))))\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code>placements = set(i for i, cell in enumerate(row) if cell is None)\n</code></pre></li>\n<li><p>When you want to return the only item of the set <code>placements</code>, you write:</p>\n\n<pre><code>list(placements)[0]\n</code></pre>\n\n<p>but it would be better to write:</p>\n\n<pre><code>next(iter(placements))\n</code></pre>\n\n<p>as this avoids having to convert the whole set to a list. (If you don't care about modifying the set, you can write <code>placements.pop()</code>.)</p></li>\n<li><p>The <code>__hash__</code> method does not seem very robust: since you just add up the numbers in the array, then any permutation of the array yields the same hash!</p>\n\n<p>But hang on a second, why are you writing a hash function at all? If you read the documentation for the <a href=\"http://docs.python.org/2/reference/datamodel.html#object.__hash__\"><code>__hash__</code></a> method, you'll see that it says:</p>\n\n<blockquote>\n <p>If a class defines mutable objects and implements a <code>__cmp__()</code> or <code>__eq__()</code> method, it should not implement <code>__hash__()</code>, since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).</p>\n</blockquote>\n\n<p>Your <code>Sudoku</code> objects are <em>mutable</em>: they can be changed by the <code>set</code> and <code>undo</code> methods. This makes them unsuitable for storing in sets or using as dictionary keys.</p>\n\n<p>So if they mustn't be hashed, how do you deduplicate solutions? Well, you could use their printed representation instead:</p>\n\n<pre><code>solutions = set() # Deduplicate solutions\nfor solution in self.guess_from(0, 0):\n r = repr(solution)\n if r not in solutions:\n solutions.add(r)\n yield solution\n</code></pre></li>\n<li><p><code>Transaction</code> and <code>Sudoku</code> are <a href=\"http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes\">old-style classes</a>. Old-style classes don't support the <a href=\"http://docs.python.org/2/library/functions.html#super\"><code>super</code></a> built-in, and that means that you can't straightforwardly use multiple inheritance. It is nearly always be better to write:</p>\n\n<pre><code>class Transaction(object):\n</code></pre>\n\n<p>to ensure that you get a new-style class.</p></li>\n<li><p>In <code>Sudoku.__init__</code>, this line seems strange to me:</p>\n\n<pre><code>self.symbols = symbols or set(range(1, 1 + int(sqrt(len(array) * len(array[0])))))\n</code></pre>\n\n<p>as it suggests the possibility that the width and height of the array might be different. But Sudoku puzzles must be square, so surely this can't happen?</p>\n\n<p>Similarly, it seems wrong for the box width and height to have the same default values:</p>\n\n<pre><code>self.box_h = box_h or int(sqrt(len(self.symbols)))\nself.box_w = box_w or int(sqrt(len(self.symbols)))\n</code></pre>\n\n<p>Surely having chosen the height, the width is then determined? I think it would be better to write something like this:</p>\n\n<pre><code>n = len(array)\nself.symbols = symbols or set(range(1, n))\nself.box_h = box_h or int(sqrt(n))\nself.box_w = box_w or n // self.box_h\nassert(self.box_h * self.box_w == n)\n</code></pre></li>\n<li><p>Your solver is very slow when it has to make a lot of guesses. For example, this puzzle takes more than a minute to solve on my computer:</p>\n\n<pre><code>>>> from timeit import timeit\n>>> puzzle = '''....79...\n... 7.4.1....\n... .6.2....9\n... 4.3..75..\n... 2.......4\n... ..64..8.3\n... 6....3.9.\n... ....6.4.2\n... ...79....'''\n>>> timeit(lambda:next(Sudoku.parse(puzzle).solutions()), number=1)\n66.50877224095166\n</code></pre>\n\n<p>And this one takes even longer, but I didn't have the patience to wait for it to complete:</p>\n\n<pre><code>>>> puzzle = '''8........\n... ..36.....\n... .7..9.2..\n... .5...7...\n... ....457..\n... ...1...3.\n... ..1....68\n... ..85...1.\n... .9....4..'''\n>>> timeit(lambda:next(Sudoku.parse(puzzle).solutions()), number=1)\n^C\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T19:39:07.390",
"Id": "37436",
"ParentId": "37343",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "37436",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T09:06:31.647",
"Id": "37343",
"Score": "12",
"Tags": [
"python",
"game",
"recursion",
"sudoku",
"community-challenge"
],
"Title": "Sudoku solver using simple deductions and brute-force guessing"
}
|
37343
|
<p>I have a small program which makes uses of pycparser to parse C header files. The code, unfortunately, kinda sprawls out everywhere to handle the different cases (example below).</p>
<p>What's the best way to make this more Pythonic? I thought about case-statements, but those don't exist in Python. Is splitting the function into smaller functions the best approach? </p>
<pre><code>def build_struct(decl):
""" Recursively builds a structure from external definition.
"""
_type = type(decl)
if _type == TypeDecl:
return build_struct(decl.type)
elif _type == IdentifierType:
return " ".join(decl.names)
elif _type == ID:
return ['ID', decl.name]
elif _type == Struct:
struct = c_types.structureDefinition()
for d in decl.decls:
field = build_struct(d)
struct.add_field(field)
return struct
elif _type == Union:
union = c_types.unionDefinition()
for d in decl.decls:
field = build_struct(d)
union.add_field(field)
return union
elif _type == Enum:
# not implemented yet... but don't raise an exception
# unsure if there is any value in supporting enums
return
else:
nested = build_struct(decl.type)
if _type == Decl:
if decl.bitsize:
# fields with bitsize defined (i.e. valid:1)
return c_types.fieldDefinition(decl.name,
int(decl.bitsize.value))
elif isinstance(nested, c_types.structureDefinition):
# if it's a structure, assign it's name
nested.name = decl.name
return nested
elif isinstance(nested, c_types.unionDefinition):
# if it's a union, assign it's name
nested.name = decl.name
return nested
elif isinstance(nested, int):
# if it's an array, we will just return the total size
return c_types.fieldDefinition(decl.name, nested)
else:
# fields w/o bitsized defined
id = nested
# using defined types, like uint32_t
if id in c_types.size_d:
size = c_types.size_d[id]
# using defined structures, like fast_ip
elif id in c_types.structs:
return c_types.structs[id]
else:
raise c_types.UnknownIdentifier(id)
# regular fields, i.e. int count;
return c_types.fieldDefinition(decl.name, int(size))
elif _type == Typename: # for function parameters
raise c_types.NotImplemented
elif _type == ArrayDecl:
#raise c_types.NotImplemented
dimval = decl.dim.value if decl.dim else ''
id = nested
# using defined types, like uint32_t
if id in c_types.size_d:
size = c_types.size_d[id]
# using defined structures, like fast_ip
elif id in c_types.structs:
return c_types.structs[id]
else:
raise c_types.UnknownIdentifier(id)
return int(dimval) * size
elif _type == PtrDecl:
raise c_types.NotImplemented
elif _type == Typedef:
id = nested
# TODO -- this is very common... refactor
if isinstance(id, c_types.structureDefinition):
# typedef struct ...
# TODO -- very similar to code above...
id.name = decl.name
return id
if isinstance(id, c_types.unionDefinition):
# typedef struct ...
# TODO -- very similar to code above...
id.name = decl.name
return id
# TODO -- change to c_types.fieldDefinition
# TODO -- this is very common... refactor
if id in c_types.size_d:
# typdef uint32 unsigned long;
c_types.size_d[decl.name] = c_types.size_d[id]
return c_types.size_d[decl.name]
elif id in c_types.structs:
return c_types.structs[id]
elif not id:
# unhandled cases, like enum
return
else:
raise c_types.UnknownIdentifier(id)
elif _type == FuncDecl:
raise c_types.NotImplementede
</code></pre>
|
[] |
[
{
"body": "<p>I don't think you're going to fundamentally be able to solve the sprawl, as you have a problem composed of lots of small details. These won't go away no matter how well you organize them, but there are options that help you organize them in ways with lesser algorithmic performance hits.</p>\n\n<p>If you can use a version of python with <a href=\"http://www.python.org/dev/peps/pep-0443/\" rel=\"nofollow\">PEP-443</a> there are some further alternatives, but assuming you don't have single dispatch support in your python (I believe only alphas/betas have been released yet), or you want to do things manually, it's quite feasible to implement this using a dict mapping types to functions as alternative to the if/elif tree or missing switch statement. The outer one could look something like this:</p>\n\n<pre><code>def build_struct(decl):\n builder = build_struct.type_builder.get(type(decl))\n if builder:\n return builder(decl)\n\n nested = build_struct(decl.type)\n builder = build_struct.nested_type_builder.get(type(decl))\n if builder:\n return builder(decl, nested)\n\nbuild_struct.type_builder = {\n TypeDecl: lambda d: build_struct(d.type),\n IdentifierType: lambda d: \" \".join(d.names),\n ID: lambda d: [\"ID\", decl.name],\n Struct: lambda d: build_definition(d, c_types.structureDefinition()),\n Union: lambda d: build_definition(d, c_types.unionDefinition()),\n Enum: lambda d: None, # XXX: let Enums be ignored silently\n}\n\ndef build_definition(decl, definition):\n for d in decl.decls:\n definition.add_field(build_struct(d))\n return definition\n\nbuild_struct.nested_type_builder = {\n ...\n}\n</code></pre>\n\n<p>I'm not fully satisfied with the lambdas, even though I chose them for shorter code length. Most of why this code looks shorter is due to not implementing the nested half of your original code. But I do think I prefer the readability for the most part.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T14:36:23.637",
"Id": "61890",
"Score": "0",
"body": "thanks, I'm going to go with single dispatch. there is a backport available in the singledispatch module"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:37:47.880",
"Id": "37351",
"ParentId": "37348",
"Score": "3"
}
},
{
"body": "<p>I'm having difficulty figuring out what this function does. I stopped concentrating when I reached the <code>else</code> statement and saw another big <code>if</code> block. Nested conditionals like that are too much for my tiny human brain.</p>\n\n<p>The problem is that this function is very low-level - everything that the function does is written out in detail. I'd say about 90% of the lines of code in this function are about <em>how</em> the function does what it does, not <em>what</em> it actually does, even though the <em>what</em> is far more important than the <em>how</em>.</p>\n\n<p>So the goal of improving code (any code, not just this code) should be to make the important points blindingly obvious and brushing the boring, confusing details under the carpet. Bear in mind that you might have to re-read this code in a year's time, once you've completely forgotten what it's about. You'll probably discover that your brain isn't big enough either!</p>\n\n<hr>\n\n<p>With that in mind, the simplest thing you could do to improve this code would to use the <a href=\"http://www.refactoring.com/catalog/extractMethod.html\" rel=\"nofollow\">'Extract Method' refactoring</a> (well, 'Extract Function' in this case) on each arm of your big <code>if</code> block. A good rule of thumb is that each arm of a big <code>if</code> block should be one line long. This refactoring is called <a href=\"http://www.refactoring.com/catalog/decomposeConditional.html\" rel=\"nofollow\">'Decompose Conditional'</a>. If you name your extracted methods carefully, the top-level function will be crystal-clear in its intentions.</p>\n\n<p>It's also a good idea to use <code>isinstance</code>, rather than explicitly switching on type, to make your functions more subclass-friendly. If some of the types you're switching on are subclasses of each other, you might need to re-order your <code>elif</code> statements to avoid changing the behaviour of the function. (I hope you have unit tests!)</p>\n\n<p>A brief example of how extracting methods can clean up a function:</p>\n\n<pre><code>def build_struct(decl):\n if isinstance(decl, TypeDecl):\n return build_struct(decl.type)\n if isinstance(decl, IdentifierType):\n return \" \".join(decl.names)\n if isinstance(decl, ID):\n return ['ID', decl.name]\n if isinstance(decl, Struct):\n # Since you know what this code does,\n # you can choose better names than these\n # for the extracted functions\n return create_structure_definition(decl)\n if isinstance(decl, Union):\n return create_union_definition(decl)\n if isinstance(decl, Enum):\n return create_enum_definition(decl)\n return build_struct_for_unknown_type(decl)\n</code></pre>\n\n<p>It's <em>obvious</em> what this function does now! If its argument is a <code>TypeDecl</code>, it recurses on <code>decl.type</code>; if it's a <code>Union</code> then it creates a union definition; if it's some unknown type then it creates a different struct for that, and so on. What's more, you can tell what each extracted function does too - just read the names! This will make it easier to find the code you're looking for when you need to debug it.</p>\n\n<hr>\n\n<p>Finally, it's worth pointing out that if this sort of switch appears more than once in your program then you get to use my personal favourite refactoring, <a href=\"http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html\" rel=\"nofollow\">'Replace Conditional With Polymorphism'</a>. This basically involves moving the repeated conditional logic into a single factory function, which returns different implementations of an interface.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:15:58.487",
"Id": "61894",
"Score": "0",
"body": "Absolutely agreed on forgetting what the first half of the `if/else` tree had done by the time I was reading the bottom. If that's not motivation enough to avoid such a construct, I don't know what is."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:44:24.610",
"Id": "37385",
"ParentId": "37348",
"Score": "2"
}
},
{
"body": "<p>This looks like a good application for the <a href=\"http://python-3-patterns-idioms-test.readthedocs.org/en/latest/FunctionObjects.html\" rel=\"nofollow noreferrer\">Chain Of Responsiblity pattern</a>. </p>\n\n<p>The essence of a COR is a that you create a lot of little classes ('handlers') that look at a stream of inputs. Each class in the chain checks to see if it can handle the input, and if so it parses it and does what ever it needs to do with it; otherwise it just passes the input along to the next handler in the chain. It's a common way to break up complex parsing tasks into a series of smaller chunks - as the other comments note, this is a fiddly problem with lots of details that will always have lots of nitpicky code in it; however by breaking your parsing tasks into lots of smaller chunks instead a long nested series of ifs or a switch you can make the code much easier to read, maintain and expand.</p>\n\n<p>In the classic COR pattern each handler has a link to the next, and requests are passed along the chain until one handler gets an answer which is passed back up the chain. There's a simpler alternative in which you just <a href=\"https://stackoverflow.com/questions/1055383/what-are-the-advantages-of-chain-of-responsibility-vs-lists-of-classes\">loop over a list of handlers until you get a result.</a> The deciding factor between the two approaches would be the need for implementing pre- and or post- answer functioniality. If each handler is atomic, a simple list of parsers will suffice. If handlers have to prepare for or postprocess each other's results then the linked-list method applies. </p>\n\n<p>In your case it looks like all of your code paths are mutually eclusive so I'd stick with the simpler list-of-handler's method</p>\n\n<p>On a structural level it would look like this:</p>\n\n<pre><code>class BaseParser(object):\n SIGNATURE = None\n # in derived classes, this is the match for incoming declaration types\n\n def handle(self, declaration):\n if declaration != self.SIGNATURE:\n return None\n else:\n return self.parse(declaration) \n\n def parse(self, declaration):\n raise NotImplementedError(\"Override in a derived class\")\n\nclass IdentifierParser(BaseParser):\n SIGNATURE = IdentifierType\n\n def parse(self, declaration):\n return \" \".join(declaration.names)\n\nclass StructParser(BaseParser):\n SIGNATURE = Struct\n\n def parse(self, declaration):\n struct = c_types.structureDefinition()\n for d in declaration.decls:\n field = build_struct(d)\n struct.add_field(field)\n return struct\n\n# you'd need to create the handlers for the rest of the code, but you get the idea.\n# the parsing proper is handled like so:\n\nHANDLERS = [\nIdentifierParser(),\nStructParser(),\n#... etc. You would need to watch the order of the parsers only if\n# there were conflicting parsers with the same signature -- which would probably\n# be best handled with a compound parser with sub-parsers inside it...\n]\n\n\ndef parse_declaration(decl):\n result = None\n for handler in HANDLERS:\n result = handler.parse(decl)\n if result: break\n return result\n</code></pre>\n\n<p>From the looks of your code above this could also be implemented without classes by just creating a list of parsing functions. However you'd then have to retype the signature check logic in all of the functions (and if future requirements change to something where state was relevant, you'd have a harder time refactoring).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:45:59.540",
"Id": "37386",
"ParentId": "37348",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37351",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T13:47:38.540",
"Id": "37348",
"Score": "6",
"Tags": [
"python",
"parsing",
"recursion"
],
"Title": "Using pycparser to parse C header files"
}
|
37348
|
<p>I am writing a cron job to manipulate and transfer remote data.
I need to cache data from a table, process it, merge with previous table, iterate the process, and eventually send the result data to remote database.</p>
<p>Here is a basic in-memory cache storage with thin simple CRUD type API.
It has to store hashes, enforce equal keys and unique ids.
The data come from tables and immediately transformed into hashes (key-value pairs). That way hashes are portable and no reference to tables is needed.
Also they can be easily ported to NoSQLs.</p>
<p>The design is inspired by Parse.com and StackMob.</p>
<p>Somehow I could not find any similar light weight library.
I need it portable to easily transfer to any server.
I would rather avoid any heavy installation or configuration.</p>
<p>An older version <a href="https://codereview.stackexchange.com/questions/35541/in-memory-data-cache-architecture">was posted here</a>.</p>
<p>Any critique is welcome.</p>
<pre><code>// I am using 'i' as primary key for all hashes
define('ID_KEY', 'i');
/** Local In-Memory Cache: Tables referred by their string names
* Storing hashes:
* all hashes must have ID_KEY as key
* all hashes must have keys other than ID_KEY
* and hashes in the same table must have the same key structure (enforced)
* Basic CRUD interface + 'readOne' for the first entry + 'realDelete'
* arrays packed into json strings, which allows for array values,
* e.g. array('key1'=>'val1', 'key2'=> array(1,2,3))
*/
class LocStore {
// assoc. array('table' => array of keys)
private $_keys = array();
// assoc. array of strings indexed by table and id (must be nonempty)
private $_values = array();
/** create entry, enforce the same keys and new id
* @param string $table
* @param ass. array $hash, must have ID_KEY not null, must have other keys
*/
public function create ($table, array $hash) {
$id = $hash[ID_KEY];
if (! $id) throw new Exception('Id is empty');
unset($hash[ID_KEY]);
if (! $hash) throw new Exception('Empty hash beside id');
// sort by keys alphabetically to ensure the same order for all entries
ksort($hash);
if ( empty($this->_keys[$table]) ) {
// first hash for $table - cache keys
$this->_keys[$table] = array_keys($hash);
} elseif ($this->_keys[$table] != array_keys($hash)) {
throw new Exception('Array keys mismatch: '. json_encode($hash) );
}
if ( isset($this->_values[$table]) && ! empty($this->_values[$table][$id]) ) {
throw new Exception("Id '$id' already exists");
}
$this->_values[$table][$id] = json_encode(array_values($hash));
// for chaining
return $this;
}
// read one entry, empty array if nothing is there
// reset pointer for iteration
public function reset ($table) {
if (! empty($this->_values[$table]) ) {
reset($this->_values[$table]);
}
}
// read next hash and advance pointer
public function readNext ($table) {
if (empty($this->_values[$table])) return array();
$id = key($this->_values[$table]);
next($this->_values[$table]);
if (! $id) return array ();
return $this->read($table, $id);
}
// read one entry if there are some or else return empty array
// in contrast to readNext, the result is always non-empty as long as table has hashes
public function readOne ($table) {
if ( empty($this->_values[$table]) ) return array();
foreach ($this->_values[$table] as $id => $val) {
return $this->read($table, $id);
}
return array();
}
// read by id, empty array if not found
public function read ($table, $id) {
if (! $id) throw new Exception('Id is empty');
if ( empty($this->_values[$table]) || empty($this->_values[$table][$id]) ) return array();
//$keys = $this->_toArray($this->_keys[$table]);
$keys = $this->_keys[$table];
//$values = $this->_toArray($this->_values[$table][$id]);
$values = json_decode($this->_values[$table][$id]);
$result = array_combine($keys, $values);
$result[ID_KEY] = (string) $id;
return $result;
}
// read and delete one nonempty array or return empty if nothing is left
public function readDeleteOne ($table) {
if ( empty($this->_values[$table]) ) return array();
foreach ($this->_values[$table] as $id => $val) {
return $this->readDelete($table, $id);
}
return array();
}
// read and delete by id, empty array if not found
public function readDelete ($table, $id) {
if (! $id) throw new Exception('Id is empty');
if ( empty($this->_values[$table]) || empty($this->_values[$table][$id]) ) return array();
$keys = $this->_keys[$table];
$values = json_decode($this->_values[$table][$id]);
$result = array_combine($keys, $values);
$result[ID_KEY] = (string) $id;
// deletion is here
unset($this->_values[$table][$id]);
return $result;
}
// delete by id, exception if not found
public function delete ($table, $id) {
if (! $id) throw new Exception('Id is empty');
if ( empty($this->_values[$table]) || empty($this->_values[$table][$id]) ) {
throw new Exception('Deleting non-existant entry');
}
unset($this->_values[$table][$id]);
return $this;
}
public function deleteAll ($table) {
$this->_values[$table] = array();
return $this;
}
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Here is the (only) method from another class using <code>reset</code> and <code>readNext</code> (where <code>$this->_locStore</code> points to the class <code>locStore</code> above):</p>
<pre><code>public function loadChains ($table, $mergeTable, $relKey) {
$this->_locStore->reset($mergeTable);
while ( $hash = $this->_locStore->readNext($mergeTable) ) {
$chain = $this->getChain($mergeTable, $hash[ID_KEY], $relKey);
$hash[$relKey] = $chain;
$this->_locStore->create($table, $hash);
}
$this->_locStore->deleteAll($mergeTable);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T20:56:43.720",
"Id": "61826",
"Score": "0",
"body": "Actually I can not understand why do you call it ***cache***?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T01:23:14.750",
"Id": "61851",
"Score": "0",
"body": "@zavg Cache is where you store your data temporarily, isn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T06:59:42.857",
"Id": "61868",
"Score": "1",
"body": "Cache is used to store data so that future requests for that data can be served faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:51:32.307",
"Id": "61884",
"Score": "0",
"body": "@zavg I've seen Laravel calling `Cache` its abstract storage API that can be e.g. database, memcached, redis ... Is this a bad terminology?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T08:34:41.347",
"Id": "62043",
"Score": "0",
"body": "1) Cache, to me, is something that outlives the request being processed (data stored in files, which can be loaded come the next request). 2) `$hash[ID_KEY]`: what is `ID_KEY`? it seems to me to be a constant, so whenever you call this method, you're using the same key of an array, why, then, are you passing an array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:18:54.803",
"Id": "62046",
"Score": "0",
"body": "@EliasVanOotegem 1) Yes, my cache here lives as long as `locStore` object. 2) Good point, I have put it at the top. It is just a constant I want to keep easily accessible to all code. I am using the same key but the value I get from the `$hash` changes. Is there a better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:52:32.920",
"Id": "62050",
"Score": "0",
"body": "@DmitriZaitsev: If your _\"cache\"_ lives as long as your object, then it isn't cache. PHP is stateless: Objects don't live on in memory once the request has been processed, so come the next request, your object is instantiated once more, and PHP has to do the work all over. Think of cache as a piece of paper. If I were to ask of you to calculate the avg distance between the earth and sun, you'd set to work, and might jot it down, so that whenever someone else asks for the same thing, you can just produce the piece of paper and answer in a matter of seconds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:55:08.107",
"Id": "62052",
"Score": "0",
"body": "Of course, in real life you'd only cache things that are requested more than once every 100 years... but the basic idea of cache is: storing the result of (complex) computations, so that instead of doing the sums over and over, you can do them once, and present the client with the same result whenever it is requested. If done well, the performance benefits are enormous"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:59:00.987",
"Id": "62053",
"Score": "0",
"body": "@EliasVanOotegem Ok, I see, so what is a good name for what this code is doing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:02:34.163",
"Id": "62054",
"Score": "0",
"body": "@DmitriZaitsev: Well, without wanting to be mean, I'd hesitate to call this anything except _\"BPP\"_ (Bad programming practice). It's sort of a register, but then registers are, generally, static (which is, IMO, BPP, too, as that's just another way of creating globals in drag). You could say that this is just a data-model, too, but then it's not exactly self-documenting (as in: it's unclear what types of data the obejct will contain)... As an asside: the constant `ID_KEY` obviously belongs to the class, so define it as a class constant, please"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:13:24.313",
"Id": "62057",
"Score": "0",
"body": "@EliasVanOotegem Thank you for the critics :) The problem is that I want to keep it a global constant available to all my classes. How can I make it a class constant for all classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:22:22.190",
"Id": "62059",
"Score": "0",
"body": "@DmitriZaitsev: If it's a constant like `APPLICATION_ROOT` or something, it's perfectly valid to keep it a global constant. That said, class constants are available globally, too: `My\\Class::SOME_CONSTANT` can be used anywhere, too"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:28:41.757",
"Id": "62060",
"Score": "0",
"body": "@EliasVanOotegem Oh I see, I can do it but then instead of `$hash[ID_KEY]` I would have `$hash[Config::ID_KEY]` which would be much longer and not pretty, where the advantages are not clear to me. It is really a very special constant, not one of many."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:09:40.410",
"Id": "62250",
"Score": "0",
"body": "@EliasVanOotegem Is there any BBP other than using a global constant?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:50:16.727",
"Id": "62260",
"Score": "0",
"body": "@DmitriZaitsev: A global constant isn't BPP. If some immutable value is used throughout the code, then a global constant is good. If an immutable value is used by 1 specific class, be it internally, in that class or as an argument to its methods, then a class constant is a better fit (think of `PDO::ATTR_ERRMODE`, for example). looking at your code (superficially), it would seem that you're trying to make your object behave like an array. That's fine, but PHP offers interfaces to do just that ([the `Traversable` interfaces](http://www.php.net/manual/en/class.traversable.php)). Look into those"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T12:21:02.297",
"Id": "62266",
"Score": "0",
"body": "@EliasVanOotegem Indeed, this is a global constant used throughout the code. I've only posted one class here as posting the whole code in one post wouldn't probably fit here. I have looked into Traversable interfaces but these are just interfaces - I still need to write the code. So I don't quite see how they can help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T12:24:53.273",
"Id": "62268",
"Score": "0",
"body": "@DmitriZaitsev: All objects that implement the `Traversable` interface can then be used as an array in language constructs like `foreach`, which means you don't have to call methods like `rewind` or `reset`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T12:37:32.720",
"Id": "62271",
"Score": "0",
"body": "@EliasVanOotegem I have included the only external method using these command (see the edit). How would you propose to change this structure?"
}
] |
[
{
"body": "<p>Ok, since there is no answer, I'll write it myself what would have been really a great help and what I have discovered:</p>\n\n<p>The main problem with this code is the usage of many expensive operations responsible for slow execution. It seems the split into keys and values before storing as well as sorting and then re-combining into arrays is really slow.</p>\n\n<p>Why it matters? Because I am running my code using this storage on <a href=\"http://www.iron.io/\" rel=\"nofollow\">Iron.io</a>\nas <a href=\"http://www.iron.io/worker\" rel=\"nofollow\">IronWorker</a>. Iron is great but has limitations: each worker gets 320 MB memory and 1 hour maximum to run. In the past I hit the memory limit because I stored my data in as <strong>hash of hashes</strong>, i.e. in the form</p>\n\n<pre><code>$mainHash = array(\n id1 => array('key1' => 'value1', ... ),\n ...\n);\n</code></pre>\n\n<p>with many rows! <strong>Bad idea!</strong> </p>\n\n<p>Then after hitting the memory limit I turned to obsessive memory saving strategy, replacing row hashes by their <em>JSONs</em>. However, since all keys are repeated, I considered it a waste of memory to store them on each hash. So I split off keys in a separate array and only stored values! This is exactly what the above code does! Memory usage went nicely under 100 MB! But ... the execution time didn't fit into the 1 hour frame. Which cost me some headache for the few past days until today I had this great idea to try with actual <em>JSONs</em>:</p>\n\n<pre><code>$mainHash = array(\n id1 => json_encode(array('key1' => 'value1', ... )),\n ...\n);\n</code></pre>\n\n<p>And the result is amazing! Memory is under 110 MB and I am inside 1 hour!!!\nSo only marginal memory loss with huge win to get everything done in one worker!</p>\n\n<p>So here is the winning cleaner solution:</p>\n\n<pre>\nclass LocStoreFast extends LocStore {\n /** just store json hashes, no enforcement\n * @param string $table\n * @param associative array $hash, must have ID_KEY not null, must have other keys\n */\n public function create ($table, array $hash) {\n $id = $hash[ID_KEY];\n if ( isset($this->_values[$table]) && ! empty($this->_values[$table][$id]) ) {\n throw new Exception(\"Id '$id' already exists\");\n }\n $this->_values[$table][$id] = json_encode($hash);\n }\n\n // read by id, empty array if not found\n public function read ($table, $id) {\n if ( ! $id || empty($this->_values[$table]) || empty($this->_values[$table][$id]) ) return array();\n return json_decode($this->_values[$table][$id], true);\n }\n\n // read and delete by id, empty array if not found\n public function readDelete ($table, $id) {\n if ( ! $id || empty($this->_values[$table]) || empty($this->_values[$table][$id]) ) return array();\n $result = json_decode($this->_values[$table][$id], true);\n unset($this->_values[$table][$id]);\n return $result;\n }\n\n}\n</pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T02:02:04.730",
"Id": "68224",
"Score": "4",
"body": "+1 awesome *selfie*! Sorry your question hasn't had more attention. Feel free to accept your own answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T10:28:28.220",
"Id": "37663",
"ParentId": "37349",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37663",
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:21:57.800",
"Id": "37349",
"Score": "5",
"Tags": [
"php",
"database",
"api",
"cache"
],
"Title": "In-memory data cache architecture for data transfer"
}
|
37349
|
<pre><code>#!/usr/bin/python3
# Description: Python script that will mount FTP-Server via SSHFS protocol
import sys
import os
import subprocess
def mount():
#Function for mounting the networked drive
if os.path.exists('/home/user/MNT/MEDIA/'):
print('Network drive is mounted')
un = input("To unmount type U/u \n")
if un == "u" or un == "U":
subprocess.call(['sudo fusermount -u /home/user/MNT/'], shell=True)
else:
pass
exit(0)
if not os.path.exists('/home/user/MNT/MEDIA/'):
IP = input("Type I/i for local connection, E/e for external\n")
if IP == "i" or IP == "I":
subprocess.call(['sudo sshfs -o idmap=user -o uid=1000 -o gid=1000 -o allow_other -o default_permissions -p 100 user@10.0.0.100:/media/Hitachi/ /home/user/MNT'], shell=True)
if IP == "e" or IP == "E":
subprocess.call(['sudo sshfs -o idmap=user -o uid=1000 -o gid=1000 -o allow_other -o default_permissions -p 100 user@xxxxxxxx.com/media/Hitachi/ /home/user/MNT'], shell=True)
elif IP == "": #returns if null value
return mount()
def makedir():
#Function to check and see if directory is created and if not create it
if not os.path.exists('/home/user/MNT/'):
subprocess.call(['sudo mkdir /home/user/MNT/'], shell=True)
if os.path.isdir('/home/user/MNT/'):
mount()
makedir()
</code></pre>
<p>EDITED:</p>
<pre><code>def sshfs():
#function to mount network drive
while True:
user = input("Type 'i' for internal, 'e' for external connection\n")
fs = File_System.get(user.lower()) #Get value from the dict called File_System
if fs is None:
print("Invalid option, enter either 'i' for internal or 'e' for external\n")
else:
subprocess.call(["sudo sshfs -o uid=1000 -o gid=1000 -o idmap=user -o default_permissions -o allow_other -p 100 %s %s" % (fs, Local_Mount)], shell=True)
exit(0)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:40:15.043",
"Id": "61771",
"Score": "0",
"body": "Please provide some more context. Looking at the code tells us one what you are actually doing, but having a general description of what you want to do may give some opportunity to provide alternative suggestions too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:28:01.940",
"Id": "61802",
"Score": "0",
"body": "Just trying to make a script to use with all my linux machines to mount to a centralized server"
}
] |
[
{
"body": "<p>Efficiency is just not an issue in this kind of task. As \"glue\" code, it's not computationally intensive. There are, however, some maintainability issues.</p>\n\n<ul>\n<li><p>In <code>mount()</code>, the basic outline is:</p>\n\n<pre><code>def mount():\n if os.path.exists('/home/user/MNT/MEDIA/'):\n ...\n exit(0) \n if not os.path.exists('/home/user/MNT/MEDIA/'):\n ...\n</code></pre>\n\n<p>… which should be expressed as:</p>\n\n<pre><code>def mount_or_unmount():\n if os.path.exists('/home/user/MNT/MEDIA/'):\n ...\n else:\n ...\n</code></pre></li>\n<li>Using recursion for error handling is weird. That would normally be handled using a while-loop. It's also slightly odd that the empty string triggers a retry, but any other invalid input would exit the script.</li>\n<li><p>The two <code>sudo sshfs</code> commands differ only slightly. Your code should be structured accordingly.</p>\n\n<pre><code>REMOTE_FS = {\n 'i': 'user@10.0.0.100:/media/Hitachi/',\n 'e': 'user@xxxxxxxx.com/media/Hitachi/',\n}\n\n...\nwhile True:\n ip = input(\"Type I/i for local connection, E/e for external\\n\")\n fs = REMOTE_FS.get(ip.lower())\n if fs is None: # Input was not 'i' or 'e'\n continue\n subprocess.call(['sudo sshfs -o idmap=user -o uid=1000 -o gid=1000 -o allow_other -o default_permissions -p 100 %s /home/user/MNT' % (fs)], shell=True)\n break\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T06:35:16.550",
"Id": "62035",
"Score": "1",
"body": "Awesome, I reedited my code and I learned a lot, especially with reducing 'glue' code. However I have one question and I need it dumbed down\n\n while True:\nTill what is true? Why/How does the loop end?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T06:52:39.810",
"Id": "62036",
"Score": "0",
"body": "Yikes! Forgot a very important `break`. Good catch!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:05:22.683",
"Id": "62038",
"Score": "0",
"body": "I did it slightly different. I'm still confused as to why the loop breaks even without the break statement?:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T09:09:13.317",
"Id": "65750",
"Score": "0",
"body": "@Joe `exit(0)` in your case is the equivalent of `break`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:30:05.987",
"Id": "37406",
"ParentId": "37350",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:31:22.247",
"Id": "37350",
"Score": "3",
"Tags": [
"python",
"linux"
],
"Title": "Is this an efficient way of mounting a file-system via SSH (SSHFS)?"
}
|
37350
|
<p>I would like to increase my performance of js code write a clean code... can you tell me how to do it... providing my fiddle below with js code...</p>
<p><a href="http://jsfiddle.net/YYg8U/" rel="nofollow">http://jsfiddle.net/YYg8U/</a></p>
<pre><code>var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];
function getClosestToZero(numberSet) {
var i = 0, positiveSet = [], positiveClosest = 0;
for (i = 0; i < numberSet.length; i += 1) {
positiveSet.push(numberSet[i] >= 0 ? numberSet[i] : numberSet[i] * -1);
}
positiveClosest = Math.min.apply(Math, positiveSet);
return numberSet[positiveSet.indexOf(positiveClosest)];
}
alert(getClosestToZero(myNumbersToSort));
</code></pre>
|
[] |
[
{
"body": "<p>In code you posted, you pass through array three times instead of one:</p>\n\n<ul>\n<li><p>1st pass when pushing absolute values to auxillary array</p></li>\n<li><p>2nd pass when searching for minimum value (in <code>Math.min</code>)</p></li>\n<li><p>3rd pass when you get the index of minimum value (in <code>indexOf</code>)</p></li>\n</ul>\n\n<p>It is more efficiently to do it in just one pass:</p>\n\n<pre><code>function getClosestToZero(set) {\n if(0 === set.length) return null;\n var closest = Math.abs(set[0]), result = 0;\n for(var i in set) {\n var next = Math.abs(set[i]);\n if(closest > next) {\n result = i;\n closest = next;\n }\n }\n return result; \n}\n</code></pre>\n\n<p>Also for the purpose of readability I will recommend you to use <code>Math.abs</code> library function instead of implementing it by yourself.</p>\n\n<p><strong>Note:</strong> The small theoretical disatavantage of my code consists in that it compares first element with itself. You can rewrite for loop to avoid it or ignore it because its impact is insigninficant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:30:19.987",
"Id": "61767",
"Score": "0",
"body": "What is the advantage of `0 === set.length` vs the more natural `set.length === 0`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:37:38.973",
"Id": "61769",
"Score": "1",
"body": "@DmitriZaitsev this kind of inverse notation is usually used to be sure that you did not accidently write set.length = 0 as your conditional statement"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:48:18.687",
"Id": "61792",
"Score": "0",
"body": "Ah yes - good point!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:10:04.477",
"Id": "37356",
"ParentId": "37352",
"Score": "5"
}
},
{
"body": "<p>Processing an array and coming up with 1 result is what <code>.reduce()</code> was meant for.</p>\n\n<p>The problem is that reduce only has 1 'previous' and I did not want to recalculate the absolute value of <code>previous</code> every time. This can be prevented by passing on a simple object. The function could easily be extended to return the value, abs value and the array index.</p>\n\n<pre><code>var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];\n\nfunction getClosestToZero( set )\n{\n return set.reduce( function( o, i )\n {\n return ( Math.abs( i ) < o.abs )? { value : i , abs: Math.abs( i ) }:o;\n } , { value : set[0] , abs : Math.abs(set[0]) } ).value;\n}\n\nalert(getClosestToZero(myNumbersToSort));\n</code></pre>\n\n<p>or, we could build on the answer of MrMinshall:</p>\n\n<pre><code>var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];\n\nfunction getClosestToZero( set )\n{\n return set.sort( function(a,b){ return Math.abs(a) - Math.abs(b) } )[0];\n} \nalert(getClosestToZero(myNumbersToSort));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:03:18.620",
"Id": "37362",
"ParentId": "37352",
"Score": "0"
}
},
{
"body": "<pre><code>function lowestEpsilon(of) {\n\n return of.reduce(minimal, [Infinity, Infinity]).shift()\n\n // pass around a pair of [value, Math.abs(value)] and replace\n // it if the current item has a better absolute value.\n function minimal(previously, value) {\n var absolute = Math.abs(value)\n if ( absolute < previously[1] )\n return [value, absolute]\n return previously\n }\n}\n\nlowestEpsilon([1,2,-0.5])\n\nlowestEpsilon([50,0.3,-0.2,1,50])\n</code></pre>\n\n<p>Ensure you have <code>[].reduce</code> available in your environment.</p>\n\n<p>Prefer comprehensible code over fancy algorithms. <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"nofollow\">Don't optimise prematurely</a>.</p>\n\n<p>Hard to find the best balance of 'clean and performant' until you've profiled your application and use cases. Do you have large arrays or small arrays as input? Is this the slowest call in your application?</p>\n\n<p>Thanks to tomdemuyt for correcting my interpretation of the problem.</p>\n\n<p>Bonus: what do you expect to be the output for <code>[-0.5, 0.5]</code> as an input?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T21:03:41.260",
"Id": "61828",
"Score": "0",
"body": "I love the simplicity of an array over the object I chose."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:11:10.773",
"Id": "37369",
"ParentId": "37352",
"Score": "2"
}
},
{
"body": "<p>There's nothing wrong with a bit of competition, but <a href=\"http://jsfiddle.net/YYg8U/5/\" rel=\"nofollow\">here's my take on it</a></p>\n\n<pre><code>function getClosestToZero(numberSet) {\n if (!numberSet || !numberSet.length) return;\n var closestNumber = numberSet[0];\n for (var i = 0; i++ < numberSet.length;)\n if (fastAbs(numberSet[i]) < fastAbs(closestNumber)) \n closestNumber = numberSet[i];\n return closestNumber;\n}\n\nfunction fastAbs(x) { return (x < 0 ? -x : x);}\n</code></pre>\n\n<p>Well, more lines doesn't mean it's slower. The main bottleneck for everyone is <code>Math.abs</code>. There's <a href=\"http://jsperf.com/math-abs-vs-bitwise/7\" rel=\"nofollow\">a much faster implementation of <code>Math.abs</code></a>, which <a href=\"http://jsperf.com/get-closest-to-0\" rel=\"nofollow\">I also used in this perf test</a>.</p>\n\n<p>Additionally, you one should not use <code>for-in</code> when looping through an array. It's because <code>for-in</code> <a href=\"http://jsperf.com/get-closest-to-0\" rel=\"nofollow\">will run over on properties other than the number-indexed members</a> (yes, Arrays are still objects.). And besides, <code>for-in</code> is a very slow loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T04:36:17.240",
"Id": "37394",
"ParentId": "37352",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T15:46:38.803",
"Id": "37352",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "cleaning up and increasing performance of js code"
}
|
37352
|
<p>I have this code:</p>
<pre><code>switch (c) {
case '-': break;
case '0': e = expr(j).reduce(C1); e=not(e); a = and(a, e); break;
case '1': e = expr(j).reduce(C1); a = and(a, e); break;
default: throw new Exception("Unexpected cube value, " + c);
}
</code></pre>
<p>The cases 0 and 1 are only different by <code>not</code>. I do not like to encode the necessity to <code>invert</code> into the arguments of the <code>and</code> function,</p>
<pre><code>switch (c) {
case '-': break;
case '0': a = and(true, a, e); break;
case '1': a = and(false, a, e); break;
default: throw new Exception("Unexpected cube value, " + c);
}
</code></pre>
<p>because this will need a conditional <code>if (invert) e = inv(e);</code> in the function, whereas we already established the need to invert when resolved the switch. </p>
<p>I mean that in <code>case1</code> you know that you do not need any <code>inv</code>. In <code>case0</code>, you know that you need one. If you now merge the cases, you will need one more <code>if</code> to resolve between <code>case1</code> (<code>inv</code> is not needed) and <code>case0</code> (<code>inv</code> is needed) once again. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:40:11.217",
"Id": "61770",
"Score": "1",
"body": "Could you provide some more context about this code? What is `a` and `e`? What does `and` though? What does `expr(j).reduce(C1)` do? You don't need to provide the code for them, just explain what it is doing and what types you are using."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:20:58.170",
"Id": "61778",
"Score": "0",
"body": "Are `a`, `e` booleans or some more exotic structure?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:25:11.700",
"Id": "61782",
"Score": "0",
"body": "@rolfl They are exotic booleans."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:30:36.387",
"Id": "61786",
"Score": "1",
"body": "I agree with @SimonAndréForsberg, and I suspect you may have an [XY problem](http://meta.stackexchange.com/q/66377/148099). It looks like you are trying to do arithmetic based on a string representation of some numbers. Maybe `BigInteger` is appropriate? I encourage you to post the entire function, probably as a separate question referencing this one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:36:48.957",
"Id": "61788",
"Score": "0",
"body": "Your question is essentially the same as a previous question you already asked. You got the same result then. I'm voting to close as duplicate. If you disagree then please tell me what's different with this question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:37:15.993",
"Id": "61789",
"Score": "0",
"body": "@200_success Yes, I think it is XY problem. I ask you to optimize the code as it is, you keep insisting that I must change the type. Exploiting other types is not allowed. Ok?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:11:08.217",
"Id": "61796",
"Score": "1",
"body": "@Val `if (c == '-') handleThatcase(); else duplicateOfYourPreviousQuestion();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:42:13.153",
"Id": "61808",
"Score": "1",
"body": "@SimonAndréForsberg You are right."
}
] |
[
{
"body": "<p>There are two significantly different ways I can think of to rewrite your code. </p>\n\n<p>The first is to put <code>case '0'</code> and <code>case '1'</code> together by letting one case 'fall through', and then using the ternary operator with in the code to see if we should invert or not.</p>\n\n<pre><code>switch (c) {\n case '-': break;\n case '0': // fall through to execute the same code as below\n case '1': \n e = expr(j).reduce(C1);\n // Using the ternary operator to determine whether or not e should go through not first.\n a = and(a, c == '0' ? not(e) : e);\n break;\n default: throw new Exception(\"Unexpected cube value, \" + c);\n}\n</code></pre>\n\n<p>The other approach is to skip the switch and use if-else</p>\n\n<pre><code>if (c == '0' || c == '1') {\n e = expr(j).reduce(C1);\n a = and(a, c == '0' ? not(e) : e); // Again, using the ternary operator.\n}\nelse if (c != '-') \n throw new Exception(\"Unexpected cube value, \" + c);\n</code></pre>\n\n<p>There might be even better ways to rewrite this code, if I would know more context about it.</p>\n\n<p>I agree that you should <strong>not</strong> move the logic of inverting <code>e</code> to the <code>and</code> method.</p>\n\n<p>Explanation of the <strong>ternary operator</strong>:</p>\n\n<pre><code>a = and(a, c == '0' ? not(e) : e);\n</code></pre>\n\n<p>This is the same thing as:</p>\n\n<pre><code>if (c == '0')\n a = and(a, not(e));\nelse \n a = and(a, e);\n</code></pre>\n\n<p>A more detailed explanation can be found on <a href=\"http://en.wikipedia.org/wiki/%3F%3a#Java\" rel=\"nofollow\">wikipedia</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:50:00.140",
"Id": "61775",
"Score": "0",
"body": "Your idea to use extra if-else right in the `fallthrough` case is better than mine to pull if-else into the and. But, it does not resolve my concern that if-else for invert must be resolved by cases and using extra if-else is bad (cyclomatic complexity, pipeline stalls and discards). I know what is the ternary operator. It is the same as if-else and I do not think that it is better than if-else. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:13:23.060",
"Id": "61776",
"Score": "0",
"body": "@Val Your question was quite unclear so it was hard to tell what level of experience you had, and what you are actually asking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:53:04.170",
"Id": "61793",
"Score": "0",
"body": "Not clear? Do you see that `not` in the common pattern? It is not ok. Merging the cases with additional `if` is also not ok."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:38:47.773",
"Id": "37360",
"ParentId": "37357",
"Score": "4"
}
},
{
"body": "<p>Following on from Simon's answer (which I believe will be more than great for 99.99% of users).....</p>\n\n<p>... actually, I have looked though the code, and I don't understand enough of it to make sense of the right answer:</p>\n\n<ul>\n<li>why do you do the map-reduce at all if <code>a = and(a,e)</code> will be 'false' if <code>a</code> starts off 'false`?</li>\n<li>the map-reduce (two method calls) are far, far more expensive than the switch and conditionals outside the methods... this loop does not need to be optimized any more.</li>\n<li>The 'boolean-like' variables <code>a</code>, <code>e</code> are not well described at all.</li>\n</ul>\n\n<p>Without knowing more about the code and it's context, I can think of only one thing that <strong>may</strong> help, and this is an extension of Simon's answer:</p>\n\n<pre><code>if (((c - '0')) >> 1 == 0) { // reduce cyclomatic complexity by 1.\n // '0' is 0x30, (c - '0') will end up with 0 for '0' and 1 for '1' - anything else is wrong\n e = expr(j).reduce(C1);\n a = and(a, c == '0' ? not(e) : e); // Again, using the ternary operator.\n} else if (c != '-') \n throw new Exception(\"Unexpected cube value, \" + c);\n</code></pre>\n\n<p>Any other suggestions would just be wild guesses.</p>\n\n<p><strong>EDIT</strong></p>\n\n<pre><code>public static void char01() {\n for (char c = Character.MIN_VALUE; c <= Character.MAX_VALUE; c++) {\n if ((c - '0') >> 1 == 0) {\n System.out.println(\"This matches '\" + c + \"'\");\n }\n }\n}\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>This matches '0'\nThis matches '1'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:26:55.850",
"Id": "61801",
"Score": "0",
"body": "`reduce` is just a placeholder for some another function. Sorry for a confusing name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:40:28.100",
"Id": "61807",
"Score": "0",
"body": "LSB of `c-'0'` is 0 or 1 for cases 0 and 1. But (`c-'0'` >> 1 != 0) passes if `c` is `2` or larger. How do your single out cases `0` and `1` this way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:43:22.657",
"Id": "61809",
"Score": "0",
"body": "@Val - it works... do the math: See my edit:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:44:06.987",
"Id": "61810",
"Score": "0",
"body": "@Val perhaps it should be `>> 1 == 0`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:45:02.507",
"Id": "61811",
"Score": "0",
"body": "Ahh... yes.... copy-paste problem/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:51:25.390",
"Id": "61813",
"Score": "0",
"body": "I looked the cyclomatic complexity article and it says that complexity of `if (a)` = complexity of `if (a | b)` because the number of branches rather than conditions that matters. I believe that that after compiler optimizations, `if (((c - '0')) >> 1 == 0)` is identical to `if (c == '1' || c == '0')`. The predicates are linear in both cases. The complexity is the same. What really affects the performance and code complexity is the number of branches."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T19:02:02.987",
"Id": "61816",
"Score": "0",
"body": "In `if(c=='1' || c == '0') { ... }` there are three code paths, complexity 3. In `if (((c - '0')) >> 1 == 0)` there are only 2 - complexity 2. Promise. With the former there are two ways to get in to the block... with the latter there's only one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T19:04:22.573",
"Id": "61817",
"Score": "0",
"body": "See: http://stackoverflow.com/questions/15240922/cyclomatic-complexity-with-compound-conditions-and-short-circuiting"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:12:19.217",
"Id": "37370",
"ParentId": "37357",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:23:39.063",
"Id": "37357",
"Score": "-2",
"Tags": [
"java"
],
"Title": "Common factor in some cases"
}
|
37357
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.